text
stringlengths 8
267k
| meta
dict |
---|---|
Q: Visual Studio 2005/2008: How can you share/force all developers to use the same formatting rules? I would like to have all developers on my team to use the same rules for formatting several types of code (ASPX, CSS, JavaScript, C#). Can I have visual studio look to a common place for these rules?
I would like to not rely on export/import settings as that brings many settings along. I (for example) don't care what font colors the developer uses when typing, I just want similar formatting. Can you import a subset of settings?
A: StyleCop, originally called "Source Analysis" is the best choice for C#. The first version was rather inflexible, but after recognizing the value that it provides for the community, Microsoft has opened it up to extensions and customizations. It's a solid tool.
For Visual Studio settings, it's trivial to export a sub-set of your settings into a .settings file and require that other team members import and use these settings.
Like any standards, the tools are only as good as the team members, so it probably goes without saying that you will need team buy-in regardless of what tool you use for enforcement.
A: If you're using C#, take a look at StyleCop.
A: Visual Studio uses the settings in Tools > Options > Text Editor > [your language] > Formatting to set how it auto-formats code.
You can set it up how you like and then use Tools > Import and Export settings to create a .settings file for your team to import and use. It won't enforce rules, but it will make the default VS behavior the same for everyone.
A: There is a tool called NArrange which will arrange your code. This is particular useful to avoid conflicts in source control systems, but also has several other advantages. Check out the web site.
A: No-one's mentioned Team Settings yet? You just export the desired settings to a network share, then get everyone to map to it. Job's a good 'un.
Tools -> Options -> Import and Export Settings, then tick "Use Team Settings"
A: An extensive use of Visual Assist's snippets (bits of pre-formatted codes) may help...
A: I second Luke's answer. StyleCop can help you enforce common coding style across your team. If you want to share formatting rules take a look at ReSharper AFAIK it allows you to export and share this settings.
A: Editor settings are stored in the registry, so no luck having a single source for them. You'll need to go with an external tool to ensure uniformity.
A free, quick solution would be exporting the relevant registry settings and loading them up on everyone's machine. They'll still be able to change them (and they will -- naughty developers!), but you'll at least have a common starting point.
A: We use the following tools:
*
*StyleCop (as mentioned before)
*Resharper
*StyleCop for Resharper
The reason we use the latter two is twofold: First you are able to do a Clean Up of your code. This allows you to clean your code in one go and solve all warnings. At least that is what the brochure says. In reality you need to set quite a few settings in Resharper. Have a look at links like this to see how that works. Second: Resharper integrates the Stylecop violations in the source editor. Extremely useful as they are visible while writing code and can therefore be solved on the spot.
A: Code Review.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39712",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Namespace with Context.Handler and Server.Transfer? What .NET namespace or class includes both Context.Handler and Server.Transfer?
I think one may include both and my hunt on MSDN returned null.
A: System.Web.
HttpContext.Current.Handler
HttpContext.Current.Request.Server.Transfer
A:
Hmmmm, I talking about them as they are implemented here:
http://blog.benday.com/archive/2008/03/31/23176.aspx
(at least Context.Handler there)
I am still having trouble in VS making that reference.
Context.Handler is an instance of an HttpContext.
HttpContext exposes the CURRENT instance for the request under the HttpContext.Current property, however the current context can also be passed in HTTPHandlers in the ProcessRequest method:
void ProcessRequest(HttpContext context)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39727",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to upgrade TFS 2005 to TFS 2008? What is the best way to go about upgrading TFS 2005 to 2008? Also, what about the Team Build scripts ("Build Types"), are those compatible with Team Build 2008 or do they need converted/migrated somehow?
A: First and foremost - backup everything! The databases, the machine itself... You can never be too careful.
I was able to upgrade the TFS installation at my company by using these resources:
http://olausson.net/blog/CommentView,guid,6f97b619-a5ac-41af-a908-f099d49a3b16.aspx
http://blogs.msdn.com/sudhir/archive/2007/05/31/upgrade-2005-with-wss2-0-to-orcas-wss3-0.aspx
http://weblogs.asp.net/dmckinstry/archive/2007/08/27/considerations-on-using-tfs-2008-with-visual-studio-2005.aspx
It's not that hard and can in fact be done in a couple of hours, with better luck.
A: On this post on Upgrading TFS 2005 to 2008 I mentioned that the SharePoint upgrade to 3.0 was the main difficulty. I thought it was performed as part of the upgrade, but it in fact is a separate upgrade process. You should also install Team Explorer 2008 before installing Visual Studio 2008 Service Pack 1 on developer's machines. If you don't, you have to go back and reinstall the service pack. Also be sure to get the SP1 RTM version, which MS just release in the past week or so. If you have already installed the SP1Beta, then you have to download a special removal tool, run that, then install SP1 RTM. We did not have any custom build types, but we did use a custom build guidance package from Conchango - and it upgraded OK.
A: Simply, follow the guidance in the Install document for TFS 2008 - It has an upgrade section. It talks about backing up databases and so on already. The instructions are clear and layed out well.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39728",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to add submenu items to the Windows Explorer context menu? I can create a menu item in the Windows Explorer context menu by adding keys in the registry to HKEY_CLASSES_ROOT\Folder\shell.
How can I create submenu items to the just created menu item?
A: I believe anything non-trival you'll have to create a Context Menu Handler.
You'll have to create a COM object that will create the menus and carry out the commands as they're clicked. I've only done this using C++ and COM. I'm not sure if there are easier ways to do this.
A: Use SubCommands
"SubCommands"="[NameOfMenu]"
Example for creating submenu for .TS files:
[HKEY_CLASSES_ROOT\SystemFileAssociations\.ts\shell\Encoding]
"MUIVerb"="Encoding video"
"SubCommands"="Encodex265Fade;EncodeTS2;watched"
"icon"="imageres.dll,-149"
"Position"=-
"MultiSelectModel"="Single"
"NeverDefault"=""
;"ExtendedSubCommandsKey"="Encode\\Fadein"
;"Icon"="C:\\Program Files (x86)\\CloudMe\\CloudMe\\favicon.ico"
More info: https://msdn.microsoft.com/en-us/library/windows/desktop/hh127431(v=vs.85).aspx
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39734",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Have you got a CascadingDropDown working with ASP.NET MVC? If so how?
Did you roll your own with jQuery or use the Microsoft AJAX toolkit?
Did you create a webservice or call an action?
EDIT : Please note that this question was asked before Microsoft announced that they were going to bundle jQuery in with VS/ASP.NET MVC. I think there is less of a discussion around this topic now and the answer would now almost always be 'use jQuery'. IainMH 11th Feb 2009
A: jQuery, action, return JSON.
http://devlicio.us/blogs/mike_nichols/archive/2008/05/25/jquery-cascade-cascading-values-from-forms.aspx
A: I've spent the past day or two getting @Matt Hinze's answer to work. It works well. jQuery is the prefferred method of doing AJAX in the forthcoming ASP.NET MVC In Action book from Manning. You can get a pdf of a free preview chapter on AJAX in MVC here.
However, Stephen Walther in his excellent ASP.NET Tip series has just blogged about creating cascading dropdowns in Tip #41.
A: CascadingDropDown jQuery Plugin for ASP.NET MVC
http://weblogs.asp.net/rajbk/archive/2010/05/20/cascadingdropdown-jquery-plugin-for-asp-net-mvc.aspx
A: http://blog.noma.li/2010/03/autopostback-and-cascading-drop-downs-in-asp-net-mvc-and-jquery/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39735",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Remote Debugging Server Side of a Web Application with Visual Studio 2008 So, I've read that it is not a good idea to install VS2008 on my test server machine as it changes the run time environment too much. I've never attempted remote debugging with Visual Studio before, so what is the "best" way to get line by line remote debugging of server side web app code. I'd like to be able to set a breakpoint, attach, and start stepping line by line to verify code flow and, you know, debug and stuff :).
I'm sure most of the answers will pertain to ASP.NET code, and I'm interested in that, but my current code base is actually Classic ASP and ISAPI Extensions, so I care about that a little more.
Also, my test server is running in VMWare, I've noticed in the latest VMWare install it mentioning something about debugging support, but I'm unfamiliar with what that means...anyone using it, what does it do for you?
A: First, this is MUCH easier if both the server and your workstation are on the same domain (the server needs access to connect to your machine). In your C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\Remote Debugger\x86 (or x64, or ia64) directory are the files you need to copy to your server. There are different versions between Visual Studio versions, so make sure they match on the client and server side. On the server, fire up msvsmon. It will say something like "Msvsmon started a new server named xxx@yyyy". This is the name you'll use in Visual Studio to connect to this server. You can go into Tools > Options to set the server name and to set the authentication mode (hopefully Windows Authentication) - BTW No Authentication doesn't work for managed code.
On the client side, open up Visual Studio and load the solution you're going to debug. Then go to Debug > Attach to Process. In the "Qualifier" field enter the name of the server as you saw it appear earlier. Click on the Select button and select the type of code you want to debug, then hit OK. Hopefully you'll see a list of the processes on the server that you can attach to (you should also see on the server that the debugging monitor just said you connected). Find the process to attach to (start up the app if necessary). If it's an ASP.NET website, you'd select w3wp.exe, then hit Attach. Set your breakpoints and hopefully you're now remotely debugging the code.
AFAIK - the VMWare option lets you start up code inside of a VM but debug it from your workstation.
A: Visual Studio comes with a remote debugger that you can run as an exe on your server. It works best if you can run it as the same domain user as your copy of visual studio. You can then do an attach to process from the debugger on your machine to the IIS process on the server and debug as if it was running on your machine. You get more options for .Net debugging, but there's support for older platforms too.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39739",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Does git have anything like `svn propset svn:keywords` or pre-/post-commit hooks? Browsing through the git documentation, I can't see anything analogous to SVN's commit hooks or the "propset" features that can, say, update a version number or copyright notice within a file whenever it is committed to the repository.
Are git users expected to write external scripts for this sort of functionality (which doesn't seem out of the question) or have I just missed something obvious?
Edit : Just to be clear, I'm more interested in, e.g.,
svn propset svn:keywords "Author Date Id Revision" expl3.dtx
where a string like this:
$Id: expl3.dtx 780 2008-08-30 12:32:34Z morten $
is kept up-to-date with the relevant info whenever a commit occurs.
A: Git does have pre-commit and post-commit hooks, they are located inside each .git/hooks directory. Just modify the files and chmod them to make them executable.
A: Although an age-old Q&A. I thought I'd throw one in since this has been bugging me for a long time.
I am used to list the files in a directory by reverse-time order (funny me, heh?). The reason is that I would like to see which files I have (or anyone else has) changed recently.
Git will mess my plans because when switching a branch the local repo will completely overwrite the tracked files from the (incremental... I know...) copies that sit in the packed local repo.
This way all files that were checked out will carry the time stamp of the checkout and will not reflect their last modification time..... How so annoying.
So, I've devised a one-liner in bash that will update a $Date:$ property inside any file WITH THE TIME OF LAST MODIFICATION ACCORDING TO WHAT IT HAS ON FILE SYSTEM such that I will have an immediate status telling of last modification without having to browse the git log , git show or any other tool that gives the commit times in blame mode.
The following procedure will modify the $Date: $ keyword only in tracked files that are going to be committed to the repo. It uses git diff --name-only which will list files that were modified, and nothing else....
I use this one-liner manually before committing the code. One thing though is that I have to navigate to the repo's root directory before applying this.
Here's the code variant for Linux (pasted as a multi-line for readability)
git diff --name-only | xargs stat -c "%n %Y" 2>/dev/null | \
perl -pe 's/[^[:ascii:]]//g;' | while read l; do \
set -- $l; f=$1; shift; d=$*; modif=`date -d "@$d"`; \
perl -i.bak -pe 's/\$Date: [\w \d\/:,.)(+-]*\$/\$Date: '"$modif"'\$/i' $f; \
git add $f; done
and OSX
git diff --name-only | xargs stat -f "%N %Sm" | while read l; do \
set -- $l; f=$1; shift; d=$*; modif=`date -j -f "%b %d %T %Y" "$d"`; \
perl -i.bak -pe 's/\$Date: [\w \d\/:,.)(+-]*\$/\$Date: '"$modif"'\$/i' $f; \
git add $f; done
A: I wrote up a fairly complete answer to this elsewhere, with code showing how to do it. A summary:
*
*You probably don't want to do this. Using git describe is a reasonable alternative.
*If you do need to do this, $Id$ and $Format$ are fairly easy.
*Anything more advanced will require using gitattributes and a custom filter. I provide an example implementation of $Date$.
Solutions based on hook functions are generally not helpful, because they make your working copy dirty.
A: Quoting from the Git FAQ:
Does git have keyword expansion?
Not recommended. Keyword expansion causes all sorts of strange problems and
isn't really useful anyway, especially within the context of an SCM. Outside
git you may perform keyword expansion using a script. The Linux kernel export
script does this to set the EXTRA_VERSION variable in the Makefile.
See gitattributes(5) if you really want to do this. If your translation is not
reversible (eg SCCS keyword expansion) this may be problematic.
A: Perhaps the most common SVN property, 'svn:ignore' is done through the .gitignore file, rather than metadata. I'm afraid I don't have anything more helpful for the other kinds of metadata.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39742",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "39"
} |
Q: Getting Configuration value from web.config file using VB and .Net 1.1 I have the following web config file. I am having some difficulty in retrieving the value from the "AppName.DataAccess.ConnectionString" key. I know I could move it to the AppSetting block and get it realtively easily but I do not wnat to duplicate the key (and thereby clutter my already cluttered web.config file). Another DLL (one to which I have no source code) uses this block and since it already exists, why not use it.
I am a C# developer (using .Net 3.5) and this is VB code (using .Net 1.1 no less) so I am already in a strange place (where is my saftey semicolon?). Thanks for your help!!
<?xml version="1.0"?>
<configuration>
<configSections>
<section name="AppNameConfiguration" type="AppName.SystemBase.AppNameConfiguration, SystemBase"/>
</configSections>
<AppNameConfiguration>
<add key="AppName.DataAccess.ConnectionString" value="(Deleted to protect guilty)" />
</AppNameConfiguration>
<appSettings>
...other key info deleted for brevity...
</appSettings>
<system.web>
...
</system.web>
</configuration>
A: <section name="AppNameConfiguration"
type="AppName.SystemBase.AppNameConfiguration, SystemBase"/>
The custom section is supposed to have a class that defines how the various configuration data can be managed, (This is in the Type section). Is this class not available for you to examine?
MSDN has a decent explanation of how to create custom configuration sections in VB that may be helpful to you:
http://msdn.microsoft.com/en-us/library/2tw134k3.aspx
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39744",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: TortoiseHg in Vista 64-bit not showing the context menu I installed TortoiseHg (Mercurial) in my Vista 64-bit and the context menu is not showing up when I right click a file or folder.
Is there any workaround for this problem?
A: Update: TortoiseHg 0.8 (released 2009-07-01) now includes both 32 and 64 bit shell extensions in the installer, and also works with Windows 7. The workaround described below is no longer necessary.
A workaround to getting the context menus in Windows Explorer is buried in the TortoiseHg development mailing list archives. One of the posts provides this very handy tip on how to run 32-bit Explorer on 64-bit Windows:
TortoiseHG context menus will show up if you run 32-bit windows explorer; create a shortcut with this (or use Start > Run):
%Systemroot%\SysWOW64\explorer.exe /separate
(Source: http://www.mail-archive.com/[email protected]/msg01055.html)
It works fairly well and is minimally invasive, but unfortunately this doesn't seem to make the icon overlays appear. I don't know of any workaround for that, but file status can still be viewed through TortoiseHg menu commands at least. All other TortoiseHg functionality seems intact.
The icon overlays are now working with TortoiseHg 0.6 in 32-bit explorer! Not sure if this is a new fix or if I had some misconfiguration in 0.5; regardless this means TortoiseHg is fully functional in 64-bit Windows.
A: In order to be able to use an extension in Explorer, the "bitness" of the extension needs to match the bitness of the operating system. This is because (at least under Windows) you can't load a 32-bit DLL into a 64-bit process -- or vice versa. If there's no 64-bit version of HgTortoise, then you can't use it with Explorer on a 64-bit Windows OS.
A: I upgraded to Windows 7 RC and the 64bit workaround seems to have stopped working
A: According to the TortoiseHg FAQ the context menus will work in 64-bit Vista if you start a 32-bit instance of explorer by creating a shortcut with the following settings (as suggested in the answer above):
Target: %windir%\syswow64\explorer.exe /separate
Start In: %windir%\syswow64\
A: You could always install the command line hg and use it in a pinch. It's a bit faster, too.
A: I can verify that xplorer2 does show the HG tortoise context menu in 64bit Vista.
A: As detailed in the TortoiseHg FAQ, you need to run a 32-bit Windows Explorer instance for the context menu and overlays to work under 64-bit Vista.
My personal preference is to create a shortcut similar to the following for each project I'm actively using with TortoiseHg:
%windir%\syswow64\explorer.exe /separate /root,C:\projects\frobnicator
This launches explorer with the C:\projects\frobnicator folder already opened. (You can omit the /root option and just use the same shortcut for all projects if you don't mind clicking your way to the target folder every time you launch it.)
A: I've just noticed that the context menu and icons work from a file open dialog from some apps (on Vista). I now just use Notepad++'s file open dialog, since I use Notepad++ all the time.
It seems to have to be the simple open dialog, not the new one Notepad has, for example.
Maybe someone can check if this trick works in Windows 7.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39746",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: Connection pooling in PHP Is it possible to cache database connections when using PHP like you would in a J2EE container? If so, how?
A: There is no connection pooling in php.
mysql_pconnect and connection pooling are two different things.
There are many problems connected with mysql_pconnect and first you should read the manual and carefully use it, but this is not connection pooling.
Connection pooling is a technique where the application server manages the connections. When the application needs a connection it asks the application server for it and the application server returns one of the pooled connections if there is one free.
We can do connection scaling in php for that please go through following link: http://www.oracle.com/technetwork/articles/dsl/white-php-part1-355135.html
So no connection pooling in php.
As Julio said apache releases all resources when the request ends for the current reques. You can use mysql_pconnect but you are limited with that function and you must be very careful. Other choice is to use singleton pattern, but none of this is pooling.
This is a good article: https://blogs.oracle.com/opal/highly-scalable-connection-pooling-in-php
Also read this one http://www.apache2.es/2.2.2/mod/mod_dbd.html
A: Persistent connections are nothing like connection pooling. A persistent connection in php will only be reused if you make multiple db connects within the same request/script execution context. In most typical web dev scenarios you'll max out your connections way faster if you use mysql_pconnect because your script will have no way to get a reference to any open connections on your next request. The best way to use db connections in php is to make a singleton instance of a db object so that the connection is reused within the context of your script execution. This still incurs at least 1 db connect per request, but it's better than making multiple db connects per reqeust.
There is no real db connection pooling in php due to the nature of php. Php is not an application server that can sit there in between requests and manage references to a pool of open connections, at least not without some kind of major hack. I think in theory you could write an app server in php and run it as a commandline script that would just sit there in the background and keep a bunch of db connections open and pass references to them to your other scripts, but I don't know if that would be possible in practice, how you'd pass the references from your commandline script to other scripts, and I sort of doubt it would perform well even if you could pull it off. Anyway that's mostly speculation. I did just notice the link someone else posted to an apache module to allow connection pooling for prefork servers such as php. Looks interesting:
https://github.com/junamai2000/mod_namy_pool#readme
A: I suppose you're using mod_php, right?
When a PHP file finishes executing all it's state is killed so there's no way (in PHP code) to do connection pooling. Instead you have to rely on extensions.
You can mysql_pconnect so that your connections won't get closed after the page finishes, that way they get reused in the next request.
This might be all that you need but this isn't the same as connection pooling as there's no way to specify the number of connections to maintain opened.
A: You can use MySQLi.
For more info, scroll down to Connection pooling section @ http://www.php.net/manual/en/mysqli.quickstart.connections.php#example-1622
Note that Connection pooling is also dependent on your server (i.e. Apache httpd) and its configuration.
A: If an unused persistent connection for a given combination of "host, username, password, socket, port and default database can not be found" in the open connection pool, then only mysqli opens a new connection otherwise it would reuse already open available persistent connections, which is in a way similar to the concept of connection pooling. The use of persistent connections can be enabled and disabled using the PHP directive mysqli.allow_persistent. The total number of connections opened by a script can be limited with mysqli.max_links (this may be interesting to you to address max_user_connections issue hitting hosting server's limit). The maximum number of persistent connections per PHP process can be restricted with mysqli.max_persistent.
In wider programming context, it's a task of web/app server however in this context, it's being handled by mysqli directive of PHP itself in a way supporting connection re-usability. You may also implement a singleton class to get a static instance of connection to reuse just like in Java. Just want to remind that java also doesn't support connection pooling as part of its standard JDBC, they're being different module/layers on top of JDBC drivers.
Coming to PHP, the good thing is that for the common databases in the PHP echosystem it does support Persistent Database Connections which persists the connection for 500 requests (config of max_requests in php.ini) and this avoids creating a new connection in each request. So check it out in docs in detail, it solves most of your challenges. Please note that PHP is not so much sophisticated in terms of extensive multi-threading mechanism and concurrent processing together with powerful asynchronous event handling, when compared to strictly object oriented Java. So in a way it is very less effective for PHP to have such in-built mechanism like pooling.
A: You cannot instantiate connection pools manually.
But you can use the "built in" connection pooling with the mysql_pconnect function.
A: I would like to suggest PDO::ATTR_PERSISTENT
Persistent connections are links that do not close when the execution of your script ends. When a persistent connection is requested, PHP checks if there's already an identical persistent connection (that remained open from earlier) - and if it exists, it uses it. If it does not exist, it creates the link.
A: Connection pooling works at MySQL server side like this.
*
*If persistence connection is enabled into MySQL server config then MySQL keep a connection open and in sleep state after requested client (php script) finises its work and die.
*When a 2nd request comes with same credential data (Same User Name, Same Password, Same Connection Parameter, Same Database name, Maybe from same IP, I am not sure about the IP) Then MySQL pool the previous connection from sleep state to active state and let the client use the connection. This helps MySQL to save time for initial resource for connection and reduce the total number of connection.
So the connection pooling option is actually available at MySQL server side. At PHP code end there is no option. mysql_pconnect() is just a wrapper that inform PHP to not send connection close request signal at the end of script run.
A: For features such as connection pooling - you need to install swoole extension first: https://openswoole.com/
It adds async features to php.
After that its trivial to add mysql and redis connection pooling:
https://github.com/open-smf/connection-pool
Some PHP frameworks come with pooling built-in: https://hyperf.wiki/2.2/#/en/pool
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39753",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "88"
} |
Q: What does Google Chrome mean to web developers? From a web developer point of view, what changes are expected in the development arena when Google Chrome is released?
Are the developments powerful enough to make another revolution in the web? Will the way we see web programming change?
Or is it just another web browser?
A: Considering most develops want to reach the larger audience, it just means one more place to test. Since it uses Webkit, hopefully it will render almost identical to Safari.
Integrated Gears may mean a solid place for apps to be developed though. If you have an internal system it may be nicer to just put Chrome on all the machines than building an app that runs locally.
A: I think the whole purpose or at least the emphasis of the release, as Kamiel said, is to provide better javascript performance. So many of Google's services rely on heavy javascript usage that this is a smart move by them. This should be good for everyone as IE and Firefox work to compete against Google every browser should get better at javascript.
A: Google Chrome looks promising. It is of course in an early beta so it's missing a lot of the things people would need or at least feel they need, like plugins, cross-machine synchronization of data (could be done with plugins), cross-platform support (ie. Linux and Mac versions).
So far it renders Gmail like a bat out of hell, so I'm going to pay very close attention to it.
Edit: In fact, these posts are done using it, and except for some minor issues like smaller font in input fields, it works as I expect it to. Fast, stable (already tested it with a javascript killer-page I have for some test applications).
A: I think this is just another web browser. The most impact I expect to be improved Javascript performance, and the usability perspective. The first will benefit developers, especially when using Google Gears. I think the users will benefit the most from an enhanced user experience, the safety features, and ease of use.
I can only hope other browser vendors (MS) will follow Mozilla and Google to create a faster Javascript implementation, since this is the only thing that can truly impact web development.
A: This is long-term positioning for Google; they are clearly trying to build a more stable application platform for web-based development. All of their changes (security, sandboxing, process isolation) are clearly intended to make the browser a better application for hosting complex apps.
This is what Microsoft was worried about with netscape, and why they broke antitrust rules to "cut off their air supply". It's going to be interesting to see how MS responds.
It's also interesting to see how the mozilla / firefox team deals with this- Google is pretty much funding firefox now, so it's going to be a potential conflict of interest for these folks down the road.
In a nutshell, things are going to get more complex, require more testing, and will (hopefully) force recalcitrant vendors like Microsoft to become more standards-compliant.
A: This is just a natural for Google. This way they can control how well their apps work in a container on & off line. Expect more tools, potentially GUI designer type tools and an IDE for use with their cloud offerings as well as a mobile version of this for Android. It's most likely a lead in to Visual Google.
If they are smart they will have this container/browser perform other tasks like parsing content for a fresher Google cache and search results.
A: Personally, I'm hoping it has less of an impact on web developers and more of an impact on browser developers. Some of the features are really nice, and while the process-oriented approach to separation of tabs will probably make it hefty compared to other browsers, I like the ideas behind it.
My guess is it's going to have to spend a year or longer post-beta to make the kind of impact that Firefox has on web development.
A: I'd say that I see the improved Javascript engine being the major contribution as far as web applications go. And hopefully will cause a new look for the other browsers and possibly make Javascript implementations a bit more standardized.
A: Chiming in on this topic. If you have used Chrome, you'll notice a significant speed upgrade, especially on sites using js. I have found that it renders things almost EXACTLY the same as Safari (as you would assume), so I think this drastically minimizes the issue of having to develop on yet another browser.
I think the main thing Chrome does is to offer another (and even perhaps the best to date) alternative to IE. If people start using these, 'advanced' web browsers (man it's sad I have to say that), Microsoft will almost certainly have to step things up with IE9. IE8 seems to me to be more of the same from Microsoft who just can't seem to grasp the UI goodness and overall speed of Safari, Firefox and now Chrome. IE8 is freaking 360MB for godsakes. I think FF3 is like 90MB.
On a side note, has anyone checked out how fast Chrome opens? I found that very impressive.
@Lassevek - The first thing I did was check the js speeds on gmail and "bat out of hell" is precisely how I would describe it.
A: I just hope Chrome, Firefox and Safari can be temporary friends so they can overthrow IE. After that, it's fair game!
A: To be quite honest I've always hated Google, with a passion. But, I love their web browser Chrome. It just works. No need to download updates every 5 minutes, No stupid security bars that pop up every time you visit a website, and when I'm writing webpages - I don't even have to test my code anymore because it is standards-compliant, and it just works properly. My current website that I'm building now is about half-done, and it works and looks perfect in Google Chrome. Looks and works perfect in Opera, but as for Internet Explorer, it looks terrible, and it looks fairly good in Firefox.
I don't know. People should stop using Internet Explorer (in my opinion) because it just doesn't work the way it should. Have YOU ever noticed after downloading Internet Explorer 8 on WindwosXP that once you start visiting a few websites, the more sites you visit the longer it takes IE to open a new tab. Sometimes I'm left frustrated, almost sending me into a murderous-rage waiting for a new empty tab to open up! Blah!
A: As always, it depends on their implementation. If they decide to mess with the rendering engine, we could be looking at a whole new list of browser "quirks" which will mean WebDev's will be uber-pissed.
If they stay standards-compliant (which TBH, I expect they will) it could be a really good thing to heat up the competition.
Be interesting to see how the sandbox mode affects plugin compat, and of course, the tight Gears integration..
That fact that its OSS is a really good thing.. Since any of the above issues could easily be fixed with a patch as soon as the dev community get on to it. :)
A: Hopefully it will be standards compliant and erase a little midget of Internet Explorer's market share - Firefox has ease of use and plugins going for it, but "security" is something non-technical people can understand... which one could hope would make development easier.
That's assuming it stays standards compliant and innovates well, of course.
A: As long as there are the other web browsers (and I don't believe that they will die - which is good, because I don't want to see the internet in the hands of Google) it's just another web browser that you need to check compatibility with.
A: It's not good. More platforms leads to more testing, leads to more time fixing bugs, leads to less time having fun implementing new features, leads to anger, hate, suffering, etc.
A: I wonder whether plugins/addons will ever be a big focus for Chrome. It seems to be very much focused on providing a fast, clean environment that puts the focus on the web rather than the browser. I suspect that in order to keep it nimble and stable, they may keep the extension capabilities fairly limited (plus, they wouldn't want Adblock for Chrome, would they :-)
I wonder also, given Google's existing relationships with OEMs to include things like the Google Desktop on PCs sold, whether we might start to see Chrome pre-installed on computers. If that were the case, it might become more prevalent than other competitors to IE.
A: @bpapa
It's just another web browser that
very few people are going to use
because there are already 4 major
browsers out there that work just fine
for most people. It doesn't have the
extensions like Firefox,
Actually, it is pretty clear that it has a plugin architecture
it doesn't
have browser sync with an iPhone like
Safari, it doesn't come with your
computer like IE, and it doesn't...
well I don't know what Opera does that
makes it stand out but I don't think
Chrome has it.
"I don't know what Opera has, but this piece of software that I've never touched clearly doesn't have it"... what??
Another reason why I don't see it
taking off - since it's not on OS X a
lot of tech people aren't going to be
using it.
Did you miss the part where the Linux and OS X distros are coming right behind Windows?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39758",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
} |
Q: What do you call the tags in Subversion and CVS that add automatic content? Things like $log$ and $version$ which add data upon check-in to the file. I'm interested in seeing the other ones and what information they can provide, but I can't get much info unless I know what they are called.
A: Both Subversion and CVS call them Keywords.
Have a look in the SVN manual here (scroll down to svn:keywords) or here for CVS.
A: In SVN these are simply called "properties". You can read about them in the SVN book:
http://svnbook.red-bean.com/en/1.8/svn.advanced.props.html
Err, so, are they called properties or keywords? Oh, I see. In SVN you can associate arbitrary metadata, called "properties", with versioned files; some of the properties you can set are to set up keyword substitution in the files themselves.
A: These are Keyword substitutions. The link to SVNBook 1.8 is here: http://svnbook.red-bean.com/en/1.8/svn.advanced.props.special.keywords.html.
Subversion's built-in keywords are:
*
*Date / LastChangedDate
*Revision / Rev / LastChangedRevision
*Author / LastChangedBy
*HeadURL / URL
*Id
The keywords are case sensitive, and remember to surround them with $.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39770",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Is a GUID unique 100% of the time? Is a GUID unique 100% of the time?
Will it stay unique over multiple threads?
A:
Is a GUID unique 100% of the time?
Not guaranteed, since there are several ways of generating one. However, you can try to calculate the chance of creating two GUIDs that are identical and you get the idea: a GUID has 128 bits, hence, there are 2128 distinct GUIDs – much more than there are stars in the known universe. Read the wikipedia article for more details.
A: The simple answer is yes.
Raymond Chen wrote a great article on GUIDs and why substrings of GUIDs are not guaranteed unique. The article goes in to some depth as to the way GUIDs are generated and the data they use to ensure uniqueness, which should go to some length in explaining why they are :-)
A: MSDN:
There is a very low probability that the value of the new Guid is all zeroes or equal to any other Guid.
A: If your system clock is set properly and hasn't wrapped around, and if your NIC has its own MAC (i.e. you haven't set a custom MAC) and your NIC vendor has not been recycling MACs (which they are not supposed to do but which has been known to occur), and if your system's GUID generation function is properly implemented, then your system will never generate duplicate GUIDs.
If everyone on earth who is generating GUIDs follows those rules then your GUIDs will be globally unique.
In practice, the number of people who break the rules is low, and their GUIDs are unlikely to "escape". Conflicts are statistically improbable.
A: I experienced a duplicate GUID.
I use the Neat Receipts desktop scanner and it comes with proprietary database software. The software has a sync to cloud feature, and I kept getting an error upon syncing. A gander at the logs revealed the awesome line:
"errors":[{"code":1,"message":"creator_guid: is already
taken","guid":"C83E5734-D77A-4B09-B8C1-9623CAC7B167"}]}
I was a bit in disbelief, but surely enough, when I found a way into my local neatworks database and deleted the record containing that GUID, the error stopped occurring.
So to answer your question with anecdotal evidence, no. A duplicate is possible. But it is likely that the reason it happened wasn't due to chance, but due to standard practice not being adhered to in some way. (I am just not that lucky) However, I cannot say for sure. It isn't my software.
Their customer support was EXTREMELY courteous and helpful, but they must have never encountered this issue before because after 3+ hours on the phone with them, they didn't find the solution. (FWIW, I am very impressed by Neat, and this glitch, however frustrating, didn't change my opinion of their product.)
A:
While each generated GUID is not
guaranteed to be unique, the total
number of unique keys (2128 or
3.4×1038) is so large that the probability of the same number being
generated twice is very small. For
example, consider the observable
universe, which contains about 5×1022
stars; every star could then have
6.8×1015 universally unique GUIDs.
From Wikipedia.
These are some good articles on how a GUID is made (for .NET) and how you could get the same guid in the right situation.
https://ericlippert.com/2012/04/24/guid-guide-part-one/
https://ericlippert.com/2012/04/30/guid-guide-part-two/
https://ericlippert.com/2012/05/07/guid-guide-part-three/
A: As a side note, I was playing around with Volume GUIDs in Windows XP. This is a very obscure partition layout with three disks and fourteen volumes.
\\?\Volume{23005604-eb1b-11de-85ba-806d6172696f}\ (F:)
\\?\Volume{23005605-eb1b-11de-85ba-806d6172696f}\ (G:)
\\?\Volume{23005606-eb1b-11de-85ba-806d6172696f}\ (H:)
\\?\Volume{23005607-eb1b-11de-85ba-806d6172696f}\ (J:)
\\?\Volume{23005608-eb1b-11de-85ba-806d6172696f}\ (D:)
\\?\Volume{23005609-eb1b-11de-85ba-806d6172696f}\ (P:)
\\?\Volume{2300560b-eb1b-11de-85ba-806d6172696f}\ (K:)
\\?\Volume{2300560c-eb1b-11de-85ba-806d6172696f}\ (L:)
\\?\Volume{2300560d-eb1b-11de-85ba-806d6172696f}\ (M:)
\\?\Volume{2300560e-eb1b-11de-85ba-806d6172696f}\ (N:)
\\?\Volume{2300560f-eb1b-11de-85ba-806d6172696f}\ (O:)
\\?\Volume{23005610-eb1b-11de-85ba-806d6172696f}\ (E:)
\\?\Volume{23005611-eb1b-11de-85ba-806d6172696f}\ (R:)
| | | | |
| | | | +-- 6f = o
| | | +---- 69 = i
| | +------ 72 = r
| +-------- 61 = a
+---------- 6d = m
It's not that the GUIDs are very similar but the fact that all GUIDs have the string "mario" in them. Is that a coincidence or is there an explanation behind this?
Now, when googling for part 4 in the GUID I found approx 125.000 hits with volume GUIDs.
Conclusion: When it comes to Volume GUIDs they aren't as unique as other GUIDs.
A: It should not happen. However, when .NET is under a heavy load, it is possible to get duplicate guids. I have two different web servers using two different sql servers. I went to merge the data and found I had 15 million guids and 7 duplicates.
A: Yes, a GUID should always be unique. It is based on both hardware and time, plus a few extra bits to make sure it's unique. I'm sure it's theoretically possible to end up with two identical ones, but extremely unlikely in a real-world scenario.
Here's a great article by Raymond Chen on Guids:
https://blogs.msdn.com/oldnewthing/archive/2008/06/27/8659071.aspx
A: For more better result the best way is to append the GUID with the timestamp (Just to make sure that it stays unique)
Guid.NewGuid().ToString() + DateTime.Now.ToString();
A: Guids are statistically unique. The odds of two different clients generating the same Guid are infinitesimally small (assuming no bugs in the Guid generating code). You may as well worry about your processor glitching due to a cosmic ray and deciding that 2+2=5 today.
Multiple threads allocating new guids will get unique values, but you should get that the function you are calling is thread safe. Which environment is this in?
A: Eric Lippert has written a very interesting series of articles about GUIDs.
There are on the order 230 personal computers in the world (and of
course lots of hand-held devices or non-PC computing devices that have
more or less the same levels of computing power, but lets ignore
those). Let's assume that we put all those PCs in the world to the
task of generating GUIDs; if each one can generate, say, 220 GUIDs per
second then after only about 272 seconds -- one hundred and fifty
trillion years -- you'll have a very high chance of generating a
collision with your specific GUID. And the odds of collision get
pretty good after only thirty trillion years.
*
*GUID Guide, part one
*GUID Guide, part two
*GUID Guide, part three
A: Theoretically, no, they are not unique. It's possible to generate an identical guid over and over. However, the chances of it happening are so low that you can assume they are unique.
I've read before that the chances are so low that you really should stress about something else--like your server spontaneously combusting or other bugs in your code. That is, assume it's unique and don't build in any code to "catch" duplicates--spend your time on something more likely to happen (i.e. anything else).
I made an attempt to describe the usefulness of GUIDs to my blog audience (non-technical family memebers). From there (via Wikipedia), the odds of generating a duplicate GUID:
*
*1 in 2^128
*1 in 340 undecillion (don’t worry, undecillion is not on the
quiz)
*1 in 3.4 × 10^38
*1 in 340,000,000,000,000,000,000,000,000,000,000,000,000
A: None seems to mention the actual math of the probability of it occurring.
First, let's assume we can use the entire 128 bit space (Guid v4 only uses 122 bits).
We know that the general probability of NOT getting a duplicate in n picks is:
(1-1/2128)(1-2/2128)...(1-(n-1)/2128)
Because 2128 is much much larger than n, we can approximate this to:
(1-1/2128)n(n-1)/2
And because we can assume n is much much larger than 0, we can approximate that to:
(1-1/2128)n^2/2
Now we can equate this to the "acceptable" probability, let's say 1%:
(1-1/2128)n^2/2 = 0.01
Which we solve for n and get:
n = sqrt(2* log 0.01 / log (1-1/2128))
Which Wolfram Alpha gets to be 5.598318 × 1019
To put that number into perspective, lets take 10000 machines, each having a 4 core CPU, doing 4Ghz and spending 10000 cycles to generate a Guid and doing nothing else. It would then take ~111 years before they generate a duplicate.
A: GUID algorithms are usually implemented according to the v4 GUID specification, which is essentially a pseudo-random string. Sadly, these fall into the category of "likely non-unique", from Wikipedia (I don't know why so many people ignore this bit): "... other GUID versions have different uniqueness properties and probabilities, ranging from guaranteed uniqueness to likely non-uniqueness."
The pseudo-random properties of V8's JavaScript Math.random() are TERRIBLE at uniqueness, with collisions often coming after only a few thousand iterations, but V8 isn't the only culprit. I've seen real-world GUID collisions using both PHP and Ruby implementations of v4 GUIDs.
Because it's becoming more and more common to scale ID generation across multiple clients, and clusters of servers, entropy takes a big hit -- the chances of the same random seed being used to generate an ID escalate (time is often used as a random seed in pseudo-random generators), and GUID collisions escalate from "likely non-unique" to "very likely to cause lots of trouble".
To solve this problem, I set out to create an ID algorithm that could scale safely, and make better guarantees against collision. It does so by using the timestamp, an in-memory client counter, client fingerprint, and random characters. The combination of factors creates an additive complexity that is particularly resistant to collision, even if you scale it across a number of hosts:
http://usecuid.org/
A: I have experienced the GUIDs not being unique during multi-threaded/multi-process unit-testing (too?). I guess that has to do with, all other tings being equal, the identical seeding (or lack of seeding) of pseudo random generators. I was using it for generating unique file names. I found the OS is much better at doing that :)
Trolling alert
You ask if GUIDs are 100% unique. That depends on the number of GUIDs it must be unique among. As the number of GUIDs approach infinity, the probability for duplicate GUIDs approach 100%.
A: In a more general sense, this is known as the "birthday problem" or "birthday paradox". Wikipedia has a pretty good overview at:
Wikipedia - Birthday Problem
In very rough terms, the square root of the size of the pool is a rough approximation of when you can expect a 50% chance of a duplicate. The article includes a probability table of pool size and various probabilities, including a row for 2^128. So for a 1% probability of collision you would expect to randomly pick 2.6*10^18 128-bit numbers. A 50% chance requires 2.2*10^19 picks, while SQRT(2^128) is 1.8*10^19.
Of course, that is just the ideal case of a truly random process. As others mentioned, a lot is riding on the that random aspect - just how good is the generator and seed? It would be nice if there was some hardware support to assist with this process which would be more bullet-proof except that anything can be spoofed or virtualized. I suspect that might be the reason why MAC addresses/time-stamps are no longer incorporated.
A: The Answer of "Is a GUID is 100% unique?" is simply "No" .
*
*If You want 100% uniqueness of GUID then do following.
*
*generate GUID
*check if that GUID is Exist in your table column where you are looking for uniquensess
*if exist then goto step 1 else step 4
*use this GUID as unique.
A: If you are scared of the same GUID values then put two of them next to each other.
Guid.NewGuid().ToString() + Guid.NewGuid().ToString();
If you are too paranoid then put three.
A: From http://www.guidgenerator.com/online-guid-generator.aspx
What is a GUID?
GUID (or UUID) is an acronym for 'Globally Unique Identifier' (or 'Universally Unique Identifier'). It is a 128-bit integer number used to identify resources. The term GUID is generally used by developers working with Microsoft technologies, while UUID is used everywhere else.
How unique is a GUID?
128-bits is big enough and the generation algorithm is unique enough that if 1,000,000,000 GUIDs per second were generated for 1 year the probability of a duplicate would be only 50%. Or if every human on Earth generated 600,000,000 GUIDs there would only be a 50% probability of a duplicate.
A: The hardest part is not about generating a duplicated Guid.
The hardest part is designed a database to store all of the generated ones to check if it is actually duplicated.
From WIKI:
For example, the number of random version 4 UUIDs which need to be generated in order to have a 50% probability of at least one collision is 2.71 quintillion, computed as follows:
enter image description here
This number is equivalent to generating 1 billion UUIDs per second for about 85 years, and a file containing this many UUIDs, at 16 bytes per UUID, would be about 45 exabytes, many times larger than the largest databases currently in existence, which are on the order of hundreds of petabytes
A: GUID stands for Global Unique Identifier
In Brief:
(the clue is in the name)
In Detail:
GUIDs are designed to be unique; they are calculated using a random method based on the computers clock and computer itself, if you are creating many GUIDs at the same millisecond on the same machine it is possible they may match but for almost all normal operations they should be considered unique.
A: I think that when people bury their thoughts and fears in statistics, they tend to forget the obvious. If a system is truly random, then the result you are least likely to expect (all ones, say) is equally as likely as any other unexpected value (all zeros, say). Neither fact prevents these occurring in succession, nor within the first pair of samples (even though that would be statistically "truly shocking"). And that's the problem with measuring chance: it ignores criticality (and rotten luck) entirely.
IF it ever happened, what's the outcome? Does your software stop working? Does someone get injured? Does someone die? Does the world explode?
The more extreme the criticality, the worse the word "probability" sits in the mouth. In the end, chaining GUIDs (or XORing them, or whatever) is what you do when you regard (subjectively) your particular criticality (and your feeling of "luckiness") to be unacceptable. And if it could end the world, then please on behalf of all of us not involved in nuclear experiments in the Large Hadron Collider, don't use GUIDs or anything else indeterministic!
A: Enough GUIDs to assign one to each and every hypothetical grain of sand on every hypothetical planet around each and every star in the visible universe.
Enough so that if every computer in the world generates 1000 GUIDs a second for 200 years, there might (MIGHT) be a collision.
Given the number of current local uses for GUIDs (one sequence per table per database for instance) it is extraordinarily unlikely to ever be a problem for us limited creatures (and machines with lifetimes that are usually less than a decade if not a year or two for mobile phones).
... Can we close this thread now?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39771",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "647"
} |
Q: Encrypt data from users in web applications Some web applications, like Google Docs, store data generated by the users. Data that can only be read by its owner. Or maybe not?
As far as I know, this data is stored as is in a remote database. So, if anybody with enough privileges in the remote system (a sysadmin, for instance) can lurk my data, my privacy could get compromised.
What could be the best solution to store this data encrypted in a remote database and that only the data's owner could decrypt it? How to make this process transparent to the user? (You can't use the user's password as the key to encrypt his data, because you shouldn't know his password).
A: If encryption/decryption is performed on the server, there is no way you can make sure that the cleartext is not dumped somewhere in some log file or the like.
You need to do the encryption/decryption inside the browser using JavaScript/Java/ActiveX or whatever. As a user, you need to trust the client-side of the web service not to send back the info unencrypted to the server.
Carl
A: I think Carl, nailed it on the head, but I wanted to say that with any website, if you are providing it any confidential/personal/privileged information then you have to have a certain level of trust, and it is the responsibility of the service provider to establish this trust. This is one of those questions that has been asked many times, across the internet since it's inception, and it will only continue to grow until we all have our own SSL certs encoded on our fingerprint, and even then we will have to ask the question 'How do I know that the finger is still attached to the user?'.
A: Well, I'd consider a process similar to Amazons AWS. You authenticate with a private password that is not saved remotely. Just a hash is used to validate the user. Then you generate a certificate with one of the main and long-tested algorithms and provide this from a secure page. Then a public/private key algorithm can be used to encrypt things for the users.
But the main problem remains the same: If someone with enough privileges can access the data (say: hacked your server), you're lost. Given enough time and power, everything could be breaked. It's just a matter of time.
But I think algorithms and applications like GPG/PGP and similar are very well known and can be implemented in a way that secure web applications - and keep the usability at a score that the average user can handle.
edit I want to catch up with @Carl and Unkwntech and add their statement: If you don't trust the site itself, don't give private data away. That's even before someone hacks their servers... ;-)
A:
Auron asked: How do you generate a key for the client to encrypt/decrypt the data? Where do you store this key?
Well, the key is usually derived from some password the user has chosen. You don't store it, you trust the user to remember it. What you can store is maybe some salt value associated to that user, to increase security against rainbow-table attacks for instance.
Crypto is hard to get right ;-) I would recommend to look at the source code for AxCrypt and for Xecrets' off-line client.
Carl
A: No, you can't use passwords, but you could use password hashes. However, Google Docs are all about sharing, so such a method would require storing a copy of the document for each user.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39772",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Implementing a '20 Questions'-like Wizard in a Database I am looking to implement a data-driven wizard with the question tree stored in an Oracle database. What is the best schema to use to make the database portion flexible (i.e. easy to add new paths of questions) without sacrificing too much in terms of performance?
A: You can build a tree structure using a foreign key that references the same table (a "pig's ear" relationship as it is often known). Then you can use the CONNECT BY syntax to traverse the tree. Here is a simple example:
SQL> create table qs
2 ( q_id integer primary key
3 , parent_q_id integer references qs
4 , parent_q_answer varchar2(1)
5 , q_text varchar2(100)
6* );
Table created.
SQL> insert into qs values (1, null, null, 'Is it bigger than a person?');
1 row created.
SQL> insert into qs values (2, 1, 'Y', 'Does it have a long neck?');
1 row created.
SQL> insert into qs values (3, 2, 'Y', 'It is a giraffe');
1 row created.
SQL> insert into qs values (4, 2, 'N', 'It is an elephant');
1 row created.
SQL> insert into qs values (5, 1, 'N', 'Does it eat cheese?');
1 row created.
SQL> insert into qs values (6, 5, 'Y', 'It is a mouse');
1 row created.
SQL> insert into qs values (7, 5, 'N', 'It is a cat');
1 row created.
SQL> commit;
Commit complete.
SQL> select rpad(' ',level*4,' ')||parent_q_answer||': '||q_text
2 from qs
3 start with parent_q_id is null
4 connect by prior q_id = parent_q_id;
RPAD('',LEVEL*4,'')||PARENT_Q_ANSWER||':'||Q_TEXT
------------------------------------------------------------------------------------------------------------------------------
: Is it bigger than a person?
Y: Does it have a long neck?
Y: It is a giraffe
N: It is an elephant
N: Does it eat cheese?
Y: It is a mouse
N: It is a cat
7 rows selected.
Note how the special keyword LEVEL can be used to determine how far down the tree we are, which I have then used to indent the data to show the structure.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39777",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I check job status from SSIS control flow? Here's my scenario - I have an SSIS job that depends on another prior SSIS job to run. I need to be able to check the first job's status before I kick off the second one. It's not feasible to add the 2nd job into the workflow of the first one, as it is already way too complex. I want to be able to check the first job's status (Failed, Successful, Currently Executing) from the second one's, and use this as a condition to decide whether the second one should run, or wait for a retry. I know this can be done by querying the MSDB database on the SQL Server running the job. I'm wondering of there is an easier way, such as possibly using the WMI Data Reader Task? Anyone had this experience?
A: You may want to create a third package the runs packageA and then packageB. The third package would only contain two execute package tasks.
http://msdn.microsoft.com/en-us/library/ms137609.aspx
@Craig
A status table is an option but you will have to keep monitoring it.
Here is an article about events in SSIS for you original question.
http://www.databasejournal.com/features/mssql/article.php/3558006
A: Why not use a table? Just have the first job update the table with it's status. The second job can use the table to check the status. That should do the trick if I am reading the question correctly. The table would (should) only have one row so it won't kill performance and shouldn't cause any deadlocking (of course, now that I write it, it will happen) :)
@Jason: Yeah, you could monitor it or you could have a trigger start the second job when the end status is recieved. :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39780",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How do I do multiple updates in a single SQL query? I have an SQL query that takes the following form:
UPDATE foo
SET flag=true
WHERE id=?
I also have a PHP array which has a list of IDs. What is the best way to accomplish this other than with parsing, as follows, ...
foreach($list as $item){
$querycondition = $querycondition . " OR " . $item;
}
... and using the output in the WHERE clause?
A: This would achieve the same thing, but probably won't yield much of a speed increase, but looks nicer.
mysql_query("UPDATE foo SET flag=true WHERE id IN (".implode(', ',$list).")");
A: You should be able to use the IN clause (assuming your database supports it):
UPDATE foo
SET flag=true
WHERE id in (1, 2, 3, 5, 6)
A: Use IN statement. Provide comma separated list of key values. You can easily do so using implode function.
UPDATE foo SET flag = true WHERE id IN (1, 2, 3, 4, 5, ...)
Alternatively you can use condition:
UPDATE foo SET flag = true WHERE flag = false
or subquery:
UPDATE foo SET flag = true WHERE id IN (SELECT id FROM foo WHERE .....)
A: Use join/implode to make a comma-delimited list to end up with:
UPDATE foo SET flag=true WHERE id IN (1,2,3,4)
A: I haven't ever seen a way to do that other than your foreach loop.
But, if $list is in any way gotten from the user, you should stick to using the prepared statement and just updating a row at a time (assuming someone doesn't have a way to update several rows with a prepared statement). Otherwise, you are wide open to sql injection.
A: you can jam you update with case statements but you will have to build the query on your own.
UPDATE foo
SET flag=CASE ID WHEN 5 THEN true ELSE flag END
,flag=CASE ID WHEN 6 THEN false ELSE flag END
WHERE id in (5,6)
The where can be omitted but saves you from a full table update.
A: VB.NET code:
dim delimitedIdList as string = arrayToString(listOfIds)
dim SQL as string = " UPDATE foo SET flag=true WHERE id in (" + delimitedIdList + ")"
runSql(SQL)
A: If you know a bound on the number of items then use the "IN" clause, as others have suggested:
UPDATE foo SET flag=true WHERE id in (1, 2, 3, 5, 6)
One warning though, is that depending on your db there may be a limit to the number of elements in the clause. Eg oracle 7 or 8 (?) used to have a limit of 256 items (this was increased significantly in later versions)
If you do iterate over a list use a transaction so you can rollback if one of the updates fails
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39792",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Debugging an exception in an empty catch block I'm debugging a production application that has a rash of empty catch blocks sigh:
try {*SOME CODE*}
catch{}
Is there a way of seeing what the exception is when the debugger hits the catch in the IDE?
A: In Visual Studio - Debug -> Exceptions -> Check the box by "Common Language Runtime Exceptions" in the Thrown Column
A: In VS, if you look in the Locals area of your IDE while inside the catch block, you will have something to the effect of $EXCEPTION which will have all of the information for the exception that was just caught.
A: You can write
catch (Exception ex) { }
Then when an exception is thrown and caught here, you can inspect ex.
A: No it is impossible, because that code block says "I don't care about the exception". You could do a global find and replace with the following code to see the exception.
catch {}
with the following
catch (Exception exc) {
#IF DEBUG
object o = exc;
#ENDIF
}
What this will do is keep your current do nothing catch for Production code, but when running in DEBUG it will allow you to set break points on object o.
A: If you're using Visual Studio, there's the option to break whenever an exception is thrown, regardless of whether it's unhandled or not. When the exception is thrown, the exception helper (maybe only VS 2005 and later) will tell you what kind of exception it is.
Hit Ctrl+Alt+E to bring up the exception options dialog and turn this on.
A: Can't you just add an Exception at that point and inspect it?
A: @sectrean
That doesn't work because the compiler ignores the Exception ex value if there is nothing using it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39824",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: HTML Help keyword location I'm writing a manual and some important keywords are repeated in several pages. In the project's index I defined the keywords like this:
<LI> <OBJECT type="text/sitemap">
<param name="Name" value="Stackoverflow">
<param name="Name" value="Overview">
<param name="Local" value="overview.html#stackoverflow">
<param name="Name" value="Cover">
<param name="Local" value="cover.html#stackoverflow">
<param name="Name" value="Intro">
<param name="Local" value="intro.html#stackoverflow">
</OBJECT>
It works but instead of the title the dialog shows the keyword and the name of the project repeated three times.
Here's how it looks: http://img54.imageshack.us/img54/3342/sokeywordjs9.png
How can I display the tile of the page that contains the keyword in that dialog? I would like to show like this:
Stackoverflow Overview
Stackoverflow Cover
Stackoverflow Intro
Thanks
A:
How can I display the tile of the page
that contains the keyword in that
dialog?
You can't. The Location column in the Topics Found dialog always contains the name of the source chm file of the topic. The only way to get around this is to use modular help, which comes with it's own share of problems and overhead.
The search and indexing features don't gracefully support topics with the same title within the same project. This seems shortsighted, but HTMLHelp is now over ten years old, so maybe they just planned to fix it later and never got around to it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39835",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I create a base page in WPF? I have decided that all my WPF pages need to register a routed event. Rather than include
public static readonly RoutedEvent MyEvent= EventManager.RegisterRoutedEvent("MyEvent", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(BasePage));
on every page, I decided to create a base page (named BasePage). I put the above line of code in my base page and then changed a few of my other pages to derive from BasePage. I can't get past this error:
Error 12 'CTS.iDocV7.BasePage' cannot
be the root of a XAML file because it
was defined using XAML. Line 1
Position
22. C:\Work\iDoc7\CTS.iDocV7\UI\Quality\QualityControlQueuePage.xaml 1 22 CTS.iDocV7
Does anyone know how to best create a base page when I can put events, properties, methods, etc that I want to be able to use from any wpf page?
A: Also, have a look at Attached Events and see if you can attach your event to every Page in your app. Might be easier than a custom intermediary class.
A: Here's how I've done this in my current project.
First I've defined a class (as @Daren Thomas said - just a plain old C# class, no associated XAML file), like this (and yes, this is a real class - best not to ask):
public class PigFinderPage : Page
{
/* add custom events and properties here */
}
Then I create a new Page and change its XAML declaration to this:
<my:PigFinderPage x:Class="Qaf.PigFM.WindowsClient.PenSearchPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:my="clr-namespace:Qaf.PigFM.WindowsClient"
/>
So I declare it as a PigFinderPage in the "my" namespace. Any page-wide resources you need have to be declared using a similar syntax:
<my:PigFinderPage.Resources>
<!-- your resources go here -->
</my:PigFinderPage.Resources>
Lastly, switch to the code-behind for this new page, and change its class declaration so that it derives from your custom class rather than directly from Page, like this:
public partial class EarmarkSearchPage : PigFinderPage
Remember to keep it as a partial class.
That's working a treat for me - I can define a bunch of custom properties and events back in "PigFinderPage" and use them in all the descendants.
A: I'm not sure on this one, but looking at your error, I would try to define the base class with just c# (.cs) code - do not create one with XAML, just a standard .cs file that extends the WPF Page class.
A: Here is a tutorial too !
it's pretty simple and easy.
A: Little update : I just tried to do it, and it didn't work. He is what I changed to solve the problem:
1.In many forums, you will read that the sub pages must inherit from a simple cs class, without XAML. Though it works. I do inherit from a normal XAML page without any problem.
2.I replaced the following code :
<my:PigFinderPage x:Class="Qaf.PigFM.WindowsClient.PenSearchPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:my="clr-namespace:Qaf.PigFM.WindowsClient"
/>
with
<my:PigFinderPage x:Class="Qaf.PigFM.WindowsClient.PenSearchPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:my="using:Qaf.PigFM.WindowsClient"
/>
because when I had "clr-namespace" instead of "using", the Intellisense could recognize PigFinderPage, but not the compiler.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39843",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Using C in a shared multi-platform POSIX environment I write tools that are used in a shared workspace. Since there are multiple OS's working in this space, we generally use Python and standardize the version that is installed across machines. However, if I wanted to write some things in C, I was wondering if maybe I could have the application wrapped in a Python script, that detected the operating system and fired off the correct version of the C application. Each platform has GCC available and uses the same shell.
One idea was to have the C compiled to the users local ~/bin, with timestamp comparison with C code so it is not compiled each run, but only when code is updated. Another was to just compile it for each platform, and have the wrapper script select the proper executable.
Is there an accepted/stable process for this? Are there any catches? Are there alternatives (assuming the absolute need to use native C code)?
Clarification: Multiple OS's are involved that do not share ABI. Eg. OS X, various Linuxes, BSD etc. I need to be able to update the code in place in shared folders and have the new code working more or less instantaneously. Distributing binary or source packages is less than ideal.
A: Launching a Python interpreter instance just to select the right binary to run would be much heavier than you need. I'd distribute a shell .rc file which provides aliases.
In /shared/bin, you put the various binaries: /shared/bin/toolname-mac, /shared/bin/toolname-debian-x86, /shared/bin/toolname-netbsd-dreamcast, etc. Then, in the common shared shell .rc file, you put the logic to set the aliases according to platform, so that on OSX, it gets alias toolname=/shared/bin/toolname-mac, and so forth.
This won't work as well if you're adding new tools all the time, because the users will need to reload the aliases.
I wouldn't recommend distributing tools this way, though. Testing and qualifying new builds of the tools should be taking up enough time and effort that the extra time required to distribute the tools to the users is trivial. You seem to be optimizing to reduce the distribution time. Replacing tools that quickly in a live environment is all too likely to result in lengthy and confusing downtime if anything goes wrong in writing and building the tools--especially when subtle cross-platform issues creep in.
A: Also, you could use autoconf and distribute your application in source form only. :)
A: You know, you should look at static linking.
These days, we all have HUGE hard drives, and a few extra megabytes (for carrying around libc and what not) is really not that big a deal anymore.
You could also try running your applications in chroot() jails and distributing those.
A: Depending on your mix os OSes, you might be better off creating packages for each class of system.
Alternatively, if they all share the same ABI and hardware architecture, you could also compile static binaries.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39847",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Embed a PowerPoint presentation into HTML Is it possible to embed a PowerPoint presentation (.ppt) into a webpage (.xhtml)?
This will be used on a local intranet where there is a mix of Internet Explorer 6 and Internet Explorer 7 only, so no need to consider other browsers.
I've given up... I guess Flash is the way forward.
A: Google Docs can serve up PowerPoint (and PDF) documents in it's document viewer. You don't have to sign up for Google Docs, just upload it to your website, and call it from your page:
<iframe src="//docs.google.com/gview?url=https://www.yourwebsite.com/powerpoint.ppt&embedded=true" style="width:600px; height:500px;" frameborder="0"></iframe>
A: DocStoc.com and Scribd.com both work well with Internet Explorer 6 and Internet Explorer 7. They'll show a variety of document types, including PowerPoint files (.ppt). I use these services for my intranet here at work. Of course, just remember to mark your documents as 'private' after you upload them.
A: besides, if you save ppt as .pps format using microsoft powerpoint, you can use the following code:
<iframe src="file.pps" width="800px" heigt="600px"></iframe>
Another common way to do it is to convert ppt/doc to pdf,
then use swftool(http://www.swftools.org) to convert it to swf
finally, take FlexPaper(http://flexpaper.devaldi.com) as document viewer.
A: I don't know of a way to embed PowerPoint slides directly into HTML. However, there are a number of solutions online for converting a PPT file into a SWF, which can be embedded into HTML just like any other Flash movie.
Googling for 'ppt to swf' seems to give a lot of hits. Some are free, others aren't. Some handle things like animations, others just do still images. There's got to be one out there that does what you need. :)
A: You can use Microsoft Office Web Apps to embed PowerPoint and Excel Files. See Say more in your blog with embedded PowerPoint and Excel files.
A: I ended up going for screenshooting each slide, and using two different tabs to navigate, this was put into an . this gives high-res, but you sacrifice animations and interactivity, the only thing the user can do is read and change slide. heres an example off my website: http://deepschool.jaberwokkee.kodingen.com/~/Miss%20Necchi%27s%20powerpoints/Volume%20of%20prisms%20powerpoint/slide1.htm
A: Google Docs allows you to upload a PowerPoint document, you can then 'Share' it with everyone then you can 'Publish' it and this will provide code to embed it in your site or you can use a direct link which runs at the full size of the browser window. The conversion is pretty good and scales well because the text is retained rather than converted to an image. The conversion is pretty good and the whole thing is free. Definitely worth a go.
A: Tried all of the options in this stack and couldn't reach something that loaded swiftly, used PPT. file directly, and scaled easily. Saved out my ppt. as .gif and opted for "Infinite Carousel" (javascript) that I can drop images into easily. Has left right controls, play option, all the same stuff you find in ppt. presenter mode...
http://www.catchmyfame.com/2009/12/30/huge-updates-to-jquery-infinite-carousel-version-2-released/
A: I got so sick of trying all of the different options to web host a power point that were flaky or required flash so I rolled my own.
My solution uses a very simple javascript function to simply scroll / replace a image tag with GIFs that I saved from the Power Point presentation itself.
*
*In the power point presentation click Save As and select GIF. Pick the quality you want to display the presentation at. Power Point will save one GIF image for each slide and name them Slide1.GIF, Slide2.GIF, etc.....
*Create a HTML page and add a image tag to display the Power point GIF images.
<img src="Slide1.GIF" id="mainImage" name="mainImage" width="100%" height="100%" alt="">
*Add some first, previous, next and last clickable objects with the onClick action as below:
<a href="#" onclick="swapImage(0);"><img src="/images/first.png" border=0 alt="First"></a>
<a href="#" onclick="swapImage(currentIndex-1);"><img src="/images/left.png" border=0 alt="Back"></a>
<a href="#" onclick="swapImage(currentIndex+1);"><img src="/images/right.png" border=0 alt="Next"></a>
<a href="#" onclick="swapImage(maxIndex);"><img src="/images/last.png" border=0 alt="Last"></a>
*Finally, add the below javascript function that when called grabs the next Slide.GIF image and displays it to the img tag.
<script type="text/javascript">
//Initilize start value to 1 'For Slide1.GIF'
var currentIndex = 1;
//NOTE: Set this value to the number of slides you have in the presentation.
var maxIndex=12;
function swapImage(imageIndex){
//Check if we are at the last image already, return if we are.
if(imageIndex>maxIndex){
currentIndex=maxIndex;
return;
}
//Check if we are at the first image already, return if we are.
if(imageIndex<1){
currentIndex=1;
return;
}
currentIndex=imageIndex;
//Otherwise update mainImage
document.getElementById("mainImage").src='Slide' + currentIndex + '.GIF';
return;
}
</script>
Make sure the GIFs are reachable from the HTMl page. They are by default expected to be in the same directory but you should be able to see the logic and how to set to a image directory if required
I have training material up for my company that uses this technique at http://www.vanguarddata.com.au so before you spend any time trying it out you are welcome to look at in action.
I hope this helps someone else out there who is having as much headaches with this as I did.....
A: Id recommend the official View Office documents online
link
for embeding you can simply use
<iframe src='https://view.officeapps.live.com/op/embed.aspx?src={urlencode(site-to-ppt)}' width='962px' height='565px' frameborder='0'></iframe>
A: The 'actual answer' is that you cannot do it directly. You have to convert your PowerPoint presentation to something that the browser can process. You can save each page of the PowerPoint presentation as a JPEG image and then display as a series of images. You can save the PowerPoint presentation as HTML. Both of these solutions will render only static pages, without any of the animations of PowerPoint. You can use a tool to convert your PowerPoint presentation to Flash (.swf) and embed it that way. This will preserve any animations and presumably allow you to do an automatic slideshow without the need for writing special code to change the images.
A: Power point supports converting to mp4 which can be posted using a html5 video tag.
Save As > MPEG-4 Video (*.mp4)
<video controls autoplay reload="none" style="width:1000px;">
<source src="my_power_point.mp4" type="video/mp4" />
</video>
A: As an alternate solution, you can convert PPT/PPTX to JPG/SVG images and display them with revealjs. See example code here.
PS. I am working as SW developer at Aspose.
A: The first few results on Google all sound like good options:
http://www.pptfaq.com/FAQ00708.htm
http://www.webdeveloper.com/forum/showthread.php?t=86212
A: Try PowerPoint ActiveX 2.4. This is an ActiveX component that embeds PowerPoint into an OCX.
Since you are using just Internet Explorer 6 and Internet Explorer 7 you can embed this component into the HTML.
A: As a side note: If your intranet users also have access to the Internet, you can use the SlideShare widget to embed your PowerPoint presentations in your website.
(Remember to mark your presentation as private!)
A: Some Flash tool that can convert the PowerPoint file to Flash could be helpful. Slide share is also helpful. For me, I will take something like PPT2Flash Pro or things like that.
A: Well, I think you get to convert the powerpoint to flash first. PowerPoint is not a sharable format on Internet. Some tool like PowerPoint to Flash could be helpful for you.
A: I spent a while looking into this and pretty much all of the freeware and shareware on the web sucked. This included software to directly convert the .ppt file to Flash or some sort of video format and also software to record your desktop screen. Software was clunky, and the quality was poor.
The solution we eventually came up with is a little bit manual, but it gave by far the best quality results:
*
*Export the .ppt file into some sort of image format (.bmp, .jpeg, .png, .tif) - it writes out one file per slide
*Import all the slide image files into Google Picasa and use them to create a video. You can add in some nice simple transitions (it hasn't got some of the horrific .ppt one's, but who cares) and it dumps out a WMV file of your specified resolution.
Saving out as .wmv isn't perfect, but I'm sure it's probably quite straightforward to convert that to some other format or Flash. We were looking to get them up on YouTube and this did the trick.
A: An easy (and free) way is to download OpenOffice and use Impress to open the PowerPoint presentation. Then export into a separate folder as HTML. Your presentation will consist of separate HTML files and images for each PowerPoint slide. Link to the title page, and you're done.
A: I was looking for a solution for similar problem.
I looked into http://phppowerpoint.codeplex.com/
But they have no better documentation, and even no demo page I could see over there and it was seemingly difficult.
What I came up with is: SkyDrive by Microsoft. https://skydrive.live.com
All you need is an account with them and upload your PPT and embed them straightaway. PPT player is quite clean to use and I like it.
A: I've noticed people recommending some PPT-to-Flash solutions, but Flash doesn't work on mobile devices. There's a hosting service called iSpring Cloud that automatically converts your PPT to combined Flash+HTML5 format and lets you generate an embed code for your website or blog. Full instructions can be found on their website.
A: Another option is to use Apple Keynote on a Mac (Libre Office couldn't event open a pptx I had) to save the presentation to HTML5. It does a pretty good job to produce exactly what it displays in keynote, e.g. it includes animations and video. Compatibility of keynote to powerpoint has it's limits though (independent of the export).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39855",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "65"
} |
Q: how do I import a class to use inside Flex application? I have an actionscript file that defines a class that I would like to use inside a Flex application.
I have defined some custom controls in a actionscript file and then import them via the application tag:
<mx:Application
xmlns:mx="http://www.adobe.com/2006/mxml"
xmlns:scorecard="com.apterasoftware.scorecard.controls.*"
...
</mx:Application>
but this code is not a flex component, rather it is a library for performing math routines, how do I import this class?
A: You'd need to import the class inside a script tag.
<mx:Application
xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
import com.apterasoftware.scorecard.controls.*;
// Other imports go here
// Functions and other code go here
</mx:Script>
<!-- Components and other MXML stuff go here -->
<mx:VBox>
<!-- Just a sample -->
</mx:VBox>
</mx:Application>
Then you'll be able to reference that class anywhere else in your script tag. Depending on how the class is written you may not be able to use binding within the MXML, but you could define your own code to handle that.
Namespace declarations are only used to import other MXML components. AS classes are imported using the import statement either within a Script block or another AS file.
A: @Herms: To clarify a little, namespace declarations can be used to "import" AS classes as well, when you're going to instantiate them using MXML.
For example, consider having a custom visual component you've written entirely in AS, let's say com.apterasoftware.scorecard.controls.MathVisualizer. To use it within MXML:
<mx:Application
xmlns:mx="http://www.adobe.com/2006/mxml"
xmlns:aptera="com.apterasoftware.scorecard.controls.*">
<aptera:MathVisualizer width="400" height="300" />
</mx:Application>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39856",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to run gpg from a script run by cron? I have a script that has a part that looks like that:
for file in `ls *.tar.gz`; do
echo encrypting $file
gpg --passphrase-file /home/$USER/.gnupg/backup-passphrase \
--simple-sk-checksum -c $file
done
For some reason if I run this script manually, works perfectly fine and all files are encrypted. If I run this as cron job, echo $file works fine (I see "encrypting <file>" in the log), but the file doesn't get encrypted and gpg silent fails with no stdout/stderr output.
Any clues?
A: In my case gpg cant find home dir for using keys:
gpg: no default secret key: No secret key
gpg: 0003608.cmd: sign+encrypt failed: No secret key
So I added --homedir /root/.gnupg. The final command can looks like
echo 'password' | gpg -vvv --homedir /root/.gnupg --batch --passphrase-fd 0
--output /usr/share/file.gpg --encrypt --sign /usr/share/file.tar.bz2
A: It turns out that the answer was easier than I expected. There is a --batch parameter missing, gpg tries to read from /dev/tty that doesn't exist for cron jobs. To debug that I have used --exit-on-status-write-error param. But to use that I was inspired by exit status 2, reported by echoing $? as Cd-Man suggested.
A: You should make sure that GPG is in your path when the cronjob is running. Your best guess would be do get the full path of GPG (by doing which gpg) and running it using the full path (for example /usr/bin/gpp...).
Some other debugging tips:
*
*output the value of $? after running GPG (like this: echo "$?"). This gives you the exit code, which should be 0, if it succeded
*redirect the STDERR to STDOUT for GPG and then redirect STDOUT to a file, to inspect any error messages which might get printed (you can do this a command line: /usr/bin/gpg ... 2>&1 >> gpg.log)
A: make sure the user that is running the cron job has the permissions needed to encrypt the file.
A: I've came across this problem once.
I can't really tell you why, but I dont think cron executes with the same environment variable as the user do.
I actually had to export the good path for my programs to execute well.
Is gpg at least trying to execute?
Or are the files you are trying to encypt actually in the current directory when the cron executes?
Maybe try to execute a echo whereis gpg and echo $PATH in your script to see if it's included... Worked for me.
A: @skinp Cron jobs are executed by sh, whereas most modern Unixes use bash or ksh for interactive logins. The biggest problem (in my experience) is that sh doesn't understand things like:
export PS1='\u@\h:\w> '
which needs to be changed to:
PS1='\u@\h:\w> '
export PS1
So if cron runs a shell script which defines an environment variable using the first syntax, before running some other command, the other command will never be executed because sh bombs out trying to define the variable.
A: In my case: "gpg: decryption failed: Bad session key".
Tried adding /usr/bin/gpg, checking the version, setting --batch, setting --home (with /root/.gnupg and /home/user/.gnupg) and all did not work.
/usr/bin/gpg -d --batch --homedir /home/ec2-user/.gnupg --no-mdc-warning -quiet --passphrase "$GPG_PP" "$file"
Turned out that cron on AWS beanstalk instance needed the environment variable being used to set the --passphrase $GPG_PP. Cron now:
0 15 * * * $(source /opt/elasticbeanstalk/support/envvars && /home/ec2-user/bin/script.sh >> /home/ec2-user/logs/cron_out.log 2>&1)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39867",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "26"
} |
Q: How do I model a chessboard when programming a computer to play chess? What data structures would you use to represent a chessboard for a computer chess program?
A: The simple approach is to use an 8x8 integer array. Use 0 for empty squares and assign values for the pieces:
1 white pawns
2 white knights
3 white bishops
4 white rooks
5 white queens
6 white king
Black pieces use negative values
-1 black pawn
-2 black knight
etc
8| -4 -2 -3 -5 -6 -3 -2 -4
7| -1 -1 -1 -1 -1 -1 -1 -1
6| 0 0 0 0 0 0 0 0
5| 0 0 0 0 0 0 0 0
4| 0 0 0 0 0 0 0 0
3| 0 0 0 0 0 0 0 0
2| 1 1 1 1 1 1 1 1
1| 4 2 3 5 6 3 2 4
-------------------------
1 2 3 4 5 6 7 8
Piece moves can be calculated by using the array indexes. For example the white pawns move by increasing the row index by 1, or by 2 if it's the pawn's first move. So the white pawn on [2][1] could move to [3][1] or [4][1].
However this simple 8x8 array representation of has chessboard has several problems. Most notably when you're moving 'sliding' pieces like rooks, bishops and queens you need to constantly be checking the indexes to see if the piece has moved off the board.
Most chessprograms today, especially those that run on a 64 bit CPU, use a bitmapped approach to represent a chessboard and generate moves. x88 is an alternate board model for machines without 64 bit CPUs.
A: Array of 120 bytes.
This is a chessboard of 8x8 surrounded by sentinel squares (e.g. a 255 to indicate that a piece can't move to this square). The sentinels have a depth of two so that a knight can't jump over.
To move right add 1. To move left add -1. Up 10, down -10, up and right diagonal 11 etc. Square A1 is index 21. H1 is index 29. H8 is index 99.
All designed for simplicity. But it's never going to be as fast as bitboards.
A: There are of course a number of different ways to represent a chessboard, and the best way will depend on what is most important to you.
Your two main choices are between speed and code clarity.
If speed is your priority then you must use a 64 bit data type for each set of pieces on the board (e.g. white pawns, black queens, en passant pawns). You can then take advantage of native bitwise operations when generating moves and testing move legality.
If clarity of code is priority then forget bit shuffling and go for nicely abstracted data types like others have already suggested. Just remember that if you go this way you will probably hit a performance ceiling sooner.
To start you off, look at the code for Crafty (C) and SharpChess (C#).
A: Well, not sure if this helps, but Deep Blue used a single 6-bit number to represent a specific position on the board. This helped it save footprint on-chip in comparison to it's competitor, which used a 64-bit bitboard.
This might not be relevant, since chances are, you might have 64 bit registers on your target hardware, already.
A: When creating my chess engine I originally went with the [8][8] approach, however recently I changed my code to represent the chess board using a 64 item array. I found that this implementation was about 1/3 more efficient, at least in my case.
One of the things you want to consider when doing the [8][8] approach is describing positions. For example if you wish to describe a valid move for a chess piece, you will need 2 bytes to do so. While with the [64] item array you can do it with one byte.
To convert from a position on the [64] item board to a [8][8] board you can simply use the following calculations:
Row= (byte)(index / 8)
Col = (byte)(index % 8)
Although I found that you never have to do that during the recursive move searching which is performance sensitive.
For more information on building a chess engine, feel free to visit my blog that describes the process from scratch: www.chessbin.com
Adam Berent
A: An alternative to the standard 8x8 board is the 10x12 mailbox (so-called because, uh, I guess it looks like a mailbox). This is a one-dimensional array that includes sentinels around its "borders" to assist with move generation. It looks like this:
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, "a8", "b8", "c8", "d8", "e8", "f8", "g8", "h8", -1,
-1, "a7", "b7", "c7", "d7", "e7", "f7", "g7", "h7", -1,
-1, "a6", "b6", "c6", "d6", "e6", "f6", "g6", "h6", -1,
-1, "a5", "b5", "c5", "d5", "e5", "f5", "g5", "h5", -1,
-1, "a4", "b4", "c4", "d4", "e4", "f4", "g4", "h4", -1,
-1, "a3", "b3", "c3", "d3", "e3", "f3", "g3", "h3", -1,
-1, "a2", "b2", "c2", "d2", "e2", "f2", "g2", "h2", -1,
-1, "a1", "b1", "c1", "d1", "e1", "f1", "g1", "h1", -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1
You can generate that array like this (in JavaScript):
function generateEmptyBoard() {
var row = [];
for(var i = 0; i < 120; i++) {
row.push((i < 20 || i > 100 || !(i % 10) || i % 10 == 9)
? -1
: i2an(i));
}
return row;
}
// converts an index in the mailbox into its corresponding value in algebraic notation
function i2an(i) {
return "abcdefgh"[(i % 10) - 1] + (10 - Math.floor(i / 10));
}
Of course, in a real implementation you'd put actual piece objects where the board labels are. But you'd keep the negative ones (or something equivalent). Those locations make move generation a lot less painful because you can easily tell when you've run off the board by checking for that special value.
Let's first look at generating the legal moves for the knight (a non-sliding piece):
function knightMoves(square, board) {
var i = an2i(square);
var moves = [];
[8, 12, 19, 21].forEach(function(offset) {
[i + offset, i - offset].forEach(function(pos) {
// make sure we're on the board
if (board[pos] != -1) {
// in a real implementation you'd also check whether
// the squares you encounter are occupied
moves.push(board[pos]);
}
});
});
return moves;
}
// converts a position in algebraic notation into its location in the mailbox
function an2i(square) {
return "abcdefgh".indexOf(square[0]) + 1 + (10 - square[1]) * 10;
}
We know that the valid Knight moves are a fixed distance from the piece's starting point, so we only needed to check that those locations are valid (i.e. not sentinel squares).
The sliding pieces aren't much harder. Let's look at the bishop:
function bishopMoves(square, board) {
var oSlide = function(direction) {
return slide(square, direction, board);
}
return [].concat(oSlide(11), oSlide(-11), oSlide(9), oSlide(-9));
}
function slide(square, direction, board) {
var moves = [];
for(var pos = direction + an2i(square); board[pos] != -1; pos += direction) {
// in a real implementation you'd also check whether
// the squares you encounter are occupied
moves.push(board[pos]);
}
return moves;
}
Here are some examples:
knightMoves("h1", generateEmptyBoard()) => ["f2", "g3"]
bishopMoves("a4", generateEmptyBoard()) => ["b3", "c2", "d1", "b5", "c6", "d7", "e8"]
Note that the slide function is a general implementation. You should be able to model the legal moves of the other sliding pieces fairly easily.
A: Using a bitboard would be an efficient way to represent the state of a chess board. The basic idea is that you use 64bit bitsets to represent each of the squares on the board, where first bit usually represents A1 (the lower left square), and the 64th bit represents H8 (the diagonally opposite square). Each type of piece (pawn, king, etc.) of each player (black, white) gets its own bit board and all 12 of these boards makes up the game state. For more information check out this Wikipedia article.
A: For a serious chess engine, using bitboards is an efficient way to represent a chess board in memory. Bitboards are faster than any array based representation, specially in 64-bit architectures where a bitboard can fit inside a single CPU register.
Bitboards
Basic idea of bitboards is to represent every chess piece type in 64 bits. In C++/C# it will be ulong/UInt64. So you'll maintain 12 UInt64 variables to represent your chess board: two (one black and one white) for each piece type, namely, pawn, rook, knight, bishop, queen and king. Every bit in a UInt64 will correspond to a square on chessboard. Typically, the least significant bit will be a1 square, the next b1, then c1 and so on in a row-major fashion. The bit corresponding to a piece's location on chess board will be set to 1, all others will be set to 0. For example, if you have two white rooks on a2 and h1 then the white rooks bitboard will look like this:
0000000000000000000000000000000000000000000000000000000110000000
Now for example, if you wanted to move your rook from a2 to g2 in the above example, all you need to do is XOR you bitboard with:
0000000000000000000000000000000000000000000000000100000100000000
Bitboards have a performance advantage when it comes to move generation. There are other performance advantages too that spring naturally from bitboards representation. For example you could use lockless hash tables which are an immense advantage when parallelising your search algorithm.
Further Reading
The ultimate resource for chess engine development is the Chess Programming Wiki. I've recently written this chess engine which implements bitboards in C#. An even better open source chess engine is StockFish which also implements bitboards but in C++.
A: Initially, use an 8 * 8 integer array to represent the chess board.
You can start programing using this notation. Give point values for the pieces. For example:
**White**
9 = white queen
5 = white rook
3 = bishop
3 = knight
1 = pawn
**black**
-9 = white queen
-5 = white rook
-3 = bishop
-3 = knight
-1 = pawn
White King: very large positive number
Black King: very large negative number
etc. (Note that the points given above are approximations of trading power of each chess piece)
After you develop the basic backbones of your application and clearly understand the working of the algorithms used, try to improve the performance by using bit boards.
In bit boards, you use eight 8 -bit words to represent the boards. This representation needs a board for each chess piece. In one bit board you will be storing the position of the rook while in another you will be storing the position of the knight... etc
Bit boards can improve the performance of your application very much because manipulating the pieces with bit boards are very easy and fast.
As you pointed out,
Most chessprograms today, especially
those that run on a 64 bit CPU, use a
bitmapped approach to represent a
chessboard and generate moves. x88 is
an alternate board model for machines
without 64 bit CPUs.
A: I would use a multidimensional array so that each element in an array is a grid reference to a square on the board.
Thus
board = arrary(A = array (1,2,3,4,5,5,6,7,8),
B = array (12,3,.... etc...
etc...
)
Then board[A][1] is then the board square A1.
In reality you would use numbers not letters to help keep your maths logic for where pieces are allowed to move to simple.
A: int[8][8]
0=no piece
1=king
2=queen
3=rook
4=knight
5=bishop
6=pawn
use positive ints for white and negative ints for black
A: I actually wouldn't model the chess board, I'd just model the position of the pieces.
You can have bounds for the chess board then.
Piece.x= x position of piece
Piece.y= y position of piece
A: I know this is a very old post which I have stumbled across a few times when googling chess programming, yet I feel I must mention it is perfectly feasible to model a chessboard with a 1D array e.g. chessboard[64];
I would say this is the simplest approach to chessboard representation...but of course it is a basic approach.
Is a 1D chessboard array structure more efficient than a 2D array (which needs a nested for loop to access and manipulate the indices)?
It is also possible to use a 1D array with more than 64 squares to represent OffBoard squares also e.g. chessboard[120]; (with the array sentinel and board playing squares correctly initialised).
Finally and again for completeness for this post I feel I must mention the 0x88 board array representation. This is quite a popular way to represent a chessboard which also accounts for offboard squares.
A: An array would probably be fine. If you wanted more convenient means of "traversing" the board, you could easily build methods to abstract away the details of the data structure implementation.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39874",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "27"
} |
Q: Why doesn't JavaScript support multithreading? Is it a deliberate design decision or a problem with our current day browsers which will be rectified in the coming versions?
A: Just as matt b said, the question is not very clear. Assuming that you are asking about multithreading support in the language: because it isn't needed for 99.999% of the applications running in the browser currently. If you really need it, there are workarounds (like using window.setTimeout).
In general multithreading is very, very, very, very, very, very hard (did I say that it is hard?) to get right, unless you put in extra restrictions (like using only immutable data).
A: JavaScript multi-threading (with some limitations) is here. Google implemented workers for Gears, and workers are being included with HTML5. Most browsers have already added support for this feature.
Thread-safety of data is guaranteed because all data communicated to/from the worker is serialized/copied.
For more info, read:
http://www.whatwg.org/specs/web-workers/current-work/
http://ejohn.org/blog/web-workers/
A: Intel has been doing some open-source research on multithreading in Javascript, it was showcased recently on GDC 2012.
Here is the link for the video. The research group used OpenCL which primarily focuses on Intel Chip sets and Windows OS. The project is code-named RiverTrail and the code is available on GitHub
Some more useful links:
Building a Computing Highway for Web Applications
A: Traditionally, JS was intended for short, quick-running pieces of code. If you had major calculations going on, you did it on a server - the idea of a JS+HTML app that ran in your browser for long periods of time doing non-trivial things was absurd.
Of course, now we have that. But, it'll take a bit for browsers to catch up - most of them have been designed around a single-threaded model, and changing that is not easy. Google Gears side-steps a lot of potential problems by requiring that background execution is isolated - no changing the DOM (since that's not thread-safe), no accessing objects created by the main thread (ditto). While restrictive, this will likely be the most practical design for the near future, both because it simplifies the design of the browser, and because it reduces the risk involved in allowing inexperienced JS coders mess around with threads...
@marcio:
Why is that a reason not to implement multi-threading in Javascript? Programmers can do whatever they want with the tools they have.
So then, let's not give them tools that are so easy to misuse that every other website i open ends up crashing my browser. A naive implementation of this would bring you straight into the territory that caused MS so many headaches during IE7 development: add-on authors played fast and loose with the threading model, resulting in hidden bugs that became evident when object lifecycles changed on the primary thread. BAD. If you're writing multi-threaded ActiveX add-ons for IE, i guess it comes with the territory; doesn't mean it needs to go any further than that.
A: JavaScript does not support multi-threading because the JavaScript interpreter in the browser is a single thread (AFAIK). Even Google Chrome will not let a single web page’s JavaScript run concurrently because this would cause massive concurrency issues in existing web pages. All Chrome does is separate multiple components (different tabs, plug-ins, etcetera) into separate processes, but I can’t imagine a single page having more than one JavaScript thread.
You can however use, as was suggested, setTimeout to allow some sort of scheduling and “fake” concurrency. This causes the browser to regain control of the rendering thread, and start the JavaScript code supplied to setTimeout after the given number of milliseconds. This is very useful if you want to allow the viewport (what you see) to refresh while performing operations on it. Just looping through e.g. coordinates and updating an element accordingly will just let you see the start and end positions, and nothing in between.
We use an abstraction library in JavaScript that allows us to create processes and threads which are all managed by the same JavaScript interpreter. This allows us to run actions in the following manner:
*
*Process A, Thread 1
*Process A, Thread 2
*Process B, Thread 1
*Process A, Thread 3
*Process A, Thread 4
*Process B, Thread 2
*Pause Process A
*Process B, Thread 3
*Process B, Thread 4
*Process B, Thread 5
*Start Process A
*Process A, Thread 5
This allows some form of scheduling and fakes parallelism, starting and stopping of threads, etcetera, but it will not be true multi-threading. I don’t think it will ever be implemented in the language itself, since true multi-threading is only useful if the browser can run a single page multi-threaded (or even more than one core), and the difficulties there are way larger than the extra possibilities.
For the future of JavaScript, check this out:
https://developer.mozilla.org/presentations/xtech2006/javascript/
A: Currently some browsers do support multithreading. So, if you need that you could use specific libraries. For example, view the next materials:
*
*https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers
(support background threads);
*https://keithwhor.github.io/multithread.js/ (the library).
A: Javascript is a single-threaded language. This means it has one call stack and one memory heap. As expected, it executes code in order and must finish executing a piece code before moving onto the next. It's synchronous, but at times that can be harmful. For example, if a function takes a while to execute or has to wait on something, it freezes everything up in the meanwhile.
A: I don't know the rationale for this decision, but I know that you can simulate some of the benefits of multi-threaded programming using setTimeout. You can give the illusion of multiple processes doing things at the same time, though in reality, everything happens in one thread.
Just have your function do a little bit of work, and then call something like:
setTimeout(function () {
... do the rest of the work...
}, 0);
And any other things that need doing (like UI updates, animated images, etc) will happen when they get a chance.
A: Do you mean why doesn't the language support multithreading or why don't JavaScript engines in browsers support multithreading?
The answer to the first question is that JavaScript in the browser is meant to be run in a sandbox and in a machine/OS-independent way, to add multithreading support would complicate the language and tie the language too closely to the OS.
A: Node.js 10.5+ supports worker threads as experimental feature (you can use it with --experimental-worker flag enabled): https://nodejs.org/api/worker_threads.html
So, the rule is:
*
*if you need to do I/O bound ops, then use the internal mechanism (aka callback/promise/async-await)
*if you need to do CPU bound ops, then use worker threads.
Worker threads are intended to be long-living threads, meaning you spawn a background thread and then you communicate with it via message passing.
Otherwise, if you need to execute a heavy CPU load with an anonymous function, then you can go with https://github.com/wilk/microjob, a tiny library built around worker threads.
A: It's the implementations that doesn't support multi-threading. Currently Google Gears is providing a way to use some form of concurrency by executing external processes but that's about it.
The new browser Google is supposed to release today (Google Chrome) executes some code in parallel by separating it in process.
The core language, of course can have the same support as, say Java, but support for something like Erlang's concurrency is nowhere near the horizon.
A: As far as I have heared Google Chrome will have multithreaded javascript, so it is a "current implementations" problem.
A: Without proper language support for thread syncronization, it doesn't even make sense for new implementations to try. Existing complex JS apps (e.g. anything using ExtJS) would most likely crash unexpectedly, but without a synchronized keyword or something similar, it would also be very hard or even impossible to write new programs that behave correctly.
A: Actually multi-threading is not related with the language itself.
Here is a Multithreaded Javascript Engine for .NET.
It works pretty well with multi-threading scenarios.
It integrates with C# runtime so all the synchronization logic is similar to C#. You can start/await/wait tasks, and you can start threads. You can even put locks. Following sample demonstrates parallel loop using Javascript syntax in .NET runtime.
https://github.com/koculu/topaz
var engine = new TopazEngine();
engine.AddType(typeof(Console), "Console");
topazEngine.AddType(typeof(Parallel), "Parallel");
engine.ExecuteScript(@"
var sharedVariable = 0
function f1(i) {
sharedVariable = i
}
Parallel.For(0, 100000 , f1)
Console.WriteLine(`Final value: {sharedVariable}`);
");
Besides that, Microsoft is working on Napa.js, a multi-threading supported Node.js clone.
https://github.com/microsoft/napajs
A: However you can use eval function to bring concurrency TO SOME EXTENT
/* content of the threads to be run */
var threads = [
[
"document.write('Foo <br/>');",
"document.write('Foo <br/>');",
"document.write('Foo <br/>');",
"document.write('Foo <br/>');",
"document.write('Foo <br/>');",
"document.write('Foo <br/>');",
"document.write('Foo <br/>');",
"document.write('Foo <br/>');",
"document.write('Foo <br/>');",
"document.write('Foo <br/>');"
],
[
"document.write('Bar <br/>');",
"document.write('Bar <br/>');",
"document.write('Bar <br/>');",
"document.write('Bar <br/>');",
"document.write('Bar <br/>');",
"document.write('Bar <br/>');",
"document.write('Bar <br/>');",
"document.write('Bar <br/>');",
"document.write('Bar <br/>');"
]
];
window.onload = function() {
var lines = 0, quantum = 3, max = 0;
/* get the longer thread length */
for(var i=0; i<threads.length; i++) {
if(max < threads[i].length) {
max = threads[i].length;
}
}
/* execute them */
while(lines < max) {
for(var i=0; i<threads.length; i++) {
for(var j = lines; j < threads[i].length && j < (lines + quantum); j++) {
eval(threads[i][j]);
}
}
lines += quantum;
}
}
A: Multi-threading with javascript is clearly possible using webworkers bring by HTML5.
Main difference between webworkers and a standard multi-threading environment is memory resources are not shared with the main thread, a reference to an object is not visible from one thread to another. Threads communicate by exchanging messages, it is therefore possible to implement a synchronzization and concurrent method call algorithm following an event-driven design pattern.
Many frameworks exists allowing to structure programmation between threads, among them OODK-JS, an OOP js framework supporting concurrent programming
https://github.com/GOMServices/oodk-js-oop-for-js
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39879",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "326"
} |
Q: How To Write a Plug-In for IE The IE Developer Toolbar is a plugin that can dock or separate from the browser. I understand its much more difficult to do this in IE than in Firefox.
*
*How does one create an IE plugin?
*What languages are available for this task?
*How can I make a Hello World plugin?
A: See http://www.enhanceie.com/ie/dev.asp for my favorite resources on this topic.
A: Here are a few resources that might help you in your quest to create browser helper objects (BHO).
http://petesearch.com/wiki/ (archived)
http://www.hackszine.com/blog/archive/2007/06/howto_port_firefox_extensions.html
http://msdn.microsoft.com/en-us/library/ms182554(VS.80).aspx
http://www.codeplex.com/TeamTestPlugins
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39892",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "21"
} |
Q: VS.NET defaults to private class Why does Visual Studio declare new classes as private in C#? I almost always switch them over to public, am I the crazy one?
A: Private access by default seems like a reasonable design choice on the part of the C# language specifiers.
A good general design principle is to make all access levels as restrictive as possible, to minimize dependencies. You are less likely to end up with the wrong access level if you start as restrictive as possible and make the developer take some action to make a class or member more visible. If something is less public than you need, then that is apparent immediately when you get a compilation error, but it is not nearly as easy to spot something that is more visible than it should be.
A: I am not sure WHY it does that, but here's what you do in order to get Visual Studio to create the class as Public by default:
Go over to “Program Files\Microsoft Visual Studio 9.0\Common7\IDE\ItemTemplates\CSharp\Code\1033″, you will find a file called Class.zip, inside the .zip file open the file called Class.cs, the content of the file looks like this:
using System;
using System.Collections.Generic;
$if$ ($targetframeworkversion$ == 3.5)using System.Linq;
$endif$using System.Text;
namespace $rootnamespace$
{
class $safeitemrootname$
{
}
}
All you need to do is add “Public” before the class name. The outcome should look like this:
using System;
using System.Collections.Generic;
$if$ ($targetframeworkversion$ == 3.5)using System.Linq;
$endif$using System.Text;
namespace $rootnamespace$
{
public class $safeitemrootname$
{
}
}
One last thing you need to do is flush all the Templates Visual Studio is using, and make him reload them. The command for that is ( it takes a while so hold on):
devenv /installvstemplates
And that’s it, no more private classes by default. Of course you can also add internal or whatever you want.
Source
A: No I always have to slap that "public" keyword on the front of the class, so you are not alone. I guess the template designers thought it was a good idea to start with the very basics. You can edit these templates though in your Visual Studio install, if it really annoys you that much, but I haven't gotten to that point yet.
A: Even if you mark a class as public, members are still private by default. In other words, the class is pretty much useless outside the same namespace. I think making it public by default instead may go too far, though. Try using 'internal' some. It should provide enough access for most purposes.
A: For security reasons.
You want to expose certain methods and not your whole class.
A: C++, upon which C# is derived, specified that the default class access level is private. C# carries this forward for better or worse.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39903",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: How to use the SharePoint MultipleLookupField control? I want to use the MultipleLookupField control in a web page that will run in the context of SharePoint. I was wondering if anyone would help me with an example, which shows step by step how to use the control two display two SPField Collections.
A: I'm not entirely sure I understand your question, especially the bit about displaying two SPField collections. Sorry if this turns out to be the answer to a completely different question!
Anyway here's a quick demo walkthrough of using the MultipleLookupField in a web part.
Create a team site. Add a few tasks to the task list. Also put a document in the Shared Documents library. Create a new column in the Shared Documents library; call it "Related", have it be a Lookup into the Title field of the Tasks list, and allow multiple values.
Now create a web part, do all the usual boilerplate and then add this:
Label l;
MultipleLookupField mlf;
protected override void CreateChildControls()
{
base.CreateChildControls();
SPList list = SPContext.Current.Web.Lists["Shared Documents"];
if (list != null && list.Items.Count > 0)
{
LiteralControl lit = new LiteralControl("Associate tasks to " +
list.Items[0].Name);
this.Controls.Add(lit);
mlf = new MultipleLookupField();
mlf.ControlMode = SPControlMode.Edit;
mlf.FieldName = "Related";
mlf.ItemId = list.Items[0].ID;
mlf.ListId = list.ID;
mlf.ID = "Related";
this.Controls.Add(mlf);
Button b = new Button();
b.Text = "Change";
b.Click += new EventHandler(bClick);
this.Controls.Add(b);
l = new Label();
this.Controls.Add(l);
}
}
void bClick(object sender, EventArgs e)
{
l.Text = "";
foreach (SPFieldLookupValue val in (SPFieldLookupValueCollection)mlf.Value)
{
l.Text += val.LookupValue.ToString() + " ";
}
SPListItem listitem = mlf.List.Items[0];
listitem["Related"] = mlf.Value;
listitem.Update();
mlf.Value = listitem["Related"];
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
EnsureChildControls();
}
Granted, this is borderline ridiculous -- everything is hard-coded, there is no error-handling at all, and it serves no useful purpose -- but it's only meant as a quick demo. Now build and deploy this web part and add an instance of it to your team site's homepage; it should allow you to get and set the tasks which are associated with the first document in the library.
The strange bit towards the end of the button Click handler, where we read a value from mlf.Value and then write it back again, appears to be required if you want the UI to stay in sync with the actual list values. Try omitting the last line of bClick to see what I mean. This has been driving me nuts for the last hour or so, and I'm hoping another commenter can come up with a better approach...
A: Hm. Works fine on mine, so let's see if we can work out how your setup is different...
It looks as though it's having trouble populating the control; my first guess would be that this is because the code makes so many assumptions about the lists it's talking to. Can you check that you've got a plain vanilla Team site, with (assume these names are case-sensitive):
*
*A list called Tasks, with several items in it
*A library called Shared Documents with at least one document
*A column called Related in the Shared Documents library
*The Related column is a Lookup field into the Title column of Tasks, and allows multiple values.
*The first document in Shared Documents has a value for Related
Then add the webpart. Fingers crossed...
A: Hm. OK, I'm still trying to break mine... so I went to the layouts directory and created a file foo.aspx. Here it is:
<%@ Page Language="C#" Inherits="System.Web.UI.Page" MasterPageFile="~/_layouts/simple.master" %>
<%@ Register Tagprefix="foo" Namespace="Foople" Assembly="Foople, Version=1.0.0.0, Culture=neutral, PublicKeyToken=9f4da00116c38ec5"%>
<asp:Content ContentPlaceHolderId="PlaceHolderMain" runat="server">
<foo:WebPart1 id="fred" runat="server" />
<foo:WebPart1a id="barney" runat="server" />
</asp:Content>
WebPart1 is the webpart from before. WebPart1a is the exact same code, but in a class that inherits directly from WebControl rather than from WebPart.
It works fine, apart from a security validation problem on the postback that I can't be bothered to debug.
Changing the masterpage to ~masterurl/default.master, I uploaded foo.aspx to the Shared Documents library, and it works fine from there too -- both the WebControl and the WebPart behave properly, and the security problem is gone too.
So I'm at a loss. Although I did notice this page with an obscure might-be-bug which is also in SPFolder.get_ContentTypeOrder(): http://forums.msdn.microsoft.com/en-US/sharepointdevelopment/thread/63baf273-7f36-453e-8293-26417759e2e1/
Any chance you could post your code?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39910",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do I remove an item from a stl vector with a certain value? I was looking at the API documentation for stl vector, and noticed there was no method on the vector class that allowed the removal of an element with a certain value. This seems like a common operation, and it seems odd that there's no built in way to do this.
A: From c++20:
A non-member function introduced std::erase, which takes the vector and value to be removed as inputs.
ex:
std::vector<int> v = {90,80,70,60,50};
std::erase(v,50);
A: If you want to remove an item, the following will be a bit more efficient.
std::vector<int> v;
auto it = std::find(v.begin(), v.end(), 5);
if(it != v.end())
v.erase(it);
or you may avoid overhead of moving the items if the order does not matter to you:
std::vector<int> v;
auto it = std::find(v.begin(), v.end(), 5);
if (it != v.end()) {
using std::swap;
// swap the one to be removed with the last element
// and remove the item at the end of the container
// to prevent moving all items after '5' by one
swap(*it, v.back());
v.pop_back();
}
A: If you have an unsorted vector, then you can simply swap with the last vector element then resize().
With an ordered container, you'll be best off with std::vector::erase(). Note that there is a std::remove() defined in <algorithm>, but that doesn't actually do the erasing. (Read the documentation carefully).
A: The other answers cover how to do this well, but I thought I'd also point out that it's not really odd that this isn't in the vector API: it's inefficient, linear search through the vector for the value, followed by a bunch of copying to remove it.
If you're doing this operation intensively, it can be worth considering std::set instead for this reason.
A: See also std::remove_if to be able to use a predicate...
Here's the example from the link above:
vector<int> V;
V.push_back(1);
V.push_back(4);
V.push_back(2);
V.push_back(8);
V.push_back(5);
V.push_back(7);
copy(V.begin(), V.end(), ostream_iterator<int>(cout, " "));
// The output is "1 4 2 8 5 7"
vector<int>::iterator new_end =
remove_if(V.begin(), V.end(),
compose1(bind2nd(equal_to<int>(), 0),
bind2nd(modulus<int>(), 2)));
V.erase(new_end, V.end()); [1]
copy(V.begin(), V.end(), ostream_iterator<int>(cout, " "));
// The output is "1 5 7".
A: *
C++ community has heard your request :)
*
C++ 20 provides an easy way of doing it now.
It gets as simple as :
#include <vector>
...
vector<int> cnt{5, 0, 2, 8, 0, 7};
std::erase(cnt, 0);
You should check out std::erase and std::erase_if.
Not only will it remove all elements of the value (here '0'), it will do it in O(n) time complexity. Which is the very best you can get.
If your compiler does not support C++ 20, you should use erase-remove idiom:
#include <algorithm>
...
vec.erase(std::remove(vec.begin(), vec.end(), 0), vec.end());
A: A shorter solution (which doesn't force you to repeat the vector name 4 times) would be to use Boost:
#include <boost/range/algorithm_ext/erase.hpp>
// ...
boost::remove_erase(vec, int_to_remove);
See http://www.boost.org/doc/libs/1_64_0/libs/range/doc/html/range/reference/algorithms/new/remove_erase.html
A: std::remove does not actually erase elements from the container: it moves the elements to be removed to the end of the container, and returns the new end iterator which can be passed to container_type::erase to do the actual removal of the extra elements that are now at the end of the container:
std::vector<int> vec;
// .. put in some values ..
int int_to_remove = n;
vec.erase(std::remove(vec.begin(), vec.end(), int_to_remove), vec.end());
A: Use the global method std::remove with the begin and end iterator, and then use std::vector.erase to actually remove the elements.
Documentation links
std::remove http://www.cppreference.com/cppalgorithm/remove.html
std::vector.erase http://www.cppreference.com/cppvector/erase.html
std::vector<int> v;
v.push_back(1);
v.push_back(2);
//Vector should contain the elements 1, 2
//Find new end iterator
std::vector<int>::iterator newEnd = std::remove(v.begin(), v.end(), 1);
//Erase the "removed" elements.
v.erase(newEnd, v.end());
//Vector should now only contain 2
Thanks to Jim Buck for pointing out my error.
A: Two ways are there by which you can use to erase an item particularly.
lets take a vector
std :: vector < int > v;
v.push_back(10);
v.push_back(20);
v.push_back(30);
v.push_back(40);
v.push_back(40);
v.push_back(50);
1) Non efficient way : Although it seems to be quite efficient but it's not because erase function delets the elements and shifts all the elements towards left by 1.
so its complexity will be O(n^2)
std :: vector < int > :: iterator itr = v.begin();
int value = 40;
while ( itr != v.end() )
{
if(*itr == value)
{
v.erase(itr);
}
else
++itr;
}
2) Efficient way ( RECOMMENDED ) : It is also known as ERASE - REMOVE idioms .
*
*std::remove transforms the given range into a range with all the elements that compare not equal to given element shifted to the start of the container.
*So, actually don't remove the matched elements.
It just shifted the non matched to starting and gives an iterator to new valid end.
It just requires O(n) complexity.
output of the remove algorithm is :
10 20 30 50 40 50
as return type of remove is iterator to the new end of that range.
template <class ForwardIterator, class T>
ForwardIterator remove (ForwardIterator first, ForwardIterator last, const T& val);
Now use vector’s erase function to delete elements from the new end to old end of the vector. It requires O(1) time.
v.erase ( std :: remove (v.begin() , v.end() , element ) , v.end () );
so this method work in O(n)
A: Similar to the erase remove idiom, for vector one could use resize and remove and use iterator distance computation:
std::vector<int> vec;
// .. put in some values ..
int int_to_remove = n;
vec.resize(std::remove(vec.begin(), vec.end(), int_to_remove) - vec.begin());
Tested here.
A: If you want to do it without any extra includes:
vector<IComponent*> myComponents; //assume it has items in it already.
void RemoveComponent(IComponent* componentToRemove)
{
IComponent* juggler;
if (componentToRemove != NULL)
{
for (int currComponentIndex = 0; currComponentIndex < myComponents.size(); currComponentIndex++)
{
if (componentToRemove == myComponents[currComponentIndex])
{
//Since we don't care about order, swap with the last element, then delete it.
juggler = myComponents[currComponentIndex];
myComponents[currComponentIndex] = myComponents[myComponents.size() - 1];
myComponents[myComponents.size() - 1] = juggler;
//Remove it from memory and let the vector know too.
myComponents.pop_back();
delete juggler;
}
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39912",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "158"
} |
Q: How do I set windows to perform auto login? Windows has a feature that allows an administrator to perform auto-logon whenever it is started. How can this feature be activated?
A: Based on the advice, moved the answer to the answers section:
There are tools out there that give you a GUI for setting this easily, but you can also do it relatively easily by editing the registry.
Under the following registry key:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon
Add the following values:
*
*DefaultDomainName String < domain-name >
*DefaultUserName String < username >
*DefaultPassword String < password >
*AutoAdminLogon String 1
Important: Using auto-logon is insecure and should, in general, never be used for standard computer configurations. The problem is not only that your computer is accessible to anyone with physical access to it, but also that the password is saved in plain-text in a well known location in your registry. This is usually used for test environments or for special setups. This is even more important to notice if you intend to perform auto-logon as an administrator.
A: If you don't want to store the clear-text password in the registry, use this method:
*
*Start -> Run
*enter "control userpasswords2"
*disable checkbox "Users must enter a user name and password to use this computer"
*click "OK"
*enter a valid user name and password that is used for auto-logon
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39914",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Extra tables or non-specific foreign keys? There are several types of objects in a system, and each has it's own table in the database. A user should be able to comment on any of them. How would you design the comments table(s)? I can think of a few options:
*
*One comments table, with a FK column for each object type (ObjectAID, ObjectBID, etc)
*Several comments tables, one for each object type (ObjectAComments, ObjectBComments, etc)
*One generic FK (ParentObjectID) with another column to indicate the type ("ObjectA")
Which would you choose? Is there a better method I'm not thinking of?
A: Is it feasible to design the schema so that the commentable (for lack of a better word) tables follow one of the standard inheritance-modeling patterns? If so, you can have the comment table's FK point to the common parent table.
A: @palmsey
Pretty much, but the variation on that pattern that I've seen most often gets rid of ObjectAID et al. ParentID becomes both the PK and the FK to Parents. That gets you something like:
*
*Parents
*
*ParentID
*ObjectA
*
*ParentID (FK and PK)
*ColumnFromA NOT NULL
*ObjectB
*
*ParentID (FK and PK)
*ColumnFromB NOT NULL
Comments would remain the same. Then you just need to constrain ID generation so that you don't accidentally wind up with an ObjectA row and an ObjectB row that both point to the same Parents row; the easiest way to do that is to use the same sequence (or whatever) that you're using for Parents for ObjectA and ObjectB.
You also see a lot of schemas with something like:
*
*Parents
*
*ID
*SubclassDiscriminator
*ColumnFromA (nullable)
*ColumnFromB (nullable)
and Comments would remain unchanged. But now you can't enforce all of your business constraints (the subclasses' properties are all nullable) without writing triggers or doing it at a different layer.
A: @Hank Gay
So something like:
*
*ObjectA
*
*ObjectAID
*ParentID
*ObjectB
*
*ObjectBID
*ParentID
*Comments
*
*CommentID
*ParentID
*Parents
*
*ParentID
A: Be careful with generic foreign keys that don't point to exactly one table. Query performance suffers dramatically if you have to split the where condition on a type and point to several different tables. If you only have a few types, and the number of types will not grow, it's Ok to have separate nullable foreign keys to the different tables, but if you will have more types, it's better to come up with a different data model (like @palmsey's suggestion).
A: One of the things I like to do is have a separate tables that link the generic/common table to all of the individualized tables.
So, for objects Foo and Bar and then comments on Foo & Bar, you'd have something like this:
*
*Foo
*
*Foo ID (PK)
*Bar
*
*Bar ID (PK)
*Comment
*
*Comment ID (PK)
*Comment Text
*FooComment
*
*Foo ID (PK FK)
*Comment ID (PK FK)
*BarComment
*
*Bar ID (PK FK)
*Comment ID (PK FK)
This structure:
*
*Lets you have a common Comments table
*Doesn't require a DB with table inheritance
*Doesn't pollute the Foo and Bar tables with Comment-related information
*Lets you attach a Comment to multiple objects (which can be desireable)
*Lets you attach other properties to the junction of Foo/Bar and Comment if so desired.
*Still preserves the relations with standard (ie: fast, simple, reliable) foreign keys
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39915",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Programmatically building htpasswd Is there a programmatic way to build htpasswd files, without depending on OS specific functions (i.e. exec(), passthru())?
A: .httpasswd files are just text files with a specific format depending on the hash function specified. If you are using MD5 they look like this:
foo:$apr1$y1cXxW5l$3vapv2yyCXaYz8zGoXj241
That's the login, a colon, ,$apr1$, the salt and 1000 times md5 encoded as base64. If you select SHA1 they look like this:
foo:{SHA}BW6v589SIg3i3zaEW47RcMZ+I+M=
That's the login, a colon, the string {SHA} and the SHA1 hash encoded with base64.
If your language has an implementation of either MD5 or SHA1 and base64 you can just create the file like this:
<?php
$login = 'foo';
$pass = 'pass';
$hash = base64_encode(sha1($pass, true));
$contents = $login . ':{SHA}' . $hash;
file_put_contents('.htpasswd', $contents);
?>
Here's more information on the format:
http://httpd.apache.org/docs/2.2/misc/password_encryptions.html
A: Trac ships with a Python replacement for htpasswd, which I'm sure you could port to your language of choice: htpasswd.py.
A: From what it says on the PHP website, you can use crypt() in the following method:
<?php
// Set the password & username
$username = 'user';
$password = 'mypassword';
// Get the hash, letting the salt be automatically generated
$hash = crypt($password);
// write to a file
file_set_contents('.htpasswd', $username ':' . $contents);
?>
Part of this example can be found: http://ca3.php.net/crypt
This will of course overwrite the entire existing file, so you'll want to do some kind of concatination.
I'm not 100% sure this will work, but I'm pretty sure.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39916",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "22"
} |
Q: How to fix native client error 'Connection is busy with results for another command'? I'm getting a Connection Busy With Results From Another Command error from a SQLServer Native Client driver when a SSIS package is running. Only when talking to SQLServer 2000. A different part that talks to SQLServer 2005 seems to always run fine. Any thoughts?
A: Had this error today with MS ODBC Driver 11 for SQL Server for Linux to SQL Server connection. Wanted to help next searcher considering this was the first Google search result when I made the search.
You need to set MARS_Connection in /etc/odbc.ini as following:
[ConnName]
Driver=ODBC Driver 11 for SQL Server
Server=192.168.2.218,1433
Database=DBNameHere
MARS_Connection=yes
Speaking of MS ODBC Linux Driver: It is a complete PITA to deal with it but I insisted using native solution. I experienced too many walls especially working with ZF2, however, every trouble has a solution with the driver I can say. Just to encourage people using it instead quickly give up.
A: If somebody met this annoying bug while using PHP PDO with ODBC, then use closeCursor() method after query execution.
A: As I just found out, this can also happen on SQL 2005 if you do not have MARS enabled. I never even knew that it was disabled by default, but it is. And make sure you are using the
"NATIVE OLEDB\SQL Native Client" connection type. If you're using the "OLEDB.1" type connection (or whatever...) MARS is not even an option, and you get the SQL 2000 behavior, which is nasty.
You can enable MARS by opening the connection properties, and clicking "All", and scolling down in Management Studio.
I know your question has long since been answered, but I'm just throwing this in for the next sucker like me who gets burned by this.
A: Microsoft KB article 822668 is relevant here:
FIX: "Connection is busy with results for another command" error message occurs when you run a linked server query
Symptoms
Under stress conditions, you may receive the following error message when you perform linked server activity:
Server: Msg 7399, Level 16, State 1, Procedure <storedProcedureName>, Line 18 OLE DB provider 'SQLOLEDB' reported an error.
OLE/DB Provider 'SQLOLEDB' ::GetSchemaLock returned 0x80004005:
OLE DB provider SQLOLEDB supported the Schema Lock interface, but returned 0x80004005 for GetSchemaLock .].
OLE/DB provider returned message: Connection is busy with results for another command
OLE DB error trace [OLE/DB Provider 'SQLOLEDB' ::CreateSession returned 0x80004005.
Note The OLE DB source of the error may vary. However, all variations of the error message include the text "Connection is busy with results for another command".
Resolution
To resolve this problem, obtain the latest service pack for Microsoft SQL Server 2000.
As noted there, the problem was first corrected in SQL Server 2000 Service Pack 4.
This blog post by Mark Meyerovich, a Senior Software Engineer at RDA Corp, also provides some insight (now archived, because the original link went dead):
SQL Server service pack upgrade
A quick search on Google turns up the following article (http://support.microsoft.com/kb/822668):
FIX: "Connection is busy with results for another command" error message occurs when you run a linked server query.
It basically implies the issue is a bug and recommends an upgrade to Service Pack 4. We have started out with SQL Server 2000 SP3 and we do have some linked servers in the equation, so we give it a try. After the upgrade to SP4 – same result.
A: Just for information if somebody else have the problem. I tried connecting via NetCobol of Fujitsu on an SQLEXPRESS via ODBC with embedded sql and to solve the problem I had to change a value in the registry namely
\HKLM\Software\ODBC\ODBC.INI\MyDSN
with MyDSN as a string value:
Name - MARS_Connection
Value - Yes
I just put the information here if it can help.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39928",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: PGP signatures from Python? What is the easiest way to create and verify PGP/GPG signatures from within a Python application?
I can call pgp or gpg using subprocess and parse the output, but I was looking for a way that didn't require an external program to be installed (my application is cross-platform mac/windows/unix).
A: I think GPGME and the PyMe Python wrapper should do what you need.
A: In addition to PyMe, consider python-gnupg and the gnupginterface.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39929",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Coupling and cohesion I'm trying to boil down the concepts of coupling and cohesion to a concise definition. Can someone give me a short and understandable explanation (shorter than the definitions on Wikipedia here and here)? How do they interact?
Thanks.
Anybody have a good, short example?
A: Coupling - A measure of how much a module (package, class, method) relies on other modules. It is desirable to reduce coupling, or reduce the amount that a given module relies on the other modules of a system.
Cohesion - A measure of how closely related the members (classes, methods, functionality within a method) of a module are to the other members of the same module. It is desirable to increase cohesion as that indicates that a module has a very specific task and does only that task.
A: A quick-and-dirty way to measure coupling is to measure your import (or similar) statements.
A: Coupling means dependency on others.
Cohesion means completeness with itself.
A: One of the best comprehensive discussions of software design concepts related to OO (including these ones) is Bertrand Meyer's Object Oriented Software Construction.
Regarding 'coupling', he gives his Weak Coupling / Small Interfaces rule as follows:
If two modules communicate, they should exchange as little information as possible.
Meyer's material related to cohesion isn't ever boiled down to a single pithy statement, but I think this sentence from Steve McConnell's Code Complete sums it up pretty well:
Cohesion refers to how closely all the routines in a class or all the code in a routine support a central purpose
A: Coupling
*
*Loose: You and the guy at the convenience store. You communicate through a well-defined protocol to achieve your respective goals - you pay money, he lets you walk out with the bag of Cheetos. Either one of you can be replaced without disrupting the system.
*Tight: You and your wife.
Cohesion
*
*Low: The convenience store. You go there for everything from gas to milk to ATM banking. Products and services have little in common, and the convenience of having them all in one place may not be enough to offset the resulting increase in cost and decrease in quality.
*High: The cheese store. They sell cheese. Nothing else. Can't beat 'em when it comes to cheese though.
A: "Coupling is a measure of interdependencies between modules,
which should be minimized"
"cohesion, a quality to be maximized, focuses on the relationships
between the activities performed by each module."
quoted from this paper: http://steve.vinoski.net/pdf/IEEE-Old_Measures_for_New_Services.pdf
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39946",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "76"
} |
Q: Javascript equivalent of Python's locals()? In Python one can get a dictionary of all local and global variables in the current scope with the built-in functions locals() and globals(). Is there some equivalent way of doing this in Javascript? For instance, I would like to do something like the following:
var foo = function(){ alert('foo'); };
var bar = function(){ alert('bar'); };
var s = 'foo';
locals()[s](); // alerts 'foo'
Is this at all possible, or should I just be using a local object for the lookup?
A: Well, I don't think that there is something like that in js. You can always use eval instead of locals(). Like this:
eval(s+"()");
You just have to know that actually function foo exists.
Edit:
Don't use eval:) Use:
var functionName="myFunctionName";
window[functionName]();
A: I seem to remember Brendan Eich commented on this in a recent podcast; if i recall correctly, it's not being considered, as it adds unreasonable restrictions to optimization. He compared it to the arguments local in that, while useful for varargs, its very existence removes the ability to guess at what a function will touch just by looking at its definition.
BTW: i believe JS did have support for accessing locals through the arguments local at one time - a quick search shows this has been deprecated though.
A: *
*locals() - No.
*globals() - Yes.
window is a reference to the global scope, like globals() in python.
globals()["foo"]
is the same as:
window["foo"]
A: @e-bartek, I think that window[functionName] won't work if you in some closure, and the function name is local to that closure. For example:
function foo() {
var bar = function () {
alert('hello world');
};
var s = 'bar';
window[s](); // this won't work
}
In this case, s is 'bar', but the function 'bar' only exists inside the scope of the function 'foo'. It is not defined in the window scope.
Of course, this doesn't really answer the original question, I just wanted to chime in on this response. I don't believe there is a way to do what the original question asked.
A: @pkaeding
Yes, you're right. window[functionName]() doesn't work in this case, but eval does. If I needed something like this, I'd create my own object to keep those functions together.
var func = {};
func.bar = ...;
var s = "bar";
func[s]();
A: AFAIK, no. If you just want to check the existence of a given variable, you can do it by testing for it, something like this:
if (foo) foo();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39960",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "26"
} |
Q: How are tags made in Subversion? I know how to use tags in subversion. I create a tag every time I get to a release milestone.
What I don't quite understand is how they work.
Is a tag just a copy, made from what ever revision I specify? Or is a tag more like a reference, where internally subversion just says GO TO /trunk/project/ Revision 5 or whatever.
The command to create a tag (svn copy) seems to imply that it's a copy, but I've seen other people write that subversion doesn't really copy anything.
Say I dump just the HEAD revision of a repository. I don't care about any history except the tags. Are those tags dumped along with the rest of the Head revision?
Finally, is all this just programming magic that I don't really want to know.
A: The Subversion book is online in a complete and free form:
http://svnbook.red-bean.com/en/1.4/svn-book.html#svn.branchmerge.tags
And yes, you basically do an svn copy. Subversion is smart enough to do a copy-on-write style mechanism to save space and minimize transfer time.
A: Right, a tag is just a copy:
svn copy trunk tags/BLAH
When people say SVN doesn't really copy anything, they mean that the repository doesn't need to duplicate the data. It uses something akin to symbolic links to keep track of the copies.
A: The TortoiseSVN help explains it quite nicely:
Subversion does not have special commands for branching or tagging, but uses so-called “cheap copies” instead. Cheap copies are similar to hard links in Unix, which means that instead of making a complete copy in the repository, an internal link is created, pointing to a specific tree/revision. As a result branches and tags are very quick to create, and take up almost no extra space in the repository.
[...]
If you modify a working copy created from a branch and commit, then all changes go to the new branch and not the trunk. Only the modifications are stored. The rest remains a cheap copy.
A: Yes, a svn copy (whether you are thinking of it as a tag, a branch, or copying a file in trunk) is all the same. SVN will internally create a pointer to the source location at that revision. If you then make changes to the copy (which you are likely to do if it is a branch or a copied file in trunk, but shouldn't do for tags), SVN will only store what was changed, rather than creating a whole new copy.
A: A tag is a reference to the set of revision numbers at the time the tag was taken- it's the same thing as a branch or a copy, internally.
A: an example:
$ svn copy https://jorgesysgr.com/svn/AndNews/branches \
https://jorgesysgr.com/svn/AndNews/tags/release-1.1 \
-m "release 1.1 Android News."
More info:: Creating a Simple Tag
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39977",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: Security implications of multi-threaded javascript Reading through this question on multi-threaded javascript, I was wondering if there would be any security implications in allowing javascript to spawn mutliple threads. For example, would there be a risk of a malicious script repeatedly spawning thread after thread in an attempt to overwhelm the operating system or interpreter and trigger entrance into "undefined behavior land", or is it pretty much a non-issue? Any other ways in which an attack might exploit a hypothetical implementation of javascript that supports threads that a non-threading implementation would be immune to?
Update: Note that locking up a browser isn't the same as creating an undefined behavior exploit.
A: No, multiple threads would not add extra security problems in a perfect implementation. Threaded javascript would add complexity to the javascript interpreter which makes it more likely to have an exploitable bug. But threads alone are not going to add any security issues.
Threads are not present in javascript because "Threads Suck" - read more from the language designer (http://weblogs.mozillazine.org/roadmap/archives/2007/02/threads_suck.html)
A: Well, you can already lock up a browser and seriously slow down a system with badly-behaved JS. Enlightened browsers have implemented checks for this sort of thing, and will stop it before it gets out of hand.
I would tend to assume that threads would be dealt with in a similar manner.
Perhaps you could explain what you mean by "undefined behavior" then? An interpreter that allowed untrusted script to directly control the number of OS-native threads being run would be incredibly naive - i don't know how Gears runs things, but since the API is centered around Workers in WorkerPools, i would be very surprised if they aren't limiting the total number of native threads in use to some very low number.
A: Well I think that the only major example of multi-threaded javascript is Google's chrome (WOULD THEY RELEASE IT ALREADY JEEZ) and if I understand it the javascript will only one process per tab, so unless it started spawning tabs (popups) I would assume this would be a null issue, but I think that Google has that under wraps anyway, the are running all the javascript in a sandbox.
A: Again, we need to make a distinction between 1) multithreaded support in the language (which I don't think is seriously being discussed as something that will happen) and 2) usage of multiple threads in the JavaScript engine/interpreter in the browser.
For #2, I can't see how this can really add any possible security concerns to the engine/interpreter, unless there are flaws in the implementation.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39983",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Improving performance with OPC tags I am working with a PC based automation software package called Think'n'Do created by Phoenix Contact It does real time processing, read inputs/ control logic / write outputs all done in a maximum of 50ms. We have an OPC server that is reading/writing tags from a PLC every 10ms. There is a long delay in writing a tag to the PLC and reading back the written value (Think'n'Do (50ms) > OPC Server (10ms) > PLC (10ms) > OPC Server (10ms) > Think'n'Do (50ms) ) that process takes up to 6 seconds to complete when it should by my math only take 130ms.
Any ideas of where to look or why it might be taking so much longer would be helpful.
A: It depends on how you have your OPC client configured to pull data. When you subscribe to a group in OPC, you get to specify a refresh rate. This might default to 1s or even 5s, depending on the OPC client. There's also a limit the OPC server might put on the frequency of updated data. This only applies if you have your OPC client subscribing to data change events.
The other way you can go is to do async or sync reads / writes to the OPC server. There are several reading modes as well. Since you are using OPC, you can use any OPC compatible client to test your server, this will tell you if the problem is with a setting in Think'n'Do or is it something with the PLC / server.
The best general purpose OPC client I've used is OPC Quick Client. You can get it with TOP Server here: http://www.toolboxopc.com/Features/Demo/demo.shtml. Just grab the TOP Server demo and install the OPC Quick Client. You can use it to connect to your OPC server and browse the tags and see what the data looks like. The second best OPC client I've used is from ICONICS (called OPC Data Spy) available here: http://www.iconics.com/support/free_tools.asp.
Use the OPC client to see how fast you can read the data. Make sure you set the group refresh rate correctly. I think the tools might provide some timing information for you as well (but you'll be able to figure out a 6 second delay pretty easily).
A: It sounds as if you are not using the cache in the OPC server. Normally OPC servers have a cache, if your client connects and doesn't specify that it wants to use the cache you don't get the performance that you may need. The OPC server is responsible for refreshing the cache from the device although the criteria for refreshing may differ from OPC server to OPC server.
A: If the system does syncronous reads (blocking I/O call), then implements the logic of your application then syncronous writes (again blocking) then you need to consider that there are multiple round-trips to the PLC.
A syncronous read involves App(request)->OPCServer->PLC->OPCServer->App(result). That is just the read for one item (although you can ask for a group of items in one go).
Then a similar sync write also involves App(Write)->OPCServer->PLC->OPCServer->App(Done).
Asyncronous reads & writes and group reads & writes can help reduce blocking of the application, but be careful that your aplication can cope with this ansyncronous behavior
The other thing to look at is the PLC configuration, On Allen-Bradley PLC's there is an interscan delay setting that is used to service I/O requests over external networks. If that time is short and you have a high bandwidth of data then this will slow things down.
A: Here are a few places to look: OPC Client configuration, OPC Client itself, OPC Server, or the PLC itself.
Here are things you should check:
*
*OPC Client configuration - The OPC Group you've added the OPC tags to should have a fast scan rate (ie. 100 ms to 1 sec depending on what you use it for). With the act of writing values, do you notice if the values come in faster? If not, then there might be a DCOM or network configuration issue.
*OPC Client - Download a free OPC Client software(probably from the OPC Foundation website or major OPC Server software vendors) to see if you get the values back faster. If so, there might be a problem with your client.
*OPC Server - Some OPC Server have diagnostic tools. Turn those on and see what is the time the writes actually occur and what time the reads actually take place. If you can answer those questions, you can probably identify whether the culprit of the delay is from the PLC or the OPC Server. Also observe the CPU usage of the OPC Server, if you notice it is using more CPU than normal, it probably means that the OPC Server is loaded down which might deteriorate performance.
*Others - Finally check PLC, network are working properly.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39996",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Create new page in Webtop How do I create a new webpage in the Documentum front end Webtop?
A: The short answer is that it can not be done.
WebTop is Documentum's generic application for browsing their back-end content repository. Think of it as a web-based Windows Explorer on steroids. It's a tool for storing, versioning, and sharing electronic documents (Word, Excel, etc.) - it's not a tool for creating web pages.
Documentum's Web Content Management product is called Web Publisher. It is the tool that companies use to allow non-technical business users to create and edit web pages.
A: Why WebTop? You should use Web Publisher which is built on WebTop with the specific purpose of managing web content. Is this an OOTB installation? Web Publisher / WebTop requires significant amount of customization in order to start being useful. Do you have templates defined? If so, then just go to File New and select your template.
http://www.dmdeveloper.com/ Is a good site with some very good how-to's.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40021",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Best way to update LINQ to SQL classes after database schema change I'm using LINQ to SQL classes in a project where the database design is still in a bit of flux.
Is there an easy way of synchronising the classes with the schema, or do I need to manually update the classes if a table design changes?
A: Here is an easy fix without any additional software, that just works for simple changes (like added fields, few tables, etc).
Instructions:
*
*You pull a copy of the changed table into the designer (will be removed later)
*Now select all the new (or changed) fields and (right-click ->) copy
*In your original table right click and insert them (delete changed fields first)
*Now delete the table you copied them from
I know it is kinda obvious, but somehow non-intuitive, and it helped me a lot, since all the right attributes and types will be copied, and all links stay intact. Hope it helps.
When to use:
Of course it is - as said - for small changes, but surely better than manually replacing tables with many links, or when you don't want your whole database structure generated by SQLMetal. For example when you have a big amount of tables (e.g. SAP), or when using cross-linked tables from different databases.
A: You can use SQLMetal.exe to generate your dbml and or cs/vb file. Use a pre-build script to start it and target the directory where your datacontext project belongs.
C:\Program Files\Microsoft SDKs\Windows\v6.0A\Bin\x64\sqlmetal.exe
/server:<SERVER>
/database:<database>
/code:"path\Solution\DataContextProject\dbContext.cs"
/language:csharp
/namespace:<your namespace>
A: DamienG has written some t4 templates which can replace some of what VS generates for you. These can be rerun whenever you like via a command line tool.
T4 templates have the added benefit of being editable. This allows you to tweak what is generated to you hearts content.
A: I think Jeff complained about this recently. One common technique is to drag all the objects into the designer again...
I hope someone else chimes in with a better approach!
A: I haven't tried it myself, but Huagati DBML/EDMX Tools is recommended by other people.
Huagati DBML/EDMX Tools is an add-in
for Visual Studio that adds
functionality to the Linq2SQL/DBML
diagram designer in Visual Studio
2008, and to the ADO.NET Entity
Framework designer in Visual Studio
2008 SP1. The add-in adds new menu
options for updating Linq2SQL designer
diagrams with database changes, for
renaming Linq-to-SQL (DBML) and EF
(EDMX) classes and properties to use
.net naming conventions, and for
adding documentation/descriptions to
Linq-to-SQL generated classes from the
database properties.
A: I wrote a tool to do script changes to Dbml scripts see http://code.google.com/p/linqtodbmlrunner/ and my blog http://www.adverseconditionals.com
A: How about modifying the Properties of the entity/table within the DataContext design surface within Visual Studio?
For instance if I added a column to an SQL Server table:
*
*Open the *.dbml file.
*Right click the entity and select Add > Property.
*Fill out the values in the Properties window for the new column.
*Build your solution.
The auto generated model classes should reflect the new column that was added.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40022",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "76"
} |
Q: Can the same Adobe AIR app run more than once? As the title says, is there a way to run the same Adobe AIR app more than once? I have a little widget I wrote that shows thumbnails from a couple of photo streams, and I'd like to fix it so I can look at more than one stream at a time. Thanks!
A: It seems that this is not possible. From the documentation:
Only one instance of an AIR application is started. When an already running application is invoked again, AIR dispatches a new invoke event to the running instance.
It also gives a possible workaround:
It is the responsibility of an AIR to respond to an invoke event and take the appropriate action (such as opening a new document window).
There is already a bug related to this on the bugtracker, but it is marked closed with no explicit resolution given...
A: No, it can't. AIR only allows one running instance of any app with the same ID defined in the app.xml file.
<application xmlns="http://ns.adobe.com/air/application/1.0">
<id>ApplicationID</id>
To work around this you'll either have to create individually ID'd apps for each stream, or create a master app with child windows for each stream.
A: No. AIR applications can only have one instance running at a time. If you need multiple apps running, the solution is to instantiate one app, with the app view in a separate native window (one for each "app instance").
The reason it is marked closed is because it is not considered a bug, ut rather a design / implimentation choice made by the air team.
Hope that helps...
mike chambers
[email protected]
A: I have written a utility that will allow you to copy an existing AIR application and run multiple copies side by side. Each copy will have its own working directories, so the settings and stored data should be independent.
You can download the application and source code from GitHub: https://github.com/chrisdeely/AirAppDuplicator
Contact me on Twitter @chrisdeely with any questions
A: You can create a copy of the app in a different folder, then change the <id> element in the application.xml
For instance, if the first application has:
<id>ApplicationID</id>
You can alter the second instance to say:
<id>ApplicationID2</id>
A: Last time I checked, an AIR app can only run a single instance. You could open multiple windows, but your app itself would have to support that. I hope they change this soon.
A: There are good reasons for this design, although it requires application developers to follow proper OOP techniques... In OS X, you can't have multiple instances of an app open. Instead, all applications are expected to handle multiple documents properly. This is very nice from the user's perspective, even if it means more work for developers.
A: Yes it can, but the context is on different logged in user, so it may not be the answer to your problem. So the same AIR app can run two or more instances, each on different logged in user.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40026",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to find a normal vector pointing directly from virtual world to screen in Java3D? I think it can be done by applying the transformation matrix of the scenegraph to z-normal (0, 0, 1), but it doesn't work. My code goes like this:
Vector3f toScreenVector = new Vector3f(0, 0, 1);
Transform3D t3d = new Transform3D();
tg.getTransform(t3d); //tg is Transform Group of all objects in a scene
t3d.transform(toScreenVector);
Then I tried something like this too:
Point3d eyePos = new Point3d();
Point3d mousePos = new Point3d();
canvas.getCenterEyeInImagePlate(eyePos);
canvas.getPixelLocationInImagePlate(new Point2d(Main.WIDTH/2, Main.HEIGHT/2), mousePos); //Main is the class for main window.
Transform3D motion = new Transform3D();
canvas.getImagePlateToVworld(motion);
motion.transform(eyePos);
motion.transform(mousePos);
Vector3d toScreenVector = new Vector3f(eyePos);
toScreenVector.sub(mousePos);
toScreenVector.normalize();
But still this doesn't work correctly. I think there must be an easy way to create such vector. Do you know what's wrong with my code or better way to do so?
A: If I get this right, you want a vector that is normal to the screen plane, but in world coordinates?
In that case you want to INVERT the transformation from World -> Screen and do Screen -> World of (0,0,-1) or (0,0,1) depending on which axis the screen points down.
Since the ModelView matrix is just a rotation matrix (ignoring the homogeneous transformation part), you can simply pull this out by taking the transpose of the rotational part, or simple reading in the bottom row - as this transposes onto the Z coordinate column under transposition.
A: Yes, you got my question right. Sorry that I was a little bit confused yesterday. Now I have corrected the code by following your suggestion and mixing two pieces of code in the question together:
Vector3f toScreenVector = new Vector3f(0, 0, 1);
Transform3D t3d = new Transform3D();
canvas.getImagePlateToVworld(t3d);
t3d.transform(toScreenVector);
tg.getTransform(t3d); //tg is Transform Group of all objects in a scene
t3d.transform(toScreenVector);
Thank you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40028",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Mobile devices for developers I need to develop some programs for mobile devices but haven't decided the platform to build upon. I'm looking for Palm or Pocket PC devices that have Touch screen and Wi-Fi connection and are cheep because I'll need to buy several of them.
I don't really need camera, mp3 players, video players, pdf readers or anything else since the apps are going to be simple data collection to feed via wireless to a server database.
I'm proficient with C and C#. I could learn Java if I had to.
What devices do you recommend? Linux devices maybe?
PS: Changed the title because I don't want a flamewar between platforms. Please, don't answer with Windows Mobile sucks/rules. I'm looking for devices instead.
Thanks
A: Windows Mobile
It supports C#, and Visual Studio comes with the mobile SDK. So if you know C# you probably already have the tools you need. And in spite of the iPhone/iPodTouch buzz, the Windows Mobile deployment is still 10X greater.
A: In order of preference
*
*Neo Freerunner
*Maemo & the N800 (cheap)
*Beagleboard
A: If you are comfortable with Visual Studio then programming for windows mobile is extremely easy. The SDK for mobile comes with emulators for all the latest and popular versions of windows mobile- and you can even debug on teh device itself using a USB cable.
On windows mobile you have a choice: Develop a .Net application or develop native (likely MFC based). Either one gives you a great development environment.
As far as iPhone development goes- you would need an apple computer to install and use iPhone SDK- and you can't run an iPhone app on your phone. You would have to go through the process of getting it registered with iTunes for you to install your own apps on your own phone!
When I first started playing with mobile development I had a few questions:
*
*Can I develop using my favorite IDE- Visual Studio. Will it be as easy as developing a desktop app: yes.
*Will I be able to access the internet from my application without 'unlocking' or in some other way enabling the phone that was not intended by the service provider? yes.
*Will I be able to access device specific functionality such as GPS easily? Is there good support for doing so within the API? Yes.
A: You should probably target the Windows Mobile platform. The Palm platform is rather archaic and no longer widely used. The development environment is also rather spartan, while Microsoft has full IDEs available for Windows Mobile development. You might also consider the iPhone/iPod touch platform - I have a feeling the number of devices will multiply at an exponential rate and I've heard that developing applications is much easier due to the completeness of the system stack.
A: You should probably at least evaluate the Apple iPod Touch. It certainly meets your basic "touch screen + WiFi" spec, and your users presumably won't object to all the the other nice features that will come along for the ride.
I don't know what your cutoff for "cheap" is, but $299 for the base model seems pretty reasonable for a high-quality touch screen and WiFi in a pocketable device.
A: Windows Mobile and CE used to suck, really, really badly. These days however it's definitely passable and worth checking out, especially if you code C#.
Just remember that it is the baby brother of the full framework and has nowhere near enough toys and throws a lot of NotImplementedExceptions. :)
A: Blackberry publishes its SDK on its web site. Its apps run J2ME, so with some Java experience it shouldn't be too difficult to get started. They also give you an emulator. Disclaimer: I have no experience in writing Blackberry apps, but I looked into it once.
I would not recommend a PalmOS based handset. I have written code for PalmOS and it's about as painful as writing raw Win32 code in C. Since Palm has switched its high end handsets to Windows Mobile, PalmOS will just remain stagnant and only run on the slower, less capable hardware.
If I were to write a mobile app, I'd agree that Windows Mobile is worth checking out.
A: It all depends on the users who you are targeting at, If you are looking for a wide market then you should be fine with J2ME/Blackberry . However most of them lack the touchscreen and wifi features ( The HTC range of phones [WIFI/TouchScreen/Windows Mobile] have a JVM built with it),so it would work on most of the Windows devices also.
If you are making a more niche product, moving with the current buzz 'iphone' will be good . Windows Mobile is also worth checking out
A: The best option here would be the Neo Freerunner, with that device you can build a dedicated unit were every aspect is made especially for you're needs. The Freerunner is WiFi enabled, and has a touch interface. If you use the Qt SDK, a lot of the work is already done for you. It comes complete with emulator, as a Live linux cd. You can run in a WM, such as wmplayer. Everything is included.
I'm not gonna lie, it will take tweaking. But the final product would be really nice and intuitive.
A: Looking at Windows Mobile devices, your requirement of touchscreen pretty much sets your pricing at the higher end of the spectrum. You'll get those things you say you don't need just because of that.
Here's expansys's selection of touchscreens.
Mobdeal is a handy one too as that effectively filters all phones by features.
I've developed against the HTC TYTN 2, HTC Touch Diamond and randomly a PSION Teklogix Ikon
There's generally very little difference between these models, some manufacturers have SDKs that can help sometimes.
I think your cheapest option will probably be something like getting HTC TYTN 2s on ebay. They're pretty old now (hence cheap) but have Wifi, camera, touchscreen, qwerty keypad all the things you seem to be after.
A: you can target iPhone "touch" platform with Apple's iPhone SDK. the development environment requires a Mac, but you can get the entire IDE + tool chain + excellent debugging and profiling tools for free. And the free documentation is top notch.
As a registered iPhone developer, it is free (no cost) to target the simulator, which is sufficient for most learning and development you'll likely need to up front.
To target the actual hardware device (and up to and including release/selling your app on the Apple's AppStore) is only $99/yr. If you got an iPod Touch for your hardware target, most of the SDK applies and you are not tied into a service contract for an iPhone.
iPhone app development environment is in Objective-C, but it is a really productive, object-oriented environment so do not concerned that that may be a language you are unfamiliar with.
If you decide that your mobile app(s) would be better suited as webapps, the iPhone/iPod touch platform again is an industry leader in this space, and you have the additional benefit or being able to target other mobile platforms (and not necessarily be tied to one mobile SDK).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40032",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How do I read and write raw ip packets from java on a mac? What would be the easiest way to be able to send and receive raw network packets. Do I have to write my own JNI wrapping of some c API, and in that case what API am I looking for?
EDIT: I want to be able to do what wireshark does, i.e. record all incomming packets on an interface, and in addition be able to send back my own created packets. And I want to do it on a mac.
A: If you start with the idea that you need something like a packet sniffer, you'll want to look at http://netresearch.ics.uci.edu/kfujii/jpcap/doc/.
A: Raw Socket for Java is a request for JDK for a looong long time. See the request here. There's a long discussion there where you can look for workarounds and solutions. I once needed this for a simple PING operation, but I can't remember how I resolved this. Sorry :)
A: My best bet so far seems to be the BPF api and to write a thin JNI wrapper
A: TINI is a java ethernet controller, which may have libraries and classes for directly accessing data from ethernet frames to TCP streams. You may be able to find something in there that implements your needed classes. If not, there should be pointers or user groups that will give you a head start.
A: You can't access raw sockets from pure Java, so you will need some sort of layer between your Java code and the network interfaces.
Also note that access to raw sockets is normally only available to "root" processes, since otherwise any user could both a) sniff all traffic, and b) generate spoofed packets.
Rather than write your whole program so that it needs to run as "root", you might consider having the packet capture and generation done in a standalone program with some sort of IPC (RMI, named pipe, TCP socket, etc) to exchange the data with your Java app.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40039",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How do I create a database programmatically in SQL Server? How can I create a new database from my C# application?
I'm assuming once I create it, I can simply generate a connection string on the fly and connect to it, and the issue all the CREATE TABLE statements.
A: KB307283 explains how to create a database using ADO.NET.
From the article:
String str;
SqlConnection myConn = new SqlConnection ("Server=localhost;Integrated security=SSPI;database=master");
str = "CREATE DATABASE MyDatabase ON PRIMARY " +
"(NAME = MyDatabase_Data, " +
"FILENAME = 'C:\\MyDatabaseData.mdf', " +
"SIZE = 2MB, MAXSIZE = 10MB, FILEGROWTH = 10%) " +
"LOG ON (NAME = MyDatabase_Log, " +
"FILENAME = 'C:\\MyDatabaseLog.ldf', " +
"SIZE = 1MB, " +
"MAXSIZE = 5MB, " +
"FILEGROWTH = 10%)";
SqlCommand myCommand = new SqlCommand(str, myConn);
try
{
myConn.Open();
myCommand.ExecuteNonQuery();
MessageBox.Show("DataBase is Created Successfully", "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (System.Exception ex)
{
MessageBox.Show(ex.ToString(), "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
finally
{
if (myConn.State == ConnectionState.Open)
{
myConn.Close();
}
}
A: CREATE DATABASE works
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40043",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: How can I update in Linq an entity that is disconnected from database? Code below does not run correctly and throws InvalidOperationExcepiton.
public void Foo()
{
DataContext context = new DataContext();
LinqEntity item = new LinqEntity(){ Id = 1, Name = "John", Surname = "Doe"} ;
context.LinqEntities.Attach(item, true);
}
A: By default, the entities will use all fields for checking concurrency when making edits. That's what's throwing the InvalidOperationException.
This can be setting the Update Check property for all fields to Never. This must be done on all fields to attach the entity as modified. If this is done, an additional call to context.SubmitChanges() will save the data.
Alternatively, if you know the original values, you can attach and then make the updates, but all values that are being checked must match the original values.
LinqEntity item = new LinqEntity(){ Id = 1, Name = "OldName", Surname = "OldSurname"};
context.LinqEntities.Attach(item);
item.Name = "John";
item.Surname = "Doe";
context.SubmitChanges();
A: I'm not sure what you mean by disconnected from the database.
It appears that you are trying to insert a new row into the LinqEntities table -- is that correct?
If that is the case you'll want to do
context.LinqEntities.InsertOnSubmit(item);
context.Submit();
A: OK, if you're trying to update a row with ID = 1, you'll do it like this:
DataContext context = new DataContext();
LinqEntity item = (from le in context.LinqEntities
where le.ID == 1
select le).Single();
item.Name = "John";
item.Surname = "Doe";
context.Submit();
You could also replace the Linq expression with a more concise lambda:
LinqEntity item = context.LinqEntities.Single(le => le.ID == 1);
The most important thing the DataContext does is track any changes you make, so that when you call the Submit method it will autogenerate the Insert statements for the things you've changed.
A: When using an ORM you typically select an object before updating it.
You can use DataContext.ExecuteCommand(...) to bypass the ORM if you do not want to do a select.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40054",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Generic Map/Reduce List Extensions in C# I am writing a few extensions to mimic the map and reduce functions in Lisp.
public delegate R ReduceFunction<T,R>(T t, R previous);
public delegate void TransformFunction<T>(T t, params object[] args);
public static R Reduce<T,R>(this List<T> list, ReduceFunction<T,R> r, R initial)
{
var aggregate = initial;
foreach(var t in list)
aggregate = r(t,aggregate);
return aggregate;
}
public static void Transform<T>(this List<T> list, TransformFunction<T> f, params object [] args)
{
foreach(var t in list)
f(t,args);
}
The transform function will cut down on cruft like:
foreach(var t in list)
if(conditions && moreconditions)
//do work etc
Does this make sense? Could it be better?
A: According to this link Functional Programming in C# 3.0: How Map/Reduce/Filter can Rock your World the following are the equivalent in C# under the System.Linq namespace:
*
*map --> Enumerable.Select
*reduce --> Enumerable.Aggregate
*filter --> Enumerable.Where
A: These look very similar to extensions in Linq already:
//takes a function that matches the Func<T,R> delegate
listInstance.Aggregate(
startingValue,
(x, y) => /* aggregate two subsequent values */ );
//takes a function that matches the Action<T> delegate
listInstance.ForEach(
x => /* do something with x */);
Why is the 2nd example called Transform? Do you intend to change the values in the list somehow? If that's the case you may be better off using ConvertAll<T> or Select<T>.
A: I would use the built in Func delegates instead. This same code would work on any IEnumerable. Your code would turn into:
public static R Reduce<T,R>(this IEnumerable<T> list, Func<T,R> r, R initial)
{
var aggregate = initial;
foreach(var t in list)
aggregate = r(t,aggregate);
return aggregate;
}
public static void Transform<T>(this IEnumerable<T> list, Func<T> f)
{
foreach(var t in list)
f(t);
}
A: You might want to add a way to do a map but return a new list, instead of working on the list passed in (and returning the list can prove useful to chain other operations)... perhaps an overloaded version with a boolean that indicates if you want to return a new list or not, as such:
public static List<T> Transform<T>(this List<T> list, TransformFunction<T> f,
params object [] args)
{
return Transform(list, f, false, args);
}
public static List<T> Transform<T>(this List<T> list, TransformFunction<T> f,
bool create, params object [] args)
{
// Add code to create if create is true (sorry,
// too lazy to actually code this up)
foreach(var t in list)
f(t,args);
return list;
}
A: I would recommend to create extension methods that internally use LinQ like this:
public static IEnumerable<R> Map<T, R>(this IEnumerable<T> self, Func<T, R> selector) {
return self.Select(selector);
}
public static T Reduce<T>(this IEnumerable<T> self, Func<T, T, T> func) {
return self.Aggregate(func);
}
public static IEnumerable<T> Filter<T>(this IEnumerable<T> self, Func<T, bool> predicate) {
return self.Where(predicate);
}
Here some example usages:
IEnumerable<string> myStrings = new List<string>() { "1", "2", "3", "4", "5" };
IEnumerable<int> convertedToInts = myStrings.Map(s => int.Parse(s));
IEnumerable<int> filteredInts = convertedToInts.Filter(i => i <= 3); // Keep 1,2,3
int sumOfAllInts = filteredInts.Reduce((sum, i) => sum + i); // Sum up all ints
Assert.Equal(6, sumOfAllInts); // 1+2+3 is 6
(See https://github.com/cs-util-com/cscore#ienumerable-extensions for more examples)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40075",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "28"
} |
Q: Is overloading the only way to have default function arguments in C#? Is it true that the only way to handle default function arguments is through function overloading?
For example, in PHP I can do this:
function foo($x, $y=0)
{
}
Would the best way to handle it in C# be this?
void foo(int x)
{
foo(x, 0);
}
void foo(int x, int y)
{
}
Example lifted from here
Edit
Made the C# example into actual C# (Thanks Blair Conrad)
A: Yes, that'd be best, except you'd omit the $s on the parameter names, as others have pointed out. For those interested in the rationale behind the lack of default parameter values, see @Giovanni Galbo's explanation.
A: Regarding the excerpt from the c# faq:
Most of the problems listed there were solved for VB.Net (specifically the intellisense and xml comments issues), meaning they're really red herrings-- there is code available to the C# team that will solve the problem.
Another reason has to do with forcing a user of a class to re-compile, but that's a bit of a red herring, too. If you change a default value in your framework class and the user does not have to recompile, you risk the user not knowing that the default value changed. Now you have a potential bug in the code that doesn't show up until runtime. In other words, the alternative of overloading the function is at least as bad. Of course, this also presumes a specific implementation of the feature, but it's the implementation suggested in the faq.
Therefore you have to weigh the remaining reason ("try to limit the magic") vs the fact (which they acknowledge) that writing the overloads is "a bit less convenient". Personally, I say put the feature in, and let the programmer decide whether or not to use it.
A: Just to satisfy some curiosity:
From Why doesn't C# support default parameters?:
In languages such as C++, a default value can be included as part of the method declaration:
void Process(Employee employee, bool bonus = false)
This method can be called either with:
a.Process(employee, true);
or
a.Process(employee);
in the second case, the parameter bonus is set to false.
C# doesn't have this feature.
One reason we don't have this feature is related to a specific implementation of the feature. In the C++ world, when the user writes:
a.Process(employee);
the compiler generates
a.process(employee, false);
In other words, the compiler takes the default value that is specified in the method prototype and puts it into the method call - it's just as if the user wrote 'false' as the second parameter. There's no way to change that default value without forcing the user of the class to recompile, which is unfortunate.
The overloading model works better in this respect. The framework author just defines two separate methods, and the single-parameter one calls the two-parameter method. This keeps the default value in the framework, where it can be modified if necessary.
It would be possible for a compiler to take something like the C++ definition and produce the overloads, but there are a few issues with that approach.
The first one is that the correlation between the code that the user writes and the code the compiler generates is less obvious. We generally try to limit magic when possible, as it makes it harder for programmers. The second issue has to do with things like XML doc comments and intellisense. The compiler would have to have special rules for how it generates doc comments for the overloaded methods, and intellisense would need to have smarts to collapse the overloaded methods into a single method.
Writing overloads yourself is a bit less convenient, but we think it's an acceptable solution.
A: Default arguments are part of C++, but as of C# 3.5 default arguments are still not supported-- you'll have to overload. They've been available in VB.Net since 1.0.
A: Yes.
Or currying.
Or abstracting into a class and using default values there.
A: No, AFAIK C# does not support overriding, and yes, that is the recommended way of accomplishing the same effect.
A: doe this not do the job?
void foo(int x):this(x, 0){}
void foo(int x, int y){
// code here
}
A: As pointed out, this isn't currently available in C# however they will be present within C# 4.0 as Sam Ng discusses on his blog:
http://blogs.msdn.com/samng/archive/2009/02/03/named-arguments-optional-arguments-and-default-values.aspx
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40090",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Using attributes to cut down on enum to enum mapping and enum/const to action switch statments I imagine everyone has seen code like:
public void Server2ClientEnumConvert( ServerEnum server)
{
switch(server)
{
case ServerEnum.One:
return ClientEnum.ABC
//And so on.
Instead of this badness we could do somthing like:
public enum ServerEnum
{
[Enum2Enum(ClientEnum.ABC)]
One,
}
Now we can use reflection to rip through ServerEnum and get the conversion mappings from the enum declaration itself.
The problem I am having here is in the declaration of the Enum2Enum attribute.
This works but replacing object o with Enum e does not. I do not want to be able to pass in objects to the constructor, only other enums.
public class EnumToEnumAttribute : Attribute
{
public EnumToEnumAttribute(object o){}
}
This fails to compile.
public class EnumToEnumAttribute : Attribute
{
public EnumToEnumAttribute(Enum e){}
}
Is there a reason for the compile error? How else could I pass in the information needed to map besides:
EnumtoEnumAttribute(Type dest, string enumString)
This seems too verbose but if it is the only way then I guess I will use it.
A: Using almost the same example, you can achieve this directly in the enum:
public enum ServerEnum
{
One = ClientEnum.ABC,
}
This has the benefit of not requiring Reflection, is easier to read (in my opinion), and overall requires less overhead.
A: I would probably use struct as the type, and then throw an exception if it isn't an Enum type. I don't see how your (Type, string) option is any safer than using object or struct.
A: Here are the rules for the types that can be included as Attribute parameters:
A:
@Danial Jennings I read through the rules there and found: "An enum type, provided it has public accessibility and the types in which it is nested (if any) also have public accessibility (Section 17.2).".
How does trying for Enum e in the constructor fail based on the quoted rule? Is it because being of type enum does not guarantee that the enums passed in are publicly visibly? This seems right. Is there a way for force this rule at compile time?
@ bdukes You are exactly correct. I should have thought about that more.
It looks like run time type checking is my only option to make sure I am only mapping enums to other enums.
A: Why not use a Dictionary? This could be a static property of your class, initialized with those fancy schmancy object initializers we got in 3.0? You would not be typing more code (the mapping has to be done even with the Attribute sollution).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40107",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Is there a way to get ms-access to display images from external files I've got an MS-Access app (1/10th MS-Acccess, 9/10ths MS-SQL) that needs to display photographs of some assets along with their specifications. Currently the images are stored in an MS-Access table as an OLE Object (and copy-n-pasted into the field by the users).
For various reasons, I would like to do is store the original .jpgs in a folder on the network drive, and reference them from the application portion. I have considered moving into MS-SQL's image data type (and its replacement varbinary), but I think my user population will more easily grasp the concept of the network folder.
How can I get MS Access to display the contents of a .jpg?
A: Another option is to put an image control on your form. There is a property of that control (Picture) that is simply the path to the image. Here is a short example in VBA of how you might use it.
txtPhoto would be a text box bound to the database field with the path to the image
imgPicture is the image control
The example is a click event for a button that would advance to the next record.
Private Sub cmdNextClick()
DoCmd.GoToRecord , , acNext
txtPhoto.SetFocus
imgPicture.Picture = txtPhoto.Text
Exit Sub
End Sub
A: Have you looked at Stephen Lebans' solutions? Here's one:
Image Class Module for Access
Check out the list of other great code along the left-hand side of that web page. You may find something that fully matches what you need.
A: I found that this article by Microsoft with full VBA worked very well for me.
How to display images from a folder in a form, a report, or a data access page
A: The easiest way is probably to plop an Internet Explorer onto one of your forms. Check out this site: http://www.acky.net/tutorials/vb/wbrowser/
Since you can reference that object in Access, you will only need to point the webbrowser control to the path of the .jpg (NavigateTo() if I remember correctly).
EDIT: The above link was just googled and picked from the results (first one that opened quickly). I do not think it is a very good tutorial, it just has all the pointers you need... Check out msdn etc. if you need more information!
A: You can try an ActiveX control called AccessImagine, makes adding images to database more convenient - you can load from file, scan, paste from buffer or drag-n-drop. You can crop image right inside the database and resample it automatically. It handles external image storage automatically if you need it.
A: Note that in Access 2010 (and later) this is dead simple to do because the Image control can be bound to a field in the table that contains the path to the image file (.jpg, .png, ...). No VBA required.
For more details see my other answer here.
A: Do you mean something like this?
Display images in MS-Access Form tabular view.
Here's the original post from microsoft:
https://learn.microsoft.com/en-us/office/troubleshoot/access/display-images-using-custom-function
You just need to modify something in the form events:
Modify this part of the form code
Image Control
Name: ImageFrame
Picture: "C:\Windows\Zapotec.bmp"
Control Source: txtImageName
Note that the Control Source named "txtImageName" is the field name in your table which has the name and path of your images.
Everything get's fine after you modify that part.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40112",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: How do I install and use the ASP.NET AJAX Control Toolkit in my .NET 3.5 web applications? How do I get it to work with my project?
http://ajax.asp.net/
http://www.codeplex.com/AjaxControlToolkit/
A: Install the ASP.NET AJAX Control Toolkit
*
*Download the ZIP file
AjaxControlToolkit-Framework3.5SP1-DllOnly.zip
from the ASP.NET AJAX Control
Toolkit Releases page of the
CodePlex web site.
*Copy the contents of this zip file
directly into the bin directory of
your web site.
Update web.config
*Put this in your web.config under the <controls> section:
<?xml version="1.0"?>
<configuration>
...
<system.web>
...
<pages>
...
<controls>
...
<add tagPrefix="ajaxtoolkit"
namespace="AjaxControlToolkit"
assembly="AjaxControlToolKit"/>
</controls>
</pages>
...
</system.web>
...
</configuration>
Setup Visual Studio
*Right-click on the Toolbox and select "Add Tab", and add a tab called "AJAX Control Toolkit"
*Inside that tab, right-click on the Toolbox and select "Choose Items..."
*When the "Choose Toolbox Items" dialog appears, click the "Browse..." button. Navigate to your project's "bin" folder. Inside that folder, select "AjaxControlToolkit.dll" and click OK. Click OK again to close the Choose Items Dialog.
You can now use the controls in your web sites!
A: If you are using MasterPages and Content pages in your app - you also have the option of putting the ScriptManager on the Masterpage and then every ContentPage that uses that MasterPage will NOT need a script manager added. If you need some of the special configurations of the ScriptManager - like javascript file references - you can use a ScriptManagerProxy control on the content page that needs it.
A: You can easily install it by writing
Install-Package AjaxControlToolkit in package manager console.
for more information you can check this link
A: you will also need to have a asp:ScriptManager control on every page that you want to use ajax controls on. you should be able to just drag the scriptmanager over from your toolbox one the toolkit is installed following Zack's instructions.
A: It's really simple, just download the latest toolkit from Codeplex and add the extracted AjaxControlToolkit.dll to your toolbox in Visual Studio by right clicking the toolbox and selecting 'choose items'. You will then have the controls in your Visual STudio toolbox and using them is just a matter of dragging and dropping them onto your form, of course don't forget to add a asp:ScriptManager to every page that uses controls from the toolkit, or optionally include it in your master page only and your content pages will inherit the script manager.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40116",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
} |
Q: How to find a Java Memory Leak How do you find a memory leak in Java (using, for example, JHat)? I have tried to load the heap dump up in JHat to take a basic look. However, I do not understand how I am supposed to be able to find the root reference (ref) or whatever it is called. Basically, I can tell that there are several hundred megabytes of hash table entries ([java.util.HashMap$Entry or something like that), but maps are used all over the place... Is there some way to search for large maps, or perhaps find general roots of large object trees?
[Edit]
Ok, I've read the answers so far but let's just say I am a cheap bastard (meaning I am more interested in learning how to use JHat than to pay for JProfiler). Also, JHat is always available since it is part of the JDK. Unless of course there is no way with JHat but brute force, but I can't believe that can be the case.
Also, I do not think I will be able to actually modify (adding logging of all map sizes) and run it for long enough for me to notice the leak.
A: Questioner here, I have got to say getting a tool that does not take 5 minutes to answer any click makes it a lot easier to find potential memory leaks.
Since people are suggesting several tools ( I only tried visual wm since I got that in the JDK and JProbe trial ) I though I should suggest a free / open source tool built on the Eclipse platform, the Memory Analyzer (sometimes referenced as the SAP memory analyzer) available on http://www.eclipse.org/mat/ .
What is really cool about this tool is that it indexed the heap dump when I first opened it which allowed it to show data like retained heap without waiting 5 minutes for each object (pretty much all operations were tons faster than the other tools I tried).
When you open the dump, the first screen shows you a pie chart with the biggest objects (counting retained heap) and one can quickly navigate down to the objects that are to big for comfort. It also has a Find likely leak suspects which I reccon can come in handy, but since the navigation was enough for me I did not really get into it.
A: There are tools that should help you find your leak, like JProbe, YourKit, AD4J or JRockit Mission Control. The last is the one that I personally know best. Any good tool should let you drill down to a level where you can easily identify what leaks, and where the leaking objects are allocated.
Using HashTables, Hashmaps or similar is one of the few ways that you can acually leak memory in Java at all. If I had to find the leak by hand I would peridically print the size of my HashMaps, and from there find the one where I add items and forget to delete them.
A: Well, there's always the low tech solution of adding logging of the size of your maps when you modify them, then search the logs for which maps are growing beyond a reasonable size.
A: A tool is a big help.
However, there are times when you can't use a tool: the heap dump is so huge it crashes the tool, you are trying to troubleshoot a machine in some production environment to which you only have shell access, etc.
In that case, it helps to know your way around the hprof dump file.
Look for SITES BEGIN. This shows you what objects are using the most memory. But the objects aren't lumped together solely by type: each entry also includes a "trace" ID. You can then search for that "TRACE nnnn" to see the top few frames of the stack where the object was allocated. Often, once I see where the object is allocated, I find a bug and I'm done. Also, note that you can control how many frames are recorded in the stack with the options to -Xrunhprof.
If you check out the allocation site, and don't see anything wrong, you have to start backward chaining from some of those live objects to root objects, to find the unexpected reference chain. This is where a tool really helps, but you can do the same thing by hand (well, with grep). There is not just one root object (i.e., object not subject to garbage collection). Threads, classes, and stack frames act as root objects, and anything they reference strongly is not collectible.
To do the chaining, look in the HEAP DUMP section for entries with the bad trace id. This will take you to an OBJ or ARR entry, which shows a unique object identifier in hexadecimal. Search for all occurrences of that id to find who's got a strong reference to the object. Follow each of those paths backward as they branch until you figure out where the leak is. See why a tool is so handy?
Static members are a repeat offender for memory leaks. In fact, even without a tool, it'd be worth spending a few minutes looking through your code for static Map members. Can a map grow large? Does anything ever clean up its entries?
A: I use following approach to finding memory leaks in Java. I've used jProfiler with great success, but I believe that any specialized tool with graphing capabilities (diffs are easier to analyze in graphical form) will work.
*
*Start the application and wait until it get to "stable" state, when all the initialization is complete and the application is idle.
*Run the operation suspected of producing a memory leak several times to allow any cache, DB-related initialization to take place.
*Run GC and take memory snapshot.
*Run the operation again. Depending on the complexity of operation and sizes of data that is processed operation may need to be run several to many times.
*Run GC and take memory snapshot.
*Run a diff for 2 snapshots and analyze it.
Basically analysis should start from greatest positive diff by, say, object types and find what causes those extra objects to stick in memory.
For web applications that process requests in several threads analysis gets more complicated, but nevertheless general approach still applies.
I did quite a number of projects specifically aimed at reducing memory footprint of the applications and this general approach with some application specific tweaks and trick always worked well.
A: Most of the time, in enterprise applications the Java heap given is larger than the ideal size of max 12 to 16 GB. I have found it hard to make the NetBeans profiler work directly on these big java apps.
But usually this is not needed. You can use the jmap utility that comes with the jdk to take a "live" heap dump , that is jmap will dump the heap after running GC. Do some operation on the application, wait till the operation is completed, then take another "live" heap dump. Use tools like Eclipse MAT to load the heapdumps, sort on the histogram, see which objects have increased, or which are the highest, This would give a clue.
su proceeuser
/bin/jmap -dump:live,format=b,file=/tmp/2930javaheap.hrpof 2930(pid of process)
There is only one problem with this approach; Huge heap dumps, even with the live option, may be too big to transfer out to development lap, and may need a machine with enough memory/RAM to open.
That is where the class histogram comes into picture. You can dump a live class histogram with the jmap tool. This will give only the class histogram of memory usage.Basically it won't have the information to chain the reference. For example it may put char array at the top. And String class somewhere below. You have to draw the connection yourself.
jdk/jdk1.6.0_38/bin/jmap -histo:live 60030 > /tmp/60030istolive1330.txt
Instead of taking two heap dumps, take two class histograms, like as described above; Then compare the class histograms and see the classes that are increasing. See if you can relate the Java classes to your application classes. This will give a pretty good hint. Here is a pythons script that can help you compare two jmap histogram dumps. histogramparser.py
Finally tools like JConolse and VisualVm are essential to see the memory growth over time, and see if there is a memory leak. Finally sometimes your problem may not be a memory leak , but high memory usage.For this enable GC logging;use a more advanced and new compacting GC like G1GC; and you can use jdk tools like jstat to see the GC behaviour live
jstat -gccause pid <optional time interval>
Other referecences to google for -jhat, jmap, Full GC, Humongous allocation, G1GC
A: NetBeans has a built-in profiler.
A: You really need to use a memory profiler that tracks allocations. Take a look at JProfiler - their "heap walker" feature is great, and they have integration with all of the major Java IDEs. It's not free, but it isn't that expensive either ($499 for a single license) - you will burn $500 worth of time pretty quickly struggling to find a leak with less sophisticated tools.
A: You can find out by measuring memory usage size after calling garbage collector multiple times:
Runtime runtime = Runtime.getRuntime();
while(true) {
...
if(System.currentTimeMillis() % 4000 == 0){
System.gc();
float usage = (float) (runtime.totalMemory() - runtime.freeMemory()) / 1024 / 1024;
System.out.println("Used memory: " + usage + "Mb");
}
}
If the output numbers were equal, there is no memory leak in your application, but if you saw difference between the numbers of memory usage (increasing numbers), there is memory leak in your project. For example:
Used memory: 14.603279Mb
Used memory: 14.737213Mb
Used memory: 14.772224Mb
Used memory: 14.802681Mb
Used memory: 14.840599Mb
Used memory: 14.900841Mb
Used memory: 14.942261Mb
Used memory: 14.976143Mb
Note that sometimes it takes some time to release memory by some actions like streams and sockets. You should not judge by first outputs, You should test it in a specific amount of time.
A: Checkout this screen cast about finding memory leaks with JProfiler.
It's visual explanation of @Dima Malenko Answer.
Note: Though JProfiler is not freeware, But Trial version can deal with current situation.
A: As most of us use Eclipse already for writing code, Why not use the Memory Analyser Tool(MAT) in Eclipse. It works great.
The Eclipse MAT is a set of plug-ins for the Eclipse IDE which provides tools to analyze heap dumps from Java application and to identify memory problems in the application.
This helps the developer to find memory leaks with the following features
*
*Acquiring a memory snapshot (Heap Dump)
*Histogram
*Retained Heap
*Dominator Tree
*Exploring Paths to the GC Roots
*Inspector
*Common Memory Anti-Patterns
*Object Query Language
A: I have recently dealt with a memory leak in our application. Sharing my experience here
The garbage collector removes unreferenced objects periodically, but it never collects the objects that are still being referenced. This is where memory leaks can occur.
Here is some options to find out the referenced objects.
*
*Using jvisualvm which is located in JDK/bin folder
Options : Watch Heap space
If you see that the heap space keep increasing, definitely there is a memory leak.
To find out the cause, you can use memory sampler under sampler .
*Get a Java heap histogram by using jmap ( which is also available in JDK/bin folder) in different time span of the application
jmap -histo <pid> > histo1.txt
Here the object reference can be analyzed. If some of the objects are never garbage collected, that is the potential memory leak.
You can read the some of the most common cause of memory leak here in this article : Understanding Memory Leaks in Java
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40119",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "149"
} |
Q: Exceptions in Web Services My group is developing a service-based (.NET WCF) application and we're trying to decide how to handle exceptions in our internal services. Should we throw exceptions? Return exceptions serialized as XML? Just return an error code?
Keep in mind that the user will never see these exceptions, it's only for other parts of the application.
A: WCF uses SoapFaults as its native way of transmitting exceptions from either the service to the client, or the client to the service.
You can declare a custom SOAP fault using the FaultContract attribute in your contract interface:
For example:
[ServiceContract(Namespace="foobar")]
interface IContract
{
[OperationContract]
[FaultContract(typeof(CustomFault))]
void DoSomething();
}
[DataContract(Namespace="Foobar")]
class CustomFault
{
[DataMember]
public string error;
public CustomFault(string err)
{
error = err;
}
}
class myService : IContract
{
public void DoSomething()
{
throw new FaultException<CustomFault>( new CustomFault("Custom Exception!"));
}
}
A: Well, why not just throw the standard SOAPExceptions? The problem with error codes and serialized XML is that they both require additional logic to recognize that an error did in fact happen. Such an approach is only useful if you have specialized logging or logic that needs to happen on the other side of the web service. Such an example would be returning a flag that says "it's ok to continue" with an error exception report.
Regardless of how you throw it, it won't make the job any easier, as the calling side still needs to recognize there was an exception and deal with it.
A: I'm a bit confused, I'm not being flippant -- you say you want to return exceptions serialised as XML on the one hand and that the user will never see the exceptions on the other hand. Who will be seeing these exceptions?
Normally I'd say to use WCF fault contracts.
A: Phil, different parts of the application call each other using WCF. By "return exceptions serialized as XML," I meant that the return value of the function wold be an exception object. Success would be indicated by null.
I don't think that's the right option.
WCF fault contracts sound good, but I don't know anything about them. Checking google right now.
A: I would avoid sending exceptions directly back to the client unless you are okay with that much detail being sent back.
I would recommend using WCF faults to transmit your error message and code (something that can be used to make a decision on the receiver to retry, error out, etc) depending if it is the sender or receiver at fault.
This can be done using FaultCode.CreateReceiverFaultCode and FaultCode.CreateSenderFaultCode.
I'm in the process of going through this right now, but ran into a nasty snag it seems in the WCF fault generated SOAP 1.1 response. If you are interested, you can check out my question about it here:
.NET WCF faults generating incorrect SOAP 1.1 faultcode values
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40122",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Reading from a http-get presenting in Firefox bookmarks I'm trying to get a Firefox plugin to read data from a HTTP get, parse the results and present them as links in a bookmark-like drop-down menu.
My quesion then is: Does anyone have any sample code that will do this?
A: Having never developed one myself, I'm not certain how this is typically done in Firefox plugins, but since plugin scripting is JavaScript, I can probably help out with the loading part. Assuming a variable named url containing the URL you want to request:
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", url, true);
xmlhttp.onreadystatechange = function() {
if(this.readyState == 4) { // Done loading?
if(this.status == 200) { // Everything okay?
// read content from this.responseXML or this.responseText
} else { // Error occurred; handle it
alert("Error " + this.status + ":\n" + this.statusText);
}
}
};
xmlhttp.send(null);
A couple of notes on this code:
*
*You may want more sophisticated status code handling. For example, 200 is not the only non-error status code. Details on status codes can be found here.
*You probably want to have a timeout to handle the case where, for some reason, you don't get to readyState 4 in a reasonable amount of time.
*You may want to do things when earlier readyStates are received. This page documents the readyState codes, along with other properties and methods on the XMLHttpRequest object which you may find useful.
A: Robert Walker did a great job of describing how to send the request. You can read more about Mozilla's xmlhttprequest here.
I would just add that the response would be found (using Robert's code) using
xmlhttp.responseText
(Edit - i didn't read closely enough, thanks Robert)
You didn't indicate exactly what the data was, although you mentioned wanting to parse links from the data. You could the xmlhttp.responseText as an xml document, parse out the links, and place it into a menulist or whatever you like.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40125",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Best way to pass a large number of arguments into a configuration dialog I've got a situation where I have a main form that pops up an advanced configuration form that just has half a dozen matched check boxes and combo boxes to select some advanced options (the check boxes to enable/disable, the combo to select a media if enabled).
If I just pass the individual settings for the check and combo boxes in to the constructor for the dialog that's obviously a dozen arguments, which seems a bit excessive.
My other obvious option would be since in the main form these settings are stored in a large IDictionary with all the other main form settings I could just pass this dictionary in and fetch it back afterward with the updated values, but my understanding is that this wouldn't really be very good coding practice.
Am I missing a good way to do this that is both efficient and good coding practice?
(this particular code is in C#, although I have a feeling a general solution would apply to other languages as well)
A: I personally would create a carrier object to store the values. You then get the nice intellisense for it, and changes to it would be quite straightforward. It would also be faster than dictionary lookups for parameter values. And of course, you get type safety. :)
A: You could go with Rob's solution; that's the prettiest for development. Your "carrier object" could contain the entire IDictionary and have typed properties to help intellisense. The properties could update the IDictionary. When you're done, you can pass the carrier object back and fetch the IDictionary directly from it.
For example, if your dictionary had key/value pair "FirstEnabled"/boolean, you could do this:
class ContainerObject
{
public IDictionary<object, object> _dict;
public ContainerObject(IDictionary<object, object> dict)
{
_dict = dict;
}
public bool FirstEnabled
{
get { return (bool) _dict["FirstEnabled"]; }
set { _dict["FirstEnabled"] = value; }
}
}
You can change the member "_dict" to private or protected and have a accessor function if you want.
A: Something like this should be good:
MyConfigurationDialog dialog = new MyConfigurationDialog();
//Copy the dictionary so that the dialog can't mess with our settings
dialog.Settings = new Dictionary(existingSettings);
if(DialogResult.OK == dialog.Show()) {
//grab the settings that the dialog may have changed
existingSettings["setting1"] = dialog.Settings["setting1"];
existingSettings["setting2"] = dialog.Settings["setting2"];
}
A: I agree with Rob Cooper. Create a class to represent your configuration, and pass that into the constructor of your form. This will also allow you to define methods on your new "config" class like "saveSettings", "LoadSettings", etc. That in turn should keep the code more maintainable in general.
As an quick-and-dirty alternative, if you are saving these to a file somewhere, just pass the name of the file, and have your form read that at run-time.
The first option really is the way to go though, IMO.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40132",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Getting Apache to modify static webpages on the fly I have been experimenting with woopra.com A web analytics tool. Which requires a piece of javascript code to be added to each page to function. This is easy enough with more dynamic sites with universal headers or footers but not for totally static html pages.
I attempted to work round it by using a combination of Apache rewrites and SSI's to "Wrap" the static html with the required code. For example...
I made the following changes to my apache config
RewriteEngine On
RewriteCond %{REQUEST_URI} !=test.shtml
RewriteCond %{IS_SUBREQ} false
RewriteRule (.*)\.html test.shtml?$1.html
The test.shtml file contains...
<script type="text/javascript">
var XXXXid = 'xxxxxxx';
</script>
<script src="http://xxxx.woopra.com/xx/xxx.js"></script>
<!--#set var="page" value="$QUERY_STRING" -->
<!--#include virtual= $page -->
The idea was that a request coming in for
/abc.html
would be redirected to
/test.shtml?abc.html
the shtml would then include the original file into the response page.
Unfortunately it doesn't quite work as planed :) can anyone see what I am doing wrong or perhaps suggest an alternative approach. Is there any apache modules that could do the same thing. Preferably that can be configured on a per site basis.
Thanks
Peter
A: I think that mod_filter_ext is the module you are looking for. You can write a short Perl script for example to insert the JS code in the pages and register it to process HTML pages:
while (<>) {
s/<html>/\Q<script>....\E/;
print $_;
}
You could even use something like sed to perform the substitution.
A: If the pages are static, why would you change them on the fly instead of preprocessing all pages on a site, adding the piece of requiered javascript to each one of them? This is simple and probably more efficent (you probably have more pageviews than pages to change)
This could be done a lots of way. I would suggest a small perl to to inline replacement.
A: ok the method above's biggest problem is it would break your html validity by placing a script tag outside the <html> tags
i'd agree with the others on a pre-process run over your html files such as a sed/awk script
heres a quick example {assuming the script part can be added before the </head>
and that the </head> is at the start of a newline
#!/bin/bash
cd /var/webserver/whatever/
grep -r '<\/head>' */*|grep "^.*\.html*:" >/var/tmp/tempfile.txt
((lines = $(wc -l /var/tmp/dom-tempfile.txt | awk '{print $1}')))
if [ $lines -gt 0 ]
then
while read line; do
sed 's/<script type="text\/javascript"> var XXXXid = "xxxxxxx"; <\/script><script src="http:\/\/xxxx\.woopra\.com\/xx\/xxx\.js"><\/script><\/head>/^<\/head>/g' $line>/var/tmp/tempfile.htm
mv /var/tmp/tempfile.htm $line
done < <(sed 's/\(^.*\.html*\):.*$/\1/' /var/tmp/tempfile.txt)
fi
exit 0
A: You may have a syntax error since $page is not included in quotes, however the two main reasons that this doesn't are the following:
*
*include virtual should a path starting with /, in your example the query string should be /abc.html , not abc.html
*the rewrite rule should start with the path as well, so the rewrite rule has to be
RewriteRule ^(.*)\.html /test.shtml?$1.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40133",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Why do jQuery selectors sometimes not work in Internet Explorer I have a very strange problem. Under some elusive circumstances I fail to apply any jQuery selector on my pages under IE. It's OK under Firefox though. The jQuery function simply returns empty array.
Any suggestions?
Page is too complex to post it here. Practically any selector, except "#id" selectors, returns a zero element array. The jQuery version is 1.2.3
A: What version(s) of IE is it failing under? Is it failing for a specific complex selector? I think we need an example.
Edit: Does the problem go away if you upgrade to 1.2.6? 1.2.6 is primarily a bug-fix release according to this page.
Failing that, the best way to find the problem is to create a minimum page that can reproduce the bug. Without that, it's just about impossible to troubleshoot.
A: Try upgrading to jQuery 1.2.6, you should be on the latest release of jQuery if you are having problems first ensure you are on the latest and greatest.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40151",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
} |
Q: How do you beta test an iphone app? How can you beta test an iPhone app? I can get it on my own device, and anyone that gives me a device, I can run it on theirs, but is there a way to do a limited release via the app store for beta testing?
Related: Also, see this question on getting your app onto phones without using the App Store.
A: In 2014 along with iOS 8 and XCode 6 apple introduced Beta Testing of iOS App using iTunes Connect.
You can upload your build to iTunes connect and invite testers using their mail id's. You can invite up to 2000 external testers using just their email address. And they can install the beta app through TestFlight
A: Diawi Alternatives
Since diawi.com have added some limitations for free accounds.
Next best available and easy to use alternative is
Microsoft
https://appcenter.ms
Google
https://firebase.google.com/docs/app-distribution/ios/distribute-console
Others
https://hockeyapp.net/
http://buildtry.com
Happy build sharing!
A: Creating ad-hoc distribution profiles
The instructions that Apple provides are here, but here is how I created a general provisioning profile that will work with multiple apps, and added a beta tester.
My setup:
*
*Xcode 3.2.1
*iPhone SDK 3.1.3
Before you get started, make sure that..
*
*You can run the app on your own iPhone through Xcode.
Step A: Add devices to the Provisioning Portal
*
*Send an email to each beta tester with the following message:
To get my app on onto your iPhone I need some information about your phone. Guess what, there is an app for that!
Click on the below link and install and then run the app.
http://itunes.apple.com/app/ad-hoc-helper/id285691333?mt=8
This app will create an email. Please send it to me.
*Collect all the UDIDs from your testers.
*Go to the Provisioning Portal.
*Go to the section Devices.
*Click on the button Add Devices and add the devices previously collected.
Step B: Create a new provisioning profile
*
*Start the Mac OS utility program Keychain Access.
*In its main menu, select Keychain Access / Certificate Assistant / Request a Certificate From a Certificate Authority...
*The dialog that pops up should aready have your email and name it it.
*Select the radio button Saved to disk and Continue.
*Save the file to disk.
*Go back to the Provisioning Portal.
*Go to the section Certificates.
*Go to the tab Distribution.
*Click the button Request Certificate.
*Upload the file you created with Keychain Access: CertificateSigningRequest.certSigningRequest.
*Click the button Aprove.
*Refresh your browser until the status reads Issued.
*Click the Download button and save the file distribution_identify.cer.
*Doubleclick the file to add it to the Keychain.
*Backup the certificate by selecting its private key and the File / Export Items....
*Go back to the Provisioning Portal again.
*Go to the section Provisioning.
*Go to the tab Distribution.
*Click the button New Profile.
*Select the radio button Ad hoc.
*Enter a profile name, I named mine Evertsson Common Ad Hoc.
*Select the app id. I have a common app id to use for multiple apps: Evertsson Common.
*Select the devices, in my case my own and my tester's.
*Submit.
*Refresh the browser until the status field reads Active.
*Click the button Download and save the file to disk.
*Doubleclick the file to add it to Xcode.
Step C: Build the app for distribution
*
*Open your project in Xcode.
*Open the Project Info pane: In Groups & Files select the topmost item and press Cmd+I.
*Go to the tab Configuration.
*Select the configuration Release.
*Click the button Duplicate and name it Distribution.
*Close the Project Info pane.
*Open the Target Info pane: In Groups & Files expand Targets, select your target and press Cmd+I.
*Go to the tab Build.
*Select the Configuration named Distribution.
*Find the section Code Signing.
*Set the value of Code Signing Identity / Any iPhone OS Device to iPhone Distribution.
*Close the Target Info pane.
*In the main window select the Active Configuration to Distribution.
*Create a new file from the file template Code Signing / Entitlements.
*Name it Entitlements.plist.
*In this file, uncheck the checkbox get-task-allow.
*Bring up the Target Info pane, and find the section Code Signing again.
*After Code Signing Entitlements enter the file name Entitlements.plist.
*Save, clean, and build the project.
*In Groups & Files find the folder MyApp / Products and expand it.
*Right click the app and select Reveal in Finder.
*Zip the .app file and the .mobileprovision file and send the archive to your tester.
Here is my app. To install it onto your phone:
*
*Unzip the archive file.
*Open iTunes.
*Drag both files into iTunes and drop them on the Library group.
*Sync your phone to install the app.
Done! Phew. This worked for me. So far I've only added one tester.
A: There's a relatively new service called HockeyApp, which seems to rival TestFlight, however they claim to give you access to unlimited users, but it does cost some $$ unlike TestFlight which has now been integrated directly into iTunes Connect.
A: Using testflight :
1) create the ipa file by development certificate
2) upload the ipa file on testflight
3) Now, to identify the device to be tested on , add the device id on apple account and refresh your development certificate. Download the updated certificate and upload it on testflight website. Check the device id you are getting.
4) Now email the ipa file to the testers.
5) While downloading the ipa file, if the testers are not getting any warnings, this means the device token + provisioning profile has been verified. So, the testers can now download the ipa file on device and do the testing job...
A: With iOS 8, Xcode 6, iTunes Connect and TestFlight you don't need UDIDs and Ad Hocs anymore. You will just need an Apple ID from your beta tester. Right now you can only beta test your app with 25 internal testers, but soon 1000 external testers will be available too. This blog post shows you how to setup a beta test with internal testers.
A: In year 2011, there's a new service out called "Test Flight", and it addresses this issue directly.
Apple has since bought TestFlight in 2014 and has integrated it into iTunes Connect and App Store Connect.
A: Note that there is a distinction between traditional "beta testing" which is done by professional QA engineers, and "public beta testing" which is releasing your product to the public before it's ready : )
You can do "beta testing" -- loading to specific iPhones/iPods your testers will be using. You can't do "public beta testing" -- pre-releasing to the public.
A: (As the official guide is still missing in this thread..)
TestFlight, acquired by Apple and now (iOS8+) available for beta testing makes it easy to hand your app to beta testers without the need to collect device UUIDs beforehand (you only need email addresses of your testers). An extensive guide explaining all necessary steps may be found in the iTunes Connect Developer Guide.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40154",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "469"
} |
Q: Does C# have built-in support for parsing page-number strings? Does C# have built-in support for parsing strings of page numbers? By page numbers, I mean the format you might enter into a print dialog that's a mixture of comma and dash-delimited.
Something like this:
1,3,5-10,12
What would be really nice is a solution that gave me back some kind of list of all page numbers represented by the string. In the above example, getting a list back like this would be nice:
1,3,5,6,7,8,9,10,12
I just want to avoid rolling my own if there's an easy way to do it.
A: It doesn't have a built-in way to do this, but it would be trivial to do using String.Split.
Simply split on ',' then you have a series of strings that represent either page numbers or ranges. Iterate over that series and do a String.Split of '-'. If there isn't a result, it's a plain page number, so stick it in your list of pages. If there is a result, take the left and right of the '-' as the bounds and use a simple for loop to add each page number to your final list over that range.
Can't take but 5 minutes to do, then maybe another 10 to add in some sanity checks to throw errors when the user tries to input invalid data (like "1-2-3" or something.)
A: Keith's approach seems nice. I put together a more naive approach using lists. This has error checking so hopefully should pick up most problems:-
public List<int> parsePageNumbers(string input) {
if (string.IsNullOrEmpty(input))
throw new InvalidOperationException("Input string is empty.");
var pageNos = input.Split(',');
var ret = new List<int>();
foreach(string pageString in pageNos) {
if (pageString.Contains("-")) {
parsePageRange(ret, pageString);
} else {
ret.Add(parsePageNumber(pageString));
}
}
ret.Sort();
return ret.Distinct().ToList();
}
private int parsePageNumber(string pageString) {
int ret;
if (!int.TryParse(pageString, out ret)) {
throw new InvalidOperationException(
string.Format("Page number '{0}' is not valid.", pageString));
}
return ret;
}
private void parsePageRange(List<int> pageNumbers, string pageNo) {
var pageRange = pageNo.Split('-');
if (pageRange.Length != 2)
throw new InvalidOperationException(
string.Format("Page range '{0}' is not valid.", pageNo));
int startPage = parsePageNumber(pageRange[0]),
endPage = parsePageNumber(pageRange[1]);
if (startPage > endPage) {
throw new InvalidOperationException(
string.Format("Page number {0} is greater than page number {1}" +
" in page range '{2}'", startPage, endPage, pageNo));
}
pageNumbers.AddRange(Enumerable.Range(startPage, endPage - startPage + 1));
}
A: Below is the code I just put together to do this.. You can enter in the format like.. 1-2,5abcd,6,7,20-15,,,,,,
easy to add-on for other formats
private int[] ParseRange(string ranges)
{
string[] groups = ranges.Split(',');
return groups.SelectMany(t => GetRangeNumbers(t)).ToArray();
}
private int[] GetRangeNumbers(string range)
{
//string justNumbers = new String(text.Where(Char.IsDigit).ToArray());
int[] RangeNums = range
.Split('-')
.Select(t => new String(t.Where(Char.IsDigit).ToArray())) // Digits Only
.Where(t => !string.IsNullOrWhiteSpace(t)) // Only if has a value
.Select(t => int.Parse(t)) // digit to int
.ToArray();
return RangeNums.Length.Equals(2) ? Enumerable.Range(RangeNums.Min(), (RangeNums.Max() + 1) - RangeNums.Min()).ToArray() : RangeNums;
}
A: Should be simple:
foreach( string s in "1,3,5-10,12".Split(',') )
{
// try and get the number
int num;
if( int.TryParse( s, out num ) )
{
yield return num;
continue; // skip the rest
}
// otherwise we might have a range
// split on the range delimiter
string[] subs = s.Split('-');
int start, end;
// now see if we can parse a start and end
if( subs.Length > 1 &&
int.TryParse(subs[0], out start) &&
int.TryParse(subs[1], out end) &&
end >= start )
{
// create a range between the two values
int rangeLength = end - start + 1;
foreach(int i in Enumerable.Range(start, rangeLength))
{
yield return i;
}
}
}
Edit: thanks for the fix ;-)
A: Here's something I cooked up for something similar.
It handles the following types of ranges:
1 single number
1-5 range
-5 range from (firstpage) up to 5
5- range from 5 up to (lastpage)
.. can use .. instead of -
;, can use both semicolon, comma, and space, as separators
It does not check for duplicate values, so the set 1,5,-10 will produce the sequence 1, 5, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10.
public class RangeParser
{
public static IEnumerable<Int32> Parse(String s, Int32 firstPage, Int32 lastPage)
{
String[] parts = s.Split(' ', ';', ',');
Regex reRange = new Regex(@"^\s*((?<from>\d+)|(?<from>\d+)(?<sep>(-|\.\.))(?<to>\d+)|(?<sep>(-|\.\.))(?<to>\d+)|(?<from>\d+)(?<sep>(-|\.\.)))\s*$");
foreach (String part in parts)
{
Match maRange = reRange.Match(part);
if (maRange.Success)
{
Group gFrom = maRange.Groups["from"];
Group gTo = maRange.Groups["to"];
Group gSep = maRange.Groups["sep"];
if (gSep.Success)
{
Int32 from = firstPage;
Int32 to = lastPage;
if (gFrom.Success)
from = Int32.Parse(gFrom.Value);
if (gTo.Success)
to = Int32.Parse(gTo.Value);
for (Int32 page = from; page <= to; page++)
yield return page;
}
else
yield return Int32.Parse(gFrom.Value);
}
}
}
}
A: You can't be sure till you have test cases. In my case i would prefer to be white space delimited instead of comma delimited. It make the parsing a little more complex.
[Fact]
public void ShouldBeAbleToParseRanges()
{
RangeParser.Parse( "1" ).Should().BeEquivalentTo( 1 );
RangeParser.Parse( "-1..2" ).Should().BeEquivalentTo( -1,0,1,2 );
RangeParser.Parse( "-1..2 " ).Should().BeEquivalentTo( -1,0,1,2 );
RangeParser.Parse( "-1..2 5" ).Should().BeEquivalentTo( -1,0,1,2,5 );
RangeParser.Parse( " -1 .. 2 5" ).Should().BeEquivalentTo( -1,0,1,2,5 );
}
Note that Keith's answer ( or a small variation) will fail the last test where there is whitespace between the range token. This requires a tokenizer and a proper parser with lookahead.
namespace Utils
{
public class RangeParser
{
public class RangeToken
{
public string Name;
public string Value;
}
public static IEnumerable<RangeToken> Tokenize(string v)
{
var pattern =
@"(?<number>-?[1-9]+[0-9]*)|" +
@"(?<range>\.\.)";
var regex = new Regex( pattern );
var matches = regex.Matches( v );
foreach (Match match in matches)
{
var numberGroup = match.Groups["number"];
if (numberGroup.Success)
{
yield return new RangeToken {Name = "number", Value = numberGroup.Value};
continue;
}
var rangeGroup = match.Groups["range"];
if (rangeGroup.Success)
{
yield return new RangeToken {Name = "range", Value = rangeGroup.Value};
}
}
}
public enum State { Start, Unknown, InRange}
public static IEnumerable<int> Parse(string v)
{
var tokens = Tokenize( v );
var state = State.Start;
var number = 0;
foreach (var token in tokens)
{
switch (token.Name)
{
case "number":
var nextNumber = int.Parse( token.Value );
switch (state)
{
case State.Start:
number = nextNumber;
state = State.Unknown;
break;
case State.Unknown:
yield return number;
number = nextNumber;
break;
case State.InRange:
int rangeLength = nextNumber - number+ 1;
foreach (int i in Enumerable.Range( number, rangeLength ))
{
yield return i;
}
state = State.Start;
break;
default:
throw new ArgumentOutOfRangeException();
}
break;
case "range":
switch (state)
{
case State.Start:
throw new ArgumentOutOfRangeException();
break;
case State.Unknown:
state = State.InRange;
break;
case State.InRange:
throw new ArgumentOutOfRangeException();
break;
default:
throw new ArgumentOutOfRangeException();
}
break;
default:
throw new ArgumentOutOfRangeException( nameof( token ) );
}
}
switch (state)
{
case State.Start:
break;
case State.Unknown:
yield return number;
break;
case State.InRange:
break;
default:
throw new ArgumentOutOfRangeException();
}
}
}
}
A: One line approach with Split and Linq
string input = "1,3,5-10,12";
IEnumerable<int> result = input.Split(',').SelectMany(x => x.Contains('-') ? Enumerable.Range(int.Parse(x.Split('-')[0]), int.Parse(x.Split('-')[1]) - int.Parse(x.Split('-')[0]) + 1) : new int[] { int.Parse(x) });
A: Here's a slightly modified version of lassevk's code that handles the string.Split operation inside of the Regex match. It's written as an extension method and you can easily handle the duplicates problem using the Disinct() extension from LINQ.
/// <summary>
/// Parses a string representing a range of values into a sequence of integers.
/// </summary>
/// <param name="s">String to parse</param>
/// <param name="minValue">Minimum value for open range specifier</param>
/// <param name="maxValue">Maximum value for open range specifier</param>
/// <returns>An enumerable sequence of integers</returns>
/// <remarks>
/// The range is specified as a string in the following forms or combination thereof:
/// 5 single value
/// 1,2,3,4,5 sequence of values
/// 1-5 closed range
/// -5 open range (converted to a sequence from minValue to 5)
/// 1- open range (converted to a sequence from 1 to maxValue)
///
/// The value delimiter can be either ',' or ';' and the range separator can be
/// either '-' or ':'. Whitespace is permitted at any point in the input.
///
/// Any elements of the sequence that contain non-digit, non-whitespace, or non-separator
/// characters or that are empty are ignored and not returned in the output sequence.
/// </remarks>
public static IEnumerable<int> ParseRange2(this string s, int minValue, int maxValue) {
const string pattern = @"(?:^|(?<=[,;])) # match must begin with start of string or delim, where delim is , or ;
\s*( # leading whitespace
(?<from>\d*)\s*(?:-|:)\s*(?<to>\d+) # capture 'from <sep> to' or '<sep> to', where <sep> is - or :
| # or
(?<from>\d+)\s*(?:-|:)\s*(?<to>\d*) # capture 'from <sep> to' or 'from <sep>', where <sep> is - or :
| # or
(?<num>\d+) # capture lone number
)\s* # trailing whitespace
(?:(?=[,;\b])|$) # match must end with end of string or delim, where delim is , or ;";
Regex regx = new Regex(pattern, RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled);
foreach (Match m in regx.Matches(s)) {
Group gpNum = m.Groups["num"];
if (gpNum.Success) {
yield return int.Parse(gpNum.Value);
} else {
Group gpFrom = m.Groups["from"];
Group gpTo = m.Groups["to"];
if (gpFrom.Success || gpTo.Success) {
int from = (gpFrom.Success && gpFrom.Value.Length > 0 ? int.Parse(gpFrom.Value) : minValue);
int to = (gpTo.Success && gpTo.Value.Length > 0 ? int.Parse(gpTo.Value) : maxValue);
for (int i = from; i <= to; i++) {
yield return i;
}
}
}
}
}
A: The answer I came up with:
static IEnumerable<string> ParseRange(string str)
{
var numbers = str.Split(',');
foreach (var n in numbers)
{
if (!n.Contains("-"))
yield return n;
else
{
string startStr = String.Join("", n.TakeWhile(c => c != '-'));
int startInt = Int32.Parse(startStr);
string endStr = String.Join("", n.Reverse().TakeWhile(c => c != '-').Reverse());
int endInt = Int32.Parse(endStr);
var range = Enumerable.Range(startInt, endInt - startInt + 1)
.Select(num => num.ToString());
foreach (var s in range)
yield return s;
}
}
}
A: Regex is not efficient as following code. String methods are more efficient than Regex and should be used when possible.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string[] inputs = {
"001-005/015",
"009/015"
};
foreach (string input in inputs)
{
List<int> numbers = new List<int>();
string[] strNums = input.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string strNum in strNums)
{
if (strNum.Contains("-"))
{
int startNum = int.Parse(strNum.Substring(0, strNum.IndexOf("-")));
int endNum = int.Parse(strNum.Substring(strNum.IndexOf("-") + 1));
for (int i = startNum; i <= endNum; i++)
{
numbers.Add(i);
}
}
else
numbers.Add(int.Parse(strNum));
}
Console.WriteLine(string.Join(",", numbers.Select(x => x.ToString())));
}
Console.ReadLine();
}
}
}
A: My solution:
*
*return list of integers
*reversed/typo/duplicate possible: 1,-3,5-,7-10,12-9 => 1,3,5,7,8,9,10,12,11,10,9 (used when you want to extract, repeat pages)
*option to set total of pages: 1,-3,5-,7-10,12-9 (Nmax=9) => 1,3,5,7,8,9,9
*autocomplete: 1,-3,5-,8 (Nmax=9) => 1,3,5,6,7,8,9,8
public static List<int> pageRangeToList(string pageRg, int Nmax = 0)
{
List<int> ls = new List<int>();
int lb,ub,i;
foreach (string ss in pageRg.Split(','))
{
if(int.TryParse(ss,out lb)){
ls.Add(Math.Abs(lb));
} else {
var subls = ss.Split('-').ToList();
lb = (int.TryParse(subls[0],out i)) ? i : 0;
ub = (int.TryParse(subls[1],out i)) ? i : Nmax;
ub = ub > 0 ? ub : lb; // if ub=0, take 1 value of lb
for(i=0;i<=Math.Abs(ub-lb);i++)
ls.Add(lb<ub? i+lb : lb-i);
}
}
Nmax = Nmax > 0 ? Nmax : ls.Max(); // real Nmax
return ls.Where(s => s>0 && s<=Nmax).ToList();
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40161",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "20"
} |
Q: Is it okay to have a lot of database views? I infrequently (monthly/quarterly) generate hundreds of Crystal Reports reports using Microsoft SQL Server 2005 database views. Are those views wasting CPU cycles and RAM during all the time that I am not reading from them? Should I instead use stored procedures, temporary tables, or short-lived normal tables since I rarely read from my views?
I'm not a DBA so I don't know what's going on behind the scenes inside the database server.
Is it possible to have too many database views? What's considered best practice?
A: For the most part, it doesn't matter. Yes, SQL Server will have more choices when it parses SELECT * FROM table (it'll have to look in the system catalogs for 'table') but it's highly optimized for that, and provided you have sufficient RAM (most servers nowadays do), you won't notice a difference between 0 and 1,000 views.
However, from a people-perspective, trying to manage and figure out what "hundreds" of views are doing is probably impossible, so you likely have a lot of duplicated code in there. What happens if some business rules change that are embedded in these redundant views?
The main point of views is to encapsulate business logic into a pseudo table (so you may have a person table, but then a view called "active_persons" which does some magic). Creating a view for each report is kind of silly unless each report is so isolated and unique that there is no ability to re-use.
A: A view is a query that you run often with preset parameters. If you know you will be looking at the same data all the time you can create a view for ease of use and for data binding.
That being said, when you select from a view the view defining query is run along with the query you are running.
For example, if vwCustomersWhoHavePaid is:
Select * from customers where paid = 1
and the query you are running returns the customers who have paid after August first is formatted like this:
Select * from vwCustomersWhoHavePaid where datepaid > '08/01/08'
The query you are actually running is:
Select * from (Select * from customers where paid = 1) where datepaid > '08/01/08'
This is something you should keep in mind when creating views, they are a way of storing data that you look at often. It's just a way of organizing data so it's easier to access.
A: The views are only going to take up cpu/memory resources when they are called.
Anyhow, best practice would be to consolidate what can be consolidated, remove what can be removed, and if it's literally only used by your reports, choose a consistent naming standard for the views so they can easily be grouped together when looking for a particular view.
Also, unless you really need transactional isolation, consider using the NOLOCK table hint in your queries.
-- Kevin Fairchild
A: You ask: What's going on behind the scenes?
A view is a bunch of SQL text. When a query uses a view, SQL Server places that SQL text into the query. This happens BEFORE optimization. The result is the optimizer can consider the combined code instead of two separate pieces of code for the best execution plan.
You should look at the execution plans of your queries! There is so much to learn there.
SQL Server also has a concept of a clustered view. A clustered view is a system maintained result set (each insert/update/delete on the underlying tables can cause insert/update/deletes on the clustered view's data). It is a common mistake to think that views operate in the way that clustered views operate.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40169",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: How to compress JPEG images with ASP on Windows CE The ASP page gets data uses that to draw a graph, I then need to save the image created to JPEG to be displayed on the browser and also used in PDF and other format. What is the best way to compress the image? I am currently porting a JPEG compression library to ASP but I think it will be too slow on this ARM device running Windows CE 6.0.
So, the ASP page, running in Windows CE webservers, gets data, renders it into a bitmap image than then needs to be delivered to the browser accessing that ASP page. The same image is also used in PDF and one other proprietary format that can contain JPEG streams.
Edit:
What I am looking for is to way to create an array representing a bitmap and then compressing it to JPEG with ASP in Windows CE's IIS which has quite limited ASP implementation.
A: Take a look at the Imaging APIs (start your traversal at the IImagingFactory interface). If your device has a JPG compression codec installed (remember that CE is modular, so it may or may not be present) you can use it to create a stream (or file) from the image. From there you can do with it what you wish.
A: I'm confused...
The images from ASP would be compressed on the server side--not client side.
I'm sure your web server is not running on Windows CE, so I don't think your concern is warranted.
EDIT: Seems as though you can run a web server on Windows CE: http://www.microsoft.com/windows/embedded/products/windowsce/default.mspx. I'll keep my thoughts to myself from now on. :-x
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40171",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Quick ls command I've got to get a directory listing that contains about 2 million files, but when I do an ls command on it nothing comes back. I've waited 3 hours. I've tried ls | tee directory.txt, but that seems to hang forever.
I assume the server is doing a lot of inode sorting. Is there any way to speed up the ls command to just get a directory listing of filenames? I don't care about size, dates, permission or the like at this time.
A: This question seems to be interesting and I was going through multiple answers that were posted. To understand the efficiency of the answers posted, I have executed them on 2 million files and found the results as below.
$ time tar cvf /dev/null . &> /tmp/file-count
real 37m16.553s
user 0m11.525s
sys 0m41.291s
------------------------------------------------------
$ time echo ./* &> /tmp/file-count
real 0m50.808s
user 0m49.291s
sys 0m1.404s
------------------------------------------------------
$ time ls &> /tmp/file-count
real 0m42.167s
user 0m40.323s
sys 0m1.648s
------------------------------------------------------
$ time find . &> /tmp/file-count
real 0m2.738s
user 0m1.044s
sys 0m1.684s
------------------------------------------------------
$ time ls -U &> /tmp/file-count
real 0m2.494s
user 0m0.848s
sys 0m1.452s
------------------------------------------------------
$ time ls -f &> /tmp/file-count
real 0m2.313s
user 0m0.856s
sys 0m1.448s
------------------------------------------------------
To summarize the results
*
*ls -f command ran a bit faster than ls -U. Disabling color might have caused this improvement.
*find command ran third with an average speed of 2.738 seconds.
*Running just ls took 42.16 seconds. Here in my system ls is an alias for ls --color=auto
*Using shell expansion feature with echo ./* ran for 50.80 seconds.
*And the tar based solution took about 37 miuntes.
All tests were done seperately when system was in idle condition.
One important thing to note here is that the file lists are not printed in the terminal rather
they were redirected to a file and the file count was calculated later with wc command.
Commands ran too slow if the outputs where printed on the screen.
Any ideas why this happens ?
A: This would be the fastest option AFAIK: ls -1 -f.
*
*-1 (No columns)
*-f (No sorting)
A: Using
ls -1 -f
is about 10 times faster and it is easy to do (I tested with 1 million files, but my original problem had 6 800 000 000 files)
But in my case I needed to check if some specific directory contains more than 10 000 files. If there were more than 10 000 files, I am not anymore interested that how many files there is. I just quit the program so that it will run faster and wont try to read the rest one-by-one. If there are less than 10 000, I will print the exact amount. Speed of my program is quite similar to ls -1 -f if you specify bigger value for parameter than amount of files.
You can use my program find_if_more.pl in current directory by typing:
find_if_more.pl 999999999
If you are just interested if there are more than n files, script will finish faster than ls -1 -f with very large amount of files.
#!/usr/bin/perl
use warnings;
my ($maxcount) = @ARGV;
my $dir = '.';
$filecount = 0;
if (not defined $maxcount) {
die "Need maxcount\n";
}
opendir(DIR, $dir) or die $!;
while (my $file = readdir(DIR)) {
$filecount = $filecount + 1;
last if $filecount> $maxcount
}
print $filecount;
closedir(DIR);
exit 0;
A: You can redirect output and run the ls process in the background.
ls > myls.txt &
This would allow you to go on about your business while its running. It wouldn't lock up your shell.
Not sure about what options are for running ls and getting less data back. You could always run man ls to check.
A: ls -U
will do the ls without sorting.
Another source of slowness is --color. On some linux machines, there is a convenience alias which adds --color=auto' to the ls call, making it look up file attributes for each file found (slow), to color the display. This can be avoided by ls -U --color=never or \ls -U.
A: This is probably not a helpful answer, but if you don't have find you may be able to make do with tar
$ tar cvf /dev/null .
I am told by people older than me that, "back in the day", single-user and recovery environments were a lot more limited than they are nowadays. That's where this trick comes from.
A: I'm assuming you are using GNU ls?
try
\ls
It will unalias the usual ls (ls --color=auto).
A: I have a directory with 4 million files in it and the only way I got ls to spit out files immediately without a lot of churning first was
ls -1U
A: If a process "doesn't come back", I recommend strace to analyze how a process is interacting with the operating system.
In case of ls:
$strace ls
you would have seen that it reads all directory entries (getdents(2)) before it actually outputs anything. (sorting… as it was already mentioned here)
A: Try using:
find . -type f -maxdepth 1
This will only list the files in the directory, leave out the -type f argument if you want to list files and directories.
A: How about find ./ -type f (which will find all files in the currently directory)? Take off the -type f to find everything.
A: Things to try:
Check ls isn't aliased?
alias ls
Perhaps try find instead?
find . \( -type d -name . -prune \) -o \( -type f -print \)
Hope this helps.
A: What partition type are you using?
Having millions of small files in one directory it might be a good idea to use JFS or ReiserFS which have better performance with many small sized files.
A: Some followup:
You don't mention what OS you're running on, which would help indicate which version of ls you're using. This probably isn't a 'bash' question as much as an ls question. My guess is that you're using GNU ls, which has some features that are useful in some contexts, but kill you on big directories.
GNU ls Trying to have prettier arranging of columns. GNU ls tries to do a smart arrange of all the filenames. In a huge directory, this will take some time, and memory.
To 'fix' this, you can try:
ls -1 # no columns at all
find BSD ls someplace, http://www.freebsd.org/cgi/cvsweb.cgi/src/bin/ls/ and use that on your big directories.
Use other tools, such as find
A: There are several ways to get a list of files:
Use this command to get a list without sorting:
ls -U
or send the list of files to a file by using:
ls /Folder/path > ~/Desktop/List.txt
A: You should provide information about what operating system and the type of filesystem you are using. On certain flavours of UNIX and certain filesystems you might be able to use the commands ff and ncheck as alternatives.
A: I had a directory with timestamps in the file names. I wanted to check the date of the latest file and found find . -type f -maxdepth 1 | sort | tail -n 1 to be about twice as fast as ls -alh.
A: You can also make use of xargs. Just pipe the output of ls through xargs.
ls | xargs
If that doesn't work and the find examples above aren't working, try piping them to xargs as it can help the memory usage that might be causing your problems.
A: Lots of other good solutions here, but in the interest of completeness:
echo *
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40193",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "52"
} |
Q: How to Compare Flags in C#? I have a flag enum below.
[Flags]
public enum FlagTest
{
None = 0x0,
Flag1 = 0x1,
Flag2 = 0x2,
Flag3 = 0x4
}
I cannot make the if statement evaluate to true.
FlagTest testItem = FlagTest.Flag1 | FlagTest.Flag2;
if (testItem == FlagTest.Flag1)
{
// Do something,
// however This is never true.
}
How can I make this true?
A: For those who have trouble visualizing what is happening with the accepted solution
(which is this),
if ((testItem & FlagTest.Flag1) == FlagTest.Flag1)
{
// Do stuff.
}
testItem (as per the question) is defined as,
testItem
= flag1 | flag2
= 001 | 010
= 011
Then, in the if statement, the left hand side of the comparison is,
(testItem & flag1)
= (011 & 001)
= 001
And the full if statement (that evaluates to true if flag1 is set in testItem),
(testItem & flag1) == flag1
= (001) == 001
= true
A: if((testItem & FlagTest.Flag1) == FlagTest.Flag1)
{
...
}
A: For bit operations, you need to use bitwise operators.
This should do the trick:
if ((testItem & FlagTest.Flag1) == FlagTest.Flag1)
{
// Do something,
// however This is never true.
}
Edit: Fixed my if check - I slipped back into my C/C++ ways (thanks to Ryan Farley for pointing it out)
A: Regarding the edit. You can't make it true. I suggest you wrap what you want into another class (or extension method) to get closer to the syntax you need.
i.e.
public class FlagTestCompare
{
public static bool Compare(this FlagTest myFlag, FlagTest condition)
{
return ((myFlag & condition) == condition);
}
}
A: Try this:
if ((testItem & FlagTest.Flag1) == FlagTest.Flag1)
{
// do something
}
Basically, your code is asking if having both flags set is the same as having one flag set, which is obviously false. The code above will leave only the Flag1 bit set if it is set at all, then compares this result to Flag1.
A: In .NET 4 there is a new method Enum.HasFlag. This allows you to write:
if ( testItem.HasFlag( FlagTest.Flag1 ) )
{
// Do Stuff
}
which is much more readable, IMO.
The .NET source indicates that this performs the same logic as the accepted answer:
public Boolean HasFlag(Enum flag) {
if (!this.GetType().IsEquivalentTo(flag.GetType())) {
throw new ArgumentException(
Environment.GetResourceString(
"Argument_EnumTypeDoesNotMatch",
flag.GetType(),
this.GetType()));
}
ulong uFlag = ToUInt64(flag.GetValue());
ulong uThis = ToUInt64(GetValue());
// test predicate
return ((uThis & uFlag) == uFlag);
}
A: @phil-devaney
Note that except in the simplest of cases, the Enum.HasFlag carries a heavy performance penalty in comparison to writing out the code manually. Consider the following code:
[Flags]
public enum TestFlags
{
One = 1,
Two = 2,
Three = 4,
Four = 8,
Five = 16,
Six = 32,
Seven = 64,
Eight = 128,
Nine = 256,
Ten = 512
}
class Program
{
static void Main(string[] args)
{
TestFlags f = TestFlags.Five; /* or any other enum */
bool result = false;
Stopwatch s = Stopwatch.StartNew();
for (int i = 0; i < 10000000; i++)
{
result |= f.HasFlag(TestFlags.Three);
}
s.Stop();
Console.WriteLine(s.ElapsedMilliseconds); // *4793 ms*
s.Restart();
for (int i = 0; i < 10000000; i++)
{
result |= (f & TestFlags.Three) != 0;
}
s.Stop();
Console.WriteLine(s.ElapsedMilliseconds); // *27 ms*
Console.ReadLine();
}
}
Over 10 million iterations, the HasFlags extension method takes a whopping 4793 ms, compared to the 27 ms for the standard bitwise implementation.
A: I set up an extension method to do it: related question.
Basically:
public static bool IsSet( this Enum input, Enum matchTo )
{
return ( Convert.ToUInt32( input ) & Convert.ToUInt32( matchTo ) ) != 0;
}
Then you can do:
FlagTests testItem = FlagTests.Flag1 | FlagTests.Flag2;
if( testItem.IsSet ( FlagTests.Flag1 ) )
//Flag1 is set
Incidentally the convention I use for enums is singular for standard, plural for flags. That way you know from the enum name whether it can hold multiple values.
A: One more piece of advice... Never do the standard binary check with the flag whose value is "0". Your check on this flag will always be true.
[Flags]
public enum LevelOfDetail
{
[EnumMember(Value = "FullInfo")]
FullInfo=0,
[EnumMember(Value = "BusinessData")]
BusinessData=1
}
If you binary check input parameter against FullInfo - you get:
detailLevel = LevelOfDetail.BusinessData;
bool bPRez = (detailLevel & LevelOfDetail.FullInfo) == LevelOfDetail.FullInfo;
bPRez will always be true as ANYTHING & 0 always == 0.
Instead you should simply check that the value of the input is 0:
bool bPRez = (detailLevel == LevelOfDetail.FullInfo);
A: if ((testItem & FlagTest.Flag1) == FlagTest.Flag1)
{
// Do something
}
(testItem & FlagTest.Flag1) is a bitwise AND operation.
FlagTest.Flag1 is equivalent to 001 with OP's enum. Now let's say testItem has Flag1 and Flag2 (so it's bitwise 101):
001
&101
----
001 == FlagTest.Flag1
A: even without [Flags], you could use something like this
if((testItem & (FlagTest.Flag1 | FlagTest.Flag2 ))!=0){
//..
}
or if you have a Zero value enum
if((testItem & (FlagTest.Flag1 | FlagTest.Flag2 ))!=FlagTest.None){
//..
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40211",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "162"
} |
Q: GUIDs as Primary Keys - Offline OLTP We are working on designing an application that is typically OLTP (think: purchasing system). However, this one in particular has the need that some users will be offline, so they need to be able to download the DB to their machine, work on it, and then sync back once they're on the LAN.
I would like to note that I know this has been done before, I just don't have experience with this particular model.
One idea I thought about was using GUIDs as table keys. So for example, a Purchase Order would not have a number (auto-numeric) but a GUID instead, so that every offline client can generate those, and I don't have clashes when I connect back to the DB.
Is this a bad idea for some reason?
Will access to these tables through the GUID key be slow?
Have you had experience with these type of systems? How have you solved this problem?
Thanks!
Daniel
A: Using Guids as primary keys is acceptable and is considered a fairly standard practice for the same reasons that you are considering them. They can be overused which can make things a bit tedious to debug and manage, so try to keep them out of code tables and other reference data if at all possible.
The thing that you have to concern yourself with is the human readable identifier. Guids cannot be exchanged by people - can you imagine trying to confirm your order number over the phone if it is a guid? So in an offline scenario you may still have to generate something - like a publisher (workstation/user) id and some sequence number, so the order number may be 123-5678 -.
However this may not satisfy business requirements of having a sequential number. In fact regulatory requirements can be and influence - some regulations (SOX maybe) require that invoice numbers are sequential. In such cases it may be neccessary to generate a sort of proforma number which is fixed up later when the systems synchronise. You may land up with tables having OrderId (Guid), OrderNo (int), ProformaOrderNo (varchar) - some complexity may creep in.
At least having guids as primary keys means that you don't have to do a whole lot of cascading updates when the sync does eventually happen - you simply update the human readable number.
A: @SqlMenace
There are other problems with GUIDs, you see GUIDs are not sequential, so inserts will be scattered all over the place, this causes page splits and index fragmentation
Not true. Primary key != clustered index.
If the clustered index is another column ("inserted_on" springs to mind) then the inserts will be sequential and no page splits or excessive fragmentation will occur.
A: This is a perfectly good use of GUIDs. The only draw backs would be a slight complexity in working with GUIDs over INTs and the slight size difference (16 bytes vs 4 bytes).
I don't think either of those are a big deal.
A:
Will access to these tables through
the GUID key be slow?
There are other problems with GUIDs, you see GUIDs are not sequential, so inserts will be scattered all over the place, this causes page splits and index fragmentation
In SQL Server 2005 MS introduced NEWSEQUENTIALID() to fix this, the only problem for you might be that you can only use NEWSEQUENTIALID as a default value in a table
A: You're correct that this is an old problem, and it has two canonical solutions:
*
*Use unique identifiers as the primary key. Note that if you're concerned about readability you can roll your own unique identifier instead of using a GUID. A unique identifier will use information about the date and the machine to generate a unique value.
*Use a composite key of 'Actor' + identifier. Every user gets a numeric actor ID, and the keys of newly inserted rows use the actor ID as well as the next available identifier. So if two actors both insert a new row with ID "100", the primary key constraint will not be violated.
Personally, I prefer the first approach, as I think composite keys are really tedious as foreign keys. I think the human readability complaint is overstated -- end-users shouldn't have to know anything about your keys, anyways!
A: Make sure to utilize guid.comb - takes care of the indexing stuff. If you are dealing with performance issues after that then you will be, in short order, an expert on scaling.
Another reason to use GUIDs is to enable database refactoring. Say you decide to apply polymorphism or inheritance or whatever to your Customers entity. You now want Customers and Employees to derive from Person and have them share a table. Having really unique identifiers makes data migration simple. There are no sequences or integer identity fields to fight with.
A: I'm just going to point you to What are the performance improvement of Sequential Guid over standard Guid?, which covers the GUID talk.
For human readability, consider assigning machine IDs and then using sequential numbers from those machines as a possibility. This will require managing the assignment of machine IDs, though. Could be done in one or two columns.
I'm personally fond of the SGUID answer, though.
A: Guids will certainly be slower (and use more memory) than standard integer keys, but whether or not that is an issue will depend on the type of load your system will see. Depending on your backend DB there may be issues with indexing guid fields.
Using guids simplifies a whole class of problems, but you pay for it part will performance and also debuggability - typing guids into those test queries will get old real fast!
A: The backend will be SQL Server 2005
Frontend / Application Logic will be .Net
Besides GUIDs, can you think of other ways to resolve the "merge" that happens when the offline computer syncs the new data back into the central database?
I mean, if the keys are INTs, i'll have to renumber everything when importing basically. GUIDs will spare me of that.
A: Using GUIDs saved us a lot of work when we had to merge two databases into one.
A: If your database is small enough to download to a laptop and work with it offline, you probably don't need to worry too much about the performance differences between ints and Guids. But do not underestimate how useful ints are when developing and troubleshooting a system! You will probably need to come up with some fairly complex import/synch logic regardless of whether or not you are using Guids, so they might not help as much as you think.
A: @Simon,
You raise very good points. I was already thinking about the "temporary" "human-readable" numbers i'd generate while offline, that i'd recreate on sync. But i wanted to avoid doing with with foreign keys, etc.
A: i would start to look at SQL Server Compact Edition for this! It helps with all of your issues.
Data Storage Architecture with SQL Server 2005 Compact Edition
It specifically designed for
Field force applications (FFAs). FFAs
usually share one or more of the
following attributes
They allow the user to perform their
job functions while disconnected from
the back-end network—on-site at a
client location, on the road, in an
airport, or from home.
FFAs are usually designed for
occasional connectivity, meaning that
when users are running the client
application, they do not need to have
a network connection of any kind. FFAs
often involve multiple clients that
can concurrently access and use data
from the back-end database, both in a
connected and disconnected mode.
FFAs must be able to replicate data
from the back-end database to the
client databases for offline support.
They also need to be able to replicate
modified, added, or deleted data
records from the client to the server
when the application is able to
connect to the network
A: First thought that comes to mind: Hasn't MS designed the DataSet and DataAdapter model to support scenarios like this?
I believe I read that MS changed their ADO recordset model to the current DataSet model so it works great offline too. And there's also this Sync Services for ADO.NET
I believe I have seen code that utilizes the DataSet model which also uses foreign keys and they still sync perfectly when using the DataAdapter. Havn't try out the Sync Services though but I think you might be able to benefit from that too.
Hope this helps.
A: @Portman By default PK == Clustered Index, creating a primary key constraint will automatically create a clustered index, you need to specify non clustered if you don't want it clustered.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40230",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: What is the best way to migrate an existing messy webapp to elegant MVC? I joined a new company about a month ago. The company is rather small in size and has pretty strong "start-up" feel to it. I'm working as a Java developer on a team of 3 others. The company primarily sells a service to for businesses/business-type people to use in communicating with each other.
One of the main things I have been, and will be working on, is the main website for the company - from which the service is sold, existing users login to check their service and pay their bills, new users can sign up for a trial, etc. Currently this is a JSP application deployed on Tomcat, with access to a database done thru a persistence layer written by the company itself.
A repeated and growing frustration I am having here (and I'm pretty happy with the job overall, so this isn't an "oh no I don't like my job"-type post) is the lack of any larger design or architecture for this web application. The app is made up of several dozen JSP pages, with almost no logic existing in Servlets or Beans or any other sort of framework. Many of the JSP pages are thousands of lines of code, they jsp:include other JSP pages, business logic is mixed in with the HTML, frequently used snippets of code (such as obtaining a web service connection) is cut and paste rather than reused, etc. In other words, the application is a mess.
There have been some rumblings within the company of trying to re-architect this site so that it fits MVC better; I think that the developers and higher-ups are beginning to realize that this current pattern of spaghetti code isn't sustainable or very easily scalable to add more features for the users. The higher-ups and developers are wary of completely re-writing the thing (with good reason, since this would mean several weeks or months of work re-writing existing functionality), but we've had some discussions of (slowly) re-writing certain areas of the site into a new framework.
What are some of the best strategies to enable moving the application and codebase into this direction? How can I as a developer really help move this along, and quickly, without seeming like the jerk-y new guy who comes into a job and tells everyone that what they've written is crap? Are there any proven strategies or experiences that you've used in your own job experience when you've encountered this sort of thing?
A: First pick up a copy of Michael Feather's Working Effectively with Legacy Code. Then identify how best to test the existing code. The worst case is that you are stuck with just some high level regression tests (or nothing at all) and If you are lucky there will be unit tests. Then it is a case of slow steady refactoring hopefully while adding new business functionality at the same time.
A: In my experience, the "elegance" of an app typically has more to do with the database design than anything. If you have a great database design, including a well-defined stored procedure interface, good application code tends to follow no matter what platform you use. If you have poor database design, no matter what platform you use you'll have a very difficult time building elegant application code, as you'll be constantly compensating for the database.
Of course, there's plenty of room between great and poor, but my point is that if you want good application code, start by making sure your database is up to snuff.
A: This is harder to do in applications that are only in maintenance mode because it is hard to convince management that rewriting something that is already 'working' is worth doing. I would start by applying the principles of MVC to any new code that you are able to work on (ie. move business logic to something akin to a model, put all your layout/view code in one place)
As you gain experience with new code in MVC you can start seeing opportunities to change the existing code subtly so that it also falls in line. It can be a very slow process, but if you can show the benefits of this way of doing it then you will be able to convince others and get the entire team on board.
A: I would agree with the slow refactoring approach; for example, take that copy-and-pasted code and extract it into whatever the appropriate Java paradigm is (a class, perhaps? or better yet, use an existing library?). When your code is really clean and terse, yet still lacking in overall architectural strategy, then you'll be able to make things fit into an overall architecture much more easily.
A: Your best bet is probably to refactor it slowly as you go along. Few us of have the resources that would be required to completely start from scratch with something that has so many business rules buried in it. Management really hates it when you spend months on developing an app that has more bugs than the one you replaced.
If you have the opportunity to build any separate apps from scratch, use all of the best practices there and use it to demonstrate how effective they are. When you can, incorporate those ideas gradually into the old application.
A: Iteratively refactor. Also look for new features that can be done completely in the new framework as a way to show the value of the new framework.
A: My suggestion would be to find the rare pages that do not require an import of other JSPs, or have very few imports. Treat each JSP imported as a black box, and refactor these pages around them (iteratively, testing each change and making sure it works before continuing). Once these are cleaned up, you can continue finding pages with more and more imports, until finally you have refactored the imports.
When refactoring, note the parts that try to access resources not given to the page and try to take this out to a controller. For instance, anything that accesses the database should be inside a controller, let the JSP handle the display of the information the controller gives to it via a forward. In this way you will develop several servlets, or things like servlets, for each page. I would suggest using a front-controller based framework for this refactoring (from personal experience I recommend Spring and its Controller interface), so that each controller isn't a separate Servlet but is rather delegated to from a single servlet that is mapped appropriately.
For the controller, it is better to do database hits all at once rather than attempt them piecemeal. Users can and generally do tolerate a page load, but the page output will be much faster if all the database data is given to the rendering code rather than the rendering code hanging and not giving data to the client while it is trying to read yet another piece of data from the database.
I feel your pain and wish you luck in this endeavor. Now, when you have to maintain an application that abuses Spring Webflow, that's another story :)
A: The best way is to print out the code, crumple it up, and throw it out. Don't even recycle the paper.
You've got an application that is written in 1,000+ line long JSPs. It probably has a god-awful Domain Model (if it even has one at all) and doesn't just MIX presentation with business logic, it BLENDS it and sits there and keeps stirring for hours. There is no way to take out the code that is crappy and move into an MVC Controller class and still be doing the right thing, you'll just end up with a MVC app with an anemic domain model or one that has stuff like Database calls in Controller code, you're still failing.
You could try a new app that does the right thing and then have the two apps talk to each other, but that's new complexity in itself. Also you're likely going to be doing the same amount of work that you were going to do if you just started from scratch, but you might have an easier time trying to convince your bosses that this is a better approach.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40242",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How to make a pipe loop in bash Assume that I have programs P0, P1, ...P(n-1) for some n > 0. How can I easily redirect the output of program Pi to program P(i+1 mod n) for all i (0 <= i < n)?
For example, let's say I have a program square, which repeatedly reads a number and than prints the square of that number, and a program calc, which sometimes prints a number after which it expects to be able to read the square of it. How do I connect these programs such that whenever calc prints a number, square squares it returns it to calc?
Edit: I should probably clarify what I mean with "easily". The named pipe/fifo solution is one that indeed works (and I have used in the past), but it actually requires quite a bit of work to do properly if you compare it with using a bash pipe. (You need to get a not yet existing filename, make a pipe with that name, run the "pipe loop", clean up the named pipe.) Imagine you could no longer write prog1 | prog2 and would always have to use named pipes to connect programs.
I'm looking for something that is almost as easy as writing a "normal" pipe. For instance something like { prog1 | prog2 } >&0 would be great.
A: This is a very interesting question. I (vaguely) remember an assignment very similar in college 17 years ago. We had to create an array of pipes, where our code would get filehandles for the input/output of each pipe. Then the code would fork and close the unused filehandles.
I'm thinking you could do something similar with named pipes in bash. Use mknod or mkfifo to create a set of pipes with unique names you can reference then fork your program.
A: My solutions uses pipexec (Most of the function implementation comes from your answer):
square.sh
function square() {
# square numbers
read j # receive first "request"
while [ "$j" != "" ]; do
let jj=$j*$j
echo "square($j) = $jj" >&2 # debug message
echo $jj # send square
read j # receive next "request"
done
}
square $@
calc.sh
function calc() {
# calculate sum of squares of numbers 0,..,10
sum=0
for ((i=0; i<10; i++)); do
echo $i # "request" the square of i
read ii # read the square of i
echo "got $ii" >&2 # debug message
let sum=$sum+$ii
done
echo "sum $sum" >&2 # output result to stderr
}
calc $@
The command
pipexec [ CALC /bin/bash calc.sh ] [ SQUARE /bin/bash square.sh ] \
"{CALC:1>SQUARE:0}" "{SQUARE:1>CALC:0}"
The output (same as in your answer)
square(0) = 0
got 0
square(1) = 1
got 1
square(2) = 4
got 4
square(3) = 9
got 9
square(4) = 16
got 16
square(5) = 25
got 25
square(6) = 36
got 36
square(7) = 49
got 49
square(8) = 64
got 64
square(9) = 81
got 81
sum 285
Comment: pipexec was designed to start processes and build arbitrary pipes in between. Because bash functions cannot be handled as processes, there is the need to have the functions in separate files and use a separate bash.
A: After spending quite some time yesterday trying to redirect stdout to stdin, I ended up with the following method. It isn't really nice, but I think I prefer it over the named pipe/fifo solution.
read | { P0 | ... | P(n-1); } >/dev/fd/0
The { ... } >/dev/fd/0 is to redirect stdout to stdin for the pipe sequence as a whole (i.e. it redirects the output of P(n-1) to the input of P0). Using >&0 or something similar does not work; this is probably because bash assumes 0 is read-only while it doesn't mind writing to /dev/fd/0.
The initial read-pipe is necessary because without it both the input and output file descriptor are the same pts device (at least on my system) and the redirect has no effect. (The pts device doesn't work as a pipe; writing to it puts things on your screen.) By making the input of the { ... } a normal pipe, the redirect has the desired effect.
To illustrate with my calc/square example:
function calc() {
# calculate sum of squares of numbers 0,..,10
sum=0
for ((i=0; i<10; i++)); do
echo $i # "request" the square of i
read ii # read the square of i
echo "got $ii" >&2 # debug message
let sum=$sum+$ii
done
echo "sum $sum" >&2 # output result to stderr
}
function square() {
# square numbers
read j # receive first "request"
while [ "$j" != "" ]; do
let jj=$j*$j
echo "square($j) = $jj" >&2 # debug message
echo $jj # send square
read j # receive next "request"
done
}
read | { calc | square; } >/dev/fd/0
Running the above code gives the following output:
square(0) = 0
got 0
square(1) = 1
got 1
square(2) = 4
got 4
square(3) = 9
got 9
square(4) = 16
got 16
square(5) = 25
got 25
square(6) = 36
got 36
square(7) = 49
got 49
square(8) = 64
got 64
square(9) = 81
got 81
sum 285
Of course, this method is quite a bit of a hack. Especially the read part has an undesired side-effect: termination of the "real" pipe loop does not lead to termination of the whole. I couldn't think of anything better than read as it seems that you can only determine that the pipe loop has terminated by try to writing write something to it.
A: A named pipe might do it:
$ mkfifo outside
$ <outside calc | square >outside &
$ echo "1" >outside ## Trigger the loop to start
A: Named pipes.
Create a series of fifos, using mkfifo
i.e fifo0, fifo1
Then attach each process in term to the pipes you want:
processn < fifo(n-1) > fifon
A: A command stack can be composed as string from an array of arbitrary commands
and evaluated with eval. The following example gives the result 65536.
function square ()
{
read n
echo $((n*n))
} # ---------- end of function square ----------
declare -a commands=( 'echo 4' 'square' 'square' 'square' )
#-------------------------------------------------------------------------------
# build the command stack using pipes
#-------------------------------------------------------------------------------
declare stack=${commands[0]}
for (( COUNTER=1; COUNTER<${#commands[@]}; COUNTER++ )); do
stack="${stack} | ${commands[${COUNTER}]}"
done
#-------------------------------------------------------------------------------
# run the command stack
#-------------------------------------------------------------------------------
eval "$stack"
A: I doubt sh/bash can do it.
ZSH would be a better bet, with its MULTIOS and coproc features.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40244",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "23"
} |
Q: GUI/TUI linux library Is there any UI library that can be to build both a text user interface (ncurses) and graphical user interface (GTK? QT?) from the same source?
I know that debconf can be used with various frontends, I would like to build something similar but programmable.
A: The library that powers YaST independence to do ncurses, gtk and qt with one codebase provides what you are looking for, and it is not tied to YaST itself.
Actually libyui only requires the standard C++ library and phtreads (IIRC). The UI plugins require of course the respective libraries (Qt, ncurses). YaST uses libyui via a set of YCP bindings that export a YCP like API on top of libyui.
The library is a bit lowlevel (one layer below an event loop), my colleage Klaus Kämpf wrote about using it some time ago in his blog, including binding to scripting languages it using swig.
The only part that is SUSE specific is the packaging, so you would need to package it yourself. Stackoverflow did not allow me to link more than once. The code of the library is linked from Klaus blog. Replace libyui for "qt" and "ncurses" for the plugin's code.
Also google for "YaST Independence From YCP" to find a blog entry from Andreas Jäger on the subject.
A: you could write your program to uses ncurses, and then use PDCurses to convert it to an X11 application - as the readme advertise.
I know it because I've used it as portable curses, though I've never tested its X11 capabilities
A: Not exactly a library but you could consider writing a web app that degrades well to Lynx
A: The GoboLinux guys have created their own toolkit for python called AbsTK, they use it for their installer, which actually works really good. I have never used the toolkit myself, but the apps built with it seems solid.
A: There's Cursed GTK, but it seems a bit dated. I found some references to a port of Qt to ncurses called Qt Console, but it seems to have disappeared.
A: By using a library that targets both the text-mode and GUI environments, you have a big risk of getting stuck with the worst of both worlds.
You will be better off structuring your code using the MVC pattern, and providing separate views and controllers for each platform you target. Pushing all the logic down to the model classes has several other benefits:
*
*The code will be easier to test because you are forced to keep the user interface out of the actual domain logic.
*Your program can have user interfaces that have very little in common, e.g. a web UI, or an UI driven by speech.
*You can run the program easily with no UI at all (i.e. script it) by accessing the model classes directly in the same way that the controller classes do.
A: Maybe tcl/tk would provide what you want http://www.tcl.tk/
Here's the page on interfacing with curses. There is a claim there of integration with ncurses.
http://www2.tcl.tk/2372
A: I think what's used for configuring the linux kernel when compiling is dialog/cdialog/xdialog. But it's been a while since I've compiled a kernel, so my memory may be off. The most promising link I can find is this one for Xdialog.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40259",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: How many constructor arguments is too many? Let's say you have a class called Customer, which contains the following fields:
*
*UserName
*Email
*First Name
*Last Name
Let's also say that according to your business logic, all Customer objects must have these four properties defined.
Now, we can do this pretty easily by forcing the constructor to specify each of these properties. But it's pretty easy to see how this can spiral out of control when you are forced to add more required fields to the Customer object.
I've seen classes that take in 20+ arguments into their constructor and it's just a pain to use them. But, alternatively, if you don't require these fields you run into the risk of having undefined information, or worse, object referencing errors if you rely on the calling code to specify these properties.
Are there any alternatives to this or do you you just have to decide whether X amount of constructor arguments is too many for you to live with?
A: If you have unpalatably many arguments, then just package them together into structs / POD classes, preferably declared as inner classes of the class you are constructing. That way you can still require the fields while making the code that calls the constructor reasonably readable.
A: I think it all depends on the situation. For something like your example, a customer class, I wouldn't risk the chance of having that data being undefined when needed. On the flip side, passing a struct would clear up the argument list, but you would still have a lot of things to define in the struct.
A: I think your question is more about the design of your classes than about the number of arguments in the constructor. If I needed 20 pieces of data (arguments) to successfully initialize an object, I would probably consider breaking up the class.
A: I see that some people are recommending seven as an upper limit. Apparently it is not true that people can hold seven things in their head at once; they can only remember four (Susan Weinschenk, 100 Things Every Designer Needs to Know about People, 48). Even so, I consider four to be something of a high earth orbit. But that's because my thinking has been altered by Bob Martin.
In Clean Code, Uncle Bob argues for three as an general upper limit for number of parameters. He makes the radical claim (40):
The ideal number of arguments for a function is zero (niladic). Next comes one (monadic) followed closely by two (dyadic). Three arguments (triadic) should be avoided where possible. More than three (polyadic) requires very special justification—and then shouldn't be used anyway.
He says this because of readability; but also because of testability:
Imagine the difficulty of writing all the test cases to ensure that all various combinations of arguments work properly.
I encourage you to find a copy of his book and read his full discussion of function arguments (40-43).
I agree with those who have mentioned the Single Responsibility Principle. It is hard for me to believe that a class that needs more than two or three values/objects without reasonable defaults really has only one responsibility, and would not be better off with another class extracted.
Now, if you are injecting your dependencies through the constructor, Bob Martin's arguments about how easy it is to invoke the constructor do not so much apply (because usually then there is only one point in your application where you wire that up, or you even have a framework that does it for you). However, the Single Responsibility Principle is still relevant: once a class has four dependencies, I consider that a smell that it is doing a large amount of work.
However, as with all things in computer science, there are doubtless valid cases for having a large number of constructor parameters. Don't contort your code to avoid using a large number of parameters; but if you do use a large number of parameters, stop and give it some thought, because it may mean your code is already contorted.
A: Steve Mcconnell writes in Code Complete that people have trouble keeping more 7 things in their head at a time, so that'd be the number I try to stay under.
A: I'd encapsulate similar fields into an object of its own with its own construction/validation logic.
Say for example, if you've got
*
*BusinessPhone
*BusinessAddress
*HomePhone
*HomeAddress
I'd make a class that stores phone and address together with a tag specifying wether its a "home" or a "business" phone/address. And then reduce the 4 fields to merely an array.
ContactInfo cinfos = new ContactInfo[] {
new ContactInfo("home", "+123456789", "123 ABC Avenue"),
new ContactInfo("biz", "+987654321", "789 ZYX Avenue")
};
Customer c = new Customer("john", "doe", cinfos);
That should make it look less like spaghetti.
Surely if you have a lot of fields, there must be some pattern you can extract out that would make a nice unit of function of its own. And make for more readable code too.
And the following is also possible solutions:
*
*Spread out the validation logic instead of storing it in a single class. Validate when user input them and then validate again at the database layer etc...
*Make a CustomerFactory class that would help me construct Customers
*@marcio's solution is also interesting...
A: Style counts for a lot, and it seems to me that if there is a constructor with 20+ arguments, then the design should be altered. Provide reasonable defaults.
A: I would think the easiest way would be to find an acceptable default for each value. In this case, each field looks like it would be required to construct, so possibly overload the function call so that if something is not defined in the call, to set it to a default.
Then, make getter and setter functions for each property so that the default values could be changed.
Java implementation:
public static void setEmail(String newEmail){
this.email = newEmail;
}
public static String getEmail(){
return this.email;
}
This is also good practice to keep your global variables secure.
A: In your case, stick with the constructor. The information belongs in Customer and 4 fields are fine.
In the case you have many required and optional fields the constructor is not the best solution. As @boojiboy said, it's hard to read and it's also hard to write client code.
@contagious suggested using the default pattern and setters for optional attributs. That mandates that the fields are mutable, but that's a minor problem.
Joshua Block on Effective Java 2 say that in this case you should consider a builder. An example taken from the book:
public class NutritionFacts {
private final int servingSize;
private final int servings;
private final int calories;
private final int fat;
private final int sodium;
private final int carbohydrate;
public static class Builder {
// required parameters
private final int servingSize;
private final int servings;
// optional parameters
private int calories = 0;
private int fat = 0;
private int carbohydrate = 0;
private int sodium = 0;
public Builder(int servingSize, int servings) {
this.servingSize = servingSize;
this.servings = servings;
}
public Builder calories(int val)
{ calories = val; return this; }
public Builder fat(int val)
{ fat = val; return this; }
public Builder carbohydrate(int val)
{ carbohydrate = val; return this; }
public Builder sodium(int val)
{ sodium = val; return this; }
public NutritionFacts build() {
return new NutritionFacts(this);
}
}
private NutritionFacts(Builder builder) {
servingSize = builder.servingSize;
servings = builder.servings;
calories = builder.calories;
fat = builder.fat;
soduim = builder.sodium;
carbohydrate = builder.carbohydrate;
}
}
And then use it like this:
NutritionFacts cocaCola = new NutritionFacts.Builder(240, 8).
calories(100).sodium(35).carbohydrate(27).build();
The example above was taken from Effective Java 2
And that doesn't only applies to constructor. Citing Kent Beck in Implementation Patterns:
setOuterBounds(x, y, width, height);
setInnerBounds(x + 2, y + 2, width - 4, height - 4);
Making the rectangle explicit as an object explains the code better:
setOuterBounds(bounds);
setInnerBounds(bounds.expand(-2));
A: Two design approaches to consider
The essence pattern
The fluent interface pattern
These are both similar in intent, in that we slowly build up an intermediate object, and then create our target object in a single step.
An example of the fluent interface in action would be:
public class CustomerBuilder {
String surname;
String firstName;
String ssn;
public static CustomerBuilder customer() {
return new CustomerBuilder();
}
public CustomerBuilder withSurname(String surname) {
this.surname = surname;
return this;
}
public CustomerBuilder withFirstName(String firstName) {
this.firstName = firstName;
return this;
}
public CustomerBuilder withSsn(String ssn) {
this.ssn = ssn;
return this;
}
// client doesn't get to instantiate Customer directly
public Customer build() {
return new Customer(this);
}
}
public class Customer {
private final String firstName;
private final String surname;
private final String ssn;
Customer(CustomerBuilder builder) {
if (builder.firstName == null) throw new NullPointerException("firstName");
if (builder.surname == null) throw new NullPointerException("surname");
if (builder.ssn == null) throw new NullPointerException("ssn");
this.firstName = builder.firstName;
this.surname = builder.surname;
this.ssn = builder.ssn;
}
public String getFirstName() { return firstName; }
public String getSurname() { return surname; }
public String getSsn() { return ssn; }
}
import static com.acme.CustomerBuilder.customer;
public class Client {
public void doSomething() {
Customer customer = customer()
.withSurname("Smith")
.withFirstName("Fred")
.withSsn("123XS1")
.build();
}
}
A: I think the "pure OOP" answer is that if operations on the class are invalid when certain members aren't initialized, then these members must be set by the constructor. There's always the case where default values can be used, but I'll assume we're not considering that case. This is a good approach when the API is fixed, because changing the single allowable constructor after the API goes public will be a nightmare for you and all users of your code.
In C#, what I understand about the design guidelines is that this isn't necessarily the only way to handle the situation. Particularly with WPF objects, you'll find that .NET classes tend to favor parameterless constructors and will throw exceptions if the data has not been initialized to a desirable state before calling the method. This is probably mainly specific to component-based design though; I can't come up with a concrete example of a .NET class that behaves in this manner. In your case, it'd definitely cause an increased burden on testing to ensure that the class is never saved to the data store unless the properties have been validated. Honestly because of this I'd prefer the "constructor sets the required properties" approach if your API is either set in stone or not public.
The one thing I am certain of is that there are probably countless methodologies that can solve this problem, and each of them introduces its own set of problems. The best thing to do is learn as many patterns as possible and pick the best one for the job. (Isn't that such a cop-out of an answer?)
A: Just use default arguments. In a language that supports default method arguments (PHP, for example), you could do this in the method signature:
public function doSomethingWith($this = val1, $this = val2, $this = val3)
There are other ways to create default values, such as in languages that support method overloading.
Of course, you could also set default values when you declare the fields, if you deem it appropriate to do so.
It really just comes down to whether or not it is appropriate for you to set these default values, or if your objects should be specced out at construction all the time. That's really a decision that only you can make.
A: I agree on the 7 item limit Boojiboy mentions. Beyond that, it may be worth looking at anonymous (or specialized) types, IDictionary, or indirection via primary key to another data source.
A: In a more Object-Oriented situation of the problem, you can use properties in C#. It doesn't help much if you create an instance of an object, but suppose we have a parent class that needs too many parameters in its constructor.
Since you can have abstract properties, you can use this to your advantage. The parent class needs to define an abstract property that the child class must override.
Normally a class might look like:
class Customer {
private string name;
private int age;
private string email;
Customer(string name, int age, string email) {
this.name = name;
this.age = age;
this.email = email;
}
}
class John : Customer {
John() : base("John", 20, "[email protected]") {
}
}
It can become messy and unreadable with too many parameters.
Whereas this method:
class Customer {
protected abstract string name { get; }
protected abstract int age { get; }
protected abstract string email { get; }
}
class John : Customer {
protected override string name => "John";
protected override int age => 20;
protected override string email=> "[email protected]";
}
Which is much cleaner code in my opinion and no contractors are needed in this case, which saves room for other necessary parameters.
A: Unless it's more than 1 argument, I always use arrays or objects as constructor parameters and rely on error checking to make sure the required parameters are there.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40264",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "162"
} |
Q: Finding the storage card path on WM6 Is there an easy way to find the storage card's path on a Windows Mobile device
when there is a storage card and a bluetooth ftp connection?
A: Keep in mind that "\Storage Card" is english oriented. A device made for a different region may have a different name. The name of the storage card path on my device varies with how I am using the device.
Some time ago in the MSDN forms I responded to a few questions on how to detect the storage cards in the file system and how does one get the storage card's capacity. I wrote the following could are a response to those questions and thought it would be helpful to share. Storage cards show up in the file system as temporary directories. This program examines the objects in the root of the device and any folders that have temp attribute are considered to be a positive match
using System;
using System.IO;
using System.Runtime.InteropServices;
namespace StorageCardInfo
{
class Program
{
const ulong Megabyte = 1048576;
const ulong Gigabyte = 1073741824;
[DllImport("CoreDLL")]
static extern int GetDiskFreeSpaceEx(
string DirectoryName,
out ulong lpFreeBytesAvailableToCaller,
out ulong lpTotalNumberOfBytes,
out ulong lpTotalNumberOfFreeBytes
);
static void Main(string[] args)
{
DirectoryInfo root = new DirectoryInfo("\\");
DirectoryInfo[] directoryList = root.GetDirectories();
ulong FreeBytesAvailable;
ulong TotalCapacity;
ulong TotalFreeBytes;
for (int i = 0; i < directoryList.Length; ++i)
{
if ((directoryList.Attributes & FileAttributes.Temporary) != 0)
{
GetDiskFreeSpaceEx(directoryList.FullName, out FreeBytesAvailable, out TotalCapacity, out TotalFreeBytes);
Console.Out.WriteLine("Storage card name: {0}", directoryList.FullName);
Console.Out.WriteLine("Available Bytes : {0}", FreeBytesAvailable);
Console.Out.WriteLine("Total Capacity : {0}", TotalCapacity);
Console.Out.WriteLine("Total Free Bytes : {0}", TotalFreeBytes);
}
}
}
}
A: I've found using the FindFirstFlashCard/FindNextFlashCard APIs to be more reliable than enumerating directories and checking the temporary flag (which will return bluetooth shared folders for example).
The following sample application demonstrates how to use them and the required P/Invoke statements.
using System;
using System.Runtime.InteropServices;
namespace RemovableStorageTest
{
class Program
{
static void Main(string[] args)
{
string removableDirectory = GetRemovableStorageDirectory();
if (removableDirectory != null)
{
Console.WriteLine(removableDirectory);
}
else
{
Console.WriteLine("No removable drive found");
}
}
public static string GetRemovableStorageDirectory()
{
string removableStorageDirectory = null;
WIN32_FIND_DATA findData = new WIN32_FIND_DATA();
IntPtr handle = IntPtr.Zero;
handle = FindFirstFlashCard(ref findData);
if (handle != INVALID_HANDLE_VALUE)
{
do
{
if (!string.IsNullOrEmpty(findData.cFileName))
{
removableStorageDirectory = findData.cFileName;
break;
}
}
while (FindNextFlashCard(handle, ref findData));
FindClose(handle);
}
return removableStorageDirectory;
}
public static readonly IntPtr INVALID_HANDLE_VALUE = (IntPtr)(-1);
// The CharSet must match the CharSet of the corresponding PInvoke signature
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct WIN32_FIND_DATA
{
public int dwFileAttributes;
public FILETIME ftCreationTime;
public FILETIME ftLastAccessTime;
public FILETIME ftLastWriteTime;
public int nFileSizeHigh;
public int nFileSizeLow;
public int dwOID;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string cFileName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 14)]
public string cAlternateFileName;
}
[StructLayout(LayoutKind.Sequential)]
public struct FILETIME
{
public int dwLowDateTime;
public int dwHighDateTime;
};
[DllImport("note_prj", EntryPoint = "FindFirstFlashCard")]
public extern static IntPtr FindFirstFlashCard(ref WIN32_FIND_DATA findData);
[DllImport("note_prj", EntryPoint = "FindNextFlashCard")]
[return: MarshalAs(UnmanagedType.Bool)]
public extern static bool FindNextFlashCard(IntPtr hFlashCard, ref WIN32_FIND_DATA findData);
[DllImport("coredll")]
public static extern bool FindClose(IntPtr hFindFile);
}
}
A: There's a pure C# way to do this without native calls.
Taken from here.
//codesnippet:06EE3DE0-D469-44DD-A15F-D8AF629E4E03
public string GetStorageCardFolder()
{
string storageCardFolder = string.Empty;
foreach (string directory in Directory.GetDirectories("\\"))
{
DirectoryInfo dirInfo = new DirectoryInfo(directory);
//Storage cards have temporary attributes do a bitwise check.
//http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=612136&SiteID=1
if ((dirInfo.Attributes & FileAttributes.Temporary) == FileAttributes.Temporary)
storageCardFolder = directory;
}
return storageCardFolder;
}
A: Can't add a comment on the TreeUK and ctacke discusion below :
This isn't guaranteed to find a
Storage Card - many devices mount
built-in flash in teh same way, and it
would show up in this list as well. –
ctacke May 8 at 18:23
This has
worked well for me on HTC and Psion
devices. What devices are you aware
this doesn't work on? Would be worth
seeing if there's another attribute
you can discount the build in flash
memory with. – TreeUK May 9 at 22:29
To give a idea on a Motorola MC75 (used to be SymboL), i used this piece (of native) code :
WIN32_FIND_DATA cardinfo;
HANDLE card = FindFirstFlashCard(&cardinfo);
if (card != INVALID_HANDLE_VALUE)
{
TCHAR existFile[MAX_PATH];
wprintf(_T("found : %s\n"), cardinfo.cFileName);
while(FindNextFlashCard(card, &cardinfo))
{
wprintf(_T("found : %s\n"), cardinfo.cFileName);
}
}
FindClose(card);
Debug output :
cardinfo.dwFileAttributes 0x00000110 unsigned long int
cardinfo.cFileName "Application" wchar_t[260]
cardinfo.dwFileAttributes 0x00000110 unsigned long int
cardinfo.cFileName "Cache Disk" wchar_t[260]
cardinfo.dwFileAttributes 0x00000110 unsigned long int
cardinfo.cFileName "Storage Card" wchar_t[260]
The "Application" and "Cache disk" are internal Flash drives. The "Storage Card" a removable SD Card. All are marked as a FlashDrive (which they are), but only "Storage Card" is removable.
A: I post here the code that I use to get the mount dirs of the storage cards.
The part where I get the flash cards paths is copied from Sibly's post with a few changes.
The main difference is in that I search through the mount dirs of all the flash cards and I keep the one(s) that match the default storage card name that I read from windows' registry.
It solves the problem that one has on motorola's smart devices where there are multiple flash cards and only one sd card reader whose mount dir's name can change from the default by the numeric suffix (ie. in english WM systems: 'Storage Card' , 'Storage Card2' and so on).
I tested it on some motorola models (MC75, MC75A, MC90, MC65) with WM 6.5 english.
This solution should work well with different windows mobile's languages but I don't know if it can deal with those that change the
default name of the storage cards.
It all depends whether the device's manufacturer updates the windows registry with the new default name.
It would be great if you can test it on different WMs or devices.
Feedback is welcome.
//
// the storage card is a flash drive mounted as a directory in the root folder
// of the smart device
//
// on english windows mobile systems the storage card is mounted in the directory "/Storage Card",
// if that directory already exists then it's mounted in "/Storage Card2" and so on
//
// the regional name of the mount base dir of the storage card can be found in
// the registry at [HKEY_LOCAL_MACHINE\System\StorageManager\Profiles\SDMemory\Folder]
//
// in order to find the path of the storage card we look for the flash drive that starts
// with the base name
//
public class StorageCard
{
private StorageCard()
{
}
public static List<string> GetMountDirs()
{
string key = @"HKEY_LOCAL_MACHINE\System\StorageManager\Profiles\SDMemory";
string storageCardBaseName = Registry.GetValue(key, "Folder", "Storage Card") as String;
List<string> storageCards = new List<string>();
foreach (string flashCard in GetFlashCardMountDirs())
{
string path = flashCard.Trim();
if (path.StartsWith(storageCardBaseName))
{
storageCards.Add(path);
}
}
return storageCards;
}
private static List<string> GetFlashCardMountDirs()
{
List<string> storages = new List<string>();
WIN32_FIND_DATA findData = new WIN32_FIND_DATA();
IntPtr handle = IntPtr.Zero;
handle = FindFirstFlashCard(ref findData);
if (handle != INVALID_HANDLE_VALUE)
{
do
{
if (!string.IsNullOrEmpty(findData.cFileName))
{
storages.Add(findData.cFileName);
storages.Add(findData.cAlternateFileName);
}
}
while (FindNextFlashCard(handle, ref findData));
FindClose(handle);
}
return storages;
}
private static readonly IntPtr INVALID_HANDLE_VALUE = (IntPtr)(-1);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
private struct WIN32_FIND_DATA
{
public int dwFileAttributes;
public FILETIME ftCreationTime;
public FILETIME ftLastAccessTime;
public FILETIME ftLastWriteTime;
public int nFileSizeHigh;
public int nFileSizeLow;
public int dwOID;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string cFileName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 14)]
public string cAlternateFileName;
}
[StructLayout(LayoutKind.Sequential)]
private struct FILETIME
{
public int dwLowDateTime;
public int dwHighDateTime;
};
[DllImport("note_prj", EntryPoint = "FindFirstFlashCard")]
private extern static IntPtr FindFirstFlashCard(ref WIN32_FIND_DATA findData);
[DllImport("note_prj", EntryPoint = "FindNextFlashCard")]
[return: MarshalAs(UnmanagedType.Bool)]
private extern static bool FindNextFlashCard(IntPtr hFlashCard, ref WIN32_FIND_DATA findData);
[DllImport("coredll")]
private static extern bool FindClose(IntPtr hFindFile);
}
A: I have combined a number of the solutions above, particularly qwlice's code, to find SD cards on a range of devices. This solution finds SD cards only (so excludes all of the internal "storage cards" that some devices have) without using native dll calls.
The code searches the HKEY_LOCAL_MACHINE\System\StorageManager\Profiles\ key for keys containing "SD" as the name varies slightly on some devices, finds the default mount dir and then looks for temp directories that start with this. This means that it will find \StorageCard2, \StorageCard3, etc.
I have been using this on a range of Intermec and Motorola/Symbol devices and haven't had any problems. Here is the code below:
public class StorageCardFinder
{
public static List<string> GetMountDirs()
{
//get default sd card folder name
string key = @"HKEY_LOCAL_MACHINE\System\StorageManager\Profiles";
RegistryKey profiles = Registry.LocalMachine.OpenSubKey(@"System\StorageManager\Profiles");
string sdprofilename = profiles.GetSubKeyNames().FirstOrDefault(k => k.Contains("SD"));
if (sdprofilename == null)
return new List<string>();
key += "\\" + sdprofilename;
string storageCardBaseName = Registry.GetValue(key, "Folder", "Storage Card") as String;
if (storageCardBaseName == null)
return new List<string>();
//find storage card
List<string> cardDirectories = GetFlashCardMountDirs();
List<string> storageCards = new List<string>();
foreach (string flashCard in GetFlashCardMountDirs())
{
string path = flashCard.Trim();
if (path.StartsWith(storageCardBaseName))
{
storageCards.Add("\\" + path);
}
}
return storageCards;
}
private static List<string> GetFlashCardMountDirs()
{
DirectoryInfo root = new DirectoryInfo("\\");
return root.GetDirectories().Where(d => (d.Attributes & FileAttributes.Temporary) != 0)
.Select(d => d.Name).ToList();
}
}
A: The mount point is usually "\Storage Card" but can be localized into other languages or modified by OEMs (some devices use "\SD Card" or other mount points, and some devices support mounting multiple storage media). The best way to enumerate the available cards is to use FindFirstFlashCard and FindNextFlashCard.
Both functions fill in a WIN32_FIND_DATA structure. The most important field is cFileName, which will contain the path to the card's mount point (e.g. "\Storage Card").
Note that the device's internal memory will also be enumerated by these functions. If you only care about external volumes, ignore the case where cFileName is an empty string ("").
Using these functions require you to #include <projects.h> and link with note_prj.lib. Both are included in the Windows Mobile SDKs for WM 2000 and later.
A: On Windows CE 5 (which is the base for Windows Mobile 6) the storage cards get mounted at the root file system as "Storage Card\", "Storage Card2\", etc.
To find out if it's mounted call GetFileAttributes (or the remote version CeGetFileAttributes I believe) passing in the full path ("\Storage Card\"). If it returns INVALID_FILE_ATTRIBUTES then it's not mounted, otherwise check to make sure it's a directory before returning true.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40269",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: What's the best way to use SOAP with Ruby? A client of mine has asked me to integrate a 3rd party API into their Rails app. The only problem is that the API uses SOAP. Ruby has basically dropped SOAP in favor of REST. They provide a Java adapter that apparently works with the Java-Ruby bridge, but we'd like to keep it all in Ruby, if possible. I looked into soap4r, but it seems to have a slightly bad reputation.
So what's the best way to integrate SOAP calls into a Rails app?
A: I also recommend Savon. I spent too many hours trying to deal with Soap4R, without results. Big lack of functionality, no doc.
Savon is the answer for me.
A: Try SOAP4R
*
*SOAP4R
*Getting Started with SOAP4R
And I just heard about this on the Rails Envy Podcast (ep 31):
*
*WS-Deathstar SOAP walkthrough
A: We used the built in soap/wsdlDriver class, which is actually SOAP4R.
It's dog slow, but really simple. The SOAP4R that you get from gems/etc is just an updated version of the same thing.
Example code:
require 'soap/wsdlDriver'
client = SOAP::WSDLDriverFactory.new( 'http://example.com/service.wsdl' ).create_rpc_driver
result = client.doStuff();
That's about it
A: Just got my stuff working within 3 hours using Savon.
The Getting Started documentation on Savon's homepage was really easy to follow - and actually matched what I was seeing (not always the case)
A: Kent Sibilev from Datanoise had also ported the Rails ActionWebService library to Rails 2.1 (and above).
This allows you to expose your own Ruby-based SOAP services.
He even has a scaffold/test mode which allows you to test your services using a browser.
A: I have used HTTP call like below to call a SOAP method,
require 'net/http'
class MyHelper
def initialize(server, port, username, password)
@server = server
@port = port
@username = username
@password = password
puts "Initialised My Helper using #{@server}:#{@port} username=#{@username}"
end
def post_job(job_name)
puts "Posting job #{job_name} to update order service"
job_xml ="<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ns=\"http://test.com/Test/CreateUpdateOrders/1.0\">
<soapenv:Header/>
<soapenv:Body>
<ns:CreateTestUpdateOrdersReq>
<ContractGroup>ITE2</ContractGroup>
<ProductID>topo</ProductID>
<PublicationReference>#{job_name}</PublicationReference>
</ns:CreateTestUpdateOrdersReq>
</soapenv:Body>
</soapenv:Envelope>"
@http = Net::HTTP.new(@server, @port)
puts "server: " + @server + "port : " + @port
request = Net::HTTP::Post.new(('/XISOAPAdapter/MessageServlet?/Test/CreateUpdateOrders/1.0'), initheader = {'Content-Type' => 'text/xml'})
request.basic_auth(@username, @password)
request.body = job_xml
response = @http.request(request)
puts "request was made to server " + @server
validate_response(response, "post_job_to_pega_updateorder job", '200')
end
private
def validate_response(response, operation, required_code)
if response.code != required_code
raise "#{operation} operation failed. Response was [#{response.inspect} #{response.to_hash.inspect} #{response.body}]"
end
end
end
/*
test = MyHelper.new("mysvr.test.test.com","8102","myusername","mypassword")
test.post_job("test_201601281419")
*/
Hope it helps. Cheers.
A: I have used SOAP in Ruby when i've had to make a fake SOAP server for my acceptance tests. I don't know if this was the best way to approach the problem, but it worked for me.
I have used Sinatra gem (I wrote about creating mocking endpoints with Sinatra here) for server and also Nokogiri for XML stuff (SOAP is working with XML).
So, for the beginning I have create two files (e.g. config.rb and responses.rb) in which I have put the predefined answers that SOAP server will return.
In config.rb I have put the WSDL file, but as a string.
@@wsdl = '<wsdl:definitions name="StockQuote"
targetNamespace="http://example.com/stockquote.wsdl"
xmlns:tns="http://example.com/stockquote.wsdl"
xmlns:xsd1="http://example.com/stockquote.xsd"
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns="http://schemas.xmlsoap.org/wsdl/">
.......
</wsdl:definitions>'
In responses.rb I have put samples for responses that SOAP server will return for different scenarios.
@@login_failure = "<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body>
<LoginResponse xmlns="http://tempuri.org/">
<LoginResult xmlns:a="http://schemas.datacontract.org/2004/07/WEBMethodsObjects" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<a:Error>Invalid username and password</a:Error>
<a:ObjectInformation i:nil="true"/>
<a:Response>false</a:Response>
</LoginResult>
</LoginResponse>
</s:Body>
</s:Envelope>"
So now let me show you how I have actually created the server.
require 'sinatra'
require 'json'
require 'nokogiri'
require_relative 'config/config.rb'
require_relative 'config/responses.rb'
after do
# cors
headers({
"Access-Control-Allow-Origin" => "*",
"Access-Control-Allow-Methods" => "POST",
"Access-Control-Allow-Headers" => "content-type",
})
# json
content_type :json
end
#when accessing the /HaWebMethods route the server will return either the WSDL file, either and XSD (I don't know exactly how to explain this but it is a WSDL dependency)
get "/HAWebMethods/" do
case request.query_string
when 'xsd=xsd0'
status 200
body = @@xsd0
when 'wsdl'
status 200
body = @@wsdl
end
end
post '/HAWebMethods/soap' do
request_payload = request.body.read
request_payload = Nokogiri::XML request_payload
request_payload.remove_namespaces!
if request_payload.css('Body').text != ''
if request_payload.css('Login').text != ''
if request_payload.css('email').text == some username && request_payload.css('password').text == some password
status 200
body = @@login_success
else
status 200
body = @@login_failure
end
end
end
end
I hope you'll find this helpful!
A: I built Savon to make interacting with SOAP webservices via Ruby as easy as possible.
I'd recommend you check it out.
A: We switched from Handsoap to Savon.
Here is a series of blog posts comparing the two client libraries.
A: I was having the same issue, switched to Savon and then just tested it on an open WSDL (I used http://www.webservicex.net/geoipservice.asmx?WSDL) and so far so good!
https://github.com/savonrb/savon
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40273",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "91"
} |
Q: Redirecting ".local" subdomain to unicast DNS I regularly access Windows domains that have been set up to use a domain under the .local top level name. This conflicts with Bonjour/Zeroconf which reserves .local for it's own use. A number of platforms support Bonjour out of the box (including Mac OS, iPhone, and Ubuntu) and there's numerous name resolution issues when this confict occurs.
I have a manual (per workstation) workaround in place for Mac OS by creating an /etc/resolver/ntdomain.local as per resolver(5) which works well. Unfortunately this requires manual changes on every workstation and does not work on the iPhone.
What I'm looking for is a way to redirect requests for *.ntdomain.local coming in via mDNS to a specific unicast DNS server. I don't mind writing some code if required. I can deploy on either preferably Debian or alternatively Windows 2003. It looks like Avahi may be the library I'm looking for.
Can this be done without registering every address in the subdomain or is it possible to register a single NS record of ntdomain.local that points to the Windows DNS server?
A: You can "merge" the unicast and multicast .local namespaces (with unicast taking precedence) as explained on Avahi and Unicast .local. Apple has instructions for doing the same on Mac OS X.
Another option is to add domain-name=.localnet to /etc/avahi/avahi-daemon.conf to have it use .localnet instead of .local for the multicast DNS namespace.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40295",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Create object from database row Let's say I'm building a data access layer for an application. Typically I have a class definition for a each kind of object that is stored in the database. Of course, the actual data access retrieves data in the form of a datareader, typed or untyped dataset, or similar, usually with the data needed to create one object per row in the results.
How would you go about creating your object instances in the data layer? Would have a constructor that accepts a datarow? If so, how would you make that type-safe? Or would you have your constructor list out one parameter for each field you want to instantiate, even if there could be many fields? Would you mark this constructor 'internal'?
A: If you aren't content with DataRow or SqlDataReader, you should look at an ORM system like Linq to Sql or nHibernate, instead of re-inventing the wheel yourself.
(By the way, this is called the "ActiveRecord" pattern)
A: I highly encourage you to use an ORM tool. Even simple projects can make use of ORM quickly and quietly... in particular, look at Castle's ActiveRecord tool (which sits on top of NHibernate to simplify model declaration).
A: I have accomplished this by using reflection. Where I name the column from the Select statement of the object.
This assumes you have a Templated helper class. If you want to put it on the object yourself you can just replace all the T with the object.
This is an example:
private T ObjectFromRow(DataRow row)
{
Type t = typeof(T);
T newObj = (T)Activator.CreateInstance(t);
System.Reflection.PropertyInfo[] properties = t.GetProperties();
for (int i = 0; i < properties.Length; i++)
{
if (!properties[i].CanWrite)
{
continue;
}
if (!row.Table.Columns.Contains(properties[i].Name))
{
continue;
}
if (row[properties[i].Name] == DBNull.Value)
{
continue;
}
if (properties[i].PropertyType == typeof(string))
{
properties[i].SetValue(newObj, row[properties[i].Name], null);
}
else if (properties[i].PropertyType == typeof(double))
{
properties[i].SetValue(newObj, double.Parse(row[properties[i].Name].ToString()), null);
}
else if (properties[i].PropertyType == typeof(int))
{
properties[i].SetValue(newObj, int.Parse(row[properties[i].Name].ToString()), null);
}
else if (properties[i].PropertyType == typeof(DateTime))
{
properties[i].SetValue(newObj, DateTime.Parse(row[properties[i].Name].ToString()), null);
}
else if (properties[i].PropertyType == typeof(bool))
{
properties[i].SetValue(newObj, bool.Parse(row[properties[i].Name].ToString()), null);
}
}
return newObj;
}
A: @Joel (re: complex queries, joins, etc)
The NHibernate and Castle ActiveRecord tool can handle very complex queries and joins via class relationships and a thorough 'Expression' class (which you can add to the query methods) or the use of the 'Hibernate Query Language' (HQL).
You can Google any of these details, check the official documentation, or see the awesome Summer of NHibernate screencasts.
A: As an alternative to NHibernate & Castle you can take a look at SubSonic. This also uses ActiveRecord but is more of a Swiss Army knife than NHibernate.
EDIT:
Here is a sample from the SubSonic documentation:
Simple Select with string columns
int records = new Select("productID").
From("Products").GetRecordCount();
Assert.IsTrue(records == 77);
Simple Select with typed columns
int records = new Select(Product.ProductIDColumn, Product.ProductNameColumn).
From<Product>().GetRecordCount();
Assert.IsTrue(records == 77);
And some further examples:
Standard Deviation
const double expected = 42.7698669325723;
// overload #1
double result = new
Select(Aggregate.StandardDeviation("UnitPrice"))
.From(Product.Schema)
.ExecuteScalar<double>();
Assert.AreEqual(expected, result);
// overload #2
result = new
Select(Aggregate.StandardDeviation(Product.UnitPriceColumn))
.From(Product.Schema)
.ExecuteScalar<double>();
Assert.AreEqual(expected, result);
// overload #3
result = new
Select(Aggregate.StandardDeviation("UnitPrice", "CheapestProduct"))
.From(Product.Schema)
.ExecuteScalar<double>();
Assert.AreEqual(expected, result);
// overload #4
result = new
Select(Aggregate.StandardDeviation(Product.UnitPriceColumn, "CheapestProduct"))
.From(Product.Schema)
.ExecuteScalar<double>();
Assert.AreEqual(expected, result);
And some Wildcard methods:
[Test]
public void Select_Using_StartsWith_C_ShouldReturn_9_Records() {
int records = new Select().From<Product>()
.Where(Northwind.Product.ProductNameColumn).StartsWith("c")
.GetRecordCount();
Assert.AreEqual(9, records);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40302",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Installer changes PATH variable, changes don't show up in Command Shell I added a custom install action to my installer to add one of my installation directories to the System PATH environment variable. After I run the installer, the PATH variable reflects the changes (when I access it through the Control Panel::System applet), but when I start a new command shell, the PATH variable does not reflect the changes. Is there something I'm failing to do, that causes this?
A: I think this depends on how you are starting the new Command shell. For example, when you change the PATH environment variable under System properties, the change isn't reflected until you open a new Command prompt. I think when you launch a new "cmd" process (from the Run dialog for example), you get a fresh copy of all environment variables, but if you launch the command prompt a different way then you do not.
For something done thru a script like that, you may need to restart before you notice the change.
A: How are you starting the command shell? With the TaskManager?
I suspect you might be starting it from Explorer - if I remember correctly, this could meen that you are inheriting the parent processes (Windows Explorer in this case) PATH variable. Since that was set before your installer ran, you see the old value.
Not sure if this helps...
A: http://support.microsoft.com/kb/310519 says that for system environment variables (which PATH is one of) requires a restart, although I have a feeling that logging off and on may be enough.
A: Why are you using a CustomAction for this? The Windows Installer supports modifying environment variables natively. Also, I think the Windows Installer sends a broadcast message to update the system when environment variables change. That may mean you don't need to reboot... but it's been a while since I tried so YMMV.
A: How are you adding the environment variable?
Without using any external tools, you can add it to the registry. Then, your test of opening a new command window will reflect your change.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40311",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Force unmount of NFS-mounted directory I have an NFS-mounted directory on a Linux machine that has hung. I've tried to force an unmount, but it doesn't seem to work:
$ umount -f /mnt/data
$ umount2: Device or resource busy
$ umount: /mnt/data: device is busy
If I type "mount", it appears that the directory is no longer mounted, but it hangs if I do "ls /mnt/data", and if I try to remove the mountpoint, I get:
$ rmdir /mnt/data
rmdir: /mnt/data: Device or resource busy
Is there anything I can do other than reboot the machine?
A: If the NFS server disappeared and you can't get it back online, one trick that I use is to add an alias to the interface with the IP of the NFS server (in this example, 192.0.2.55).
Linux
The command for that is something roughly like:
ifconfig eth0:fakenfs 192.0.2.55 netmask 255.255.255.255
Where 192.0.2.55 is the IP of the NFS server that went away. You should then be able to ping the address, and you should also be able to unmount the filesystem (use unmount -f). You should then destroy the aliased interface so you no longer route traffic to the old NFS server to yourself with:
ifconfig eth0:fakenfs down
FreeBSD and similar operating systems
The command would be something like:
ifconfig em0 alias 192.0.2.55 netmask 255.255.255.255
And then to remove it:
ifconfig em0 delete 192.0.2.55
man ifconfig(8) for more!
A: Your NFS server disappeared.
Ideally your best bet is if the NFS server comes back.
If not, the "umount -f" should have done the trick.
It doesn't ALWAYS work, but it often will.
If you happen to know what processes are USING the NFS filesystem,
you could try killing those processes and then maybe an unmount would work.
Finally, I'd guess you need to reboot.
Also, DON'T soft-mount your NFS drives. You use hard-mounts to guarantee
that they worked. That's necessary if you're doing writes.
A: Couldn't find a working answer here; but on linux you can run "umount.nfs4 /volume -f" and it definitely unmounts it.
A: You might try a lazy unmount:
umount -l
A: Try running
lsof | grep /mnt/data
That should list any process that is accessing /mnt/data that would prevent it from being unmounted.
A: I had the same problem, and
neither umount /path -f,
neither umount.nfs /path -f,
neither fuser -km /path,
works
finally I found a simple solution >.<
sudo /etc/init.d/nfs-common restart, then lets do the simple umount ;-)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40317",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "163"
} |
Q: I can't see "Report Builder" button in the Report Manager on SQL Server 2005 I am a member of all the roles (Browser, Content Manager, My Reports, Publisher, Report Builder). If I login with a Local Administrator account, I can see and use it fine. Any ideas?
A: Tried to do as was stated in the answer above. But didn't find "Configure system-level role definitions" as mentioned in the second bullet. Perhaps the interface has changed a little in the past 5 years.
Assuming you already have a browser window open where you see the report manager without the [Report Builder] button, I refer to this as the 1st browser window.
Like Matt said, you need to start a 2nd browser window as Administrator, go to the report manager again and click on [Site Settings].
After that, you click on [Security] and then on [New Role Assignment], type your username in the following page along with a check in [System User] Role.
When this was done, the [Report Builder] button occurred again in my 1st browser window (after refresh of course).
A: The first thing I would check is to make sure that your normal login is mapped to a role with the correct system-level permissions. The item-level role definitions don't make a difference for the "Report Builder" button.
From the browser-based report manager interface:
*
*Click "site settings"
*In the Security section, click "Configure system-level role definitions"
*Click the Role that you want to have this ability (e.g. "System Administrator" and "System User" are the default roles, but I believe that you can create your own if you want to).
*Make sure that the "Execute Report Definitions" task is checked/selected. This is the permission that controls whether or not the "Report Builder" button is displayed.
*Click "OK" and then return to the "Site Settings" page.
*In the Security section, click "Configure site-wide security"
*Click "New Role Assignment" and then map your login (or an AD group to which your login belongs might be even better) to the system-level role you edited in the previous steps.
The forms are pretty straightforward, and I'd guess that your login just isn't mapped to the proper system-level role since you can see the button with the local administrator login. If that doesn't work, you might check your IIS security settings for the report service to make sure that they're configured to use windows authentication (assuming that's what you're using in the first place).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40322",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: How to tell which disk Windows Used to Boot I'm need to find a method to programmatically determine which disk drive Windows is using to boot. In other words, I need a way from Windows to determine which drive the BIOS is using to boot the whole system.
Does Windows expose an interface to discover this? With how big the Windows API is, I'm hoping there is something buried in there that might do the trick.
Terry
p.s. Just reading the first sectors of the hard disk isn't reveling anything. On my dev box I have two hard disks, and when I look at the contents of the first couple of sectors on either of the hard disks I have a standard boiler plate MBR.
Edit to clarify a few things.
The way I want to identify the device is with a string which will identify a physical disk drive (as opposed to a logical disk drive). Physical disk drives are of the form "\\.\PHYSICALDRIVEx" where x is a number. On the other hand, a logical drive is identified by a string of the form, "\\.\x" where x is a drive letter.
Edit to discuss a few of the ideas that were thrown out.
Knowing which logical volume Windows used to boot doesn't help me here. Here is the reason. Assume that C: is using a mirrored RAID setup. Now, that means we have at least two physical drives. Now, I get the mapping from Logical Drive to Physical Drive and I discover that there are two physical drives used by that volume. Which one did Windows use to boot? Of course, this is assuming that the physical drive Windows used to boot is the same physical drive that contains the MBR.
A: Unless C: is not the drive that windows booted from.Parse the %SystemRoot% variable, it contains the location of the windows folder (i.e. c:\windows).
A: You can use WMI to figure this out. The Win32_BootConfiguration class will tell you both the logical drive and the physical device from which Windows boots. Specifically, the Caption property will tell you which device you're booting from.
For example, in powershell, just type gwmi Win32_BootConfiguration to get your answer.
A: That depends on your definition of which disk drive Windows used to boot. I can think of 3 different answers on a standard BIOS system (who knows what an EFI system does):
*
*The drive that contains the active MBR
*The active partition, with NTLDR (the system partition)
*The partition with Windows on it (the boot partition)
2 and 3 should be easy to find - I'm not so sure about 1. Though you can raw disk read to find an MBR, that doesn't mean it's the BIOS boot device this time or even next time (you could have multiple disks with MBRs).
You really can't even be sure that the PC was started from a hard drive - it's perfectly possible to boot Windows from a floppy. In that case, both 1 and 2 would technically be a floppy disk, though 3 would remain C:\Windows.
You might need to be a bit more specific in your requirements or goals.
A: You type diskpart, list disk and check disks for boot.
Ex:
dispart
list disk
select disk 0
detail disk
The disk with Boot volume is disk with windows installed:
A: There is no boot.ini on a machine with just Vista installed.
How do you want to identify the drive/partition: by the windows drive letter it is mapped to (eg. c:\, d:) or by how its hardware signature (which bus, etc).
For the simple case check out GetSystemDirectory
A: *
*Go into Control Panel
*System and Security
*Administrative Tools
*Launch the System Configuration tool
If you have multiple copies of Windows installed, the one you are booted with will be named such as:
Windows 7 (F:\Windows)
Windows 7 (C:\Windows) : Current OS, Default OS
A: Try HKEY_LOCAL_MACHINE\SYSTEM\Setup\SystemPartition
A: You can try use simple command line. bcdedit is what you need, just run cmd as administrator and type bcdedit or bcdedit \v, this doesn't work on XP, but hope it is not an issue.
Anyway for XP you can take a look into boot.ini file.
A: a simpler way
search downloads in the start menu and click on downloads in the search results to see where it will take you the drive will be highlighted in the explorer.
A: On Windows 10.
Open "Computer Management"
Look for "Storage" in list "left top side of page"
select "Disk Management"
On section of page showing the list of disks and the partitions find the disk that has the partition assigned as drive C:
On that disk containing C: partition
Use the right mouse button to select the Square section containing The Disk Number, Type of drive and size in GB . When menu opens select the Properties.
A window will open showing what drive hardware was used.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40335",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: What's the best way to work with SQL Server data non-programmatically? We have a SQL server database. To manipulate the data non-programmatically, I can use SQL Server Management Studio by right-clicking a table and selecting "Open Table". However this is slow for very large tables and sorting and filtering is cumbersome.
Typically what we have done until now is to create an Access database containing linked tables which point to the SQL Server tables and views. Opening a large table is much faster this way, and Access has easy-to-use right-click filtering and sorting.
However, since Access 2007, sorting in particular has been quite slow when working with large tables. The Access database can also inadvertently lock the database tables, blocking other processes that may need to access the data. Creating the Access database in the first place, and updating it when new tables are added to SQL Server, is also tedious.
Is there a better way to work with the data that offers the usability of Access without its drawbacks?
A: Joel Coehoorn's answer is of course correct, that if the data is critical or there are naive users using the data, then a application front end should be developed. That being said, I have cases where a wise user (ok, me) user needs to just get in there and poke around.
Instead of directly looking at the tables, use MS Access but use queries to narrow down what you're looking at both column wise and row wise. That will improve the speed. Then edit the query properties and make sure that the query is No Locks. That should eliminate any blocking behavior. You may want to limit the number of rows returned which again will improve the speed. You can still edit the data in the query as you look at it.
Depending on what you're looking at, it may also be useful to set up database Views in the SQL Server to do some of the heavy lifting on the server rather than on the client.
A: I don't know how well it will do with really large tables, but Visual Studio is much quicker than SQL Management Studio for basic table operations. Open up your database in Server Explorer, right-click on a table, and select either "Open" to just display the data or "New Query" to filter, sort, etc.
A: I've used Visual Studio to do lots of stuff, just for convenience rather than having to log into the server and work on the database manager directly.
However, have you tried Toad for MS SQL (from Quest Software)? I use it all the time for Oracle, and have had good results (often better than Oracle's tools).
A: Editing raw data is a dangerous no-no. Better to identify the situations where you find yourself doing that and put together an application interface to act as an intermediary that can prevent you from doing stupid things like breaking a foreign key.
A: I don't know what the performance would be like for large datasets, but open office has a database program (Base), which is an Access clone and may just be what you are looking for.
A: You might want to read
Tony Toews's Access Performance FAQ, which provides a number of hints on how to improve performance in an Access application. Perhaps one of those tips will solve the problem in your A2K7 app.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40344",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Coding magazines So, we have coding books, coding RSS feeds, and music to code by. Are there any coding magazines that anyone would recommend?
A: The Pragmatic Programmers' Pragmatic Bookshelf publishes a free magazine available online and for download in various formats:
Each month, our editor Michael Swaine
brings you a free magazine packed full
of interesting articles, features, and
departments. Download it in PDF, mobi
(good for the Kindle), and epub (great
for Stanza on the iPhone).
A: I also enjoy Dr. Dobb's Journal. But hey, there's a way to leech it for free (at the time of writing, anyway):
http://pages.nxtbook.com/nxtbooks/cmp/ddj<mm><yy>/offline/cmp_ddj<mm><yy>_pdf.zip
Replace <mm> and <yy> with month and year. They're available 8/2006 thru 2/2009.
Afterwards, it's known as Dr. Dobb's Digest and is instead available at URL pattern:
http://i.cmpnet.com/ddj/digest/<yyyy>/DDD_<mm><yy>.pdf
A: Dr. Dobbs Journal is a pretty good broad-based programmer's journal. Covers all manner of material.
A: The venerable Dr. Dobbs Journal is still pretty good. It covers multiple platforms, and mixes some fairly hard-core technical articles with lighter fare (interviews with notables, a "Developer Diaries" column that profiles regular-Joe (and Jane) developers from a range of fields). If you are employed and have authority to spend some non-trivial amount of money on tools (or are willing to claim that you do), you can probably get them to send it to you for free.
For the Microsoft world, MSDN Magazine is very useful. Some of their columns are excellent, particularly Jeff Richter's Concurrent Affairs.
A: Game Developer Magazine has lots of very good articles, though as you might expect they tend to skew towards C++.
A: Visual Studio Magazine has some gems every once in awhile
A: I like Dr. Dobb's Journal also but the magazine refers the reader to their web site for most of the interesting articles. I have found the Java Developer's Journal very interesting because it contains articles about Java in the context of both web and enterprise applications.
A: For the Perl crowd, there is of course The Perl Review. And for the German-speaking subset of it, there's the Foo Magazin as well.
A: VSJ, I find it a great mag :) http://www.vsj.co.uk/
Edit
This is NOT off-topic! It directly relates to programming!
A: I subscribe to MSDN magazine, it's a bit thinner now than in years past, but for .NET it covers a variety of topics, it's a good way to keep abreast of new Microsoft offerings.
All the content is available online on MSDN, and of course online resources/blogs are a lot more up to date, but sometimes it's nice to have a magazine in your bag for a flight or layover.
A: I really enjoy IEEE Software because it covers broader issues regarding software engineering.
A: Definitely Your Sinclair. Hands down.
A: I really enjoy Code and asp.netPRO ... Visual Studio is so-so.
A: The ACCU mags, Overload and C-Vu.
I like Game Developers Magazine, but since the ECTS no longer runs I no longer get free ones anymore:-(
A: Python Magazine of course ! BTW they are looking for contributors...
A: I like Embedded Systems. Even if you don't program for embedded systems, the software articles are excellent. http://www.embedded.com/
A: Both the IEEE and ACM put out a number of good computing magazines, which might be of interest depending on your exact interests. I'm a subscriber to both.
A: The ACM Queue has some hardcore content, dense, but good. I haven't read it in a while though.
A: For Delphi delvelopers "Blaise" international magazine - www.blaisepascal.eu
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40346",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "47"
} |
Q: Whats the difference between RuntimeTypeHandle and Type? And why would I use one over the other in my code?
A: In .NET 4.0 Beta 1 RuntimeTypeHandle just wraps RuntimeType.
It seems all benefits of using it as a cheap Type proxy have gone.
Evidence for the above claim:
*
*Microsoft's Reference Source for the System.RuntimeTypeHandle type shows that this type is indeed only a wrapper around System.RuntimeType these days.
*Sandro Magi's 2013 blog article "CLR: The Cost of Dynamic Type Tests"
contains a benchmark and a final note showing that the supposed performance benefits of RuntimeTypeHandle are gone in .NET 4.
A:
Caution: This answer appears to be out of date. It was posted before .NET 4 became available, which apparently introduced some optimizations regarding Type and thus rendered the information in this answer obsolete. See this more recent answer for details.
According to this blog post (from 2006) by Vance Morrison, RuntimeTypeHandle is a value type (struct) that wraps an unmanaged pointer, so Type.GetTypeHandle(obj).Equals(anotherHandle) is faster to use for strict "is exactly the same type" comparisons than obj.GetType().Equals(anotherType) — the latter creates System.Type instances which are, apparently, heavier.
However, it's also less obvious, and definitely falls under the category "micro-optimization" so if you're wondering when you need one over the other, you should probably just use System.Type.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40352",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
} |
Q: Can I create a value for a missing tag in XPath? I have an application which extracts data from an XML file using XPath. If a node in that XML source file is missing I want to return the value "N/A" (much like the Oracle NVL function). The trick is that the application doesn't support XSLT; I'd like to do this using XPath and XPath alone.
Is that possible?
A: It can be done but only if the return value when the node does exist is the string value of the node, not the node itself. The XPath
substring(concat("N/A", /foo/baz), 4 * number(boolean(/foo/baz)))
will return the string value of the baz element if it exists, otherwise the string "N/A".
To generalize the approach:
substring(concat($null-value, $node),
(string-length($null-value) + 1) * number(boolean($node)))
where $null-value is the null value string and $node the expression to select the node. Note that if $node evaluates to a node-set that contains more than one node, the string value of the first node is used.
A: Short answer: no. Such a function was considered and explicitly rejected for version 2 of the XPath spec (see the non-normative Illustrative User-written Functions section).
A: For empty nodes, you need
boolean(string-length($node))
(You can omit the call to number() as the cast from boolean to number is implicit here.)
A: It can be done with XPath 1.0. Say you have
<foo>
<bar/>
</foo>
If you want to test if foo has a baz child,
substring("N/A", 4 * number(boolean(/foo/baz)))
will return "N/A" if the expression /foo/baz returns an empty node-set, otherwise it returns an empty string.
A: @jelovirt
So if I understand this correctly, we concatenate the default answer and the value of the node, and then take the correct subset of the resulting string by testing for the existence of the node to set the offset to either zero or the position right after my default string. That is the most perverse twisting of a language I've ever seen. (I love it!)
To clarify what you said, this approach works when the the node is missing, not when the node is empty. But by replacing "number(boolean($node))" with "string-length($node)" it will work on empty nodes instead.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40361",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Maximum number of inodes in a directory? Is there a maximum number of inodes in a single directory?
I have a directory of over 2 million files and can't get the ls command to work against that directory. So now I'm wondering if I've exceeded a limit on inodes in Linux. Is there a limit before a 2^64 numerical limit?
A: df -i should tell you the number of inodes used and free on the file system.
A: What you hit is an internal limit of ls. Here is an article which explains it quite well:
http://www.olark.com/spw/2011/08/you-can-list-a-directory-with-8-million-files-but-not-with-ls/
A: Maximum directory size is filesystem-dependent, and thus the exact limit varies. However, having very large directories is a bad practice.
You should consider making your directories smaller by sorting files into subdirectories. One common scheme is to use the first two characters for a first-level subdirectory, as follows:
${topdir}/aa/aardvark
${topdir}/ai/airplane
This works particularly well if using UUID, GUIDs or content hash values for naming.
A: Try ls -U or ls -f.
ls, by default, sorts the files alphabetically. If you have 2 million files, that sort can take a long time. If ls -U (or perhaps ls -f), then the file names will be printed immediately.
A: No. Inode limits are per-filesystem, and decided at filesystem creation time. You could be hitting another limit, or maybe 'ls' just doesn't perform that well.
Try this:
tune2fs -l /dev/DEVICE | grep -i inode
It should tell you all sorts of inode related info.
A: As noted by Rob Adams, ls is sorting the files before displaying them. Note that if you are using NFS, the NFS server will be sorting the directory before sending it, and 2 million entries may well take longer than the NFS timeout. That makes the directory unlistable via NFS, even with the -f flag.
This may be true for other network file systems as well.
While there's no enforced limit to the number of entries in a directory, it's good practice to have some limit to the entries you anticipate.
A: Can you get a real count of the number of files? Does it fall very near a 2^n boundry? Could you simply be running out of RAM to hold all the file names?
I know that in windows at least file system performance would drop dramatically as the number of files in the folder went up, but I thought that linux didn't suffer from this issue, at least if you were using a command prompt. God help you if you try to get something like nautilus to open a folder with that many files.
I'm also wondering where these files come from. Are you able to calculate file names programmatically? If that's the case, you might be able to write a small program to sort them into a number of sub-folders. Often listing the name of a specific file will grant you access where trying to look up the name will fail. For example, I have a folder in windows with about 85,000 files where this works.
If this technique is successful, you might try finding a way to make this sort permanent, even if it's just running this small program as a cron job. It'll work especially well if you can sort the files by date somewhere.
A: Unless you are getting an error message, ls is working but very slowly. You can try looking at just the first ten files like this:
ls -f | head -10
If you're going to need to look at the file details for a while, you can put them in a file first. You probably want to send the output to a different directory than the one you are listing at the moment!
ls > ~/lots-of-files.txt
If you want to do something to the files, you can use xargs. If you decide to write a script of some kind to do the work, make sure that your script will process the list of files as a stream rather than all at once. Here's an example of moving all the files.
ls | xargs -I thefilename mv thefilename ~/some/other/directory
You could combine that with head to move a smaller number of the files.
ls | head -10000 | xargs -I x mv x /first/ten/thousand/files/go/here
You can probably combine ls | head into a shell script to that will split up the files into a bunch of directories with a manageable number of files in each.
A: For NetBackup, the binaries that analyze the directories in clients perform some type of listing that timeouts by the enormous quantity of files in every folder (about one million per folder, SAP work directory).
My solution was (as Charles Duffy write in this thread), reorganize the folders in subfolders with less archives.
A: Another option is find:
find . -name * -exec somcommands {} \;
{} is the absolute filepath.
The advantage/disadvantage is that the files are processed one after each other.
find . -name * > ls.txt
would print all filenames in ls.txt
find . -name * -exec ls -l {} \; > ls.txt
would print all information form ls for each file in ls.txt
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40368",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "40"
} |
Q: How can you export the saved username and passwords in FireFox 2? I need to reformat my machine but I have so many user/passwords stored in FF2 that I just keep putting it off. Yes I know about backing up the entire profile and restoring it. But for some reason my profile has many issues and I want to start fresh with that as well.
Are the username and passwords stored in a text file or is there some way to export them and import after I reformat?
A: I've had luck just copying signons2.txt and key3.db over from one profile to another. See also the documentation on MozillaZine.
A: There is a Firefox add-on called Password Exporter. It can export to XML or CSV files that can be imported in another browser or computer.
A: This extension will do it for you:
https://addons.mozilla.org/en-US/firefox/addon/2848
A: You can use the Foxmarks plugin. This exports to XML or CSV format. I used it a week ago and it works really fine.
A: Alas, this won't solve the re-importing problem, but check out http://wejn.org/stuff/moz-export.html
They have a single html page with a small javascript section that exports your passwords. Save the html to your desktop, read through to make sure it's not evil, open the page in FF, save the results.
Maybe I'm paranoid, but I'm not sure I'd trust a password-exporting extension...
A: You can use third party tools (like PasswordFox) available to export saved passwords from Firefox but many people don’t believe in third party tools because this is the matter of high security so, it is better to use Firefox add-on rather than third party tool.
Password Exporter Firefox extension is the best solution to export and import saved passwords safely and quickly. You can install Password Exporter from below URL.
http://addons.mozilla.org/en-US/firefox/addon/password-exporter and see the full documentation of installation and uses.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40372",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Handle signals in the Java Virtual Machine Is it possible to handle POSIX signals within the Java Virtual Machine?
At least SIGINT and SIGKILL should be quite platform independent.
A: Perhaps Runtime#addShutdownHook ?
A: The JVM responds to signals on its own. Some will cause the JVM to shutdown gracefully, which includes running shutdown hooks. Other signals will cause the JVM to abort without running shutdown hooks.
Shutdown hooks are added using Runtime.addShutdownHook(Thread).
I don't think the JDK provides an official way to handle signals within your Java application. However, I did find this IBM article, which describes using some undocumented sun.misc.Signal class to do exactly that. The article dates from 2002 and uses JDK 1.3.1, but I've confirmed that the sun.misc.Signal class still exists in JDK 1.6.0.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40376",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: What is the command to truncate a SQL Server log file? I need to empty an LDF file before sending to a colleague. How do I force SQL Server to truncate the log?
A: For SQL Server 2008, the command is:
ALTER DATABASE ExampleDB SET RECOVERY SIMPLE
DBCC SHRINKFILE('ExampleDB_log', 0, TRUNCATEONLY)
ALTER DATABASE ExampleDB SET RECOVERY FULL
This reduced my 14GB log file down to 1MB.
A: For SQL 2008 you can backup log to nul device:
BACKUP LOG [databaseName]
TO DISK = 'nul:' WITH STATS = 10
And then use DBCC SHRINKFILE to truncate the log file.
A: In management studio:
*
*Don't do this on a live environment, but to ensure you shrink your dev db as much as you can:
*
*Right-click the database, choose Properties, then Options.
*Make sure "Recovery model" is set to "Simple", not "Full"
*Click OK
*Right-click the database again, choose Tasks -> Shrink -> Files
*Change file type to "Log"
*Click OK.
Alternatively, the SQL to do it:
ALTER DATABASE mydatabase SET RECOVERY SIMPLE
DBCC SHRINKFILE (mydatabase_Log, 1)
Ref: http://msdn.microsoft.com/en-us/library/ms189493.aspx
A: backup log logname with truncate_only followed by a dbcc shrinkfile command
A: if I remember well... in query analyzer or equivalent:
BACKUP LOG databasename WITH TRUNCATE_ONLY
DBCC SHRINKFILE ( databasename_Log, 1)
A: Since the answer for me was buried in the comments. For SQL Server 2012 and beyond, you can use the following:
BACKUP LOG Database TO DISK='NUL:'
DBCC SHRINKFILE (Database_Log, 1)
A: Another option altogether is to detach the database via Management Studio. Then simply delete the log file, or rename it and delete later.
Back in Management Studio attach the database again. In the attach window remove the log file from list of files.
The DB attaches and creates a new empty log file. After you check everything is all right, you can delete the renamed log file.
You probably ought not use this for production databases.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40402",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "218"
} |
Q: How to traverse a maze programmatically when you've hit a dead end Moving through the maze forward is pretty easy, but I can't seem to figure out how to back up through the maze to try a new route once you hit a dead end without going back too far?
A: Use backtracking by keeping a stack of previous direction decisions.
A: The simplest (to implement) algorithm would be to just keep a stack of locations you've been at, and the route you took from each, unless backtracking gives you that information.
To go back, just pop off old locations from the stack and check for more exits from that location until you find an old location with an untested exit.
By consistently testing the exits in the same order each time, if you know that backtracking to a location comes from down (ie. last time you were at the old location you went down), then you simply pick the next direction after down.
I am not entirely sure what you mean by going back too far though, I would assume you would want to go back to the previous place you have untested routes, is that not what you want?
Note that unless you try to keep track of the path from the starting point to your current location, and avoiding those squares when you try to find new routes, you might end up going in circle, which would eventually make the stack too large.
A simple recursive method which marks the path it takes and never enters areas that are marked can easily do this.
Also, if your thing that moves through the maze is slightly smarter than just being able to move, and hit (stop at) walls, in that it can see from its current point in all directions, I have other algorithms that might help.
A: Eric Lippert did a series of articles on creating a C# implemention of A*, which might be more efficient.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40413",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Autocomplete Dropdown with Linkbuttons - or "AJAX gone wild" Ok, so I want an autocomplete dropdown with linkbuttons as selections. So, the user puts the cursor in the "text box" and is greated with a list of options. They can either start typing to narrow down the list, or select one of the options on the list. As soon as they click (or press enter) the dataset this is linked to will be filtered by the selection.
Ok, is this as easy as wrapping an AJAX autocomplete around a dropdown? No? (Please?)
A: You'll have to handle the OnSelectedIndexChanged event of your drop down list to rebind your dataset based on the users selection. If you want the filtering to happen in an asynch postback, wrap the dataset (or datagrid I'm assuming) and your drop down in an UpdatePanel. That is one way to do it anyhow.
A: This widget can be made with three items: a text input, button input, and an unordered list to hold the results.
__________ _
|__________||v|__ <-- text and button
| | <-- ul (styled to appear relative to text input)
| |
| |
|______________|
ul shown on:
*
*'keyUp' event of the text input (if value is non-empty)
*'click' event of the button input (if currently not visible)
ul hidden on:
*
*'click' event of the button input (if currently visible)
*'click' event of list items
When the ul is shown or the 'keyUp' event of the text input is triggered an AJAX call to the server needs to be made to update the list.
On success the results should be placed in the ul. When creating the list items they should have a 'click' event attached to them that sets the text input value and hides the ul (may have to add a link inside the li to attach the event to).
The hardest part is really the CSS. The JavaScript is simple especially with a solid library like prototype that supports multiple browsers.
You will probably want to support some IDs for the items, so you can add some hidden inputs to each list item with the id and next to the text input to store the selected items ID.
A: I am not entirely sure what you want, but the Ra-Ajax AutoCompleter definitely have support for having "controls" within itself. You can see that in the search box at Stacked in fact (upper right corner) where we're using links. But this could also be LinkButtons if you wish...
Disclaimer; I work with Ra-Ajax...
A: In my opinion, you shouldn't use AJAX for this at all.
here's why:
(1) On focus: ALL the options that he can select are shown in the dropdown. This means that all possible options are already sent to the client.
(2) If the user types something in, the number of entries in the drop down are filtered down to match. This can easily be done on the client side. Being ajax'y and going back to the server at this point will just slow things down.
phpguru.org has a control which is 'almost exactly' what you need:
http://www.phpguru.org/static/AutoComplete.html#demo
It differs slightly from what you need in that it shows the dropdown on double-click instead of on focus. That should be fairly easy to modify.
I hope this helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40422",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: How would you implement Erlang-like send and receive in C++? Actually, this question seems to have two parts:
*
*How to implement pattern matching?
*How to implement send and receive (i.e. the Actor model)?
For the pattern matching part, I've been looking into various projects like App and Prop. These look pretty nice, but couldn't get them to work on a recent version (4.x) of g++. The Felix language also seems to support pattern matching pretty well, but isn't really C++.
As for the Actor model, there are existing implementations like ACT++ and Theron, but I couldn't find anything but papers on the former, and the latter is single-threaded only [see answers].
Personally, I've implemented actors using threading and a thread-safe message queue. Messages are hash-like structures, and used these together with a number of preprocessor macros to implemented simple pattern matching.
Right now, I can use the following code to send a message:
(new Message(this))
->set("foo", "bar")
->set("baz", 123)
->send(recipient);
And the following to do simple pattern matching (qDebug and qPrintable are Qt-specific):
receive_and_match(m)
match_key("foo") { qDebug("foo: %s", qPrintable(m->value("foo").toString())); }
or_match_key("baz") { qDebug("baz: %d", m->value("baz").toInt()); }
or_match_ignore
end_receive
However, this looks a bit hackish to me, and isn't very robust.
How would you do it? Did I miss any existing work?
A: One of the important things about erlang is how the features are used to make robust systems.
The send/recieve model is no-sharing, and explicitly copying.
The processes themselves are lightweight threads.
If you did desire the robust properties of the erlang model, you would be best to use real processes and IPC rather than threads.
If you want robust message passing though you may end up wanting to serialize and deserialise the contents. Especially with type safety.
Pattern matching in C++ isn't always pretty but there will be a good pattern for this - you will end up creating a dispatcher object that uses some form of polymorphism to get what you want.
Although if you are not careful you end up with xml over pipes :)
Really, if you want the erlang model you really want to use erlang. If there are slow bits, I'm sure you can augment your program using a foreign function internet.
The problem about re-implementing parts, is you won't get a good cohesive library and solution. The solutions you have already don't look much like C++ anymore.
A: I'm currently implementing an actor library for C++ called "acedia" (there's nothing yet about it on google) that uses "type matching". The library is a project for my master thesis and you can send any kind of data to an actor with it.
A small snippet:
recipient.send(23, 12.23f);
And on the recipient side you can either analyze the received message like this:
Message msg = receive();
if (msg.match<int, float>() { ... }
... or you can define a rule set that invokes a function or method for you:
void doSomething(int, float);
InvokeRuleSet irs;
irs.add(on<int, float>() >> doSomething);
receiveAndInvoke(irs);
It's also possible to match both on type and on value:
Message msg = receive();
if (msg.match<int, float>(42, WILDCARD) { ... }
else if (msg.match<int, float>() { ... }
The constant "WILDCARD" means, that any value will be acceptet. Pass no arguments is equal set all arguments to "WILDCARD"; meaning that you only want to match the types.
This is certainly a small snippet. Also you can use "case classes" like in Scala. They are comparable to "atomics" in erlang. Here is a more detailed example:
ACEDIA_DECLARE_CASE_CLASS(ShutdownMessage)
ACEDIA_DECLARE_CASE_CLASS(Event1)
ACEDIA_DECLARE_CASE_CLASS(Event2)
To react to the defined case classes you can write an actor like this:
class SomeActor : public Actor
{
void shutdown() { done = true; }
void handleEvent1();
void handleEvent1();
public:
SomeActor() : done(false) { }
virtual void act()
{
InvokeRuleSet irs;
irs
.add(on<ShutdownMessage>() >> method(&SomeActor::shutdown))
.add(on<Event1>() >> method(&SomeActor::handleEvent1))
.add(on<Event2>() >> method(&SomeActor::handleEvent2))
;
while (!done) receiveAndInvoke(irs);
}
};
To create a new actor and start it, all you have to write is:
Acedia::spawn<SomeActor>();
Although the library not even reached beta stadium the shown snippets work and i have a first application running on it. One major goal of the library is to support distributed programming (also across a network).
Your question is a while ago, but if you're interested in it: let me know! :)
A: You can mimic the behavior using Qt's signal/slot mechanism, especially since Qt's signal/slot supports multithread.
A:
As for the Actor model, there are
existing implementations like ACT++
and Theron, but I couldn't find
anything but papers on the former, and
the latter is single-threaded only.
As the author of Theron, I was curious why you believe it's single-threaded?
Personally, I've implemented actors
using threading and a thread-safe
message queue
That's how Theron is implemented.. :-)
Ash
A: I would definitely be interested in looking at your "acedia" library and would love to help in any way that I could. Erlang has some wonderful constructs and C++ could definitely benefit from such a library.
A: Today I hostet the library at sourceforge: https://sourceforge.net/projects/acedia/
As I said before it's an early release. But feel free to critique it!
A: Today, if you want erlang style robust actors in C++, and pattern matching,
maybe Rust is the answer.
Of course this wasn't around publically when the OP asked ~5years ago, and as of april 2014 it still isn't v1.0 yet - but its been progressing very well and is definitely stabilizing, enough of the language core is stable I think.
And ok its not C++, but it has the same approach to memory management as C++, except that it supports lightweight tasks with no shared memory by default (then provides controlled library features for sharing - "Arc");
It can directly call (and directly expose) 'extern C' functions. You can't share templated library headers with C++ - but you can write generics that mimick C++ collection classes (and vica versa) to pass references to data-structures across.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40423",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: HTTP POST - I'm stuck I have to POST some parameters to a URL outside my network, and the developers on the other side asked me to not use HTTP Parameters: instead I have to post my key-values in HTTP Headers.
The fact is that I don't really understand what they mean: I tried to use a ajax-like post, with XmlHttp objects, and also I tried to write in the header with something like
Request.Headers.Add(key,value);
but I cannot (exception from the framework); I tried the other way around, using the Response object like
Response.AppendHeader("key", "value");
and then redirect to the page... but this doesn't work, as well.
It's evident, I think, that I'm stuck there, any help?
EDIT I forgot to tell you that my environment is .Net 2.0, c#, on Win server 2003.
The exception I got is
System.PlatformNotSupportedException was unhandled by user code
Message="Operation is not supported on this platform."
Source="System.Web"
This looks like it's caused by my tentative to Request.Add, MS an year ago published some security fixes that don't permit this.
A: Have you tried the WebClient class? An example might look like:
WebClient client = new WebClient();
NameValueCollection data = new NameValueCollection();
data["var1"] = "var1";
client.UploadValues("http://somewhere.com/api", "POST", data);
A: Take a look at HttpWebRequest. You should be able to construct a request to the URL in question using HttpWebRequest.Method = "POST".
A: Like @lassevk said, a redirect won't work.
You should use the WebRequest class to do an HTTP POST from your page or application. There's an example here.
A: You should post more information.
For instance, is this C#? It looks like it, but I might be wrong.
Also, you say you get an exception, what is the exception type and message?
In any case, you can't redirect to a page for POST, you need to submit it from the browser, not from the server redirect, so if you want to automate this, I would guess you would need to generate a html page with a form tag, with some hidden input fields, and then submit it with javascript.
A: I think they mean they don't want you to use URL parameters (GET). If you use http headers, it's not really querying through POST any more.
A: What language/framework?
Using Python and httplib2, you should be able to do something like:
http = httplib2.Http()
http.request(url, 'POST', headers={'key': 'value'}, body=urllib.urlencode(''))
A: I believe that the Request object would only accept a certain set of predefined headers.
There's an enumeration that lists all the supported HTTP Headers too.
But I can't remember it at the moment... I'll look it up in a sec...
A: I tested your scenario using 2 sample pages using XmlHttpRequest option.
Custom headers are available in the aspx page posted to, using XmlHttpRequest.
Create the following 2 pages. Make sure the aspx page is in a solution , so that you can run the in the debugger, set break point and inspect the Request.Header collection.
<html>
<head>
< script language="javascript">
function SendRequest()
{
var r = new XMLHttpRequest();
r.open('get', 'http://localhost/TestSite/CheckHeader.aspx');
r.setRequestHeader('X-Test', 'one');
r.setRequestHeader('X-Test', 'two');
r.send(null);
}
< script / >
</head>
<body>
<form>
<input type="button" value="Click Me" OnClick="SendRequest();" />
</form>
</body>
</html>
CheckHeader.aspx
using System;
using System.Web;
using System.Web.UI;
public partial class CheckHeader : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string value = string.Empty;
foreach (string key in Request.Headers)
value = Request.Headers[key].ToString();
}
}
Man.. This html editor sucks.. or i do not know how to use it...
A: The exception I was facing yesterday was caused by my stupid try to write on the headers of the already built page.
When I started creating my Request following one of the mothods indicated here, I could write my headers.
Now I'm using the WebRequest object, as in the sample indicated by @sectrean, here.
Thanks a lot to everybody. StackOverflow rocks :-)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40452",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: sql missing rows when grouped by DAY, MONTH, YEAR If I select from a table group by the month, day, year,
it only returns rows with records and leaves out combinations without any records, making it appear at a glance that every day or month has activity, you have to look at the date column actively for gaps. How can I get a row for every day/month/year, even when no data is present, in T-SQL?
A: Create a calendar table and outer join on that table
A: My developer got back to me with this code, underscores converted to dashes because StackOverflow was mangling underscores -- no numbers table required. Our example is complicated a bit by a join to another table, but maybe the code example will help someone someday.
declare @career-fair-id int
select @career-fair-id = 125
create table #data ([date] datetime null, [cumulative] int null)
declare @event-date datetime, @current-process-date datetime, @day-count int
select @event-date = (select careerfairdate from tbl-career-fair where careerfairid = @career-fair-id)
select @current-process-date = dateadd(day, -90, @event-date)
while @event-date <> @current-process-date
begin
select @current-process-date = dateadd(day, 1, @current-process-date)
select @day-count = (select count(*) from tbl-career-fair-junction where attendanceregister <= @current-process-date and careerfairid = @career-fair-id)
if @current-process-date <= getdate()
insert into #data ([date], [cumulative]) values(@current-process-date, @day-count)
end
select * from #data
drop table #data
A: Look into using a numbers table. While it can be hackish, it's the best method I've come by to quickly query missing data, or show all dates, or anything where you want to examine values within a range, regardless of whether all values in that range are used.
A: Building on what SQLMenace said, you can use a CROSS JOIN to quickly populate the table or efficiently create it in memory.
http://www.sitepoint.com/forums/showthread.php?t=562806
A: The task calls for a complete set of dates to be left-joined onto your data, such as
DECLARE @StartInt int
DECLARE @Increment int
DECLARE @Iterations int
SET @StartInt = 0
SET @Increment = 1
SET @Iterations = 365
SELECT
tCompleteDateSet.[Date]
,AggregatedMeasure = SUM(ISNULL(t.Data, 0))
FROM
(
SELECT
[Date] = dateadd(dd,GeneratedInt, @StartDate)
FROM
[dbo].[tvfUtilGenerateIntegerList] (
@StartInt,
,@Increment,
,@Iterations
)
) tCompleteDateSet
LEFT JOIN tblData t
ON (t.[Date] = tCompleteDateSet.[Date])
GROUP BY
tCompleteDateSet.[Date]
where the table-valued function tvfUtilGenerateIntegerList is defined as
-- Example Inputs
-- DECLARE @StartInt int
-- DECLARE @Increment int
-- DECLARE @Iterations int
-- SET @StartInt = 56200
-- SET @Increment = 1
-- SET @Iterations = 400
-- DECLARE @tblResults TABLE
-- (
-- IterationId int identity(1,1),
-- GeneratedInt int
-- )
-- =============================================
-- Author: 6eorge Jetson
-- Create date: 11/22/3333
-- Description: Generates and returns the desired list of integers as a table
-- =============================================
CREATE FUNCTION [dbo].[tvfUtilGenerateIntegerList]
(
@StartInt int,
@Increment int,
@Iterations int
)
RETURNS
@tblResults TABLE
(
IterationId int identity(1,1),
GeneratedInt int
)
AS
BEGIN
DECLARE @counter int
SET @counter= 0
WHILE (@counter < @Iterations)
BEGIN
INSERT @tblResults(GeneratedInt) VALUES(@StartInt + @counter*@Increment)
SET @counter = @counter + 1
END
RETURN
END
--Debug
--SELECT * FROM @tblResults
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40456",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to get an array of distinct property values from in memory lists? I have a List of Foo.
Foo has a string property named Bar.
I'd like to use LINQ to get a string[] of distinct values for Foo.Bar in List of Foo.
How can I do this?
A: I'd go lambdas... wayyy nicer
var bars = Foos.Select(f => f.Bar).Distinct().ToArray();
works the same as what @lassevk posted.
I'd also add that you might want to keep from converting to an array until the last minute.
LINQ does some optimizations behind the scenes, queries stay in its query form until explicitly needed. So you might want to build everything you need into the query first so any possible optimization is applied altogether.
By evaluation I means asking for something that explicitly requires evalution like "Count()" or "ToArray()" etc.
A: This should work if you want to use the fluent pattern:
string[] arrayStrings = fooList.Select(a => a.Bar).Distinct().ToArray();
A: Try this:
var distinctFooBars = (from foo in foos
select foo.Bar).Distinct().ToArray();
A: Shouldn't you be able to do something like:
var strings = (from a in fooList select a.Bar).Distinct();
string[] array = strings.ToArray();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40465",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: What are the differences between a HashMap and a Hashtable in Java? What are the differences between a HashMap and a Hashtable in Java?
Which is more efficient for non-threaded applications?
A: Note, that a lot of the answers state that Hashtable is synchronized. In practice this buys you very little. The synchronization is on the accessor/mutator methods will stop two threads adding or removing from the map concurrently, but in the real world, you will often need additional synchronization.
A very common idiom is to "check then put" — i.e. look for an entry in the Map, and add it if it does not already exist. This is not in any way an atomic operation whether you use Hashtable or HashMap.
An equivalently synchronised HashMap can be obtained by:
Collections.synchronizedMap(myMap);
But to correctly implement this logic you need additional synchronisation of the form:
synchronized(myMap) {
if (!myMap.containsKey("tomato"))
myMap.put("tomato", "red");
}
Even iterating over a Hashtable's entries (or a HashMap obtained by Collections.synchronizedMap) is not thread-safe unless you also guard the Map against being modified through additional synchronization.
Implementations of the ConcurrentMap interface (for example ConcurrentHashMap) solve some of this by including thread safe check-then-act semantics such as:
ConcurrentMap.putIfAbsent(key, value);
A: Take a look at this chart. It provides comparisons between different data structures along with HashMap and Hashtable. The comparison is precise, clear and easy to understand.
Java Collection Matrix
A: In addition to what izb said, HashMap allows null values, whereas the Hashtable does not.
Also note that Hashtable extends the Dictionary class, which as the Javadocs state, is obsolete and has been replaced by the Map interface.
A: Since Hashtable in Java is a subclass of Dictionary class which is now obsolete due to the existence of Map Interface, it is not used anymore. Moreover, there isn't anything you can't do with a class that implements the Map Interface that you can do with a Hashtable.
A: Old and classic topic, just want to add this helpful blog that explains this:
http://blog.manishchhabra.com/2012/08/the-5-main-differences-betwen-hashmap-and-hashtable/
Blog by Manish Chhabra
The 5 main differences betwen HashMap and Hashtable
HashMap and Hashtable both implement java.util.Map interface but there
are some differences that Java developers must understand to write
more efficient code. As of the Java 2 platform v1.2, Hashtable class
was retrofitted to implement the Map interface, making it a member of
the Java Collections Framework.
*
*One of the major differences between HashMap and Hashtable is that HashMap is non-synchronized whereas Hashtable is synchronized, which
means Hashtable is thread-safe and can be shared between multiple
threads but HashMap cannot be shared between multiple threads without
proper synchronization. Java 5 introduced ConcurrentHashMap which is
an alternative of Hashtable and provides better scalability than
Hashtable in Java.Synchronized means only one thread can modify a hash
table at one point of time. Basically, it means that any thread before
performing an update on a hashtable will have to acquire a lock on the
object while others will wait for lock to be released.
*The HashMap class is roughly equivalent to Hashtable, except that it permits nulls. (HashMap allows null values as key and value whereas
Hashtable doesn’t allow nulls).
*The third significant difference between HashMap vs Hashtable is that Iterator in the HashMap is a fail-fast iterator while the
enumerator for the Hashtable is not and throw
ConcurrentModificationException if any other Thread modifies the map
structurally by adding or removing any element except Iterator’s own
remove() method. But this is not a guaranteed behavior and will be
done by JVM on best effort. This is also an important difference
between Enumeration and Iterator in Java.
*One more notable difference between Hashtable and HashMap is that because of thread-safety and synchronization Hashtable is much slower
than HashMap if used in Single threaded environment. So if you don’t
need synchronization and HashMap is only used by one thread, it out
perform Hashtable in Java.
*HashMap does not guarantee that the order of the map will remain constant over time.
Note that HashMap can be synchronized by
Map m = Collections.synchronizedMap(hashMap);
In Summary there are significant differences between Hashtable and
HashMap in Java e.g. thread-safety and speed and based upon that only
use Hashtable if you absolutely need thread-safety, if you are running
Java 5 consider using ConcurrentHashMap in Java.
A: Synchronization or Thread Safe :
Hash Map is not synchronized hence it is not thred safe and it cannot be shared between multiple threads without proper synchronized block whereas, Hashtable is synchronized and hence it is thread safe.
Null keys and null values :
HashMap allows one null key and any number of null values.Hashtable does not allow null keys or values.
Iterating the values:
Iterator in the HashMap is a fail-fast iterator while the enumerator for the Hashtable is not and throw ConcurrentModificationException if any other Thread modifies the map structurally by adding or removing any element except Iterator’s own remove() method.
Superclass and Legacy :
HashMap is subclass of AbstractMap class whereas Hashtable is subclass of Dictionary class.
Performance :
As HashMap is not synchronized it is faster as compared to Hashtable.
Refer http://modernpathshala.com/Article/1020/difference-between-hashmap-and-hashtable-in-java for examples and interview questions and quiz related to Java collection
A: Hashtable is similar to the HashMap and has a similar interface. It is recommended that you use HashMap, unless you require support for legacy applications or you need synchronisation, as the Hashtables methods are synchronised. So in your case as you are not multi-threading, HashMaps are your best bet.
A: Hashtable is synchronized, whereas HashMap isn't. That makes Hashtable slower than Hashmap.
For single thread applications, use HashMap since they are otherwise the same in terms of functionality.
A: HashMap is emulated and therefore usable in GWT client code whereas Hashtable is not.
A: Hashtable is considered legacy code. There's nothing about Hashtable that can't be done using HashMap or derivations of HashMap, so for new code, I don't see any justification for going back to Hashtable.
A: Another key difference between hashtable and hashmap is that Iterator in the HashMap is fail-fast while the enumerator for the Hashtable is not and throw ConcurrentModificationException if any other Thread modifies the map structurally by adding or removing any element except Iterator's own remove() method. But this is not a guaranteed behavior and will be done by JVM on best effort."
My source: http://javarevisited.blogspot.com/2010/10/difference-between-hashmap-and.html
A: There are several differences between HashMap and Hashtable in Java:
*
*Hashtable is synchronized, whereas HashMap is not. This makes HashMap better for non-threaded applications, as unsynchronized Objects typically perform better than synchronized ones.
*Hashtable does not allow null keys or values. HashMap allows one null key and any number of null values.
*One of HashMap's subclasses is LinkedHashMap, so in the event that you'd want predictable iteration order (which is insertion order by default), you could easily swap out the HashMap for a LinkedHashMap. This wouldn't be as easy if you were using Hashtable.
Since synchronization is not an issue for you, I'd recommend HashMap. If synchronization becomes an issue, you may also look at ConcurrentHashMap.
A: Beside all the other important aspects already mentioned here, Collections API (e.g. Map interface) is being modified all the time to conform to the "latest and greatest" additions to Java spec.
For example, compare Java 5 Map iterating:
for (Elem elem : map.keys()) {
elem.doSth();
}
versus the old Hashtable approach:
for (Enumeration en = htable.keys(); en.hasMoreElements(); ) {
Elem elem = (Elem) en.nextElement();
elem.doSth();
}
In Java 1.8 we are also promised to be able to construct and access HashMaps like in good old scripting languages:
Map<String,Integer> map = { "orange" : 12, "apples" : 15 };
map["apples"];
Update: No, they won't land in 1.8... :(
Are Project Coin's collection enhancements going to be in JDK8?
A: *
*HashTable is synchronized, if you are using it in a single thread you can use HashMap, which is an unsynchronized version. Unsynchronized objects are often a little more performant. By the way if multiple threads access a HashMap concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally.
Youn can wrap a unsynchronized map in a synchronized one using :
Map m = Collections.synchronizedMap(new HashMap(...));
*HashTable can only contain non-null object as a key or as a value. HashMap can contain one null key and null values.
*The iterators returned by Map are fail-fast, if the map is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future. Whereas the Enumerations returned by Hashtable's keys and elements methods are not fail-fast.
*HashTable and HashMap are member of the Java Collections Framework (since Java 2 platform v1.2, HashTable was retrofitted to implement the Map interface).
*HashTable is considered legacy code, the documentation advise to use ConcurrentHashMap in place of Hashtable if a thread-safe highly-concurrent implementation is desired.
*HashMap doesn't guarantee the order in which elements are returned. For HashTable I guess it's the same but I'm not entirely sure, I don't find ressource that clearly state that.
A: HashMap and Hashtable have significant algorithmic differences as well. No one has mentioned this before so that's why I am bringing it up. HashMap will construct a hash table with power of two size, increase it dynamically such that you have at most about eight elements (collisions) in any bucket and will stir the elements very well for general element types. However, the Hashtable implementation provides better and finer control over the hashing if you know what you are doing, namely you can fix the table size using e.g. the closest prime number to your values domain size and this will result in better performance than HashMap i.e. less collisions for some cases.
Separate from the obvious differences discussed extensively in this question, I see the Hashtable as a "manual drive" car where you have better control over the hashing and the HashMap as the "automatic drive" counterpart that will generally perform well.
A: Based on the info here, I'd recommend going with HashMap. I think the biggest advantage is that Java will prevent you from modifying it while you are iterating over it, unless you do it through the iterator.
A: A Collection — sometimes called a container — is simply an object that groups multiple elements into a single unit. Collections are used to store, retrieve, manipulate, and communicate aggregate data. A collections framework W is a unified architecture for representing and manipulating collections.
The HashMap JDK1.2 and Hashtable JDK1.0, both are used to represent a group of objects that are represented in <Key, Value> pair. Each <Key, Value> pair is called Entry object. The collection of Entries is referred by the object of HashMap and Hashtable. Keys in a collection must be unique or distinctive. [as they are used to retrieve a mapped value a particular key. values in a collection can be duplicated.]
« Superclass, Legacy and Collection Framework member
Hashtable is a legacy class introduced in JDK1.0, which is a subclass of Dictionary class. From JDK1.2 Hashtable is re-engineered to implement the Map interface to make a member of collection framework. HashMap is a member of Java Collection Framework right from the beginning of its introduction in JDK1.2. HashMap is the subclass of the AbstractMap class.
public class Hashtable<K,V> extends Dictionary<K,V> implements Map<K,V>, Cloneable, Serializable { ... }
public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable { ... }
« Initial capacity and Load factor
The capacity is the number of buckets in the hash table, and the initial capacity is simply the capacity at the time the hash table is created. Note that the hash table is open: in the case of a "hash collision", a single bucket stores multiple entries, which must be searched sequentially. The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased.
HashMap constructs an empty hash table with the default initial capacity (16) and the default load factor (0.75). Where as Hashtable constructs empty hashtable with a default initial capacity (11) and load factor/fill ratio (0.75).
« Structural modification in case of hash collision
HashMap, Hashtable in case of hash collisions they store the map entries in linked lists. From Java8 for HashMap if hash bucket grows beyond a certain threshold, that bucket will switch from linked list of entries to a balanced tree. which improve worst-case performance from O(n) to O(log n). While converting the list to binary tree, hashcode is used as a branching variable. If there are two different hashcodes in the same bucket, one is considered bigger and goes to the right of the tree and other one to the left. But when both the hashcodes are equal, HashMap assumes that the keys are comparable, and compares the key to determine the direction so that some order can be maintained. It is a good practice to make the keys of HashMap comparable. On adding entries if bucket size reaches TREEIFY_THRESHOLD = 8 convert linked list of entries to a balanced tree, on removing entries less than TREEIFY_THRESHOLD and at most UNTREEIFY_THRESHOLD = 6 will reconvert balanced tree to linked list of entries. Java 8 SRC, stackpost
« Collection-view iteration, Fail-Fast and Fail-Safe
+--------------------+-----------+-------------+
| | Iterator | Enumeration |
+--------------------+-----------+-------------+
| Hashtable | fail-fast | safe |
+--------------------+-----------+-------------+
| HashMap | fail-fast | fail-fast |
+--------------------+-----------+-------------+
| ConcurrentHashMap | safe | safe |
+--------------------+-----------+-------------+
Iterator is a fail-fast in nature. i.e it throws ConcurrentModificationException if a collection is modified while iterating other than it’s own remove() method. Where as Enumeration is fail-safe in nature. It doesn’t throw any exceptions if a collection is modified while iterating.
According to Java API Docs, Iterator is always preferred over the Enumeration.
NOTE: The functionality of Enumeration interface is duplicated by the Iterator interface. In addition, Iterator adds an optional remove operation, and has shorter method names. New implementations should consider using Iterator in preference to Enumeration.
In Java 5 introduced ConcurrentMap Interface: ConcurrentHashMap - a highly concurrent, high-performance ConcurrentMap implementation backed by a hash table. This implementation never blocks when performing retrievals and allows the client to select the concurrency level for updates. It is intended as a drop-in replacement for Hashtable: in addition to implementing ConcurrentMap, it supports all of the "legacy" methods peculiar to Hashtable.
*
*Each HashMapEntrys value is volatile thereby ensuring fine grain consistency for contended modifications and subsequent reads; each read reflects the most recently completed update
*Iterators and Enumerations are Fail Safe - reflecting the state at some point since the creation of iterator/enumeration; this allows for simultaneous reads and modifications at the cost of reduced consistency. They do not throw ConcurrentModificationException. However, iterators are designed to be used by only one thread at a time.
*Like Hashtable but unlike HashMap, this class does not allow null to be used as a key or value.
public static void main(String[] args) {
//HashMap<String, Integer> hash = new HashMap<String, Integer>();
Hashtable<String, Integer> hash = new Hashtable<String, Integer>();
//ConcurrentHashMap<String, Integer> hash = new ConcurrentHashMap<>();
new Thread() {
@Override public void run() {
try {
for (int i = 10; i < 20; i++) {
sleepThread(1);
System.out.println("T1 :- Key"+i);
hash.put("Key"+i, i);
}
System.out.println( System.identityHashCode( hash ) );
} catch ( Exception e ) {
e.printStackTrace();
}
}
}.start();
new Thread() {
@Override public void run() {
try {
sleepThread(5);
// ConcurrentHashMap traverse using Iterator, Enumeration is Fail-Safe.
// Hashtable traverse using Enumeration is Fail-Safe, Iterator is Fail-Fast.
for (Enumeration<String> e = hash.keys(); e.hasMoreElements(); ) {
sleepThread(1);
System.out.println("T2 : "+ e.nextElement());
}
// HashMap traverse using Iterator, Enumeration is Fail-Fast.
/*
for (Iterator< Entry<String, Integer> > it = hash.entrySet().iterator(); it.hasNext(); ) {
sleepThread(1);
System.out.println("T2 : "+ it.next());
// ConcurrentModificationException at java.util.Hashtable$Enumerator.next
}
*/
/*
Set< Entry<String, Integer> > entrySet = hash.entrySet();
Iterator< Entry<String, Integer> > it = entrySet.iterator();
Enumeration<Entry<String, Integer>> entryEnumeration = Collections.enumeration( entrySet );
while( entryEnumeration.hasMoreElements() ) {
sleepThread(1);
Entry<String, Integer> nextElement = entryEnumeration.nextElement();
System.out.println("T2 : "+ nextElement.getKey() +" : "+ nextElement.getValue() );
//java.util.ConcurrentModificationException at java.util.HashMap$HashIterator.nextNode
// at java.util.HashMap$EntryIterator.next
// at java.util.Collections$3.nextElement
}
*/
} catch ( Exception e ) {
e.printStackTrace();
}
}
}.start();
Map<String, String> unmodifiableMap = Collections.unmodifiableMap( map );
try {
unmodifiableMap.put("key4", "unmodifiableMap");
} catch (java.lang.UnsupportedOperationException e) {
System.err.println("UnsupportedOperationException : "+ e.getMessage() );
}
}
static void sleepThread( int sec ) {
try {
Thread.sleep( 1000 * sec );
} catch (InterruptedException e) {
e.printStackTrace();
}
}
« Null Keys And Null Values
HashMap allows maximum one null key and any number of null values. Where as Hashtable doesn’t allow even a single null key and null value, if the key or value null is then it throws NullPointerException. Example
« Synchronized, Thread Safe
Hashtable is internally synchronized. Therefore, it is very much safe to use Hashtable in multi threaded applications. Where as HashMap is not internally synchronized. Therefore, it is not safe to use HashMap in multi threaded applications without external synchronization. You can externally synchronize HashMap using Collections.synchronizedMap() method.
« Performance
As Hashtable is internally synchronized, this makes Hashtable slightly slower than the HashMap.
@See
*
*A red–black tree is a kind of self-balancing binary search tree
*Performance Improvement for HashMap in Java 8
A: HashMaps gives you freedom of synchronization and debugging is lot more easier
A: HashMap is a class used to store the element in key and value format.it is not thread safe.
because it is not synchronized .where as Hashtable is synchronized.Hashmap permits null but hastable doesn't permit null.
A: This question is often asked in interviews to check whether the candidate understands the correct usage of collection classes and is aware of alternative solutions available.
*
*The HashMap class is roughly equivalent to Hashtable, except that it is non synchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesn't allow nulls).
*HashMap does not guarantee that the order of the map will remain constant over time.
*HashMap is non synchronized whereas Hashtable is synchronized.
*Iterator in the HashMap is fail-safe while the enumerator for the Hashtable is not and throw ConcurrentModificationException if any other Thread modifies the map structurally by adding or removing any element except Iterator's own remove() method. But this is not a guaranteed behavior and will be done by JVM on best effort.
Note on Some Important Terms:
*
*Synchronized means only one thread can modify a hash table at one point in time. Basically, it means that any thread before performing an update on a Hashtable will have to acquire a lock on the object while others will wait for the lock to be released.
*Fail-safe is relevant within the context of iterators. If an iterator has been created on a collection object and some other thread tries to modify the collection object "structurally", a concurrent modification exception will be thrown. It is possible for other threads though to invoke the set method since it doesn't modify the collection "structurally". However, if prior to calling set, the collection has been modified structurally, IllegalArgumentException will be thrown.
*Structurally modification means deleting or inserting element which could effectively change the structure of the map.
HashMap can be synchronized by
Map m = Collections.synchronizeMap(hashMap);
Map provides Collection views instead of direct support for iteration via Enumeration objects. Collection views greatly enhance the expressiveness of the interface, as discussed later in this section. Map allows you to iterate over keys, values, or key-value pairs; Hashtable does not provide the third option. Map provides a safe way to remove entries in the midst of iteration; Hashtable did not. Finally, Map fixes a minor deficiency in the Hashtable interface. Hashtable has a method called contains, which returns true if the Hashtable contains a given value. Given its name, you'd expect this method to return true if the Hashtable contained a given key because the key is the primary access mechanism for a Hashtable. The Map interface eliminates this source of confusion by renaming the method containsValue. Also, this improves the interface's consistency — containsValue parallels containsKey.
The Map Interface
A: For threaded apps, you can often get away with ConcurrentHashMap- depends on your performance requirements.
A: 1.Hashmap and HashTable both store key and value.
2.Hashmap can store one key as null. Hashtable can't store null.
3.HashMap is not synchronized but Hashtable is synchronized.
4.HashMap can be synchronized with Collection.SyncronizedMap(map)
Map hashmap = new HashMap();
Map map = Collections.SyncronizedMap(hashmap);
A: Apart from the differences already mentioned, it should be noted that since Java 8, HashMap dynamically replaces the Nodes (linked list) used in each bucket with TreeNodes (red-black tree), so that even if high hash collisions exist, the worst case when searching is
O(log(n)) for HashMap Vs O(n) in Hashtable.
*The aforementioned improvement has not been applied to Hashtable yet, but only to HashMap, LinkedHashMap, and ConcurrentHashMap.
FYI, currently,
*
*TREEIFY_THRESHOLD = 8 : if a bucket contains more than 8 nodes, the linked list is transformed into a balanced tree.
*UNTREEIFY_THRESHOLD = 6 : when a bucket becomes too small (due to removal or resizing) the tree is converted back to linked list.
A: There are 5 basic differentiations with HashTable and HashMaps.
*
*Maps allows you to iterate and retrieve keys, values, and both key-value pairs as well, Where HashTable don't have all this capability.
*In Hashtable there is a function contains(), which is very confusing to use. Because the meaning of contains is slightly deviating. Whether it means contains key or contains value? tough to understand. Same thing in Maps we have ContainsKey() and ContainsValue() functions, which are very easy to understand.
*In hashmap you can remove element while iterating, safely. where as it is not possible in hashtables.
*HashTables are by default synchronized, so it can be used with multiple threads easily. Where as HashMaps are not synchronized by default, so can be used with only single thread. But you can still convert HashMap to synchronized by using Collections util class's synchronizedMap(Map m) function.
*HashTable won't allow null keys or null values. Where as HashMap allows one null key, and multiple null values.
A: HashMap: An implementation of the Map interface that uses hash codes to index an array.
Hashtable: Hi, 1998 called. They want their collections API back.
Seriously though, you're better off staying away from Hashtable altogether. For single-threaded apps, you don't need the extra overhead of synchronisation. For highly concurrent apps, the paranoid synchronisation might lead to starvation, deadlocks, or unnecessary garbage collection pauses. Like Tim Howland pointed out, you might use ConcurrentHashMap instead.
A: Keep in mind that HashTable was legacy class before Java Collections Framework (JCF) was introduced and was later retrofitted to implement the Map interface. So was Vector and Stack.
Therefore, always stay away from them in new code since there always better alternative in the JCF as others had pointed out.
Here is the Java collection cheat sheet that you will find useful. Notice the gray block contains the legacy class HashTable,Vector and Stack.
A: HashMap: It is a class available inside java.util package and it is used to store the element in key and value format.
Hashtable: It is a legacy class which is being recognized inside collection framework.
A: My small contribution :
*
*First and most significant different between Hashtable and HashMap is that, HashMap is not thread-safe while Hashtable is a thread-safe collection.
*Second important difference between Hashtable and HashMap is performance, since HashMap is not synchronized it perform better than Hashtable.
*Third difference on Hashtable vs HashMap is that Hashtable is obsolete class and you should be using ConcurrentHashMap in place of Hashtable in Java.
A: *
*Hashtable is synchronized whereas HashMap is not.
*Another difference is that iterator in the HashMap is fail-safe
while the enumerator for the Hashtable isn't. If you change the map
while iterating, you'll know.
*HashMap permits null values in it, while Hashtable doesn't.
A: HashTable is a legacy class in the jdk that shouldn't be used anymore. Replace usages of it with ConcurrentHashMap. If you don't require thread safety, use HashMap which isn't threadsafe but faster and uses less memory.
A: HashMap and HashTable
*
*Some important points about HashMap and HashTable.
please read below details.
1) Hashtable and Hashmap implement the java.util.Map interface
2) Both Hashmap and Hashtable is the hash based collection. and working on hashing.
so these are similarity of HashMap and HashTable.
*
*What is the difference between HashMap and HashTable?
1) First difference is HashMap is not thread safe While HashTable is ThreadSafe
2) HashMap is performance wise better because it is not thread safe. while Hashtable performance wise is not better because it is thread safe. so multiple thread can not access Hashtable at the same time.
A: HashMap and Hashtable both are used to store data in key and value form. Both are using hashing technique to store unique keys.
ut there are many differences between HashMap and Hashtable classes that are given below.
A: There are many good answers already posted. I'm adding few new points and summarizing it.
HashMap and Hashtable both are used to store data in key and value form. Both are using hashing technique to store unique keys.
But there are many differences between HashMap and Hashtable classes that are given below.
HashMap
*
*HashMap is non synchronized. It is not-thread safe and can't be shared between many threads without proper synchronization code.
*HashMap allows one null key and multiple null values.
*HashMap is a new class introduced in JDK 1.2.
*HashMap is fast.
*We can make the HashMap as synchronized by calling this code
Map m = Collections.synchronizedMap(HashMap);
*HashMap is traversed by Iterator.
*Iterator in HashMap is fail-fast.
*HashMap inherits AbstractMap class.
Hashtable
*
*Hashtable is synchronized. It is thread-safe and can be shared with many threads.
*Hashtable doesn't allow null key or value.
*Hashtable is a legacy class.
*Hashtable is slow.
*Hashtable is internally synchronized and can't be unsynchronized.
*Hashtable is traversed by Enumerator and Iterator.
*Enumerator in Hashtable is not fail-fast.
*Hashtable inherits Dictionary class.
Further reading What is difference between HashMap and Hashtable in Java?
A: Hashtable:
Hashtable is a data structure that retains values of key-value pair. It doesn’t allow null for both the keys and the values. You will get a NullPointerException if you add null value. It is synchronized. So it comes with its cost. Only one thread can access HashTable at a particular time.
Example :
import java.util.Map;
import java.util.Hashtable;
public class TestClass {
public static void main(String args[ ]) {
Map<Integer,String> states= new Hashtable<Integer,String>();
states.put(1, "INDIA");
states.put(2, "USA");
states.put(3, null); //will throw NullPointerEcxeption at runtime
System.out.println(states.get(1));
System.out.println(states.get(2));
// System.out.println(states.get(3));
}
}
HashMap:
HashMap is like Hashtable but it also accepts key value pair. It allows null for both the keys and the values. Its performance better is better than HashTable, because it is unsynchronized.
Example:
import java.util.HashMap;
import java.util.Map;
public class TestClass {
public static void main(String args[ ]) {
Map<Integer,String> states = new HashMap<Integer,String>();
states.put(1, "INDIA");
states.put(2, "USA");
states.put(3, null); // Okay
states.put(null,"UK");
System.out.println(states.get(1));
System.out.println(states.get(2));
System.out.println(states.get(3));
}
}
A: The Hashtable class is synchronized, that is, it is designed to be used by applications that handle multiple or multithreaded process. Synchronized classes are less efficient in the classical case of an application to a process, so the Hashmap class is faster in general.
The HashTable class does not accept the Null value, either for keys or for values, while the HashMap class allows a single key with Null and as many as null as possible.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40471",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4247"
} |
Q: Is Java "pass-by-reference" or "pass-by-value"? I always thought Java uses pass-by-reference. However, I read a blog post which claims that Java uses pass-by-value. I don't think I understand the distinction the author is making.
What is the explanation?
A: Java is always pass by value, not pass by reference
First of all, we need to understand what pass by value and pass by reference are.
Pass by value means that you are making a copy in memory of the actual parameter's value that is passed in. This is a copy of the contents of the actual parameter.
Pass by reference (also called pass by address) means that a copy of the address of the actual parameter is stored.
Sometimes Java can give the illusion of pass by reference. Let's see how it works by using the example below:
public class PassByValue {
public static void main(String[] args) {
Test t = new Test();
t.name = "initialvalue";
new PassByValue().changeValue(t);
System.out.println(t.name);
}
public void changeValue(Test f) {
f.name = "changevalue";
}
}
class Test {
String name;
}
The output of this program is:
changevalue
Let's understand step by step:
Test t = new Test();
As we all know it will create an object in the heap and return the reference value back to t. For example, suppose the value of t is 0x100234 (we don't know the actual JVM internal value, this is just an example) .
new PassByValue().changeValue(t);
When passing reference t to the function it will not directly pass the actual reference value of object test, but it will create a copy of t and then pass it to the function. Since it is passing by value, it passes a copy of the variable rather than the actual reference of it. Since we said the value of t was 0x100234, both t and f will have the same value and hence they will point to the same object.
If you change anything in the function using reference f it will modify the existing contents of the object. That is why we got the output changevalue, which is updated in the function.
To understand this more clearly, consider the following example:
public class PassByValue {
public static void main(String[] args) {
Test t = new Test();
t.name = "initialvalue";
new PassByValue().changeRefence(t);
System.out.println(t.name);
}
public void changeRefence(Test f) {
f = null;
}
}
class Test {
String name;
}
Will this throw a NullPointerException? No, because it only passes a copy of the reference.
In the case of passing by reference, it could have thrown a NullPointerException, as seen below:
Hopefully this will help.
A: Java is a pass by value(stack memory)
How it works
*
*Let's first understand that where java stores primitive data type and object data type.
*Primitive data types itself and object references are stored in the stack.
Objects themselves are stored in the heap.
*It means, Stack memory stores primitive data types and also the
addresses of objects.
*And you always pass a copy of the bits of the value of the reference.
*If it's a primitive data type then these copied bits contain the value of the primitive data type itself, That's why when we change the value of argument inside the method then it does not reflect the changes outside.
*If it's an object data type like Foo foo=new Foo() then in this case copy of the address of the object passes like file shortcut , suppose we have a text file abc.txt at C:\desktop and suppose we make shortcut of the same file and put this inside C:\desktop\abc-shortcut so when you access the file from C:\desktop\abc.txt and write 'Stack Overflow' and close the file and again you open the file from shortcut then you write ' is the largest online community for programmers to learn' then total file change will be 'Stack Overflow is the largest online community for programmers to learn' which means it doesn't matter from where you open the file , each time we were accessing the same file , here we can assume Foo as a file and suppose foo stored at 123hd7h(original address like C:\desktop\abc.txt ) address and 234jdid(copied address like C:\desktop\abc-shortcut which actually contains the original address of the file inside) ..
So for better understanding make shortcut file and feel.
A: Java is always pass-by-value, the parameters are copies of what the variables passed, all Objects are defined using a reference, and reference is a variable that stores a memory address of where the object is in memory.
Check the comments to understand what happens in execution; follow numbers as they show the flow of execution ..
class Example
{
public static void test (Cat ref)
{
// 3 - <ref> is a copy of the reference <a>
// both currently reference Grumpy
System.out.println(ref.getName());
// 4 - now <ref> references a new <Cat> object named "Nyan"
ref = new Cat("Nyan");
// 5 - this should print "Nyan"
System.out.println( ref.getName() );
}
public static void main (String [] args)
{
// 1 - a is a <Cat> reference that references a Cat object in memory with name "Grumpy"
Cat a = new Cat("Grumpy");
// 2 - call to function test which takes a <Cat> reference
test (a);
// 6 - function call ends, and <ref> life-time ends
// "Nyan" object has no references and the Garbage
// Collector will remove it from memory when invoked
// 7 - this should print "Grumpy"
System.out.println(a.getName());
}
}
A: PT 1: Of Realty Listings
There is a blue, 120sq-ft "Tiny House" currently parked at 1234 Main St with a nicely manicured lawn & flower bed out front.
A Realtor with a local firm is hired and told to keep a listing for that house.
Let's call that Realtor "Bob." Hi Bob.
Bob keeps his Listing, which he calls tinyHouseAt1234Main, up to date with a webcam that allows him to note any changes to the actual house in real time. He also keeps a tally of how many people have asked about the listing.
Bob's integer viewTally for the house is at 42 today.
Whenever someone wants info about the blue Tiny House at 1234 Main St, they ask Bob.
Bob looks up his Listing tinyHouseAt1234Main and tells them all about it - the color, the nice lawn, the loft bed and the composting toilet, etc. Then he adds their inquiry to his viewTally. He doesn't tell them the real, physical address though, because Bob's firm specializes in Tiny Houses that could be moved at any time. The tally is now 43.
At another firm, Realtors might explicitly say their listing "points" to the house at 1234 Main St, denoting this with a little * next to it, because they mainly deal with houses that rarely ever move (though presumably there are reasons for doing so). Bob's firm doesn't bother doing this.
Now, of course Bob doesn't physically go and put the actual house on a truck to show it to clients directly - that would be impractical and a ridiculous waste of resources. Passing a full copy of his tally sheet is one thing, but passing around the whole house all the time is costly and ridiculous.
(Aside: Bob's firm also doesn't 3D print new & unique copies of a listed house every single time someone asks about it. That's what the upstart, similarly named web-based firm & its spinoffs do - that's expensive and slower, and people often get the 2 firms confused, but they're quite popular anyway).
At some other, older firms closer to the Sea, a realtor like Bob might not even exist to manage the Listings. Clients might instead consult the Rolodex "Annie" (& for short) for the direct address of the house. Instead of reading off the referenced house details from the listing like Bob does, clients instead get the house address from Annie (&), and go directly to 1234 Main St, sometimes w/no idea what they might find there.
One day, Bob's firm begins offering a new automated service that needs the listing for a house the client is interested in.
Well, the person with that info is Bob, so the client has Bob call up the service and send it a copy of the listing.
jobKillingAutomatedListingService(Listing tinyHouseAt1234Main, int viewTally) Bob sends along ...
The service, on its end, calls this Listing houseToLookAt, but really what it receives is an exact copy of Bob's listing, with the exact same VALUEs in it, that refer to the house at 1234 Main St.
This new service also has its own internal tally of how many people have viewed the listing. The service accepts Bob's tally out of professional courtesy, but it doesn't really care and overwrites it entirely with its own local copy anyway. It's tally for today is 1, while Bob's is still 43.
The realty firms call this "pass-by-value" since Bob's passing the current value of his viewTally and his Listing tinyHouseAt1234Main. He's not actually passing along the entire physical house, because that's impractical. Nor is he passing the real physical address like Annie(&) would do.
But he IS passing a copy of the value OF the reference he has to the house. Seems like a silly pedantic difference in some ways, but that's how his firm works ...
..............
PT II: Where things get confusing and dangerous ...
The new automated service, not being all functional and math-oriented like some other trendy financial & scientific firms, can have unforeseen side effects...
Once given a Listing object it allows clients to actually repaint the REAL house at 1234 Main St, using a remote drone robot fleet! It allows clients to control a robot bulldozer to ACTUALLY dig up the flower bed! This is madness!!!
The service also lets clients completely redirect houseToLookAt to some other house at another address, without involving Bob or his listing. All of a sudden they could be looking at 4321 Elm St. instead, which has no connection whatsoever to Bob's listing (thankfully they can't do anymore damage).
Bob watches all this on his realtime webcam.
Resigned to the drudgery of his sole job responsibility, he tells clients about the new ugly paint job & sudden lack of curb appeal. His Listing is still for 1234 Main St., after all. The new service's houseToLookAt couldn't change that. Bob reports the details of his tinyHouseAt1234Main accurately and dutifully as always, until he gets fired or the house is destroyed entirely by The Nothing.
Really the only thing the service CAN'T do with its houseToLookAt copy of the Bob's original listing is change the address from 1234 Main St. to some other address, or to a void of nothingness, or to some random type of object like a Platypus. Bob's Listing still always points to 1234 Main St, for whatever it's still worth. He passes its current value around like always.
This bizarre side-effect of passing a listing to the new automated service is confusing for people who ask about how it works. Really, what's the difference between the ability to remotely control robots that alter the state of the house at 1234 Main, vs. actually physically going there and wreaking havoc because Annie gave you the address??
Seems like kind of a nitpicky semantic argument if what you generally care about is the state of the house in the listing being copied and passed around, right?
I mean, if you were in the business of actually picking up houses and physically moving them to other addresses (not like mobile or Tiny Homes where that's sort of an expected function of the platform), or you were accessing, renaming, and shuffling entire neighborhoods like some sort of low-level God-playing madman, THEN maybe you'd care more about passing around those specific address references instead of just copies of the the latest value of the house details ...
A: Java is always pass by value, with no exceptions, ever.
So how is it that anyone can be at all confused by this, and believe that Java is pass by reference, or think they have an example of Java acting as pass by reference? The key point is that Java never provides direct access to the values of objects themselves, in any circumstances. The only access to objects is through a reference to that object. Because Java objects are always accessed through a reference, rather than directly, it is common to talk about fields and variables and method arguments as being objects, when pedantically they are only references to objects. The confusion stems from this (strictly speaking, incorrect) change in nomenclature.
So, when calling a method
*
*For primitive arguments (int, long, etc.), the pass by value is the actual value of the primitive (for example, 3).
*For objects, the pass by value is the value of the reference to the object.
So if you have doSomething(foo) and public void doSomething(Foo foo) { .. } the two Foos have copied references that point to the same objects.
Naturally, passing by value a reference to an object looks very much like (and is indistinguishable in practice from) passing an object by reference.
A: Shortest answer :)
*
*Java has pass-by-value (and pass-reference-by-value.)
*C# also has pass-by-reference
In C# this is accomplished with the "out" and "ref" keywords.
Pass By Reference: The variable is passed in such a way that a reassignment inside the method is reflected even outside the method.
Here follows an example of passing-by-reference (C#).
This feature does not exist in java.
class Example
{
static void InitArray(out int[] arr)
{
arr = new int[5] { 1, 2, 3, 4, 5 };
}
static void Main()
{
int[] someArray;
InitArray(out someArray);
// This is true !
boolean isTrue = (someArray[0] == 1);
}
}
See also: MSDN library (C#): passing arrays by ref and out
See also: MSDN library (C#): passing by by value and by reference
A: Java passes parameters by value, but for object variables, the values are essentially references to objects. Since arrays are objects the following example code shows the difference.
public static void dummyIncrease(int[] x, int y)
{
x[0]++;
y++;
}
public static void main(String[] args)
{
int[] arr = {3, 4, 5};
int b = 1;
dummyIncrease(arr, b);
// arr[0] is 4, but b is still 1
}
main()
arr +---+ +---+---+---+
| # | ----> | 3 | 4 | 5 |
+---+ +---+---+---+
b +---+ ^
| 1 | |
+---+ |
|
dummyIncrease() |
x +---+ |
| # | ------------+
+---+
y +---+
| 1 |
+---+
A: Simple program
import java.io.*;
class Aclass
{
public int a;
}
public class test
{
public static void foo_obj(Aclass obj)
{
obj.a=5;
}
public static void foo_int(int a)
{
a=3;
}
public static void main(String args[])
{
//test passing an object
Aclass ob = new Aclass();
ob.a=0;
foo_obj(ob);
System.out.println(ob.a);//prints 5
//test passing an integer
int i=0;
foo_int(i);
System.out.println(i);//prints 0
}
}
From a C/C++ programmer's point of view, java uses pass by value, so for primitive data types (int, char etc) changes in the function does not reflect in the calling function. But when you pass an object and in the function you change its data members or call member functions which can change the state of the object, the calling function will get the changes.
A: There is a very simple way to understand this.
Lets's take C++ pass by reference.
#include <iostream>
using namespace std;
class Foo {
private:
int x;
public:
Foo(int val) {x = val;}
void foo()
{
cout<<x<<endl;
}
};
void bar(Foo& ref)
{
ref.foo();
ref = *(new Foo(99));
ref.foo();
}
int main()
{
Foo f = Foo(1);
f.foo();
bar(f);
f.foo();
return 0;
}
What is the outcome?
1
1
99
99
So, after bar() assigned a new value to a "reference" passed in, it actually changed the one which was passed in from main itself, explaining the last f.foo() call from main printing 99.
Now, lets see what java says.
public class Ref {
private static class Foo {
private int x;
private Foo(int x) {
this.x = x;
}
private void foo() {
System.out.println(x);
}
}
private static void bar(Foo f) {
f.foo();
f = new Foo(99);
f.foo();
}
public static void main(String[] args) {
Foo f = new Foo(1);
System.out.println(f.x);
bar(f);
System.out.println(f.x);
}
}
It says:
1
1
99
1
Voilà, the reference of Foo in main that was passed to bar, is still unchanged!
This example clearly shows that java is not the same as C++ when we say "pass by reference". Essentially, java is passing "references" as "values" to functions, meaning java is pass by value.
A: Java is only passed by value. there is no pass by reference, for example, you can see the following example.
package com.asok.cop.example.task;
public class Example {
int data = 50;
void change(int data) {
data = data + 100;// changes will be in the local variable
System.out.println("after add " + data);
}
public static void main(String args[]) {
Example op = new Example();
System.out.println("before change " + op.data);
op.change(500);
System.out.println("after change " + op.data);
}
}
Output:
before change 50
after add 600
after change 50
as Michael says in the comments:
objects are still passed by value even though operations on them behave like pass-by-reference. Consider void changePerson(Person person){ person = new Person(); } the callers reference to the person object will remain unchanged. Objects themselves are passed by value but their members can be affected by changes. To be true pass-by-reference, we would have to be able to reassign the argument to a new object and have the change be reflected in the caller.
A: A: Java does manipulate objects by reference, and all object variables are references. However, Java doesn't pass method arguments by reference; it passes them by value.
Take the badSwap() method for example:
public void badSwap(int var1, int var2)
{
int temp = var1;
var1 = var2;
var2 = temp;
}
When badSwap() returns, the variables passed as arguments will still hold their original values. The method will also fail if we change the arguments type from int to Object, since Java passes object references by value as well. Now, here is where it gets tricky:
public void tricky(Point arg1, Point arg2)
{
arg1.x = 100;
arg1.y = 100;
Point temp = arg1;
arg1 = arg2;
arg2 = temp;
}
public static void main(String [] args)
{
Point pnt1 = new Point(0,0);
Point pnt2 = new Point(0,0);
System.out.println("X: " + pnt1.x + " Y: " +pnt1.y);
System.out.println("X: " + pnt2.x + " Y: " +pnt2.y);
System.out.println(" ");
tricky(pnt1,pnt2);
System.out.println("X: " + pnt1.x + " Y:" + pnt1.y);
System.out.println("X: " + pnt2.x + " Y: " +pnt2.y);
}
If we execute this main() method, we see the following output:
X: 0 Y: 0
X: 0 Y: 0
X: 100 Y: 100
X: 0 Y: 0
The method successfully alters the value of pnt1, even though it is passed by value; however, a swap of pnt1 and pnt2 fails! This is the major source of confusion. In the main() method, pnt1 and pnt2 are nothing more than object references. When you pass pnt1 and pnt2 to the tricky() method, Java passes the references by value just like any other parameter. This means the references passed to the method are actually copies of the original references. Figure 1 below shows two references pointing to the same object after Java passes an object to a method.
Figure 1. After being passed to a method, an object will have at least two references
Java copies and passes the reference by value, not the object. Thus, method manipulation will alter the objects, since the references point to the original objects. But since the references are copies, swaps will fail.The method references swap, but not the original references. Unfortunately, after a method call, you are left with only the unswapped original references. For a swap to succeed outside of the method call, we need to swap the original references, not the copies.
A: Java is always pass by value, not pass by reference
First of all, we need to understand what pass by value and pass by reference are.
Pass by value means that you are making a copy in memory of the actual parameter's value that is passed in. This is a copy of the contents of the actual parameter.
Pass by reference (also called pass by address) means that a copy of the address of the actual parameter is stored.
Sometimes Java can give the illusion of pass by reference. Let's see how it works by using the example below:
public class PassByValue {
public static void main(String[] args) {
Test t = new Test();
t.name = "initialvalue";
new PassByValue().changeValue(t);
System.out.println(t.name);
}
public void changeValue(Test f) {
f.name = "changevalue";
}
}
class Test {
String name;
}
The output of this program is:
changevalue
Let's understand step by step:
Test t = new Test();
As we all know it will create an object in the heap and return the reference value back to t. For example, suppose the value of t is 0x100234 (we don't know the actual JVM internal value, this is just an example) .
first illustration
new PassByValue().changeValue(t);
When passing reference t to the function it will not directly pass the actual reference value of object test, but it will create a copy of t and then pass it to the function. Since it is passing by value, it passes a copy of the variable rather than the actual reference of it. Since we said the value of t was 0x100234, both t and f will have the same value and hence they will point to the same object.
second illustration
If you change anything in the function using reference f it will modify the existing contents of the object. That is why we got the output changevalue, which is updated in the function.
To understand this more clearly, consider the following example:
public class PassByValue {
public static void main(String[] args) {
Test t = new Test();
t.name = "initialvalue";
new PassByValue().changeRefence(t);
System.out.println(t.name);
}
public void changeRefence(Test f) {
f = null;
}
}
class Test {
String name;
}
Will this throw a NullPointerException? No, because it only passes a copy of the reference. In the case of passing by reference, it could have thrown a NullPointerException, as seen below:
third illustration
Hopefully this will help.
A: This will give you some insights of how Java really works to the point that in your next discussion about Java passing by reference or passing by value you'll just smile :-)
Step one please erase from your mind that word that starts with 'p' "_ _ _ _ _ _ _", especially if you come from other programming languages. Java and 'p' cannot be written in the same book, forum, or even txt.
Step two remember that when you pass an Object into a method you're passing the Object reference and not the Object itself.
*
*Student: Master, does this mean that Java is pass-by-reference?
*Master: Grasshopper, No.
Now think of what an Object's reference/variable does/is:
*
*A variable holds the bits that tell the JVM how to get to the referenced Object in memory (Heap).
*When passing arguments to a method you ARE NOT passing the reference variable, but a copy of the bits in the reference variable. Something like this: 3bad086a. 3bad086a represents a way to get to the passed object.
*So you're just passing 3bad086a that it's the value of the reference.
*You're passing the value of the reference and not the reference itself (and not the object).
*This value is actually COPIED and given to the method.
In the following (please don't try to compile/execute this...):
1. Person person;
2. person = new Person("Tom");
3. changeName(person);
4.
5. //I didn't use Person person below as an argument to be nice
6. static void changeName(Person anotherReferenceToTheSamePersonObject) {
7. anotherReferenceToTheSamePersonObject.setName("Jerry");
8. }
What happens?
*
*The variable person is created in line #1 and it's null at the beginning.
*A new Person Object is created in line #2, stored in memory, and the variable person is given the reference to the Person object. That is, its address. Let's say 3bad086a.
*The variable person holding the address of the Object is passed to the function in line #3.
*In line #4 you can listen to the sound of silence
*Check the comment on line #5
*A method local variable -anotherReferenceToTheSamePersonObject- is created and then comes the magic in line #6:
*
*The variable/reference person is copied bit-by-bit and passed to anotherReferenceToTheSamePersonObject inside the function.
*No new instances of Person are created.
*Both "person" and "anotherReferenceToTheSamePersonObject" hold the same value of 3bad086a.
*Don't try this but person==anotherReferenceToTheSamePersonObject would be true.
*Both variables have IDENTICAL COPIES of the reference and they both refer to the same Person Object, the SAME Object on the Heap and NOT A COPY.
A picture is worth a thousand words:
Note that the anotherReferenceToTheSamePersonObject arrows is directed towards the Object and not towards the variable person!
If you didn't get it then just trust me and remember that it's better to say that Java is pass by value. Well, pass by reference value. Oh well, even better is pass-by-copy-of-the-variable-value! ;)
Now feel free to hate me but note that given this there is no difference between passing primitive data types and Objects when talking about method arguments.
You always pass a copy of the bits of the value of the reference!
*
*If it's a primitive data type these bits will contain the value of the primitive data type itself.
*If it's an Object the bits will contain the value of the address that tells the JVM how to get to the Object.
Java is pass-by-value because inside a method you can modify the referenced Object as much as you want but no matter how hard you try you'll never be able to modify the passed variable that will keep referencing (not p _ _ _ _ _ _ _) the same Object no matter what!
The changeName function above will never be able to modify the actual content (the bit values) of the passed reference. In other word changeName cannot make Person person refer to another Object.
Of course you can cut it short and just say that Java is pass-by-value!
A: A reference is always a value when represented, no matter what language you use.
Getting an outside of the box view, let's look at Assembly or some low level memory management. At the CPU level a reference to anything immediately becomes a value if it gets written to memory or to one of the CPU registers. (That is why pointer is a good definition. It is a value, which has a purpose at the same time).
Data in memory has a Location and at that location there is a value (byte,word, whatever). In Assembly we have a convenient solution to give a Name to certain Location (aka variable), but when compiling the code, the assembler simply replaces Name with the designated location just like your browser replaces domain names with IP addresses.
Down to the core it is technically impossible to pass a reference to anything in any language without representing it (when it immediately becomes a value).
Lets say we have a variable Foo, its Location is at the 47th byte in memory and its Value is 5. We have another variable Ref2Foo which is at 223rd byte in memory, and its value will be 47. This Ref2Foo might be a technical variable, not explicitly created by the program. If you just look at 5 and 47 without any other information, you will see just two Values.
If you use them as references then to reach to 5 we have to travel:
(Name)[Location] -> [Value at the Location]
---------------------
(Ref2Foo)[223] -> 47
(Foo)[47] -> 5
This is how jump-tables work.
If we want to call a method/function/procedure with Foo's value, there are a few possible way to pass the variable to the method, depending on the language and its several method invocation modes:
*
*5 gets copied to one of the CPU registers (ie. EAX).
*5 gets PUSHd to the stack.
*47 gets copied to one of the CPU registers
*47 PUSHd to the stack.
*223 gets copied to one of the CPU registers.
*223 gets PUSHd to the stack.
In every cases above a value - a copy of an existing value - has been created, it is now upto the receiving method to handle it. When you write "Foo" inside the method, it is either read out from EAX, or automatically dereferenced, or double dereferenced, the process depends on how the language works and/or what the type of Foo dictates. This is hidden from the developer until she circumvents the dereferencing process. So a reference is a value when represented, because a reference is a value that has to be processed (at language level).
Now we have passed Foo to the method:
*
*in case 1. and 2. if you change Foo (Foo = 9) it only affects local scope as you have a copy of the Value. From inside the method we cannot even determine where in memory the original Foo was located.
*in case 3. and 4. if you use default language constructs and change Foo (Foo = 11), it could change Foo globally (depends on the language, ie. Java or like Pascal's procedure findMin(x, y, z: integer;var m: integer);). However if the language allows you to circumvent the dereference process, you can change 47, say to 49. At that point Foo seems to have been changed if you read it, because you have changed the local pointer to it. And if you were to modify this Foo inside the method (Foo = 12) you will probably FUBAR the execution of the program (aka. segfault) because you will write to a different memory than expected, you can even modify an area that is destined to hold executable program and writing to it will modify running code (Foo is now not at 47). BUT Foo's value of 47 did not change globally, only the one inside the method, because 47 was also a copy to the method.
*in case 5. and 6. if you modify 223 inside the method it creates the same mayhem as in 3. or 4. (a pointer, pointing to a now bad value, that is again used as a pointer) but this is still a local problem, as 223 was copied. However if you are able to dereference Ref2Foo (that is 223), reach to and modify the pointed value 47, say, to 49, it will affect Foo globally, because in this case the methods got a copy of 223 but the referenced 47 exists only once, and changing that to 49 will lead every Ref2Foo double-dereferencing to a wrong value.
Nitpicking on insignificant details, even languages that do pass-by-reference will pass values to functions, but those functions know that they have to use it for dereferencing purposes. This pass-the-reference-as-value is just hidden from the programmer because it is practically useless and the terminology is only pass-by-reference.
Strict pass-by-value is also useless, it would mean that a 100 Mbyte array should have to be copied every time we call a method with the array as argument, therefore Java cannot be stricly pass-by-value. Every language would pass a reference to this huge array (as a value) and either employs copy-on-write mechanism if that array can be changed locally inside the method or allows the method (as Java does) to modify the array globally (from the caller's view) and a few languages allows to modify the Value of the reference itself.
So in short and in Java's own terminology, Java is pass-by-value where value can be: either a real value or a value that is a representation of a reference.
A: Mr @Scott Stanchfield wrote an excellent answer. Here is the class that would you to verify
exactly what he meant:
public class Dog {
String dog ;
static int x_static;
int y_not_static;
public String getName()
{
return this.dog;
}
public Dog(String dog)
{
this.dog = dog;
}
public void setName(String name)
{
this.dog = name;
}
public static void foo(Dog someDog)
{
x_static = 1;
// y_not_static = 2; // not possible !!
someDog.setName("Max"); // AAA
someDog = new Dog("Fifi"); // BBB
someDog.setName("Rowlf"); // CCC
}
public static void main(String args[])
{
Dog myDog = new Dog("Rover");
foo(myDog);
System.out.println(myDog.getName());
}
}
So, we pass from main() a dog called Rover, then we assign a new address to the pointer that we passed, but at the end, the name of the dog is not Rover, and not Fifi, and certainly not Rowlf, but Max.
A: Understand it in 2 Steps:
You can't change the reference to the object itself but you can work with this passed parameter as a reference to the object.
If you want to change the value behind the reference you will only declare a new variable on the stack with the same name 'd'. Look at the references with the sign @ and you will find out that the reference has been changed.
public static void foo(Dog d) {
d.Name = "belly";
System.out.println(d); //Reference: Dog@1540e19d
d = new Dog("wuffwuff");
System.out.println(d); //Dog@677327b6
}
public static void main(String[] args) throws Exception{
Dog lisa = new Dog("Lisa");
foo(lisa);
System.out.println(lisa.Name); //belly
}
A: I tried to simplify the examples above, keeping only the essense of the problem.
Let me present this as a story that is easy to remember and apply correctly.
The story goes like this:
You have a pet dog, Jimmy, whose tail is 12 inches long.
You leave it with a vet for a few weeks while you are travelling abroad.
The vet doesn't like the long tail of Jimmy, so he wants to cut it by half.
But being a good vet, he knows that he has no right to mutilate other people's dogs.
So he first makes a clone of the dog (with the new key word) and cuts the tail of the clone.
When the dog finally returns to you, it has the original 12 inch tail in tact. Happy ending !
The next time you travel, you take the dog, unwittingly, to a wicked vet.
He is also a hater of long tails, so he cuts it down to a miserable 2 inches.
But he does this to your dear Jimmy, not a clone of it.
When you return, you are shocked to see Jimmy pathetically wagging a 2 inch stub.
Moral of the story: When you pass on your pet, you are giving away whole and unfettered
custody of the pet to the vet. He is free to play any kind of havoc with it.
Passing by value, by reference, by pointer are all just technical wrangling.
Unless the vet clones it first, he ends up mutilating the original dog.
public class Doggie {
public static void main(String...args) {
System.out.println("At the owner's home:");
Dog d = new Dog(12);
d.wag();
goodVet(d);
System.out.println("With the owner again:)");
d.wag();
badVet(d);
System.out.println("With the owner again(:");
d.wag();
}
public static void goodVet (Dog dog) {
System.out.println("At the good vet:");
dog.wag();
dog = new Dog(12); // create a clone
dog.cutTail(6); // cut the clone's tail
dog.wag();
}
public static void badVet (Dog dog) {
System.out.println("At the bad vet:");
dog.wag();
dog.cutTail(2); // cut the original dog's tail
dog.wag();
}
}
class Dog {
int tailLength;
public Dog(int originalLength) {
this.tailLength = originalLength;
}
public void cutTail (int newLength) {
this.tailLength = newLength;
}
public void wag() {
System.out.println("Wagging my " +tailLength +" inch tail");
}
}
Output:
At the owner's home:
Wagging my 12 inch tail
At the good vet:
Wagging my 12 inch tail
Wagging my 6 inch tail
With the owner again:)
Wagging my 12 inch tail
At the bad vet:
Wagging my 12 inch tail
Wagging my 2 inch tail
With the owner again(:
Wagging my 2 inch tail
A: Java always passes parameters by value.
All object references in Java are passed by value. This means that a copy of the value will be passed to a method. But the trick is that passing a copy of the value also changes the real value of the object.
Please refer to the below example,
public class ObjectReferenceExample {
public static void main(String... doYourBest) {
Student student = new Student();
transformIntoHomer(student);
System.out.println(student.name);
}
static void transformIntoDuleepa(Student student) {
student.name = "Duleepa";
}
}
class Student {
String name;
}
In this case, it will be Duleepa!
The reason is that Java object variables are simply references that point to real objects in the memory heap.
Therefore, even though Java passes parameters to methods by value, if the variable points to an object reference, the real object will also be changed.
A: The terms "pass-by-value" and "pass-by-reference" have special, precisely defined meanings in computer science. These meanings differ from the intuition many people have when first hearing the terms. Much of the confusion in this discussion seems to come from this fact.
The terms "pass-by-value" and "pass-by-reference" are talking about variables. Pass-by-value means that the value of a variable is passed to a function/method. Pass-by-reference means that a reference to that variable is passed to the function. The latter gives the function a way to change the contents of the variable.
By those definitions, Java is always pass-by-value. Unfortunately, when we deal with variables holding objects we are really dealing with object-handles called references which are passed-by-value as well. This terminology and semantics easily confuse many beginners.
It goes like this:
public static void main(String[] args) {
Dog aDog = new Dog("Max");
Dog oldDog = aDog;
// we pass the object to foo
foo(aDog);
// aDog variable is still pointing to the "Max" dog when foo(...) returns
aDog.getName().equals("Max"); // true
aDog.getName().equals("Fifi"); // false
aDog == oldDog; // true
}
public static void foo(Dog d) {
d.getName().equals("Max"); // true
// change d inside of foo() to point to a new Dog instance "Fifi"
d = new Dog("Fifi");
d.getName().equals("Fifi"); // true
}
In the example above aDog.getName() will still return "Max". The value aDog within main is not changed in the function foo with the Dog "Fifi" as the object reference is passed by value. If it were passed by reference, then the aDog.getName() in main would return "Fifi" after the call to foo.
Likewise:
public static void main(String[] args) {
Dog aDog = new Dog("Max");
Dog oldDog = aDog;
foo(aDog);
// when foo(...) returns, the name of the dog has been changed to "Fifi"
aDog.getName().equals("Fifi"); // true
// but it is still the same dog:
aDog == oldDog; // true
}
public static void foo(Dog d) {
d.getName().equals("Max"); // true
// this changes the name of d to be "Fifi"
d.setName("Fifi");
}
In the above example, Fifi is the dog's name after call to foo(aDog) because the object's name was set inside of foo(...). Any operations that foo performs on d are such that, for all practical purposes, they are performed on aDog, but it is not possible to change the value of the variable aDog itself.
For more information on pass by reference and pass by value, consult the following answer: https://stackoverflow.com/a/430958/6005228. This explains more thoroughly the semantics and history behind the two and also explains why Java and many other modern languages appear to do both in certain cases.
A: In Java, method arguments are all passed by value :
Java arguments are all passed by value (the value or reference is copied when used by the method) :
In the case of primitive types, Java behaviour is simple:
The value is copied in another instance of the primitive type.
In case of Objects, this is the same:
Object variables are references (mem buckets holding only Object’s address instead of a primitive value) that was created using the "new" keyword, and are copied like primitive types.
The behaviour can appear different from primitive types: Because the copied object-variable contains the same address (to the same Object).
Object's content/members might still be modified within a method and later access outside, giving the illusion that the (containing) Object itself was passed by reference.
"String" Objects appear to be a good counter-example to the urban legend saying that "Objects are passed by reference":
In effect, using a method, you will never be able, to update the value of a String passed as argument:
A String Object, holds characters by an array declared final that can't be modified.
Only the address of the Object might be replaced by another using "new".
Using "new" to update the variable, will not let the Object be accessed from outside, since the variable was initially passed by value and copied.
A: As far as I know, Java only knows call by value. This means for primitive datatypes you will work with an copy and for objects you will work with an copy of the reference to the objects. However I think there are some pitfalls; for example, this will not work:
public static void swap(StringBuffer s1, StringBuffer s2) {
StringBuffer temp = s1;
s1 = s2;
s2 = temp;
}
public static void main(String[] args) {
StringBuffer s1 = new StringBuffer("Hello");
StringBuffer s2 = new StringBuffer("World");
swap(s1, s2);
System.out.println(s1);
System.out.println(s2);
}
This will populate Hello World and not World Hello because in the swap function you use copys which have no impact on the references in the main. But if your objects are not immutable you can change it for example:
public static void appendWorld(StringBuffer s1) {
s1.append(" World");
}
public static void main(String[] args) {
StringBuffer s = new StringBuffer("Hello");
appendWorld(s);
System.out.println(s);
}
This will populate Hello World on the command line. If you change StringBuffer into String it will produce just Hello because String is immutable. For example:
public static void appendWorld(String s){
s = s+" World";
}
public static void main(String[] args) {
String s = new String("Hello");
appendWorld(s);
System.out.println(s);
}
However you could make a wrapper for String like this which would make it able to use it with Strings:
class StringWrapper {
public String value;
public StringWrapper(String value) {
this.value = value;
}
}
public static void appendWorld(StringWrapper s){
s.value = s.value +" World";
}
public static void main(String[] args) {
StringWrapper s = new StringWrapper("Hello");
appendWorld(s);
System.out.println(s.value);
}
edit: i believe this is also the reason to use StringBuffer when it comes to "adding" two Strings because you can modifie the original object which u can't with immutable objects like String is.
A: No, it's not pass by reference.
Java is pass by value according to the Java Language Specification:
When the method or constructor is invoked (§15.12), the values of the actual argument expressions initialize newly created parameter variables, each of the declared type, before execution of the body of the method or constructor. The Identifier that appears in the DeclaratorId may be used as a simple name in the body of the method or constructor to refer to the formal parameter.
A: There is a workaround in Java for the reference. Let me explain by this example:
public class Yo {
public static void foo(int x){
System.out.println(x); //out 2
x = x+2;
System.out.println(x); // out 4
}
public static void foo(int[] x){
System.out.println(x[0]); //1
x[0] = x[0]+2;
System.out.println(x[0]); //3
}
public static void main(String[] args) {
int t = 2;
foo(t);
System.out.println(t); // out 2 (t did not change in foo)
int[] tab = new int[]{1};
foo(tab);
System.out.println(tab[0]); // out 3 (tab[0] did change in foo)
}}
I hope this helps!
A: Java does manipulate objects by reference, and all object variables are references. However, Java doesn't pass method arguments by reference; it passes them by value.
Take the badSwap() method for example:
public void badSwap(int var1, int
var2{ int temp = var1; var1 = var2; var2 =
temp; }
When badSwap() returns, the variables passed as arguments will still hold their original values. The method will also fail if we change the arguments type from int to Object, since Java passes object references by value as well. Now, here is where it gets tricky:
public void tricky(Point arg1, Point arg2)
{ arg1.x = 100; arg1.y = 100; Point temp = arg1; arg1 = arg2; arg2 = temp; }
public static void main(String [] args) {
Point pnt1 = new Point(0,0); Point pnt2
= new Point(0,0); System.out.println("X:
" + pnt1.x + " Y: " +pnt1.y);
System.out.println("X: " + pnt2.x + " Y:
" +pnt2.y); System.out.println(" ");
tricky(pnt1,pnt2);
System.out.println("X: " + pnt1.x + " Y:" + pnt1.y);
System.out.println("X: " + pnt2.x + " Y: " +pnt2.y); }
If we execute this main() method, we see the following output:
X: 0 Y: 0 X: 0 Y: 0 X: 100 Y: 100 X: 0 Y: 0
The method successfully alters the value ofpnt1, even though it is passed by value; however, a swap of pnt1 and pnt2 fails! This is the major source of confusion. In themain() method, pnt1 and pnt2 are nothing more than object references. When you passpnt1 and pnt2 to the tricky() method, Java passes the references by value just like any other parameter. This means the references passed to the method are actually copies of the original references. Figure 1 below shows two references pointing to the same object after Java passes an object to a method.
Java copies and passes the reference by value, not the object. Thus, method manipulation will alter the objects, since the references point to the original objects. But since the references are copies, swaps will fail. As Figure 2 illustrates, the method references swap, but not the original references. Unfortunately, after a method call, you are left with only the unswapped original references. For a swap to succeed outside of the method call, we need to swap the original references, not the copies.
A: Let me try to explain my understanding with the help of four examples. Java is pass-by-value, and not pass-by-reference
/**
Pass By Value
In Java, all parameters are passed by value, i.e. assigning a method argument is not visible to the caller.
*/
Example 1:
public class PassByValueString {
public static void main(String[] args) {
new PassByValueString().caller();
}
public void caller() {
String value = "Nikhil";
boolean valueflag = false;
String output = method(value, valueflag);
/*
* 'output' is insignificant in this example. we are more interested in
* 'value' and 'valueflag'
*/
System.out.println("output : " + output);
System.out.println("value : " + value);
System.out.println("valueflag : " + valueflag);
}
public String method(String value, boolean valueflag) {
value = "Anand";
valueflag = true;
return "output";
}
}
Result
output : output
value : Nikhil
valueflag : false
Example 2:
/**
*
* Pass By Value
*
*/
public class PassByValueNewString {
public static void main(String[] args) {
new PassByValueNewString().caller();
}
public void caller() {
String value = new String("Nikhil");
boolean valueflag = false;
String output = method(value, valueflag);
/*
* 'output' is insignificant in this example. we are more interested in
* 'value' and 'valueflag'
*/
System.out.println("output : " + output);
System.out.println("value : " + value);
System.out.println("valueflag : " + valueflag);
}
public String method(String value, boolean valueflag) {
value = "Anand";
valueflag = true;
return "output";
}
}
Result
output : output
value : Nikhil
valueflag : false
Example 3:
/**
This 'Pass By Value has a feeling of 'Pass By Reference'
Some people say primitive types and 'String' are 'pass by value'
and objects are 'pass by reference'.
But from this example, we can understand that it is infact pass by value only,
keeping in mind that here we are passing the reference as the value.
ie: reference is passed by value.
That's why are able to change and still it holds true after the local scope.
But we cannot change the actual reference outside the original scope.
what that means is demonstrated by next example of PassByValueObjectCase2.
*/
public class PassByValueObjectCase1 {
private class Student {
int id;
String name;
public Student() {
}
public Student(int id, String name) {
super();
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + "]";
}
}
public static void main(String[] args) {
new PassByValueObjectCase1().caller();
}
public void caller() {
Student student = new Student(10, "Nikhil");
String output = method(student);
/*
* 'output' is insignificant in this example. we are more interested in
* 'student'
*/
System.out.println("output : " + output);
System.out.println("student : " + student);
}
public String method(Student student) {
student.setName("Anand");
return "output";
}
}
Result
output : output
student : Student [id=10, name=Anand]
Example 4:
/**
In addition to what was mentioned in Example3 (PassByValueObjectCase1.java), we cannot change the actual reference outside the original scope."
Note: I am not pasting the code for private class Student. The class definition for Student is same as Example3.
*/
public class PassByValueObjectCase2 {
public static void main(String[] args) {
new PassByValueObjectCase2().caller();
}
public void caller() {
// student has the actual reference to a Student object created
// can we change this actual reference outside the local scope? Let's see
Student student = new Student(10, "Nikhil");
String output = method(student);
/*
* 'output' is insignificant in this example. we are more interested in
* 'student'
*/
System.out.println("output : " + output);
System.out.println("student : " + student); // Will it print Nikhil or Anand?
}
public String method(Student student) {
student = new Student(20, "Anand");
return "output";
}
}
Result
output : output
student : Student [id=10, name=Nikhil]
A: I thought I'd contribute this answer to add more details from the Specifications.
First, What's the difference between passing by reference vs. passing by value?
Passing by reference means the called functions' parameter will be the
same as the callers' passed argument (not the value, but the identity
*
*the variable itself).
Pass by value means the called functions' parameter will be a copy of
the callers' passed argument.
Or from wikipedia, on the subject of pass-by-reference
In call-by-reference evaluation (also referred to as
pass-by-reference), a function receives an implicit reference to a
variable used as argument, rather than a copy of its value. This
typically means that the function can modify (i.e. assign to) the
variable used as argument—something that will be seen by its caller.
And on the subject of pass-by-value
In call-by-value, the argument expression is evaluated, and the
resulting value is bound to the corresponding variable in the function [...].
If the function or procedure is able to assign values to its
parameters, only its local copy is assigned [...].
Second, we need to know what Java uses in its method invocations. The Java Language Specification states
When the method or constructor is invoked (§15.12), the values of the
actual argument expressions initialize newly created parameter
variables, each of the declared type, before execution of the body of
the method or constructor.
So it assigns (or binds) the value of the argument to the corresponding parameter variable.
What is the value of the argument?
Let's consider reference types, the Java Virtual Machine Specification states
There are three kinds of reference types: class types, array types,
and interface types. Their values are references to dynamically
created class instances, arrays, or class instances or arrays that
implement interfaces, respectively.
The Java Language Specification also states
The reference values (often just references) are pointers to these objects, and a special null reference, which refers to no object.
The value of an argument (of some reference type) is a pointer to an object. Note that a variable, an invocation of a method with a reference type return type, and an instance creation expression (new ...) all resolve to a reference type value.
So
public void method (String param) {}
...
String variable = new String("ref");
method(variable);
method(variable.toString());
method(new String("ref"));
all bind the value of a reference to a String instance to the method's newly created parameter, param. This is exactly what the definition of pass-by-value describes. As such, Java is pass-by-value.
The fact that you can follow the reference to invoke a method or access a field of the referenced object is completely irrelevant to the conversation. The definition of pass-by-reference was
This typically means that the function can modify (i.e. assign to) the
variable used as argument—something that will be seen by its caller.
In Java, modifying the variable means reassigning it. In Java, if you reassigned the variable within the method, it would go unnoticed to the caller. Modifying the object referenced by the variable is a different concept entirely.
Primitive values are also defined in the Java Virtual Machine Specification, here. The value of the type is the corresponding integral or floating point value, encoded appropriately (8, 16, 32, 64, etc. bits).
A: You can never pass by reference in Java, and one of the ways that is obvious is when you want to return more than one value from a method call. Consider the following bit of code in C++:
void getValues(int& arg1, int& arg2) {
arg1 = 1;
arg2 = 2;
}
void caller() {
int x;
int y;
getValues(x, y);
cout << "Result: " << x << " " << y << endl;
}
Sometimes you want to use the same pattern in Java, but you can't; at least not directly. Instead you could do something like this:
void getValues(int[] arg1, int[] arg2) {
arg1[0] = 1;
arg2[0] = 2;
}
void caller() {
int[] x = new int[1];
int[] y = new int[1];
getValues(x, y);
System.out.println("Result: " + x[0] + " " + y[0]);
}
As was explained in previous answers, in Java you're passing a pointer to the array as a value into getValues. That is enough, because the method then modifies the array element, and by convention you're expecting element 0 to contain the return value. Obviously you can do this in other ways, such as structuring your code so this isn't necessary, or constructing a class that can contain the return value or allow it to be set. But the simple pattern available to you in C++ above is not available in Java.
A: The bottom line on pass-by-value: the called method can't change the caller's
variable, although for object reference variables, the called method can change the
object the variable referred to. What's the difference between changing the variable
and changing the object? For object references, it means the called method can't
reassign the caller's original reference variable and make it refer to a different object,
or null.
I took this code and explanation from a book on Java Certification and made some minor changes.
I think it's a
good illustration to the pass by value of an object. In the code below,
reassigning g does not reassign f! At the end of the bar() method, two Foo objects
have been created, one referenced by the local variable f and one referenced by
the local (argument) variable g.
Because the doStuff() method has a copy of the reference variable, it has a way to get
to the original Foo object, for instance to call
the setName() method. But, the doStuff() method does not have a way to get to
the f reference variable. So doStuff() can change values within the object f refers
to, but doStuff() can't change the actual contents (bit pattern) of f. In other
words, doStuff() can change the state of the object that f refers to, but it can't
make f refer to a different object!
package test.abc;
public class TestObject {
/**
* @param args
*/
public static void main(String[] args) {
bar();
}
static void bar() {
Foo f = new Foo();
System.out.println("Object reference for f: " + f);
f.setName("James");
doStuff(f);
System.out.println(f.getName());
//Can change the state of an object variable in f, but can't change the object reference for f.
//You still have 2 foo objects.
System.out.println("Object reference for f: " + f);
}
static void doStuff(Foo g) {
g.setName("Boo");
g = new Foo();
System.out.println("Object reference for g: " + g);
}
}
package test.abc;
public class Foo {
public String name = "";
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Note that the object reference has not changed in the console output below:
Console output:
Object reference for f: test.abc.Foo@62f72617
Object reference for g: test.abc.Foo@4fe5e2c3
Boo
Object reference for f: test.abc.Foo@62f72617
A: Java passes references to objects by value.
So if any modification is done to the Object to which the reference argument points it will be reflected back on the original object.
But if the reference argument point to another Object still the original reference will point to original Object.
A: Java passes everything by value!!
//create an object by passing in a name and age:
PersonClass variable1 = new PersonClass("Mary", 32);
PersonClass variable2;
//Both variable2 and variable1 now reference the same object
variable2 = variable1;
PersonClass variable3 = new PersonClass("Andre", 45);
// variable1 now points to variable3
variable1 = variable3;
//WHAT IS OUTPUT BY THIS?
System.out.println(variable2);
System.out.println(variable1);
Mary 32
Andre 45
if you could understand this example we r done.
otherwise, please visit this webPage for detailed explanation:
webPage
A: It seems everything is call by value in java as i have tried to understand by the following program
Class-S
class S{
String name="alam";
public void setName(String n){
this.name=n;
}}
Class-Sample
public class Sample{
public static void main(String args[]){
S s=new S();
S t=new S();
System.out.println(s.name);
System.out.println(t.name);
t.setName("taleev");
System.out.println(t.name);
System.out.println(s.name);
s.setName("Harry");
System.out.println(t.name);
System.out.println(s.name);
}}
Output
alam
alam
taleev
alam
taleev
harry
As we have define class S with instance variable name with value taleev so for
all the objects that we initialize from it will have the name variable with value of taleev but if we change the name's value of any objects then it is changing the name of only that copy of the class(Object) not for every class so after that also when we do System.out.println(s.name) it is printing taleev only we can not change the name's value that we have defined originally, and the value that we are changing is the object's value not the instance variable value so once we have define instance variable we are unable to change it
So i think that is how it shows that java deals with values only not with the references
The memory allocation for the primitive variables can be understood by this
A: First let's understand Memory allocation in Java:
Stack and Heap are part of Memory that JVM allocates for different purposes. The stack memory is pre-allocated to thread, when it is created, therefore, a thread cannot access the Stack of other thread. But Heap is available to all threads in a program.
For a thread, Stack stores all local data, metadata of program, primitive type data and object reference. And, Heap is responsible for storage of actual object.
Book book = new Book("Effective Java");
In the above example, the reference variable is "book" which is stored in stack. The instance created by new operator -> new Book("Effective Java") is stored in Heap. The ref variable "book" has address of the object allocated in Heap. Let's say the address is 1001.
Consider passing a primitive data type i.e. int, float, double etc.
public class PrimitiveTypeExample {
public static void main(string[] args) {
int num = 10;
System.out.println("Value before calling method: " + num);
printNum(num);
System.out.println("Value after calling method: " + num);
}
public static void printNum(int num){
num = num + 10;
System.out.println("Value inside printNum method: " + num);
}
}
Output is:
Value before calling method: 10
Value inside printNum method: 20
Value after calling method: 10
int num =10; -> this allocates the memory for "int" in Stack of the running thread, because, it is a primitive type. Now when printNum(..) is called, a private stack is created within the same thread. When "num" is passed to this method, a copy of "num" is created in the method stack frame.
num = num+10; -> this adds 10 and modifies the the int variable within the method stack frame.
Therefore, the original num outside the method stack frame remains unchanged.
Consider, the example of passing the object of a custom class as an argument.
In the above example, ref variable "book" resides in stack of thread executing the program, and the object of class Book is created in Heap space when program executes new Book(). This memory location in Heap is referred by "book". When "book" is passed as method argument, a copy of "book" is created in private stack frame of method within the same stack of thread. Therefore, the copied reference variable points to the same object of class "Book" in the Heap.
The reference variable within method stack frame sets a new value to same object. Therefore, it is reflected when original ref variable "book" gets its value.
Note that in case of passing reference variable, if it is initialized again in called method, it then points to new memory location and any operation does not affect the previous object in the Heap.
Therefore, when anything is passed as method argument, it is always the Stack entity - either primitive or reference variable. We never pass something that is stored in Heap. Hence, in Java, we always pass the value in the stack, and it is pass by value.
A: For simplicity and verbosity
Its pass reference by value:
public static void main(String[] args) {
Dog aDog = new Dog("Max");
Dog oldDog = aDog;
// we pass the object to foo
foo(aDog);
// aDog variable is still pointing to the "Max" dog when foo(...) returns
aDog.getName().equals("Max"); // true
aDog.getName().equals("Fifi"); // false
aDog == oldDog; // true
}
public static void foo(Dog d) {
d.getName().equals("Max"); // true
// change d inside of foo() to point to a new Dog instance "Fifi"
d = new Dog("Fifi");
d.getName().equals("Fifi"); // true
}
A: The distinction, or perhaps just the way I remember as I used to be under the same impression as the original poster is this: Java is always pass by value. All objects( in Java, anything except for primitives) in Java are references. These references are passed by value.
A: As many people mentioned it before, Java is always pass-by-value
Here is another example that will help you understand the difference (the classic swap example):
public class Test {
public static void main(String[] args) {
Integer a = new Integer(2);
Integer b = new Integer(3);
System.out.println("Before: a = " + a + ", b = " + b);
swap(a,b);
System.out.println("After: a = " + a + ", b = " + b);
}
public static swap(Integer iA, Integer iB) {
Integer tmp = iA;
iA = iB;
iB = tmp;
}
}
Prints:
Before: a = 2, b = 3
After: a = 2, b = 3
This happens because iA and iB are new local reference variables that have the same value of the passed references (they point to a and b respectively). So, trying to change the references of iA or iB will only change in the local scope and not outside of this method.
A: I always think of it as "pass by copy". It is a copy of the value be it primitive or reference. If it is a primitive it is a copy of the bits that are the value and if it is an Object it is a copy of the reference.
public class PassByCopy{
public static void changeName(Dog d){
d.name = "Fido";
}
public static void main(String[] args){
Dog d = new Dog("Maxx");
System.out.println("name= "+ d.name);
changeName(d);
System.out.println("name= "+ d.name);
}
}
class Dog{
public String name;
public Dog(String s){
this.name = s;
}
}
output of java PassByCopy:
name= Maxx
name= Fido
Primitive wrapper classes and Strings are immutable so any example using those types will not work the same as other types/objects.
A: I'd say it in another way:
In java references are passed (but not objects) and these references are passed-by-value (the reference itself is copied and you have 2 references as a result and you have no control under the 1st reference in the method).
Just saying: pass-by-value might be not clear enough for beginners. For instance in Python the same situation but there are articles, which describe that they call it pass-by-reference, only cause references are used.
A: Here a more precise definition:
*
*Pass/call by value: Formal parameter is like a local variable in
scope of function, it evaluates to actual parameter at the moment of
function call.
*Pass/call by reference: Formal parameter is just a alias for the real
value, any change of it in the scope of function can have side
effects outside in any other part of code.
So in C/C++ you can create a function that swaps two values passed using the references:
void swap(int& a, int& b)
{
int tmp = a;
a = b;
b = tmp;
}
You can see it has a unique reference to a and b, so we do not have a copy, tmp just hold unique references.
The same function in java does not have side effects, the parameter passing is just like the code above without references.
Although java work with pointers/references, the parameters are not unique pointers, in each attribution, they are copied instead just assigned like C/C++
A: Java passes references by value.
So you can't change the reference that gets passed in.
A: Java has only pass by value. A very simple example to validate this.
public void test() {
MyClass obj = null;
init(obj);
//After calling init method, obj still points to null
//this is because obj is passed as value and not as reference.
}
private void init(MyClass objVar) {
objVar = new MyClass();
}
A: Unlike some other languages, Java does not allow you to choose between pass-by-value and pass-by-reference—all arguments are passed by value. A method call can pass two types of values to a method—copies of primitive values (e.g., values of int and double) and copies of references to objects.
When a method modifies a primitive-type parameter, changes to the parameter have no effect on the original argument value in the calling method.
When it comes to objects, objects themselves cannot be passed to methods. So we pass the reference(address) of the object. We can manipulate the original object using this reference.
How Java creates and stores objects: When we create an object we store the object’s address in a reference variable. Let's analyze the following statement.
Account account1 = new Account();
“Account account1” is the type and name of the reference variable, “=” is the assignment operator, “new” asks for the required amount of space from the system. The constructor to the right of keyword new which creates the object is called implicitly by the keyword new. Address of the created object(result of right value, which is an expression called "class instance creation expression") is assigned to the left value (which is a reference variable with a name and a type specified) using the assign operator.
Although an object’s reference is passed by value, a method can still interact with the referenced object by calling its public methods using the copy of the object’s reference. Since the reference stored in the parameter is a copy of the reference that was passed as an argument, the parameter in the called method and the argument in the calling method refer to the same object in memory.
Passing references to arrays, instead of the array objects themselves, makes sense for performance reasons. Because everything in Java is passed by value, if array objects were passed,
a copy of each element would be passed. For large arrays, this would waste time and consume
considerable storage for the copies of the elements.
In the image below you can see we have two reference variables(These are called pointers in C/C++, and I think that term makes it easier to understand this feature.) in the main method. Primitive and reference variables are kept in stack memory(left side in images below). array1 and array2 reference variables "point" (as C/C++ programmers call it) or reference to a and b arrays respectively, which are objects (values these reference variables hold are addresses of objects) in heap memory (right side in images below).
If we pass the value of array1 reference variable as an argument to the reverseArray method, a reference variable is created in the method and that reference variable starts pointing to the same array (a).
public class Test
{
public static void reverseArray(int[] array1)
{
// ...
}
public static void main(String[] args)
{
int[] array1 = { 1, 10, -7 };
int[] array2 = { 5, -190, 0 };
reverseArray(array1);
}
}
So, if we say
array1[0] = 5;
in reverseArray method, it will make a change in array a.
We have another reference variable in reverseArray method (array2) that points to an array c. If we were to say
array1 = array2;
in reverseArray method, then the reference variable array1 in method reverseArray would stop pointing to array a and start pointing to array c (Dotted line in second image).
If we return value of reference variable array2 as the return value of method reverseArray and assign this value to reference variable array1 in main method, array1 in main will start pointing to array c.
So let's write all the things we have done at once now.
public class Test
{
public static int[] reverseArray(int[] array1)
{
int[] array2 = { -7, 0, -1 };
array1[0] = 5; // array a becomes 5, 10, -7
array1 = array2; /* array1 of reverseArray starts
pointing to c instead of a (not shown in image below) */
return array2;
}
public static void main(String[] args)
{
int[] array1 = { 1, 10, -7 };
int[] array2 = { 5, -190, 0 };
array1 = reverseArray(array1); /* array1 of
main starts pointing to c instead of a */
}
}
And now that reverseArray method is over, its reference variables(array1 and array2) are gone. Which means we now only have the two reference variables in main method array1 and array2 which point to c and b arrays respectively. No reference variable is pointing to object (array) a. So it is eligible for garbage collection.
You could also assign value of array2 in main to array1. array1 would start pointing to b.
A: I just noticed you referenced my article.
The Java Spec says that everything in Java is pass-by-value. There is no such thing as "pass-by-reference" in Java.
The key to understanding this is that something like
Dog myDog;
is not a Dog; it's actually a pointer to a Dog. The use of the term "reference" in Java is very misleading and is what causes most of the confusion here. What they call "references" act/feel more like what we'd call "pointers" in most other languages.
What that means, is when you have
Dog myDog = new Dog("Rover");
foo(myDog);
you're essentially passing the address of the created Dog object to the foo method.
(I say essentially because Java pointers/references aren't direct addresses, but it's easiest to think of them that way.)
Suppose the Dog object resides at memory address 42. This means we pass 42 to the method.
if the Method were defined as
public void foo(Dog someDog) {
someDog.setName("Max"); // AAA
someDog = new Dog("Fifi"); // BBB
someDog.setName("Rowlf"); // CCC
}
let's look at what's happening.
*
*the parameter someDog is set to the value 42
*at line "AAA"
*
*someDog is followed to the Dog it points to (the Dog object at address 42)
*that Dog (the one at address 42) is asked to change his name to Max
*at line "BBB"
*
*a new Dog is created. Let's say he's at address 74
*we assign the parameter someDog to 74
*at line "CCC"
*
*someDog is followed to the Dog it points to (the Dog object at address 74)
*that Dog (the one at address 74) is asked to change his name to Rowlf
*then, we return
Now let's think about what happens outside the method:
Did myDog change?
There's the key.
Keeping in mind that myDog is a pointer, and not an actual Dog, the answer is NO. myDog still has the value 42; it's still pointing to the original Dog (but note that because of line "AAA", its name is now "Max" - still the same Dog; myDog's value has not changed.)
It's perfectly valid to follow an address and change what's at the end of it; that does not change the variable, however.
Java works exactly like C. You can assign a pointer, pass the pointer to a method, follow the pointer in the method and change the data that was pointed to. However, the caller will not see any changes you make to where that pointer points. (In a language with pass-by-reference semantics, the method function can change the pointer and the caller will see that change.)
In C++, Ada, Pascal and other languages that support pass-by-reference, you can actually change the variable that was passed.
If Java had pass-by-reference semantics, the foo method we defined above would have changed where myDog was pointing when it assigned someDog on line BBB.
Think of reference parameters as being aliases for the variable passed in. When that alias is assigned, so is the variable that was passed in.
Update
A discussion in the comments warrants some clarification...
In C, you can write
void swap(int *x, int *y) {
int t = *x;
*x = *y;
*y = t;
}
int x = 1;
int y = 2;
swap(&x, &y);
This is not a special case in C. Both languages use pass-by-value semantics. Here the call site is creating additional data structure to assist the function to access and manipulate data.
The function is being passed pointers to data, and follows those pointers to access and modify that data.
A similar approach in Java, where the caller sets up assisting structure, might be:
void swap(int[] x, int[] y) {
int temp = x[0];
x[0] = y[0];
y[0] = temp;
}
int[] x = {1};
int[] y = {2};
swap(x, y);
(or if you wanted both examples to demonstrate features the other language doesn't have, create a mutable IntWrapper class to use in place of the arrays)
In these cases, both C and Java are simulating pass-by-reference. They're still both passing values (pointers to ints or arrays), and following those pointers inside the called function to manipulate the data.
Pass-by-reference is all about the function declaration/definition, and how it handles its parameters. Reference semantics apply to every call to that function, and the call site only needs to pass variables, no additional data structure.
These simulations require the call site and the function to cooperate. No doubt it's useful, but it's still pass-by-value.
A: To make a long story short, Java objects have some very peculiar properties.
In general, Java has primitive types (int, bool, char, double, etc) that are passed directly by value. Then Java has objects (everything that derives from java.lang.Object). Objects are actually always handled through a reference (a reference being a pointer that you can't touch). That means that in effect, objects are passed by reference, as the references are normally not interesting. It does however mean that you cannot change which object is pointed to as the reference itself is passed by value.
Does this sound strange and confusing? Let's consider how C implements pass by reference and pass by value. In C, the default convention is pass by value. void foo(int x) passes an int by value. void foo(int *x) is a function that does not want an int a, but a pointer to an int: foo(&a). One would use this with the & operator to pass a variable address.
Take this to C++, and we have references. References are basically (in this context) syntactic sugar that hide the pointer part of the equation: void foo(int &x) is called by foo(a), where the compiler itself knows that it is a reference and the address of the non-reference a should be passed. In Java, all variables referring to objects are actually of reference type, in effect forcing call by reference for most intends and purposes without the fine grained control (and complexity) afforded by, for example, C++.
A: I have created a thread devoted to these kind of questions for any programming languages here.
Java is also mentioned. Here is the short summary:
*
*Java passes it parameters by value
*"by value" is the only way in java to pass a parameter to a method
*using methods from the object given as parameter will alter the
object as the references point to
the original objects. (if that
method itself alters some values)
A: A few corrections to some posts.
C does NOT support pass by reference. It is ALWAYS pass by value. C++ does support pass by reference, but is not the default and is quite dangerous.
It doesn't matter what the value is in Java: primitive or address(roughly) of object, it is ALWAYS passed by value.
If a Java object "behaves" like it is being passed by reference, that is a property of mutability and has absolutely nothing to do with passing mechanisms.
I am not sure why this is so confusing, perhaps because so many Java "programmers" are not formally trained, and thus do not understand what is really going on in memory?
A: Java passes parameters by value, There is no option of passing a reference in Java.
But at the complier binding level layer, It uses reference internally not exposed to the user.
It is essential as it saves a lot of memory and improves speed.
A: public class Test {
static class Dog {
String name;
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Dog other = (Dog) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
public String getName() {
return name;
}
public void setName(String nb) {
this.name = nb;
}
Dog(String sd) {
this.name = sd;
}
}
/**
*
* @param args
*/
public static void main(String[] args) {
Dog aDog = new Dog("Max");
// we pass the object to foo
foo(aDog);
Dog oldDog = aDog;
System.out.println(" 1: " + aDog.getName().equals("Max")); // false
System.out.println(" 2 " + aDog.getName().equals("huahua")); // false
System.out.println(" 3 " + aDog.getName().equals("moron")); // true
System.out.println(" 4 " + " " + (aDog == oldDog)); // true
// part2
Dog aDog1 = new Dog("Max");
foo(aDog1, 5);
Dog oldDog1 = aDog;
System.out.println(" 5 : " + aDog1.getName().equals("huahua")); // true
System.out.println(" part2 : " + (aDog1 == oldDog1)); // false
Dog oldDog2 = foo(aDog1, 5, 6);
System.out.println(" 6 " + (aDog1 == oldDog2)); // true
System.out.println(" 7 " + (aDog1 == oldDog)); // false
System.out.println(" 8 " + (aDog == oldDog2)); // false
}
/**
*
* @param d
*/
public static void foo(Dog d) {
System.out.println(d.getName().equals("Max")); // true
d.setName("moron");
d = new Dog("huahua");
System.out.println(" -:- " + d.getName().equals("huahua")); // true
}
/**
*
* @param d
* @param a
*/
public static void foo(Dog d, int a) {
d.getName().equals("Max"); // true
d.setName("huahua");
}
/**
*
* @param d
* @param a
* @param b
* @return
*/
public static Dog foo(Dog d, int a, int b) {
d.getName().equals("Max"); // true
d.setName("huahua");
return d;
}
}
The sample code to demonstrate the impact of changes to the object at different functions .
A: I think this simple explanation might help you understand as I wanted to understand this same thing when I was struggling through this.
When you pass a primitive data to a function call it's content is being copied to the function's argument and when you pass an object it's reference is being copied to the function's argument. Speaking of object, you can't change the copied reference-the argument variable is referencing to in the calling function.
Consider this simple example, String is an object in java and when you change the content of a string the reference variable will now point to some new reference as String objects are immutable in java.
String name="Mehrose"; // name referencing to 100
ChangeContenet(String name){
name="Michael"; // refernce has changed to 1001
}
System.out.print(name); //displays Mehrose
Fairly simple because as I mentioned you are not allowed to change the copied reference in the calling function. But the problem is with the array when you pass an array of String/Object. Let us see.
String names[]={"Mehrose","Michael"};
changeContent(String[] names){
names[0]="Rose";
names[1]="Janet"
}
System.out.println(Arrays.toString(names)); //displays [Rose,Janet]
As we said that we can't change the copied reference in the function call and we also have seen in the case of a single String object. The reason is names[] variable referencing to let's say 200 and names[0] referencing to 205 and so on. You see we didn't change the names[] reference it still points to the old same reference still after the function call but now names[0] and names[1] reference has been changed. We Still stand on our definition that we can't change the reference variable's reference so we didn't.
The same thing happens when you pass a Student object to a method and you are still able to change the Student name or other attributes, the point is we are not changing the actual Student object rather we are changing the contents of it
You can't do this
Student student1= new Student("Mehrose");
changeContent(Student Obj){
obj= new Student("Michael") //invalid
obj.setName("Michael") //valid
}
A: Java uses pass-by-value, but the effects differ whether you are using primitive or a reference type.
When you pass a primitive type as an argument to a method, it's getting a copy of the primitive and any changes inside the block of the method won't change the original variable.
When you pass a reference type as an argument to a method, it's still getting a copy but it's a copy of the reference to the object (in other words, you are getting a copy of the memory address in the heap where the object is located), so any changes in the object inside the block of the method will affect the original object outside the block.
A: I feel like arguing about "pass-by-reference vs pass-by-value" is not super-helpful.
If you say, "Java is pass-by-whatever (reference/value)", in either case, you're not provide a complete answer. Here's some additional information that will hopefully aid in understanding what's happening in memory.
Crash course on stack/heap before we get to the Java implementation:
Values go on and off the stack in a nice orderly fashion, like a stack of plates at a cafeteria.
Memory in the heap (also known as dynamic memory) is haphazard and disorganized. The JVM just finds space wherever it can, and frees it up as the variables that use it are no longer needed.
Okay. First off, local primitives go on the stack. So this code:
int x = 3;
float y = 101.1f;
boolean amIAwesome = true;
results in this:
When you declare and instantiate an object. The actual object goes on the heap. What goes on the stack? The address of the object on the heap. C++ programmers would call this a pointer, but some Java developers are against the word "pointer". Whatever. Just know that the address of the object goes on the stack.
Like so:
int problems = 99;
String name = "Jay-Z";
An array is an object, so it goes on the heap as well. And what about the objects in the array? They get their own heap space, and the address of each object goes inside the array.
JButton[] marxBros = new JButton[3];
marxBros[0] = new JButton("Groucho");
marxBros[1] = new JButton("Zeppo");
marxBros[2] = new JButton("Harpo");
So, what gets passed in when you call a method? If you pass in an object, what you're actually passing in is the address of the object. Some might say the "value" of the address, and some say it's just a reference to the object. This is the genesis of the holy war between "reference" and "value" proponents. What you call it isn't as important as that you understand that what's getting passed in is the address to the object.
private static void shout(String name){
System.out.println("There goes " + name + "!");
}
public static void main(String[] args){
String hisName = "John J. Jingleheimerschmitz";
String myName = hisName;
shout(myName);
}
One String gets created and space for it is allocated in the heap, and the address to the string is stored on the stack and given the identifier hisName, since the address of the second String is the same as the first, no new String is created and no new heap space is allocated, but a new identifier is created on the stack. Then we call shout(): a new stack frame is created and a new identifier, name is created and assigned the address of the already-existing String.
So, value, reference? You say "potato".
A: One of the biggest confusion in Java programming language is whether Java is Pass by Value or Pass by Reference.
First of all, we should understand what is meant by pass by value or pass by reference.
Pass by Value: The method parameter values are copied to another variable and then the copied object is passed, that’s why it’s called pass by value.
Pass by Reference: An alias or reference to the actual parameter is passed to the method, that’s why it’s called pass by reference.
Let’s say we have a class Balloon like below.
public class Balloon {
private String color;
public Balloon(){}
public Balloon(String c){
this.color=c;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}
And we have a simple program with a generic method to swap two objects, the class looks like below.
public class Test {
public static void main(String[] args) {
Balloon red = new Balloon("Red"); //memory reference 50
Balloon blue = new Balloon("Blue"); //memory reference 100
swap(red, blue);
System.out.println("red color="+red.getColor());
System.out.println("blue color="+blue.getColor());
foo(blue);
System.out.println("blue color="+blue.getColor());
}
private static void foo(Balloon balloon) { //baloon=100
balloon.setColor("Red"); //baloon=100
balloon = new Balloon("Green"); //baloon=200
balloon.setColor("Blue"); //baloon = 200
}
//Generic swap method
public static void swap(Object o1, Object o2){
Object temp = o1;
o1=o2;
o2=temp;
}
}
When we execute the above program, we get following output.
red color=Red
blue color=Blue
blue color=Red
If you look at the first two lines of the output, it’s clear that swap method didn’t work. This is because Java is passed by value, this swap() method test can be used with any programming language to check whether it’s pass by value or pass by reference.
Let’s analyze the program execution step by step.
Balloon red = new Balloon("Red");
Balloon blue = new Balloon("Blue");
When we use the new operator to create an instance of a class, the instance is created and the variable contains the reference location of the memory where the object is saved. For our example, let’s assume that “red” is pointing to 50 and “blue” is pointing to 100 and these are the memory location of both Balloon objects.
Now when we are calling swap() method, two new variables o1 and o2 are created pointing to 50 and 100 respectively.
So below code snippet explains what happened in the swap() method execution.
public static void swap(Object o1, Object o2){ //o1=50, o2=100
Object temp = o1; //temp=50, o1=50, o2=100
o1=o2; //temp=50, o1=100, o2=100
o2=temp; //temp=50, o1=100, o2=50
} //method terminated
Notice that we are changing values of o1 and o2 but they are copies of “red” and “blue” reference locations, so actually, there is no change in the values of “red” and “blue” and hence the output.
If you have understood this far, you can easily understand the cause of confusion. Since the variables are just the reference to the objects, we get confused that we are passing the reference so Java is passed by reference. However, we are passing a copy of the reference and hence it’s pass by value. I hope it clears all the doubts now.
Now let’s analyze foo() method execution.
private static void foo(Balloon balloon) { //baloon=100
balloon.setColor("Red"); //baloon=100
balloon = new Balloon("Green"); //baloon=200
balloon.setColor("Blue"); //baloon = 200
}
The first line is the important one when we call a method the method is called on the Object at the reference location. At this point, the balloon is pointing to 100 and hence it’s color is changed to Red.
In the next line, balloon reference is changed to 200 and any further methods executed are happening on the object at memory location 200 and not having any effect on the object at memory location 100. This explains the third line of our program output printing blue color=Red.
I hope above explanation clear all the doubts, just remember that variables are references or pointers and its copy is passed to the methods, so Java is always passed by value. It would be more clear when you will learn about Heap and Stack memory and where different objects and references are stored.
A: Java passes parameters by VALUE, and by value ONLY.
To cut long story short:
For those coming from C#: THERE IS NO "out" parameter.
For those coming from PASCAL: THERE IS NO "var" parameter.
It means you can't change the reference from the object itself, but you can always change the object's properties.
A workaround is to use StringBuilder parameter instead String. And you can always use arrays!
A: This is the best way to answer the question imo...
First, we must understand that, in Java, the parameter passing behavior...
public void foo(Object param)
{
// some code in foo...
}
public void bar()
{
Object obj = new Object();
foo(obj);
}
is exactly the same as...
public void bar()
{
Object obj = new Object();
Object param = obj;
// some code in foo...
}
not considering stack locations, which aren't relevant in this discussion.
So, in fact, what we're looking for in Java is how variable assignment works. I found it in the docs :
One of the most common operators that you'll encounter is the simple assignment operator "=" [...] it assigns the value on its right to the operand on its left:
int cadence = 0;
int speed = 0;
int gear = 1;
This operator can also be used on objects to assign object references [...]
It's clear how this operator acts in two distinct ways: assign values and assign references. The last, when it's an object... the first, when it isn't an object, that is, when it's a primitive. But so, can we understand that Java's function params can be pass-by-value and pass-by-reference?
The truth is in the code. Let's try it:
public class AssignmentEvaluation
{
static public class MyInteger
{
public int value = 0;
}
static public void main(String[] args)
{
System.out.println("Assignment operator evaluation using two MyInteger objects named height and width\n");
MyInteger height = new MyInteger();
MyInteger width = new MyInteger();
System.out.println("[1] Assign distinct integers to height and width values");
height.value = 9;
width.value = 1;
System.out.println("-> height is " + height.value + " and width is " + width.value + ", we are different things! \n");
System.out.println("[2] Assign to height's value the width's value");
height.value = width.value;
System.out.println("-> height is " + height.value + " and width is " + width.value + ", are we the same thing now? \n");
System.out.println("[3] Assign to height's value an integer other than width's value");
height.value = 9;
System.out.println("-> height is " + height.value + " and width is " + width.value + ", we are different things yet! \n");
System.out.println("[4] Assign to height the width object");
height = width;
System.out.println("-> height is " + height.value + " and width is " + width.value + ", are we the same thing now? \n");
System.out.println("[5] Assign to height's value an integer other than width's value");
height.value = 9;
System.out.println("-> height is " + height.value + " and width is " + width.value + ", we are the same thing now! \n");
System.out.println("[6] Assign to height a new MyInteger and an integer other than width's value");
height = new MyInteger();
height.value = 1;
System.out.println("-> height is " + height.value + " and width is " + width.value + ", we are different things again! \n");
}
}
This is the output of my run:
Assignment operator evaluation using two MyInteger objects named height and width
[1] Assign distinct integers to height and width values
-> height is 9 and width is 1, we are different things!
[2] Assign to height's value the width's value
-> height is 1 and width is 1, are we the same thing now?
[3] Assign to height's value an integer other than width's value
-> height is 9 and width is 1, we are different things yet!
[4] Assign to height the width object
-> height is 1 and width is 1, are we the same thing now?
[5] Assign to height's value an integer other than width's value
-> height is 9 and width is 9, we are the same thing now!
[6] Assign to height a new MyInteger and an integer other than width's value
-> height is 1 and width is 9, we are different things again!
In [2] we have distinct objects and assign one variable's value to the other. But after assigning a new value in [3] the objects had different values, which means that in [2] the assigned value was a copy of the primitive variable, usually called pass-by-value, otherwise, the values printed in [3] should be the same.
In [4] we still have distinct objects and assign one object to the other. And after assigning a new value in [5] the objects had the same values, which means that in [4] the assigned object was not a copy of the other, which should be called pass-by-reference. But, if we look carefully in [6], we can't be so sure that no copy was done... ?????
We can't be so sure because in [6] the objects were the same, then we assigned a new object to one of them, and after, the objects had different values! How can they be distinct now if they were the same? They should be the same here too! ?????
We'll need to remember the docs to understand what's going on:
This operator can also be used on objects to assign object references
So our two variables were storing references... our variables had the same reference after [4] and different references after [6]... if such a thing is possible, this means that assignment of objects is done by copy of the object's reference, otherwise, if it was not a copy of reference, the printed value of the variables in [6] should be the same. So objects (references), just like primitives, are copied to variables through assignment, what people usually call pass-by-value. That's the only pass-by- in Java.
A: Basically, reassigning Object parameters doesn't affect the argument, e.g.,
private static void foo(Object bar) {
bar = null;
}
public static void main(String[] args) {
String baz = "Hah!";
foo(baz);
System.out.println(baz);
}
will print out "Hah!" instead of null. The reason this works is because bar is a copy of the value of baz, which is just a reference to "Hah!". If it were the actual reference itself, then foo would have redefined baz to null.
A: Java copies the reference by value. So if you change it to something else (e.g, using new) the reference does not change outside the method. For native types, it is always pass by value.
A: Just to show the contrast, compare the following C++ and Java snippets:
In C++: Note: Bad code - memory leaks! But it demonstrates the point.
void cppMethod(int val, int &ref, Dog obj, Dog &objRef, Dog *objPtr, Dog *&objPtrRef)
{
val = 7; // Modifies the copy
ref = 7; // Modifies the original variable
obj.SetName("obj"); // Modifies the copy of Dog passed
objRef.SetName("objRef"); // Modifies the original Dog passed
objPtr->SetName("objPtr"); // Modifies the original Dog pointed to
// by the copy of the pointer passed.
objPtr = new Dog("newObjPtr"); // Modifies the copy of the pointer,
// leaving the original object alone.
objPtrRef->SetName("objRefPtr"); // Modifies the original Dog pointed to
// by the original pointer passed.
objPtrRef = new Dog("newObjPtrRef"); // Modifies the original pointer passed
}
int main()
{
int a = 0;
int b = 0;
Dog d0 = Dog("d0");
Dog d1 = Dog("d1");
Dog *d2 = new Dog("d2");
Dog *d3 = new Dog("d3");
cppMethod(a, b, d0, d1, d2, d3);
// a is still set to 0
// b is now set to 7
// d0 still have name "d0"
// d1 now has name "objRef"
// d2 now has name "objPtr"
// d3 now has name "newObjPtrRef"
}
In Java,
public static void javaMethod(int val, Dog objPtr)
{
val = 7; // Modifies the copy
objPtr.SetName("objPtr") // Modifies the original Dog pointed to
// by the copy of the pointer passed.
objPtr = new Dog("newObjPtr"); // Modifies the copy of the pointer,
// leaving the original object alone.
}
public static void main()
{
int a = 0;
Dog d0 = new Dog("d0");
javaMethod(a, d0);
// a is still set to 0
// d0 now has name "objPtr"
}
Java only has the two types of passing: by value for built-in types, and by value of the pointer for object types.
A: Java passes references to objects by value.
A: It's really quite, quite simple:
For a variable of primitive type (eg. int, boolean, char, etc...), when you use its name for a method argument, you are passing the value contained in it (5, true, or 'c'). This value gets "copied", and the variable retains its value even after the method invocation.
For a variable of reference type (eg. String, Object, etc...), when you use its name for a method argument, you are passing the value contained in it (the reference value that "points" to the object). This reference value gets "copied", and the variable retains its value even after the method invocation. The reference variable keeps "pointing" to the same object.
Either way, you're always passing stuff by value.
Compare this to say C++ where you can have a method to take an int&, or in C# where you could have take a ref int (although, in this case, you also have to use the ref modifier when passing the variable's name to the method.)
A: Throughout all the answers we see that Java pass-by-value or rather as @Gevorg
wrote: "pass-by-copy-of-the-variable-value" and this is the idea that we should have in mind all the time.
I am focusing on examples that helped me understand the idea and it is rather addendum to previous answers.
From [1] In Java you always are passing arguments by copy; that is you're always creating a new instance of the value inside the function. But there are certain behaviors that can make you think you're passing by reference.
*
*Passing by copy: When a variable is passed to a method/function, a copy is made (sometimes we hear that when you pass primitives, you're making copies).
*Passing by reference: When a variable is passed to a method/function, the code in the method/function operates on the original variable (You're still passing by copy, but references to values inside the complex object are parts of both versions of the variable, both the original and the version inside the function. The complex objects themselves are being copied, but the internal references are being retained)
Examples of Passing by copy/ by value
Example from [ref 1]
void incrementValue(int inFunction){
inFunction ++;
System.out.println("In function: " + inFunction);
}
int original = 10;
System.out.print("Original before: " + original);
incrementValue(original);
System.out.println("Original after: " + original);
We see in the console:
> Original before: 10
> In Function: 11
> Original after: 10 (NO CHANGE)
Example from [ref 2]
shows nicely the mechanism
watch max 5 min
(Passing by reference) pass-by-copy-of-the-variable-value
Example from [ref 1]
(remember that an array is an object)
void incrementValu(int[] inFuncion){
inFunction[0]++;
System.out.println("In Function: " + inFunction[0]);
}
int[] arOriginal = {10, 20, 30};
System.out.println("Original before: " + arOriginal[0]);
incrementValue(arOriginal[]);
System.out.println("Original before: " + arOriginal[0]);
We see in the console:
>Original before: 10
>In Function: 11
>Original before: 11 (CHANGE)
The complex objects themselves are being copied, but the internal references are being retained.
Example from[ref 3]
package com.pritesh.programs;
class Rectangle {
int length;
int width;
Rectangle(int l, int b) {
length = l;
width = b;
}
void area(Rectangle r1) {
int areaOfRectangle = r1.length * r1.width;
System.out.println("Area of Rectangle : "
+ areaOfRectangle);
}
}
class RectangleDemo {
public static void main(String args[]) {
Rectangle r1 = new Rectangle(10, 20);
r1.area(r1);
}
}
The area of the rectangle is 200 and the length=10 and width=20
Last thing I would like to share was this moment of the lecture:
Memory Allocation
which I found very helpful in understanding the Java passing by value or rather “pass-by-copy-of-the-variable-value” as @Gevorg has written.
*
*REF 1 Lynda.com
*REF 2 Professor Mehran Sahami
*
*watch max 5 min
*Memory Allocation
*REF 3 c4learn
*
*passing-object-as-parameter-to-method
A: Java always passes arguments by value, NOT by reference.
Let me explain this through an example:
public class Main {
public static void main(String[] args) {
Foo f = new Foo("f");
changeReference(f); // It won't change the reference!
modifyReference(f); // It will modify the object that the reference variable "f" refers to!
}
public static void changeReference(Foo a) {
Foo b = new Foo("b");
a = b;
}
public static void modifyReference(Foo c) {
c.setAttribute("c");
}
}
I will explain this in steps:
*
*Declaring a reference named f of type Foo and assign it a new object of type Foo with an attribute "f".
Foo f = new Foo("f");
*From the method side, a reference of type Foo with a name a is declared and it's initially assigned null.
public static void changeReference(Foo a)
*As you call the method changeReference, the reference a will be assigned the object which is passed as an argument.
changeReference(f);
*Declaring a reference named b of type Foo and assign it a new object of type Foo with an attribute "b".
Foo b = new Foo("b");
*a = b makes a new assignment to the reference a, not f, of the object whose attribute is "b".
*As you call modifyReference(Foo c) method, a reference c is created and assigned the object with attribute "f".
*c.setAttribute("c"); will change the attribute of the object that reference c points to it, and it's the same object that reference f points to it.
I hope you understand now how passing objects as arguments works in Java :)
A: The Java programming language passes arguments only by value, that is,
you cannot change the argument value in the calling method from within
the called method.
However, when an object instance is passed as an argument to a method,
the value of the argument is not the object itself but a reference to the
object. You can change the contents of the object in the called method but
not the object reference.
To many people, this looks like pass-by-reference, and behaviorally, it has
much in common with pass-by-reference. However, there are two reasons
this is inaccurate.
*
*Firstly, the ability to change the thing passed into a
method only applies to objects, not primitive values.
*Second, the actual
value associated with a variable of object type is the reference to the
object, and not the object itself. This is an important distinction in other
ways, and if clearly understood, is entirely supporting of the point that
the Java programming language passes arguments by value.
The following code example illustrates this point:
1 public class PassTest {
2
3 // Methods to change the current values
4 public static void changeInt(int value) {
5 value = 55;
6 }
7 public static void changeObjectRef(MyDate ref) {
8 ref = new MyDate(1, 1, 2000);
9 }
10 public static void changeObjectAttr(MyDate ref) {
11 ref.setDay(4);
12 }
13
14 public static void main(String args[]) {
15 MyDate date;
16 int val;
17
18 // Assign the int
19 val = 11;
20 // Try to change it
21 changeInt(val);
22 // What is the current value?
23 System.out.println("Int value is: " + val);
24
25 // Assign the date
26 date = new MyDate(22, 7, 1964);
27 // Try to change it
28 changeObjectRef(date);
29 // What is the current value?
30 System.out.println("MyDate: " + date);
31
32 // Now change the day attribute
33 // through the object reference
34 changeObjectAttr(date);
35 // What is the current value?
36 System.out.println("MyDate: " + date);
37 }
38 }
This code outputs the following:
java PassTest
Int value is: 11
MyDate: 22-7-1964
MyDate: 4-7-1964
The MyDate object is not changed by the changeObjectRef method;
however, the changeObjectAttr method changes the day attribute of the
MyDate object.
A: So many long answers. Let me give a simple one:
*
*Java always passes everything by value
*that means also references are passed by value
In short, you can not modify value of any parameter passed, but you can call methods or change attributes of an object reference passed.
A: Java is strictly passed by value
When I say pass by value it means whenever caller has invoked the callee the arguments(ie: the data to be passed to the other function) is copied and placed in the formal parameters (callee's local variables for receiving the input). Java makes data communications from one function to other function only in a pass by value environment.
An important point would be to know that even C language is strictly passed by value only:
ie: Data is copied from caller to the callee and more ever the operation performed by the callee are on the same memory location and
what we pass them is the address of that location that we obtain from (&) operator and the identifier used in the formal parameters are declared to be a pointer variable (*) using which we can get inside the memory location for accessing the data in it.
Hence here the formal parameter is nothing but mere aliases for that location. And any modifications done on that location is visible where ever that scope of the variable (that identifies that location) is alive.
In Java, there is no concept of pointers (ie: there is nothing called a pointer variable), although we can think of reference variable as a pointer technically in java we call it as a handle. The reason why we call the pointer to an address as a handle in java is because a pointer variable is capable of performing not just single dereferencing but multiple dereferencing
for example: int *p; in P means p points to an integer
and int **p; in C means p is pointer to a pointer to an integer
we dont have this facility in Java, so its absolutely correct and technically legitimate to say it as an handle, also there are rules for pointer arithmetic in C. Which allows performing arithmetic operation on pointers with constraints on it.
In C we call such mechanism of passing address and receiving them with pointer variables as pass by reference since we are passing their addresses and receiving them as pointer variable in formal parameter but at the compiler level that address is copied into pointer variable (since data here is address even then its data ) hence we can be 100% sure that C is Strictly passed by value (as we are passing data only)
(and if we pass the data directly in C we call that as pass by value.)
In java when we do the same we do it with the handles; since they are not called pointer variables like in (as discussed above) even though we are passing the references we cannot say its pass by reference since we are not collecting that with a pointer variable in Java.
Hence Java strictly use pass by value mechanism
A: Java is pass by constant reference where a copy of the reference is passed which means that it is basically a pass by value. You might change the contents of the reference if the class is mutable but you cannot change the reference itself. In other words the address can not be changed since it is passed by value but the content that is pointed by the address can be changed. In case of immutable classes, the content of the reference cannot be changed either.
A: Java always uses call by value. That means the method gets copy of all parameter values.
Consider next 3 situations:
1) Trying to change primitive variable
public static void increment(int x) { x++; }
int a = 3;
increment(a);
x will copy value of a and will increment x, a remains the same
2) Trying to change primitive field of an object
public static void increment(Person p) { p.age++; }
Person pers = new Person(20); // age = 20
increment(pers);
p will copy reference value of pers and will increment age field, variables are referencing to the same object so age is changed
3) Trying to change reference value of reference variables
public static void swap(Person p1, Person p2) {
Person temp = p1;
p1 = p2;
p2 = temp;
}
Person pers1 = new Person(10);
Person pers2 = new Person(20);
swap(pers1, pers2);
after calling swap p1, p2 copy reference values from pers1 and pers2, are swapping with values, so pers1 and pers2 remain the same
So. you can change only fields of objects in method passing copy of reference value to this object.
A: Java, for sure, without a doubt, is "pass by value". Also, since Java is (mostly) object-oriented and objects work with references, it's easy to get confused and think of it to be "pass by reference"
Pass by value means you pass the value to the method and if the method changes the passed value, the real entity doesn't change. Pass by reference, on the other hand, means a reference is passed to the method, and if the method changes it, the passed object also changes.
In Java, usually when we pass an object to a method, we basically pass the reference of the object as-a-value because that's how Java works; it works with references and addresses as far as Object in the heap goes.
But to test if it is really pass by value or pass by reference, you can use a primitive type and references:
@Test
public void sampleTest(){
int i = 5;
incrementBy100(i);
System.out.println("passed ==> "+ i);
Integer j = new Integer(5);
incrementBy100(j);
System.out.println("passed ==> "+ j);
}
/**
* @param i
*/
private void incrementBy100(int i) {
i += 100;
System.out.println("incremented = "+ i);
}
The output is:
incremented = 105
passed ==> 5
incremented = 105
passed ==> 5
So in both cases, whatever happens inside the method doesn't change the real Object, because the value of that object was passed, and not a reference to the object itself.
But when you pass a custom object to a method, and the method and changes it, it will change the real object too, because even when you passed the object, you passed it's reference as a value to the method. Let's try another example:
@Test
public void sampleTest2(){
Person person = new Person(24, "John");
System.out.println(person);
alterPerson(person);
System.out.println(person);
}
/**
* @param person
*/
private void alterPerson(Person person) {
person.setAge(45);
Person altered = person;
altered.setName("Tom");
}
private static class Person{
private int age;
private String name;
public Person(int age, String name) {
this.age=age;
this.name =name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Person [age=");
builder.append(age);
builder.append(", name=");
builder.append(name);
builder.append("]");
return builder.toString();
}
}
In this case, the output is:
Person [age=24, name=John]
Person [age=45, name=Tom]
A: I can't believe that nobody mentioned Barbara Liskov yet. When she designed CLU in 1974, she ran into this same terminology problem, and she invented the term call by sharing (also known as call by object-sharing and call by object) for this specific case of "call by value where the value is a reference".
A: The major cornerstone knowledge must be the quoted one,
When an object reference is passed to a method, the reference itself
is passed by use of call-by-value. However, since the value being
passed refers to an object, the copy of that value will still refer to
the same object referred to by its corresponding argument.
Java: A Beginner's Guide, Sixth Edition, Herbert Schildt
A: Data is shared between functions by passing parameters. Now, there are 2 ways of passing parameters:
*
*passed by reference : caller and callee use same variable for parameter.
*passed by value : caller and callee have two independent variables with same value.
Java uses pass by value
*
*When passing primitive data, it copies the value of primitive data type.
*When passing object, it copies the address of object and passes to callee method variable.
Java follows the following rules in storing variables:
*
*Local variables like primitives and object references are created on Stack memory.
*Objects are created on Heap memory.
Example using primitive data type:
public class PassByValuePrimitive {
public static void main(String[] args) {
int i=5;
System.out.println(i); //prints 5
change(i);
System.out.println(i); //prints 5
}
private static void change(int i) {
System.out.println(i); //prints 5
i=10;
System.out.println(i); //prints 10
}
}
Example using object:
public class PassByValueObject {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("prem");
list.add("raj");
new PassByValueObject().change(list);
System.out.println(list); // prints [prem, raj, ram]
}
private void change(List list) {
System.out.println(list.get(0)); // prem
list.add("ram");
list=null;
System.out.println(list.add("bheem")); //gets NullPointerException
}
}
A: I see that all answers contain the same: pass by value. However, a recent Brian Goetz update on project Valhalla actually answers it differently:
Indeed, it is a common “gotcha” question about whether Java objects are passed by value or by reference, and the answer is “neither”: object references are passed by value.
You can read more here: State of Valhalla. Section 2: Language Model
Edit: Brian Goetz is Java Language Architect, leading such projects as Project Valhalla and Project Amber.
Edit-2020-12-08: Updated State of Valhalla
A: The crux of the matter is that the word reference in the expression "pass by reference" means something completely different from the usual meaning of the word reference in Java.
Usually in Java reference means a a reference to an object. But the technical terms pass by reference/value from programming language theory is talking about a reference to the memory cell holding the variable, which is something completely different.
A: Have a look at this code. This code will not throw NullPointerException... It will print "Vinay"
public class Main {
public static void main(String[] args) {
String temp = "Vinay";
print(temp);
System.err.println(temp);
}
private static void print(String temp) {
temp = null;
}
}
If Java is pass by reference then it should have thrown NullPointerException as reference is set to Null.
A: Unlike some other languages, Java does not allow you to choose between pass-by-value and pass-by-reference.
All arguments are passed by value.
A method call can pass two types of valuesto a method
*
*copies of primitive values (e.g., values of type int and double)
*copies of references to objects.
Objects themselves cannot be passed to methods. When a method modifies a primitive-type parameter, changes to the parameter have no effect on the original argument value in the calling method.
This is also true for reference-type parameters. If you modify a reference-type parameter so that it refers to another object, only the parameter refers to the new object—the reference stored in the caller’s variable still refers to the original object.
References: Java™ How To Program (Early Objects), Tenth Edition
A: Long story short:
*
*Non-primitives: Java passes the Value of the Reference.
*Primitives: just value.
The End.
(2) is too easy. Now if you want to think of what (1) implies, imagine you have a class Apple:
class Apple {
private double weight;
public Apple(double weight) {
this.weight = weight;
}
// getters and setters ...
}
then when you pass an instance of this class to the main method:
class Main {
public static void main(String[] args) {
Apple apple = new Apple(3.14);
transmogrify(apple);
System.out.println(apple.getWeight()+ " the goose drank wine...";
}
private static void transmogrify(Apple apple) {
// does something with apple ...
apple.setWeight(apple.getWeight()+0.55);
}
}
oh.. but you probably know that, you're interested in what happens when you do something like this:
class Main {
public static void main(String[] args) {
Apple apple = new Apple(3.14);
transmogrify(apple);
System.out.println("Who ate my: "+apple.getWeight()); // will it still be 3.14?
}
private static void transmogrify(Apple apple) {
// assign a new apple to the reference passed...
apple = new Apple(2.71);
}
}
A: Java passes primitive types by value and class types by reference
Now, people like to bicker endlessly about whether "pass by reference" is the correct way to describe what Java et al. actually do. The point is this:
*
*Passing an object does not copy the object.
*An object passed to a function can have its members modified by the function.
*A primitive value passed to a function cannot be modified by the function. A copy is made.
In my book that's called passing by reference.
— Brian Bi - Which programming languages are pass by reference?
A: A simple test to check whether a language supports pass-by-reference is simply writing a traditional swap.
Can you write a traditional swap(a,b) method/function in Java?
A traditional swap method or function takes two arguments and swaps them such that variables passed into the function are changed outside the function. Its basic structure looks like
(Non-Java) Basic swap function structure
swap(Type arg1, Type arg2) {
Type temp = arg1;
arg1 = arg2;
arg2 = temp;
}
If you can write such a method/function in your language such that calling
Type var1 = ...;
Type var2 = ...;
swap(var1,var2);
actually switches the values of the variables var1 and var2, the language supports pass-by-reference.
But Java does not allow such a thing as it supports passing the values only and not pointers or references.
A: Not to repeat, but one point to those who might still be confused after reading many answers:
*
*pass by value in Java is NOT EQUAL to pass by value in C++, though it sounds like that, which is probably why there's confusion
Breaking it down:
*
*pass by value in C++ means passing the value of the object (if object), literarily the copy of the object
*pass by value in Java means passing the address value of the object (if object), not really the "value" (a copy) of the object like C++
*By pass by value in Java, operating on an object (e.g. myObj.setName("new")) inside a function has effects on the object outside the function; by pass by value in C++, it has NO effects on the one outside.
*However, by pass by reference in C++, operating on an object in a function DOES have effects on the one outside! Similar (just similar, not the same) to pass by value in Java, no?.. and people always repeat "there's no pass by reference in Java", => BOOM, confusion starts...
So, friends, all is just about the difference of terminology definition (across languages), you just need to know how it works and that's it (though sometimes a bit confusing how it's called I admit)!
A: It's a bit hard to understand, but Java always copies the value - the point is, normally the value is a reference. Therefore you end up with the same object without thinking about it...
A: In an attempt to add even more to this, I thought I'd include the SCJP Study Guide section on the topic. This is from the guide that is made to pass the Sun/Oracle test on the behaviour of Java so it's a good source to use for this discussion.
Passing Variables into Methods (Objective 7.3)
7.3 Determine the effect upon object references and primitive values when they are passed into methods that perform assignments or other modifying operations on the parameters.
Methods can be declared to take primitives and/or object references. You need to know how (or if) the caller's variable can be affected by the called method. The difference between object reference and primitive variables, when passed into methods, is huge and important. To understand this section, you'll need to be comfortable with the assignments section covered in the first part of this chapter.
Passing Object Reference Variables
When you pass an object variable into a method, you must keep in mind that you're passing the object reference, and not the actual object itself. Remember that a reference variable holds bits that represent (to the underlying VM) a way to get to a specific object in memory (on the heap). More importantly, you must remember that you aren't even passing the actual reference variable, but rather a copy of the reference variable. A copy of a variable means you get a copy of the bits in that variable, so when you pass a reference variable, you're passing a copy of the bits representing how to get to a specific object. In other words, both the caller and the called method will now have identical copies of the reference, and thus both will refer to the same exact (not a copy) object on the heap.
For this example, we'll use the Dimension class from the java.awt package:
1. import java.awt.Dimension;
2. class ReferenceTest {
3. public static void main (String [] args) {
4. Dimension d = new Dimension(5,10);
5. ReferenceTest rt = new ReferenceTest();
6. System.out.println("Before modify() d.height = " + d.height);
7. rt.modify(d);
8. System.out.println("After modify() d.height = "
9. }
10.
11.
12.
13. }
14. }
When we run this class, we can see that the modify() method was indeed able to modify the original (and only) Dimension object created on line 4.
C:\Java Projects\Reference>java ReferenceTest
Before modify() d.height = 10
dim = 11
After modify() d.height = 11
Notice when the Dimension object on line 4 is passed to the modify() method, any changes to the object that occur inside the method are being made to the object whose reference was passed. In the preceding example, reference variables d and dim both point to the same object.
Does Java Use Pass-By-Value Semantics?
If Java passes objects by passing the reference variable instead, does that mean Java uses pass-by-reference for objects? Not exactly, although you'll often hear and read that it does. Java is actually pass-by-value for all variables running within a single VM. Pass-by-value means pass-by-variable-value. And that means, pass-by-copy-of- the-variable! (There's that word copy again!)
It makes no difference if you're passing primitive or reference variables, you are always passing a copy of the bits in the variable. So for a primitive variable, you're passing a copy of the bits representing the value. For example, if you pass an int variable with the value of 3, you're passing a copy of the bits representing 3. The called method then gets its own copy of the value, to do with it what it likes.
And if you're passing an object reference variable, you're passing a copy of the bits representing the reference to an object. The called method then gets its own copy of the reference variable, to do with it what it likes. But because two identical reference variables refer to the exact same object, if the called method modifies the object (by invoking setter methods, for example), the caller will see that the object the caller's original variable refers to has also been changed. In the next section, we'll look at how the picture changes when we're talking about primitives.
The bottom line on pass-by-value: the called method can't change the caller's variable, although for object reference variables, the called method can change the object the variable referred to. What's the difference between changing the variable and changing the object? For object references, it means the called method can't reassign the caller's original reference variable and make it refer to a different object, or null. For example, in the following code fragment,
void bar() {
Foo f = new Foo();
doStuff(f);
}
void doStuff(Foo g) {
g.setName("Boo");
g = new Foo();
}
reassigning g does not reassign f! At the end of the bar() method, two Foo objects have been created, one referenced by the local variable f and one referenced by
the local (argument) variable g. Because the doStuff() method has a copy of the reference variable, it has a way to get to the original Foo object, for instance to call the setName() method. But, the doStuff() method does not have a way to get to the f reference variable. So doStuff() can change values within the object f refers to, but doStuff() can't change the actual contents (bit pattern) of f. In other words, doStuff() can change the state of the object that f refers to, but it can't make f refer to a different object!
Passing Primitive Variables
Let's look at what happens when a primitive variable is passed to a method:
class ReferenceTest {
public static void main (String [] args) {
int a = 1;
ReferenceTest rt = new ReferenceTest();
System.out.println("Before modify() a = " + a);
rt.modify(a);
System.out.println("After modify() a = " + a);
}
void modify(int number) {
number = number + 1;
System.out.println("number = " + number);
}
}
In this simple program, the variable a is passed to a method called modify(),
which increments the variable by 1. The resulting output looks like this:
Before modify() a = 1
number = 2
After modify() a = 1
Notice that a did not change after it was passed to the method. Remember, it was a copy of a that was passed to the method. When a primitive variable is passed to a method, it is passed by value, which means pass-by-copy-of-the-bits-in-the-variable.
A: I made this little diagram that shows how the data gets created and passed
Note: Primitive values are passed as a value, the first reference to to that value is the method's argument
That means:
*
*You can change the value of myObject inside the function
*But you can't change what myObject references to, inside the function, because point is not myObject
*Remember, both point and myObject are references, different references, however, those references point at the same new Point(0,0)
A: A lot of the confusion surrounding this issue comes from the fact that Java has attempted to redefine what "Pass by value" and "Pass by reference" mean. It's important to understand that these are Industry Terms, and cannot be correctly understood outside of that context. They are meant to help you as you code and are valuable to understand, so let's first go over what they mean.
A good description of both can be found here.
Pass By Value The value the function received is a copy of the object the caller is using. It is entirely unique to the function and anything you do to that object will only be seen within the function.
Pass By Reference The value the function received is a reference to the object the caller is using. Anything the function does to the object that value refers to will be seen by the caller and it will be working with those changes from that point on.
As is clear from those definitions, the fact that the reference is passed by value is irrelevant. If we were to accept that definition, then these terms become meaningless and all languages everywhere are only Pass By Value.
No matter how you pass the reference in, it can only ever be passed by value. That isn't the point. The point is that you passed a reference to your own object to the function, not a copy of it. The fact that you can throw away the reference you received is irrelevant. Again, if we accepted that definition, these terms become meaningless and everyone is always passing by value.
And no, C++'s special "pass by reference" syntax is not the exclusive definition of pass by reference. It is purely a convenience syntax meant to make it so that you don't need to use pointer syntax after passing the pointer in. It is still passing a pointer, the compiler is just hiding that fact from you. It also still passes that pointer BY VALUE, the compiler is just hiding that from you.
So, with this understanding, we can look at Java and see that it actually has both. All Java primitive types are always pass by value because you receive a copy of the caller's object and cannot modify their copy. All Java reference types are always pass by reference because you receive a reference to the caller's object and can directly modify their object.
The fact that you cannot modify the caller's reference has nothing to do with pass by reference and is true in every language that supports pass by reference.
A: Java is pass by value.
There are already great answers on this thread. Somehow, I was never clear on pass by value/reference with respect to primitive data types and with respect to objects. Therefore, I tested it out for my satisfaction and clarity with the following piece of code; might help somebody seeking similar clarity:
class Test {
public static void main (String[] args) throws java.lang.Exception
{
// Primitive type
System.out.println("Primitve:");
int a = 5;
primitiveFunc(a);
System.out.println("Three: " + a); //5
//Object
System.out.println("Object:");
DummyObject dummyObject = new DummyObject();
System.out.println("One: " + dummyObject.getObj()); //555
objectFunc(dummyObject);
System.out.println("Four: " + dummyObject.getObj()); //666 (555 if line in method uncommented.)
}
private static void primitiveFunc(int b) {
System.out.println("One: " + b); //5
b = 10;
System.out.println("Two:" + b); //10
}
private static void objectFunc(DummyObject b) {
System.out.println("Two: " + b.getObj()); //555
//b = new DummyObject();
b.setObj(666);
System.out.println("Three:" + b.getObj()); //666
}
}
class DummyObject {
private int obj = 555;
public int getObj() { return obj; }
public void setObj(int num) { obj = num; }
}
If the line b = new DummyObject() is uncommented, the modifications made thereafter are made on a new object, a new instantiation. Hence, it is not reflected in the place where the method is called from. However, otherwise, the change is reflected as the modifications are only made on a "reference" of the object, i.e - b points to the same dummyObject.
Illustrations in one of the answers in this thread (https://stackoverflow.com/a/12429953/4233180) can help gain a deeper understanding.
A: There are already great answers that cover this. I wanted to make a small contribution by sharing a very simple example (which will compile) contrasting the behaviors between Pass-by-reference in c++ and Pass-by-value in Java.
A few points:
*
*The term "reference" is a overloaded with two separate meanings. In Java it simply means a pointer, but in the context of "Pass-by-reference" it means a handle to the original variable which was passed in.
*Java is Pass-by-value. Java is a descendent of C (among other languages). Before C, several (but not all) earlier languages like FORTRAN and COBOL supported PBR, but C did not. PBR allowed these other languages to make changes to the passed variables inside sub-routines. In order to accomplish the same thing (i.e. change the values of variables inside functions), C programmers passed pointers to variables into functions. Languages inspired by C, such as Java, borrowed this idea and continue to pass pointer to methods as C did, except that Java calls its pointers References. Again, this is a different use of the word "Reference" than in "Pass-By-Reference".
*C++ allows Pass-by-reference by declaring a reference parameter using the "&" character (which happens to be the same character used to indicate "the address of a variable" in both C and C++). For example, if we pass in a pointer by reference, the parameter and the argument are not just pointing to the same object. Rather, they are the same variable. If one gets set to a different address or to null, so does the other.
*In the C++ example below I'm passing a pointer to a null terminated string by reference. And in the Java example below I'm passing a Java reference to a String (again, the same as a pointer to a String) by value. Notice the output in the comments.
C++ pass by reference example:
using namespace std;
#include <iostream>
void change (char *&str){ // the '&' makes this a reference parameter
str = NULL;
}
int main()
{
char *str = "not Null";
change(str);
cout<<"str is " << str; // ==>str is <null>
}
Java pass "a Java reference" by value example
public class ValueDemo{
public void change (String str){
str = null;
}
public static void main(String []args){
ValueDemo vd = new ValueDemo();
String str = "not null";
vd.change(str);
System.out.println("str is " + str); // ==> str is not null!!
// Note that if "str" was
// passed-by-reference, it
// WOULD BE NULL after the
// call to change().
}
}
EDIT
Several people have written comments which seem to indicate that either they are not looking at my examples or they don't get the c++ example. Not sure where the disconnect is, but guessing the c++ example is not clear. I'm posting the same example in pascal because I think pass-by-reference looks cleaner in pascal, but I could be wrong. I might just be confusing people more; I hope not.
In pascal, parameters passed-by-reference are called "var parameters". In the procedure setToNil below, please note the keyword 'var' which precedes the parameter 'ptr'. When a pointer is passed to this procedure, it will be passed by reference. Note the behavior: when this procedure sets ptr to nil (that's pascal speak for NULL), it will set the argument to nil--you can't do that in Java.
program passByRefDemo;
type
iptr = ^integer;
var
ptr: iptr;
procedure setToNil(var ptr : iptr);
begin
ptr := nil;
end;
begin
new(ptr);
ptr^ := 10;
setToNil(ptr);
if (ptr = nil) then
writeln('ptr seems to be nil'); { ptr should be nil, so this line will run. }
end.
EDIT 2
Some excerpts from "THE Java Programming Language" by Ken Arnold, James Gosling (the guy who invented Java), and David Holmes, chapter 2, section 2.6.5
All parameters to methods are passed "by value". In other words,
values of parameter variables in a method are copies of the invoker
specified as arguments.
He goes on to make the same point regarding objects . . .
You should note that when the parameter is an object reference, it is
the object reference-not the object itself-that is passed "by value".
And towards the end of the same section he makes a broader statement about java being only pass by value and never pass by reference.
The Java programming language does not pass objects by reference; it
passes object references by value. Because two copies of the same
reference refer to the same actual object, changes made through one
reference variable are visible through the other. There is exactly one
parameter passing mode-pass by value-and that helps keep things
simple.
This section of the book has a great explanation of parameter passing in Java and of the distinction between pass-by-reference and pass-by-value and it's by the creator of Java. I would encourage anyone to read it, especially if you're still not convinced.
I think the difference between the two models is very subtle and unless you've done programming where you actually used pass-by-reference, it's easy to miss where two models differ.
I hope this settles the debate, but probably won't.
EDIT 3
I might be a little obsessed with this post. Probably because I feel that the makers of Java inadvertently spread misinformation. If instead of using the word "reference" for pointers they had used something else, say
dingleberry, there would've been no problem. You could say, "Java passes dingleberries by value and not by reference", and nobody would be confused.
That's the reason only Java developers have issue with this. They look at the word "reference" and think they know exactly what that means, so they don't even bother to consider the opposing argument.
Anyway, I noticed a comment in an older post, which made a balloon analogy which I really liked. So much so that I decided to glue together some clip-art to make a set of cartoons to illustrate the point.
Passing a reference by value--Changes to the reference are not reflected in the caller's scope, but the changes to the object are. This is because the reference is copied, but the both the original and the copy refer to the same object.
Pass by reference--There is no copy of the reference. Single reference is shared by both the caller and the function being called. Any changes to the reference or the Object's data are reflected in the caller's scope.
EDIT 4
I have seen posts on this topic which describe the low level implementation of parameter passing in Java, which I think is great and very helpful because it makes an abstract idea concrete. However, to me the question is more about the behavior described in the language specification than about the technical implementation of the behavior. This is an exerpt from the Java Language Specification, section 8.4.1 :
When the method or constructor is invoked (§15.12), the values of the
actual argument expressions initialize newly created parameter
variables, each of the declared type, before execution of the body of
the method or constructor. The Identifier that appears in the
DeclaratorId may be used as a simple name in the body of the method or
constructor to refer to the formal parameter.
Which means, java creates a copy of the passed parameters before executing a method. Like most people who studied compilers in college, I used "The Dragon Book" which is THE compilers book. It has a good description of "Call-by-value" and "Call-by-Reference" in Chapter 1. The Call-by-value description matches up with Java Specs exactly.
Back when I studied compilers-in the 90's, I used the first edition of the book from 1986 which pre-dated Java by about 9 or 10 years. However, I just ran across a copy of the 2nd Eddition from 2007 which actually mentions Java! Section 1.6.6 labeled "Parameter Passing Mechanisms" describes parameter passing pretty nicely. Here is an excerpt under the heading "Call-by-value" which mentions Java:
In call-by-value, the actual parameter is evaluated (if it is an
expression) or copied (if it is a variable). The value is placed in
the location belonging to the corresponding formal parameter of the
called procedure. This method is used in C and Java, and is a common
option in C++ , as well as in most other languages.
A: In java everything is reference, so when you have something like:
Point pnt1 = new Point(0,0); Java does following:
*
*Creates new Point object
*Creates new Point reference and initialize that reference to point (refer to) on previously created Point object.
*From here, through Point object life, you will access to that object through pnt1
reference. So we can say that in Java you manipulate object through its reference.
Java doesn't pass method arguments by reference; it passes them by value. I will use example from this site:
public static void tricky(Point arg1, Point arg2) {
arg1.x = 100;
arg1.y = 100;
Point temp = arg1;
arg1 = arg2;
arg2 = temp;
}
public static void main(String [] args) {
Point pnt1 = new Point(0,0);
Point pnt2 = new Point(0,0);
System.out.println("X1: " + pnt1.x + " Y1: " +pnt1.y);
System.out.println("X2: " + pnt2.x + " Y2: " +pnt2.y);
System.out.println(" ");
tricky(pnt1,pnt2);
System.out.println("X1: " + pnt1.x + " Y1:" + pnt1.y);
System.out.println("X2: " + pnt2.x + " Y2: " +pnt2.y);
}
Flow of the program:
Point pnt1 = new Point(0,0);
Point pnt2 = new Point(0,0);
Creating two different Point object with two different reference associated.
System.out.println("X1: " + pnt1.x + " Y1: " +pnt1.y);
System.out.println("X2: " + pnt2.x + " Y2: " +pnt2.y);
System.out.println(" ");
As expected output will be:
X1: 0 Y1: 0
X2: 0 Y2: 0
On this line 'pass-by-value' goes into the play...
tricky(pnt1,pnt2); public void tricky(Point arg1, Point arg2);
References pnt1 and pnt2 are passed by value to the tricky method, which means that now yours references pnt1 and pnt2 have their copies named arg1 and arg2.So pnt1 and arg1 points to the same object. (Same for the pnt2 and arg2)
In the tricky method:
arg1.x = 100;
arg1.y = 100;
Next in the tricky method
Point temp = arg1;
arg1 = arg2;
arg2 = temp;
Here, you first create new temp Point reference which will point on same place like arg1 reference. Then you move reference arg1 to point to the same place like arg2 reference.
Finally arg2 will point to the same place like temp.
From here scope of tricky method is gone and you don't have access any more to the references: arg1, arg2, temp. But important note is that everything you do with these references when they are 'in life' will permanently affect object on which they are point to.
So after executing method tricky, when you return to main, you have this situation:
So now, completely execution of program will be:
X1: 0 Y1: 0
X2: 0 Y2: 0
X1: 100 Y1: 100
X2: 0 Y2: 0
A: Everything is passed by value. Primitives and Object references. But objects can be changed, if their interface allows it.
When you pass an object to a method, you are passing a reference, and the object can be modified by the method implementation.
void bithday(Person p) {
p.age++;
}
The reference of the object itself, is passed by value: you can reassign the parameter, but the change is not reflected back:
void renameToJon(Person p) {
p = new Person("Jon"); // this will not work
}
jack = new Person("Jack");
renameToJon(jack);
sysout(jack); // jack is unchanged
As matter of effect, "p" is reference (pointer to the object) and can't be changed.
Primitive types are passed by value. Object's reference can be considered a primitive type too.
To recap, everything is passed by value.
A: There are only two versions:
*
*You can pass the value i.e. (4,5)
*You can pass an address i.e. 0xF43A
Java passes primivates as values and objects as addresses. Those who say, "address are values too", do not make a distinction between the two. Those who focus on the effect of the swap functions focus on what happens after the passing is done.
In C++ you can do the following:
Point p = Point(4,5);
This reserves 8 bytes on the stack and stores (4,5) in it.
Point *x = &p;
This reserves 4 bytes on the stack and stores 0xF43A in it.
Point &y = p;
This reserves 4 bytes on the stack and stores 0xF43A in it.
*
*I think everyone will agree that a call to f(p) is a pass-by-value if the definition of f is f(Point p). In this case an additional 8 bytes being reserved and (4,5) being copied into it. When f changes p the the the original is guarantieed to be unchanged when f returns.
*I think that everyone will agree that a call to f(p) is a pass-by-reference if the definition of f is f(Point &p). In this case an additional 4 bytes being reserved and 0xF43A being copied into it. When f changes p the the original is guarantieed to be changed when f returns.
*A call to f(&p) is also pass-by-reference if the definition of f is f(Point *p). In this case an additional 4 bytes being reserved and 0xF43A being copied into it. When f changes *p the the original is guarantieed to be changed when f returns.
*A call to f(x) is also pass-by-reference if the definition of f is f(Point *p). In this case an additional 4 bytes being reserved and 0xF43A being copied into it. When f changes *p the the original is guarantieed to be changed when f returns.
*A call to f(y) is also pass-by-reference if the definition of f is f(Point &p). In this case an additional 4 bytes being reserved and 0xF43A being copied into it. When f changes p the the original is guarantieed to be changed when f returns.
Sure what happens after the passing is done differs, but that is only a language construct. In the case of pointer you have to use -> to access the members and in the case of references you have to use .. If you want to swap the values of the original then you can do tmp=a; a=b; b=tmp; in the case of references and tmp=*a; *b=tmp; *a=tmp for pointers. And in Java you would have do: tmp.set(a); a.set(b); b.set(tmp). Focussing on the assignment statement statement is silly. You can do the exact same thing in Java if you write a little bit of code.
So Java passes primivates by values and objects by references. And Java copy values to achieve that, but so does C++.
For completeness:
Point p = new Point(4,5);
This reserves 4 bytes on the stack and stores 0xF43A in it and reserves 8 bytes on the heap and stores (4,5) in it.
If you want to swap the memory locations like so
void swap(int& a, int& b) {
int *tmp = &a;
&a = &b;
&b = tmp;
}
Then you will find that you run into the limitations of your hardware.
A: If you want it to put into a single sentence to understand and remember easily, simplest answer:
Java is always pass the value with a new reference
(So you can modify the original object but can not access the original reference)
A: Guess, the common canon is wrong based on inaccurate language
Authors of a programming language do not have the authority to rename established programming concept.
Primitive Java types byte, char, short, int, long float, double are definitely passed by value.
All other types are Objects: Object members and parameters technically are references.
So these "references" are passed "by value", but there occurs no object construction on the stack. Any change of object members (or elements in case of an array) apply to the same original Object; such reference precisely meets the logic of pointer of an instance passed to some function in any C-dialect, where we used to call this passing an object by reference
Especially we do have this thing java.lang.NullPointerException, which makes no sense in a pure by-value-concept
A: "I am a Junior Java Developer and I would like to know if Java uses Call-by-Value or Call-by-Reference?"
There is no universal answer to that and there cannot be for it's a false dichotomy. We have 2 different terms (Call-by-Value/Call-by-Reference) but at least 3(!) different ways of handling said data when passing it to a method:
*
*Our data is copied and the copy fed to a method. Changes to the copy do not propagate outside.(Think an int in Java or C++ or C#.)
*A pointer (the memory address) of our data is fed to the method instead. Changes to our data do propagate outside. We can also point to some new instance, leaving our original data dangling. (Think pointers in C++.)
*Like #2, except we can only change the original data but not what our pointer is pointing too. (Think instances passed as parameters in Java.)
It's uncontentious in the OO world that #1 is Call-by-Value and #2 is Call-by-Reference.
However, since we have only two terms for three options, there is no clear delineation between the two terms, thanks to option #3.
"What does that mean for me?"
It means that within the Java sphere you may reasonably assume #3 to be assumed under Call-by-Value (or the more verbal gymnastics term, Call-References-by-Value).
However, in the wider OO world, it means you have to ask for an explicit delineation between Call-by-Value and Call-by-Reference, specifically how the other party classifies #3.
"But I read that the JLS defines it as Call-by-Value!"
Which is why your initial assumption when dealing with Java developers should be the above. The JLS has much less authority outside of Java, however.
"Why would Java developers insist on their own terminology?"
It's not for me to speculate but I think it's fair to point out that there is some potential problems with #2 (what is clearly Call-by-Reference), as hinted at, leading to Call-by-Reference not having the best of reputation everywhere.
"Is there a solution to this mess?"
3 options, only 2 ubiquitous names. The obvious exit is a 3rd term that gains equal wide-spread use as Call-by-Value and Call-by-Reference (and which is less confusing than Call-References-by-Value, perhaps Call-by-Sharing). Until then you need to presume or ask, as outlined above.
Ultimately, it does not matter what we call it, for as long as we understand each other and there is no confusion.
A: Is Java a pass-by-value or reference? Prove it.
Java strictly enforces pass-by-value. Passing the parameters by using pass-by-values does not affect/alter the original variable. In the following program, we have initialized a variable called 'x' with some value and used the pass-by-value technique to demonstrate how the value of the variable remains unchanged.
Code:
public class Main
{
public static void main(String[] args)
{
//Original value of 'x' will remain unchanged
// in case of call-by-value
int x = 5;
System.out.println( "Value of x before call-by-value: " + x);
// 5
processData(x);
System.out.println("Value of x after call-by-value: " + x);
// 5
}
public static void processData(int x)
{
x=x+10;
}
}
Now coming to the meaning - the value of x did not change in the main function - this is called pass by value.
If the value changes in the main function it is called pass by reference.
difference between pass by value and pass by reference
What is Pass by Value?
In pass by value, the value of a function parameter is copied to another location of the memory. When accessing or modifying the variable within the function, it accesses only the copy. Thus, there is no effect on the original value.
What is Pass by Reference?
In pass by reference, the memory address is passed to that function. In other words, the function gets access to the actual variable.
Difference Between Pass by Value and Pass by Reference
Definition
Pass by value refers to a mechanism of copying the function parameter value to another variable while the pass by reference refers to a mechanism of passing the actual parameters to the function. Thus, this is the main difference between pass by value and pass by reference.
Changes
In pass by value, the changes made inside the function are not reflected in the original value. On the other hand, in pass by reference, the changes made inside the function are reflected in the original value. Hence, this is another difference between pass by value and pass by reference.
Actual Parameter
Moreover, pass by value makes a copy of the actual parameter. However, in pass by reference, the address of the actual parameter passes to the function.
A: I came across to similar issue. This story about circle was a concrete answer for me. I would like to add to the answer.
Hope it helps for people who are having similar issue.
https://docs.oracle.com/javase/tutorial/java/javaOO/arguments.html
Inside the method, circle initially refers to myCircle. The method changes the x and y coordinates of the object that circle references (that is, myCircle) by 23 and 56, respectively. These changes will persist when the method returns. Then circle is assigned a reference to a new Circle object with x = y = 0. This reassignment has no permanence, however, because the reference was passed in by value and cannot change. Within the method, the object pointed to by circle has changed, but, when the method returns, myCircle still references the same Circle object as before the method was called.
A: Every single answer here is tying to take pass pointer by reference from other languages and show how it is impossible to do in Java. For whatever reason nobody is attempting to show how to implement pass-object-by-value from other languages.
This code shows how something like this can be done:
public class Test
{
private static void needValue(SomeObject so) throws CloneNotSupportedException
{
SomeObject internalObject = so.clone();
so=null;
// now we can edit internalObject safely.
internalObject.set(999);
}
public static void main(String[] args)
{
SomeObject o = new SomeObject(5);
System.out.println(o);
try
{
needValue(o);
}
catch(CloneNotSupportedException e)
{
System.out.println("Apparently we cannot clone this");
}
System.out.println(o);
}
}
public class SomeObject implements Cloneable
{
private int val;
public SomeObject(int val)
{
this.val = val;
}
public void set(int val)
{
this.val = val;
}
public SomeObject clone()
{
return new SomeObject(val);
}
public String toString()
{
return Integer.toString(val);
}
}
Here we have a function needValue and what it does is right away create a clone of the object, which needs be implemented in the class of the object itself and the class needs to be marked as Cloneable. It is not essential to set so to null after that, but i have done so here to show that we are not going to be using that reference after that.
It may well be that Java does not have pass-by-reference semantics, but to call the language "pass-by-value" is along the lines of wishful thinking.
A: After following an exhaustive discussion, I think it's time to put all serious results together in a snippet.
/**
*
* @author Sam Ginrich
*
* All Rights Reserved!
*
*/
public class JavaIsPassByValue
{
static class SomeClass
{
int someValue;
public SomeClass(int someValue)
{
this.someValue = someValue;
}
}
static void passReferenceByValue(SomeClass someObject)
{
if (someObject == null)
{
throw new NullPointerException(
"This Object Reference was passed by Value,\r\n that's why you don't get a value from it.");
}
someObject.someValue = 49;
}
public static void main(String[] args)
{
SomeClass someObject = new SomeClass(27);
System.out.println("Here is the original value: " + someObject.someValue);
passReferenceByValue(someObject);
System.out.println(
"\nAs ´Java is pass by value´,\r\n everything without exception is passed by value\r\n and so an object's attribute cannot change: "
+ someObject.someValue);
System.out.println();
passReferenceByValue(null);
}
}
One can easily see from the output, that in Java everything is passed by value, so simple!
Here is the original value: 27
As ´Java is pass by value´,
everything without exception is passed by value
and so an object´s attribute cannot change: 49
'Exception in thread "main" java.lang.NullPointerException: This Object Reference was passed by value,
that´s why you don´t get a value from it.
at JavaIsPassByValue.passReferenceByValue(JavaIsPassByValue.java:26)
at JavaIsPassByValue.main(JavaIsPassByValue.java:43)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40480",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7645"
} |
Q: Optimizing Conway's 'Game of Life' To experiment, I've (long ago) implemented Conway's Game of Life (and I'm aware of this related question!).
My implementation worked by keeping 2 arrays of booleans, representing the 'last state', and the 'state being updated' (the 2 arrays being swapped at each iteration). While this is reasonably fast, I've often wondered about how to optimize this.
One idea, for example, would be to precompute at iteration N the zones that could be modified at iteration (N+1) (so that if a cell does not belong to such a zone, it won't even be considered for modification at iteration (N+1)). I'm aware that this is very vague, and I never took time to go into the details...
Do you have any ideas (or experience!) of how to go about optimizing (for speed) Game of Life iterations?
A: As mentioned in Arbash's Black Book, one of the most simple and straight forward ways to get a huge speedup is to keep a change list.
Instead of iterating through the entire cell grid each time, keep a copy of all the cells that you change.
This will narrow down the work you have to do on each iteration.
A: The algorithm itself is inherently parallelizable. Using the same double-buffered method in an unoptimized CUDA kernel, I'm getting around 25ms per generation in a 4096x4096 wrapped world.
A: I am going to quote my answer from the other question, because the chapters I mention have some very interesting and fine-tuned solutions. Some of the implementation details are in c and/or assembly, yes, but for the most part the algorithms can work in any language:
Chapters 17 and 18 of
Michael Abrash's Graphics
Programmer's Black Book are one of
the most interesting reads I have ever
had. It is a lesson in thinking
outside the box. The whole book is
great really, but the final optimized
solutions to the Game of Life are
incredible bits of programming.
A: what is the most efficient algo mainly depends on the initial state.
if the majority of cells is dead, you could save a lot of CPU time by skipping empty parts and not calculating stuff cell by cell.
im my opinion it can make sense to check for completely dead spaces first, when your initial state is something like "random, but with chance for life lower than 5%."
i would just divide the matrix up into halves and start checking the bigger ones first.
so if you have a field of 10,000 * 10,000, you´d first accumulate the states of the upper left quarter of 5,000 * 5,000.
and if the sum of states is zero in the first quarter, you can ignore this first quarter completely now and check the upper right 5,000 * 5,000 for life next.
if its sum of states is >0, you will now divide up the second quarter into 4 pieces again - and repeat this check for life for each of these subspaces.
you could go down to subframes of 8*8 or 10*10 (not sure what makes the most sense here) now.
whenever you find life, you mark these subspaces as "has life".
only spaces which "have life" need to be divided into smaller subspaces - the empty ones can be skipped.
when you are finished assigning the "has life" attribute to all possible subspaces, you end up with a list of subspaces which you now simply extend by +1 to each direction - with empty cells - and perform the regular (or modified) game of life rules to them.
you might think that dividn up a 10,000*10,000 spae into subspaces of 8*8 is a lot os tasks - but accumulating their states values is in fact much, much less computing work than performing the GoL algo to each cell plus their 8 neighbours plus comparing the number and storing the new state for the net iteration somewhere...
but like i said above, for a random init state with 30% population this wont make much sense, as there will be not many completely dead 8*8 subspaces to find (leave alone dead 256*256 subpaces)
and of course, the way of perfect optimisation will last but not least depend on your language.
-110
A: There are some super-fast implementations that (from memory) represent cells of 8 or more adjacent squares as bit patterns and use that as an index into a large array of precalculated values to determine in a single machine instruction if a cell is live or dead.
Check out here:
http://dotat.at/prog/life/life.html
Also XLife:
http://linux.maruhn.com/sec/xlife.html
A: You should look into Hashlife, the ultimate optimization. It uses the quadtree approach that skinp mentioned.
A: Two ideas:
(1) Many configurations are mostly empty space. Keep a linked list (not necessarily in order, that would take more time) of the live cells, and during an update, only update around the live cells (this is similar to your vague suggestion, OysterD :)
(2) Keep an extra array which stores the # of live cells in each row of 3 positions (left-center-right). Now when you compute the new dead/live value of a cell, you need only 4 read operations (top/bottom rows and the center-side positions), and 4 write operations (update the 3 affected row summary values, and the dead/live value of the new cell). This is a slight improvement from 8 reads and 1 write, assuming writes are no slower than reads. I'm guessing you might be able to be more clever with such configurations and arrive at an even better improvement along these lines.
A: If you don't want anything too complex, then you can use a grid to slice it up, and if that part of the grid is empty, don't try to simulate it (please view Tyler's answer). However, you could do a few optimizations:
*
*Set different grid sizes depending on the amount of live cells, so if there's not a lot of live cells, that likely means they are in a tiny place.
*When you randomize it, don't use the grid code until the user changes the data: I've personally tested randomizing it, and even after a long amount of time, it still fills most of the board (unless for a sufficiently small grid, at which point it won't help that much anymore)
*If you are showing it to the screen, don't use rectangles for pixel size 1 and 2: instead set the pixels of the output. Any higher pixel size and I find it's okay to use the native rectangle-filling code. Also, preset the background so you don't have to fill the rectangles for the dead cells (not live, because live cells disappear pretty quickly)
A: Don't exactly know how this can be done, but I remember some of my friends had to represent this game's grid with a Quadtree for a assignment. I'm guess it's real good for optimizing the space of the grid since you basically only represent the occupied cells. I don't know about execution speed though.
A: It's a two dimensional automaton, so you can probably look up optimization techniques. Your notion seems to be about compressing the number of cells you need to check at each step. Since you only ever need to check cells that are occupied or adjacent to an occupied cell, perhaps you could keep a buffer of all such cells, updating it at each step as you process each cell.
If your field is initially empty, this will be much faster. You probably can find some balance point at which maintaining the buffer is more costly than processing all the cells.
A: There are table-driven solutions for this that resolve multiple cells in each table lookup. A google query should give you some examples.
A: I implemented this in C#:
All cells have a location, a neighbor count, a state, and access to the rule.
*
*Put all the live cells in array B in array A.
*Have all the cells in array A add 1 to the neighbor count of their
neighbors.
*Have all the cells in array A put themselves and their neighbors in array B.
*All the cells in Array B Update according to the rule and their state.
*All the cells in Array B set their neighbors to 0.
Pros:
*
*Ignores cells that don't need to be updated
Cons:
*
*4 arrays: a 2d array for the grid, an array for the live cells, and an array
for the active cells.
*Can't process rule B0.
*Processes cells one by one.
*Cells aren't just booleans
Possible improvements:
*
*Cells also have an "Updated" value, they are updated only if they haven't
updated in the current tick, removing the need of array B as mentioned above
*Instead of array B being the ones with live neighbors, array B could be the
cells without, and those check for rule B0.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40485",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "44"
} |
Q: Bug tracker setup with Git integration? I know I can do most of this by hacking Trac and using Git hooks, but I was wondering if someone has / knows of something ready.
Commenting on (and closing) tickets from commit messages would be nice, specially if the diff appears inline with the comment/closing remark.
sha1 hashes should be auto-linked to gitweb/cigt/custom git browser.
I tried the GitPlugin for Trac, but the code browser was soo slow... any alternatives?
A: There's also GitZilla (I'm the author).
A: Redmine can do some of what you're asking for. Integration works in one direction, you must reference issues in commit messages, and then this data will be available in redmine.
The data is then available in two views. The bug display will include a list of matched commits. The repository display will link commits to bug display pages.
Redmine keeps a local (bare) repository for each project. This can be the primary repo or a remote mirror. On updates, redmine parses the commit messages and updates an internal cross reference table of change_set,issue.
If the redmine repository is only used as a mirror, it will need to be updated. Updates can happen via cron or via external hook. We use a redmine github plugin and a github post-receive hook to keep redmine in sync with a primary github repository.
It works, but it is still a bit clumsy.
A: Yeah, I have been looking for something similar!
there is no documentation on redmine but the only feature
that I am aware is that if you append a dash (#) and a issue
number you get a link to that issue.
For example:
$ git commit -a -m '#45 makes earth rotate in reverse!'
would be on visible on the repository and the number will link
to the issue #45!
I really want to make it so if a commit is liked to a specific
issue the commit-message gets appended to the issue.
and yes, close, fixed and stuff like that would be great!
I've been browsing for such (git-hooks) or features in redmine for
a while but not much luck! (their documentation sucks!)
somebody post some updates on this topic!
A: trac has a git plugin - it works like the svn version...
http://trac-hacks.org/wiki/TracGitPlugin
A: Mantis has a good Git integration, and it's exercised by the developers themselves, as the development is driven by Git.
This is how changesets attached to an issue will appear:
You can find more documentation at Integrating Git and SVN with the Mantis Bug Tracker.
A: BugTracker.NET is a web-based bug tracking system that has git integration. The web pages for the git integration look pretty much like the ones for the subversion integration, documented here.
You can read more about the philosophy that guided BugTracker.NET/Git integration in this Stackoverflow question: How does bug tracker/version control integration work with typical git workflows?
See also this question:
https://stackoverflow.com/questions/229303/are-there-any-good-issue-tracking-systems-that-can-track-git-commits-branches
A: https://bitbucket.org - technically it's a DVCS service, but it has fully integrated issue tracking. And it's services are really free for small teams (and unlimited free service for .edu people too).
A: Check out this link here.
It provides a tutorial on how Git can be used to integrate with Rational Team Concert. It will give some basic information which can be used to integrate Git with a wide range of other products.
A: for integration with Bugzilla, you can use git-bz:
http://git.fishsoup.net/man/git-bz.html
it's heavily used in the GNOME project.
A: There is sdorra scm-manager tool, integrating Git and Jira
TrackStudio, since version 4, also has Git integration
A: Assembla offers a free git repository that is private and an integrated bug tracking system - you can change ticket statuses or track time directly through your commit messages. They also offer custom server-side hooks - which allow you to write your own logic and then use it - anything from rejecting commits that do not match certain rules of yours, to starting a CI build after a commit is received.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40495",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "36"
} |
Q: Return function pointer to a nested function in C As the title already states, I'm trying to declare a nested function and return a pointer to that function. I want this function 'not' to return a new function pointer which will return the negation of whatever the original function was.
Here is what I have:
someType not( someType original ) {
int isNot( ListEntry* entry ) {
return !original( entry );
}
someType resultFunc = calloc( 1024, 1 );
memcpy( resultFunc, &isNot, 1024 );
return resultFunc;
}
someType is defined as:
typedef int(*someType)(ListEntry* entry)
A: Steve, you have a completely wrong mental model of what is a C function.
someType resultFunc = calloc( 1024, 1 );
memcpy( resultFunc, &isNot, 1024 );
From your code fragment, I can surmise that you think that you can copy function's compiled code into a block of memory, and then reuse it. This kind of thing smells of Lisp, except even in lisp you don't do it that way.
In fact, when you say "&isNot", you get a pointer to function. Copying the memory that pointer points at is counterproductive - the memory was initialized when you loaded your executable into memory, and it's not changing. In any case, writing someFunc() would cause a core dump, as the heap memory behing someFunc cannot be executed - this protects you from all sorts of viruses.
You seem to expect an implementation of closures in C. That implementation is simply not there. Unlike Lisp or Perl or Ruby, C cannot preserve elements of a stack frame once you exited that frame. Even is nested functions are permitted in some compilers, I am sure that you cannot refer to non-global variables from inside those functions. The closes thing to closures is indeed C++ object that stores the state and implements operator(), but it's a completely different approach, and you'd still have to do things manually.
Update: here is the relevant portion of GCC documentation. Look for "But this technique works only so long as the containing function (hack, in this example) does not exit."
A: You're not going to be able to do this in the fashion you want. You have a couple of alternative options.
You can use macros:
#define FN_NOT(F) !F
#define notSomeFunc FN_NOT(someFunc)
...
x = notSomeFunc(entry);
But I suspect you wanted to be able to pass the negated function around to other functions that take function pointers, so that won't work.
You can change your interfaces to accept some extra information, eg
struct closure {
void *env;
int (*f)(struct closure* extra, ListEntry*);
};
static int isNot(struct closure* extra, ListEntry *entry) {
someType original = extra->env;
return !original(entry);
}
struct closure not(someType original) {
closure rv;
rv.env = original;
rv.f = &isNot;
return rv;
}
And then use it like:
struct closure inverse_fn;
inverse_fn = not( &fn );
if( inverse_fn.f(&inverse_fn, entry) ) {
...
}
There are other things you can try, like JITing functions at runtime, but those sorts of techniques are going to be platform and architecture dependent. This solution is awkward, but pure C and portable.
A: I'm using GCC.
You can turn on nested functions by using the flag:
-fnested-functions
when you compile.
A: I also never heard of nested functions in C, but if gcc supports it, this is not going to work the way you expect. You are just simply copying the machine instructions of isNot, and that won't include the actual value of "original" at the time "not" is being called.
You should use a C++ class to implement a function object that stores a pointer that you can initialize with the value of "original" and return an instance of this class from "not".
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40511",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Call Functions within Function - Flash Actionscript 2.0 I'm trying to call a function after I load some XML into Actionscript, and I'm just wondering how I call that function. Example:
//Function Declarations
function parentFunction()
{
function callMe()
{
textField.text = "lawl";
}
}
Now, how do I call the "callMe()" function in a different part of the code, like an onRelease function?
on(release)
{
callMe(); //doesn't work
parentFunction().callMe(); //doesn't work
parentFunction.callMe(); //doesn't work
}
ActionScript 2.0 is just so wonky! Any ideas?
A: Are you forced to declare callMe inside of parentFunction? I assume so because otherwise you would just do
function parent() { }
function callMe() { }
To be clear, a function can't own another function unless you provide some scope for that function to live in.
So in JavaScript, you would do this by using the prototype object to declare the callMe function as a method of the object that parentFunction returned.
http://www.howtocreate.co.uk/tutorials/javascript/objects
For ActionScript, read this article on Adobe's website:
http://www.adobe.com/devnet/flex/articles/as_collections_03.html
EDIT: After some more reading it appears the way you did things, you are actually declaring callMe as a private function. See this article which should make the whole private/public javascript issue a lot more understandable.
A: I'm an idiot. I forgot the whole "a function can't own another function" thing, so I figured out another way to do it. Thanks!
A: Of course a function can "own" another function. this is ECMAScript remember. Just declare a variable inside your function and assign a function to it. You can then call your function by using the "call" method.
function foo()
{
trace("foo");
var bar = function()
{
trace("bar");
};
bar.call();
}
foo();
A: //v--- on the frame
function callMe(){
textArea.text='lawl';
}
//v---- for button
on(release){
callMe();
}
--- or -----
//CUSTOM!!
//v---- on frame
function callMe(say){
textArea.text=say;
}
//v--- for button
on(release){
callMe('lawl');
}
A: Sorry for bad english,
Set a handler for (Menu-)Buttons, whitch are located in a MC.
MC "Buttons" on Stage (with 3 "testbtn" in it) @ first frame:
function SetMethod(Method:Function){
//trace(Method.call());
//or something like:
testbtn1.addEventListener(MouseEvent.CLICK, Method);
testbtn2.addEventListener(MouseEvent.CLICK, Method);
testbtn3.addEventListener(MouseEvent.CLICK, Method);
}
Stage (with MC "Butttons" in it) @ first frame:
function TheMenuListener(evt:Event):void{
trace(evt.target.name);
}
...
Buttons.SetMethod(this.TheMenuListener);
returns the testbtn.name
Edit: Oh, it´s for AS3, but maybe helps!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40525",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Why should I use Feature Driven Development? Extreme Programming, Scrum and Test Driven Development definitely seem to be the most popular Agile methods at the moment. But someone recently suggested that I take a look at Feature Driven Development.
Have you ever used this method with any success? What are the advantages of using it?
A: FDD is what I like to think of as a wrapper methodology, in that it allows you to apply a method to manage projects at a very high level, but it still allows you to use other methodologies at a lower level.
FDD's focus is on being able to set estimates and schedules and to report on the status of a project as a whole, or at a very granular level, but it doesn't prescribe a specific method to apply in order to create the schedule, leaving that up to you to decide. The idea is that you can look at your project and state with some certainty what the project status is, whether you are on time, slipping, early and so on.
I use FDD as a means to organise my projects into manageable stages, so that I know WHEN to sign off and commence any given stage. But by itself, FDD would be pretty useless. For example, I personally use Evidence Based Scheduling and a combined BDD/TDD as elements of a development processes that are managed under a kind of FDD umbrella. Personally, I couldn't do the full XP, or SCRUMM without running into problems because my projects and team would be hindered if they were forced to engage in practices from other methodologies that don't add value to our own unique circumstances.
In any case, it is better not to fixate on any given methodology, because the needs/conditions of the company and project are likely to change regularly, and you need to be flexible in how you approach managing projects if you want them to be successful. No single methodology is a silver bullet, so the trick is to determine which methods work for you and tune your methodology to suit your individual needs. This is what being "Agile" is fundamentally about.
A: FDD is an older methodology. It has lot's of the ideas of other agile methodologies and misses some of them. Like Scrum it's a bit management-focussed and I think you need some elements from XP for practical implementations.
FDD is certainly interesting to look into. But just like Scrum and XP I think you have to understand the mechanics and not just implement the practices to be succesful. If you just "do FDD" or "do Scrum" you're not as adaptive as you should be.
The things I would look into if you want to understand agile would be
Scrum or FDD to understand what management can get out of agile.
XP to understand how enable agile from a technology perspective.
Crystal Clear to understand the communications aspects.
Lean Agile to get a completely different perspective on agile methodologies
I wouldn't call TDD an agile methodology by the way. It's an practice from XP but not a complete methodology per se.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40531",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Asp.Net MVC: How to determine if you're currently on a specific view I need to determine if I'm on a particular view. My use case is that I'd like to decorate navigation elements with an "on" class for the current view. Is there a built in way of doing this?
A: Here what i am using. I think this is actually generated by the MVC project template in VS:
public static bool IsCurrentAction(this HtmlHelper helper, string actionName, string controllerName)
{
string currentControllerName = (string)helper.ViewContext.RouteData.Values["controller"];
string currentActionName = (string)helper.ViewContext.RouteData.Values["action"];
if (currentControllerName.Equals(controllerName, StringComparison.CurrentCultureIgnoreCase) && currentActionName.Equals(actionName, StringComparison.CurrentCultureIgnoreCase))
return true;
return false;
}
A: My current solution is with extension methods:
public static class UrlHelperExtensions
{
/// <summary>
/// Determines if the current view equals the specified action
/// </summary>
/// <typeparam name="TController">The type of the controller.</typeparam>
/// <param name="helper">Url Helper</param>
/// <param name="action">The action to check.</param>
/// <returns>
/// <c>true</c> if the specified action is the current view; otherwise, <c>false</c>.
/// </returns>
public static bool IsAction<TController>(this UrlHelper helper, LambdaExpression action) where TController : Controller
{
MethodCallExpression call = action.Body as MethodCallExpression;
if (call == null)
{
throw new ArgumentException("Expression must be a method call", "action");
}
return (call.Method.Name.Equals(helper.ViewContext.ViewName, StringComparison.OrdinalIgnoreCase) &&
typeof(TController) == helper.ViewContext.Controller.GetType());
}
/// <summary>
/// Determines if the current view equals the specified action
/// </summary>
/// <param name="helper">Url Helper</param>
/// <param name="actionName">Name of the action.</param>
/// <returns>
/// <c>true</c> if the specified action is the current view; otherwise, <c>false</c>.
/// </returns>
public static bool IsAction(this UrlHelper helper, string actionName)
{
if (String.IsNullOrEmpty(actionName))
{
throw new ArgumentException("Please specify the name of the action", "actionName");
}
string controllerName = helper.ViewContext.RouteData.GetRequiredString("controller");
return IsAction(helper, actionName, controllerName);
}
/// <summary>
/// Determines if the current view equals the specified action
/// </summary>
/// <param name="helper">Url Helper</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <returns>
/// <c>true</c> if the specified action is the current view; otherwise, <c>false</c>.
/// </returns>
public static bool IsAction(this UrlHelper helper, string actionName, string controllerName)
{
if (String.IsNullOrEmpty(actionName))
{
throw new ArgumentException("Please specify the name of the action", "actionName");
}
if (String.IsNullOrEmpty(controllerName))
{
throw new ArgumentException("Please specify the name of the controller", "controllerName");
}
if (!controllerName.EndsWith("Controller", StringComparison.OrdinalIgnoreCase))
{
controllerName = controllerName + "Controller";
}
bool isOnView = helper.ViewContext.ViewName.SafeEquals(actionName, StringComparison.OrdinalIgnoreCase);
return isOnView && helper.ViewContext.Controller.GetType().Name.Equals(controllerName, StringComparison.OrdinalIgnoreCase);
}
}
A: Here is something a little different, use a FilterAttribute:
[NavigationLocationFilter("Products")]
public ViewResult List()
{
return View();
}
...
public class NavigationLocationFilterAttribute : ActionFilterAttribute
{
public string CurrentLocation { get; set; }
public NavigationLocationFilterAttribute(string currentLocation)
{
CurrentLocation = currentLocation;
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var controller = (Controller)filterContext.Controller;
controller.ViewData.Add("NavigationLocation", CurrentLocation);
}
}
...
And in the view:
<%= ViewData["NavigationLocation"] %>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40535",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.