Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I want to open and manipulate Excel files with ActiveX. I've had success with Python's [Win32 Extensions](http://python.net/crew/mhammond/win32/Downloads.html) and Groovy's [Scriptom](http://groovy.codehaus.org/COM+Scripting) libraries on other projects but need to do this is pure Java this time if possible. I've trie...
Jacob is really the tool for the job here. I recommend that you take the time to learn a bit about how COM and ActiveX work, and I think you'll find that it's easier to use. COM is quite an accomplishment, but it's *hard*. Wrappers like VB make it seem easy (For the limited use that they work for), but it is not at all...
how about <http://www.nevaobject.com/_docs/_java2com/java2com.htm> -- this is commercial but works better.
What's the best/easiest way to manipulate ActiveX objects in Java?
[ "", "java", "com", "activex", "" ]
I use NHibernate for my dataacess, and for awhile not I've been using SQLite for local integration tests. I've been using a file, but I thought I would out the :memory: option. When I fire up any of the integration tests, the database seems to be created (NHibernate spits out the table creation sql) but interfacting wi...
A SQLite memory database only exists as long as the connection to it remains open. To use it in unit tests with NHibernate: 1. Open an ISession at the beginning of your test (maybe in a [SetUp] method). 2. Use the connection from that session in your SchemaExport call. 3. Use that same session in your tests. 4....
I was able to use a SQLite in-memory database and avoid having to rebuild the schema for each test by using SQLite's [support for 'Shared Cache'](http://www.sqlite.org/inmemorydb.html#sharedmemdb), which allows an in-memory database to be shared across connections. I did the following in *AssemblyInitialize* (I'm usin...
Problem using SQLite :memory: with NHibernate
[ "", "c#", "nhibernate", "sqlite", "orm", "integration-testing", "" ]
I'm a Java developer and I have a question about automating a task I've been given. I'm having to 3 times daily, login to this website we have at work, select a few form elements and then click on submit to get a report printed out. I'm wondering how I can write some sort of script that will automate this task? Where...
Check out [cURL](http://php.net/curl) in PHP. It allows you to do all the normal functions of a web browser with code (other than moving the mouse). And yes, you'll need to do screen scraping.
I think the potential sticking point that hasn't been touched on yet is your phrase "login to this website"... Depending on how you need to log in, you may need to go in through a back door to access the report. I had problems with this kind of thing in the past when I had to download a report from a third party site....
Automate getting report from webpage
[ "", "php", "post", "automation", "scripting", "greasemonkey", "" ]
Using C# in Visual Studio 2008 and stepping through a function in the debugger I get to the end of a function and am on the final curly brace } and about to return. Is there a way to find out what value the function is about to return? This is necessary if the return value is calculated such as: ``` return (x.Func() ...
It's a little low level, but if you switch to disassembly then you can single step through the instructions and see what the return value is being set to. It is typically set in the @eax register. You can place a breakpoint on the ret instructions and inspect the register at that point if you don't want to single step...
You can put ``` (x.Func() > y.Func()) ``` in a watch window to evaluate it, and see the result. Unless the statement is ``` return ValueChangesAfterEveryCall(); ``` you should be fine.
How do I discover the return value at the end of a function when debugging in VS2008?
[ "", "c#", "visual-studio-2008", "" ]
We are trying to build a High-Volume Orders Record System. There are three primary tables: 1. Orders 2. OrderDetails 3. OrderShipment The Shipment table contains n record per order and any record shipment entry can be changed before the Customer accepts th order, after which it is frozen. (A business requirement) Alt...
If you are having genuine issues with concurrent updates on the same data, then you might consider performing the entire operation in a transaction - i.e. getting the data *and* committing it. As long as you treat the get/update/commit as a short-lived, atomic operation (i.e. you don't pause for user-input in the middl...
you may want to look into [Entity Framework](http://msdn.microsoft.com/en-us/library/aa697427(VS.80).aspx) which executes everything as a transaction. Here are two podcasts which can also be interesting about Entity Framework. DNRTV - [part 1](http://www.dnrtv.com/default.aspx?showNum=117) - [part 2](http://www.dnrtv....
LINQ to SQL and Concurrency Issues
[ "", "c#", "linq", "linq-to-sql", "concurrency", "transactions", "" ]
I need to get existing web pages into an existing ASP.NET web site project in Visual Studio 2008. I simply tried to drag and drop the whole file folder content into the Visual Studio Solution Explorer or even to copy them into the web site folder. Both ways, Visual Studio seems unable to map the .designer.cs files to ...
It sounds like you are trying to bring web application files into a web site. *IIf that is the case*, The designer files are not even needed. Just dont include them. They are generated and compiled in at runtime when the website runs.
Kind of partially self-answering my question: In a **web project** - in contrast to a **web site** - it works perfectly through drag and drop onto the solution explorer, as I did for the web site before. To make the decision which type of "web site unit" to use there is another thread here on stackoverflow: [ASP.NET W...
Properly using file Designer Files in ASP.NET Web Sites
[ "", "c#", ".net", "asp.net", "visual-studio", "designer", "" ]
I am looking for a way to interact with a standalone full version of Windows Media Player. Mostly I need to know the Path of the currently played track. The iTunes SDK makes this really easy but unfortunately there really isn't any way to do it with Windows Media Player, at least not in .Net(C#) without any heavy us...
I had this <https://social.msdn.microsoft.com/Forums/vstudio/en-US/dbd43d7e-f3a6-4087-be06-df17e76b635d/windows-media-player-remoting-in-c?forum=clr> in my bookmarks but have NOT tested it in anyway. Just a pointer in the right direction. It's nothing official and will require a bit of digging, but you should get a fai...
Just add a reference to wmp.dll (\windows\system32\wmp.dll) ``` using WMPLib; ``` And then you can instantiate a media player ``` var Player = new WindowsMediaPlayer(); // Load a playlist or file and then get the title var title = Player.controls.currentItem.name; ``` See [Creating the Windows Media Player Control...
How to interact with Windows Media Player in C#
[ "", "c#", "windows", "media", "wmp", "" ]
I'm working with my ASP.NET development team to try and create "better" *(i.e. cleaner)* HTML when rendering pages. At the moment, .NET has a nasty tendency to do things like dump JavaScript into the page, making it a mandatory requirement on form controls and not allowing forms to work when JS isn't available. In some...
The ASP.NET MVC Framework would give you a much more familiar separation. Because there is no viewstate, etc in the MVC Framework you won't have to worry about JavaScript being dumped into your pages. The only JavaScript calls you see will be ones that you manually add. You can, for the most part, separate HTML / CSS ...
Depending on the view engine you're going to use. yes. But you can easilly check this by looking at the page-source for stack-overflow. It's not zen-garden but it's pretty clean. Some more clarification: The rendering of the pages is done by the view engine. You can use the standard view engine or existing ones like...
Will .NET MVC give me the HTML/CSS/JS separation I need?
[ "", "javascript", "html", "css", "asp.net-mvc", "" ]
Is it better to do this: ``` try { ... } catch (Exception ex) { ... throw; } ``` Or this: ``` try { ... } catch (Exception ex) { ... throw ex; } ``` Do they do the same thing? Is one better than the other?
You should always use the following syntax to rethrow an exception. Else you'll stomp the stack trace: ``` throw; ``` If you print the trace resulting from `throw ex`, you'll see that it ends on that statement and not at the real source of the exception. Basically, it should be deemed a criminal offense to use `thro...
My preferences is to use ``` try { } catch (Exception ex) { ... throw new Exception ("Add more context here", ex) } ``` This preserves the original error, but it allows you to add more context, such as an object ID, a connection string, and stuff like that. Often my exception reporting tool will have five c...
What is the proper way to rethrow an exception in C#?
[ "", "c#", ".net", "exception", "" ]
I am in a project where we are starting refactoring some massive code base. One problem that immediately sprang up is that each file imports a lot of other files. How do I in an elegant way mock this in my unit test without having to alter the actual code so I can start to write unit-tests? As an example: The file wit...
If you want to import a module while at the same time ensuring that it doesn't import anything, you can replace the `__import__` builtin function. For example, use this class: ``` class ImportWrapper(object): def __init__(self, real_import): self.real_import = real_import def wrapper(self, wantedModu...
"imports a lot of other files"? Imports a lot of other files that are part of your customized code base? Or imports a lot of other files that are part of the Python distribution? Or imports a lot of other open source project files? If your imports don't work, you have a "simple" `PYTHONPATH` problem. Get all of your v...
Python, unit-testing and mocking imports
[ "", "python", "unit-testing", "refactoring", "python-import", "" ]
I'm trying to setup an Apache/PHP/Postgresql server locally on my machine. I'm using Windows vista business 32bit. I tried to install everything manually (one thing at a time, apache, postgresql and php (all the latest stable releases)) and after I get everything up and running. Whenever I try to run a script on my ma...
You should have something like this in your httpd.conf file: ``` LoadModule php5_module "c:/php/php5apache2_2.dll" AddType application/x-httpd-php .php PHPIniDir "c:/php" ``` Make sure that's in place, and don't forget to restart apache! In Windows, the default location for your conf file is `C:\Program Files\Apache...
You can also have a look at the official page of PHP in the [install section](http://hu.php.net/manual/en/install.php). There is a closer link if you are on [Windows](http://hu.php.net/manual/en/install.windows.php). And you can also use some precompiled installer for this like [XAMMP](http://www.apachefriends.org/en...
Setting up local server with PHP
[ "", "php", "apache", "localhost", "" ]
How can I read the colors of an image with python using google app engine? **Example:** I like to build a function to determine the most striking colors of an image to set a harmonic background color for it.
The [Images API](http://code.google.com/appengine/docs/images/overview.html) does not (currently) contain pixel-level functions. To quote the overview document: > Note: In order to use the Images API in your local environment you must first download and install PIL, the Python Imaging Library. PIL is not available on ...
For PNG you can use [PyPNG module](http://packages.python.org/pypng/) - lightweight pure-Python PNG decoder/encoder. ``` import png point = (10, 20) # coordinates of pixel to read reader = png.Reader(filename='image.png') # streams are also accepted w, h, pixels, metadata = reader.read() pixel_byte_width = 4 if meta...
Read colors of image with Python (GAE)
[ "", "python", "google-app-engine", "image", "analysis", "" ]
[Loop unwinding](http://en.wikipedia.org/wiki/Loop_unwinding) is a common way to help the compiler to optimize performance. I was wondering if and to what extent the performance gain is affected by what is in the body of the loop: 1. number of statements 2. number of function calls 3. use of complex data types, virtua...
In general unrolling loops by hand is not worth the effort. The compiler knows better how the target architecture works and will unroll the loop if it is beneficial. There are code-paths that benefit when unrolled for Pentium-M type CPU's but don't benefit for Core2 for example. If I unroll by hand the compiler can't ...
This is an optimisation question, and as such there is only one rule of thumb: test the performance, and try a loop unwinding optimisation *only* if your testing demonstrates that you need to. Consider less disruptive optimisations first.
When is loop unwinding effective?
[ "", "c++", "performance", "algorithm", "optimization", "" ]
Is there a way to check to see if a date/time is valid you would think these would be easy to check: ``` $date = '0000-00-00'; $time = '00:00:00'; $dateTime = $date . ' ' . $time; if(strtotime($dateTime)) { // why is this valid? } ``` what really gets me is this: ``` echo date('Y-m-d', strtotime($date)); ``` r...
From [php.net](http://php.net/manual/en/function.checkdate.php#78362) ``` <?php function isValidDateTime($dateTime) { if (preg_match("/^(\d{4})-(\d{2})-(\d{2}) ([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$/", $dateTime, $matches)) { if (checkdate($matches[2], $matches[3], $matches[1])) { return...
As mentioned here: <https://bugs.php.net/bug.php?id=45647> > There is no bug here, 00-00-00 means 2000-00-00, which is 1999-12-00, > which is 1999-11-30. No bug, perfectly normal. And as shown with a few tests, rolling backwards is expected behavior, if a little unsettling: ``` >> date('Y-m-d', strtotime('2012-03-00...
php check for a valid date, weird date conversions
[ "", "php", "date", "time", "strtotime", "" ]
We currently use a hand-rolled setup and configuration script and a hand-rolled continuous integration script to build and deploy our application. I am looking at formalizing this somewhat with a third party system designed for these purposes. I have looked into Phing before, and I get that it's basically like Ant. Bu...
phing is pretty much ant written in PHP where phpUnderControl adds support for PHP projects to CruiseControl and uses phing or ant on the backend to parse the build.xml file and run commands. I just set up CruiseControl and phpUnderControl and it's been working great. It checks out my SVN, runs it through phpDocumento...
I'm sure lots of people will say this by the time I've typed this but... I know it's not PHP but we're finding [Capistrano](http://www.capify.org/) just the job for this kind of thing. It really is an excellent piece of software.
What's the difference between Phing and PHPUnderControl?
[ "", "php", "continuous-integration", "phpunit", "cruisecontrol", "phing", "" ]
I have a UserControl in my Asp.net project that has a public property. I do not want this property to show up in the Visual Studio Property Window when a user highlights an instance of the UserControl in the IDE. What attribute (or other method) should I use to prevent it from showing up? ``` class MyControl : System....
Use the following attribute ... ``` using System.ComponentModel; [Browsable(false)] public bool SampleProperty { get; set; } ``` In VB.net, this [will be](https://stackoverflow.com/questions/71440/set-a-usercontrol-property-to-not-show-up-in-vs-properties-window#71481): ``` <System.ComponentModel.Browsable(False)> ...
[Tons of attributes](http://www.c-sharpcorner.com/UploadFile/mgold/PropertyGridInCSharp11302005004139AM/PropertyGridInCSharp.aspx) out there to control how the PropertyGrid works. ``` [Browsable(false)] public bool HiddenProperty {get;set;} ```
Set a UserControl Property to Not Show Up in VS Properties Window
[ "", "c#", "asp.net", "visual-studio", "properties", "attributes", "" ]
What are the best workarounds for using a SQL `IN` clause with instances of `java.sql.PreparedStatement`, which is not supported for multiple values due to SQL injection attack security issues: One `?` placeholder represents one value, rather than a list of values. Consider the following SQL statement: ``` SELECT my_...
An analysis of the various options available, and the pros and cons of each is available in Jeanne Boyarsky's *[Batching Select Statements in JDBC](http://www.javaranch.com/journal/200510/Journal200510.jsp#a2)* entry on JavaRanch Journal. The suggested options are: * Prepare `SELECT my_column FROM my_table WHERE sear...
Solution for PostgreSQL: ``` final PreparedStatement statement = connection.prepareStatement( "SELECT my_column FROM my_table where search_column = ANY (?)" ); final String[] values = getValues(); statement.setArray(1, connection.createArrayOf("text", values)); try (ResultSet rs = statement.executeQuery()) { ...
PreparedStatement IN clause alternatives?
[ "", "java", "security", "jdbc", "prepared-statement", "in-clause", "" ]
`My ISP` account requires that I send a username & password for outbound `SMTP` mail. How do I get `PHP` to use this when executing `php.mail()?` The `php.ini` file only contains entries for the server `(SMTP= )` and `From: (sendmail_from= )`.
PHP `mail()` command does not support authentication. Your options: 1. [PHPMailer](http://sourceforge.net/projects/phpmailer)- [Tutorial](http://phpmailer.codeworxtech.com/index.php?pg=tutorial#2) 2. [PEAR](http://pear.php.net/package/Mail) - [Tutorial](http://email.about.com/od/emailprogrammingtips/qt/et073006.htm) 3...
I apply following details on php.ini file. its works fine. ``` SMTP = smtp.example.com smtp_port = 25 username = info@example.com password = yourmailpassord sendmail_from = info@example.com ``` These details are same as on outlook settings.
php.ini & SMTP= - how do you pass username & password
[ "", "php", "smtp", "email", "" ]
I'm writing a small article on humanly readable alternatives to Guids/UIDs, for example those used on TinyURL for the url hashes (which are often printed in magazines, so need to be short). The simple uid I'm generating is - 6 characters: either a lowercase letter (a-z) or 0-9. "According to my calculations captain",...
The probability of a collision against one specific ID is: ``` p = ( 0.5 * ( (0.5*1/10) + (0.5*1/26) ) )^6 ``` which is around 1.7×10^-9. The probability of a collision after generating n IDs is 1-p^n, so you'll have roughly a 0.17% chance of a collision for each new insertion after 1 million IDs have been inserted,...
Why do you want to use a random function? I always assumed that tinyurl used a base 62 (0-9A-Za-z) representation of a sequential Id. No clashes and the urls are always as short as possible. You would have a DB table like ``` Id URL 1 http://google.com 2 ... ... ... 156 ... ... ... ``` and the corresponding URL...
Creating your own Tinyurl style uid
[ "", "c#", "algorithm", "probability", "" ]
Given this data set: ``` ID Name City Birthyear 1 Egon Spengler New York 1957 2 Mac Taylor New York 1955 3 Sarah Connor Los Angeles 1959 4 Jean-Luc Picard La Barre 2305 5 Ellen Ripley Nostromo 2092 6 James T. Kirk Riverside 2233 7 ...
Probably not the most elegant of solutions, and the performance of `IN` may suffer on larger tables. The nested query gets the minimum `Birthyear` for each city. Only records who have this `Birthyear` are matched in the outer query. Ordering by age then limiting to 3 results gets you the 3 oldest people who are also t...
This is probably not the most elegant and quickest solution, but it should work. I am looking forward the see the solutions of real database gurus. ``` select p.* from people p, (select city, max(age) as mage from people group by city) t where p.city = t.city and p.age = t.mage order by p.age desc ```
MySQL: Select N rows, but with only unique values in one column
[ "", "sql", "mysql", "unique", "aggregate-functions", "min", "" ]
I have a Java application that's very String-heavy - it takes a feed of huge numbers of big, different String objects. Do I need to worry about the String Constant Pool for memory and performance? Is there any way to see how big the pool is at any point?
As Mario said, the constant pool is only relevant to intern()ed Strings, and to Strings that are constants in java code (these are implicitly interned). But there is one more caveat that might apply to your case: The `substring()` method will share the underlying `char[]` with the original String. So the pattern ``` ...
If it is a feed of objects, then they do not go into the String constant pool unless you call intern(), as far as I know. The memory consumption for interned strings is not from the Heap, but from the Perm Gen memory space, so if you intern a lot of strings the application will crash with OutOfMemory, even if there is ...
Do I need to worry about the String Constant Pool?
[ "", "java", "string", "" ]
I'm just getting started with Custom User Controls in C# and I'm wondering if there are any examples out there of how to write one which accepts nested tags? For example, when you create an `asp:repeater` you can add a nested tag for `itemtemplate`.
I wrote a [blog post](https://robertwray.co.uk/blog/describing-asp-net-control-properties-declaratively) about this some time ago. In brief, if you had a control with the following markup: ``` <Abc:CustomControlUno runat="server" ID="Control1"> <Children> <Abc:Control1Child IntegerProperty="1" /> </Chi...
I followed Rob's blog post, and made a slightly different control. The control is a conditional one, really just like an if-clause: ``` <wc:PriceInfo runat="server" ID="PriceInfo"> <IfDiscount> You don't have a discount. </IfDiscount> <IfNotDiscount> Lucky you, <b>you have a discount!</b> ...
ASP Nested Tags in a Custom User Control
[ "", "c#", ".net", "asp.net", "custom-server-controls", "" ]
Is there a way to find out what gcc flags a particular binary was compiled with?
A quick look at the GCC documentation doesn't turn anything up. The Boost guys are some of the smartest C++ developers out there, and they [resort](http://www.boost.org/doc/libs/1_36_0/more/getting_started/unix-variants.html#library-naming) to naming [conventions](http://www.boost.org/doc/libs/1_36_0/more/getting_star...
Experimental proof: ``` diciu$ gcc -O2 /tmp/tt.c -o /tmp/a.out.o2 diciu$ gcc -O3 /tmp/tt.c -o /tmp/a.out.o3 diciu$ diff /tmp/a.out.o3 /tmp/a.out.o2 diciu$ ``` I take that as a no as the binaries are identical.
Detect GCC compile-time flags of a binary
[ "", "c++", "c", "gcc", "" ]
I wonder if this would be doable ? To insert an array into one field in the database. For instance I have a title, I want to have that title with only one id, but it's going to be bilingually used on the website. It feels a bit unnecessary to make another table to have their global ids and then another table with the...
it's doable: ``` $title = serialize($array); ``` and then to decode: ``` $title = unserialize($mysql_data); ``` but as mentioned it really lessens the benefits of a database in the first place. i'd definitely suggest looking into a multi-table or multi-column option instead, depending on the amount of languages you...
There's really only two reasonable choices here: **Join with another table** pros: unlimited titles in unlimited languages cons: join overhead is more computationally expensive, SQL is marginally more complex to update/insert etc **Multiple columns** eg: TITLE\_EN, TITLE\_NL, TITLE\_DE pros: fast to insert, s...
Insert array into database in a single row
[ "", "php", "mysql", "database", "arrays", "internationalization", "" ]
You can, obviously, put a variable declaration in a for loop: ``` for (int i = 0; ... ``` and I've noticed that you can do the same thing in if and switch statements as well: ``` if ((int i = f()) != 0) ... switch (int ch = stream.get()) ... ``` But when I try to do the same thing in a while loop: ``` while ((int...
The grammar for a condition in the '03 standard is defined as follows: ``` condition: expression type-specifier-seq declarator = assignment-expression ``` The above will therefore only allow conditions such as: ``` if ( i && j && k ) {} if ( (i = j) ==0 ) {} if ( int i = j ) {} ``` The standard allows the condi...
The problem is, the standard permits you a *declaration* inside parenthesis. What you want to do is to get a declaration as part of expression, which is something that standard will not let you do. while() can have one of two syntaxes: while(<declaration>) or while(<expression>). The declaration uses "=", and looks li...
Why can't I put a variable declaration in the test portion of a while loop?
[ "", "c++", "" ]
I'm looking for way to PHP to detect if a script was run from a manual invocation on a shell (me logging in and running it), or if it was run from the crontab entry. I have various maintenance type scripts written in php that i have set to run in my crontab. Occasionally, and I need to run them manually ahead of sched...
Instead of detecting when the script is run from the crontab, it's probably easier to detect when you're running it manually. There are a lot of environment variables (in the $\_ENV array) that are set when you run a script from the command line. What these are will vary depending on your sever setup and how you log i...
``` if (php_sapi_name() == 'cli') { if (isset($_SERVER['TERM'])) { echo "The script was run from a manual invocation on a shell"; } else { echo "The script was run from the crontab entry"; } } else { echo "The script was run from a webserver, or something else"; } ```
Can PHP detect if its run from a cron job or from the command line?
[ "", "php", "cron", "" ]
I'm just starting with CodeIgniter, and I am not sure where things such as css, js, and images should go. Outside the whole system folder seems ok, but that means everything is seperate. Inside means the filepaths are longer, and I'm worried that it might mess things up. What's the best practice on this issue?
I usually put separate folders at the root level, so I end up with a directory structure like this: ``` /system /css /js /img ``` Seems to work for me - when you use `site_url(url)`, the URL it generates is from the root, so you can use `site_url('css/file.css')` to generate URLs to your stylesheets etc.
Personally, I rip the `application` directory out of the `system` directory and make it a sibling to `system`. I then create a project directory in `public_html (www)` where I move index.php and store my public assets. Let's assume the project you're working on is called `projekt`. In the parent directory to `public_h...
Where should assets go in a CodeIgniter project?
[ "", "php", "codeigniter", "" ]
I need to take a paragraph of text and extract from it a list of "tags". Most of this is quite straight forward. However I need some help now stemming the resulting word list to avoid duplicates. Example: Community / Communities I've used an implementation of Porter Stemmer algorithm (I'm writing in PHP by the way): ...
The core issue here is that stemming algorithms operate on a phonetic basis purely based on the language's spelling rules with no actual understanding of the language they're working with. To produce real words, you'll probably have to merge the stemmer's output with some form of lookup function to convert the stems ba...
If I understand correctly, then what you need is not a stemmer but a lemmatizer. Lemmatizer is a tool with knowledge about endings like *-ies*, *-ed*, etc., and exceptional wordforms like *written*, etc. Lemmatizer maps the input wordform to its lemma, which is guaranteed to be a "real" word. There are many lemmatizer...
Stemming algorithm that produces real words
[ "", "php", "nlp", "stemming", "snowball", "porter-stemmer", "" ]
In our web-app we use PHP5.2.6 + PDO to connect to a SQL Server 2005 database and store Russian texts. Database collation is `Cyrillic_General_CI_AS`, table collation is `Cyrillic_General_CI_AS`, column type is `NVARCHAR(MAX)`. We tried connecting to a database using two following schemes, both causing different prob...
Try executing `SET NAMES "charset"` after you connect. I don't know what the charset to match `Cyrillic_General_CI_AS` is, but try "Cyrillic"?
I had to do this to get usable data from my NVARCHAR fields in MSSQL: ``` $_ = iconv('Windows-1252', 'UTF-8', $_); ```
PHP/PDO and SQL Server connection and i18n issues
[ "", "php", "sql-server", "sql-server-2005", "" ]
This is pretty simple, I come from a swing/awt background. I'm just wondering what the proper way to set the background color for a SWT widget is? I've been trying: ``` widget.setBackground( ); ``` Except I have no idea how to create the color Object in SWT?
To create a color, try this: ``` Device device = Display.getCurrent (); Color red = new Color (device, 255, 0, 0); ```
For standard colors (including common colors and default colors used by the operating system) Use `Display.getSystemColor(int)`, and pass in the `SWT.COLOR_*` constant for the color you want. ``` Display display = Display.getCurrent(); Color blue = display.getSystemColor(SWT.COLOR_BLUE); Color listBackground = display...
Setting Colors in SWT
[ "", "java", "swt", "colors", "" ]
I have a function that is declared and defined in a header file. This is a problem all by itself. When that function is not inlined, every translation unit that uses that header gets a copy of the function, and when they are linked together there are duplicated. I've "fixed" that by making the function `inline`, but I...
I guess you're missing something, here. ## static function? Declaring a function static will make it "hidden" in its compilation unit. > A name having namespace scope (3.3.6) has internal linkage if it is the name of > > — a variable, function or function template that is explicitly declared static; > > 3.5/3 - C++1...
I believe the compiler creates many copies of the variable, but the linker picks one and makes all the others reference it. I had similar results when I tried an experiment to create different versions of an inline function; if the function wasn't actually inlined (debug mode), all calls went to the same function regar...
What happens to static variables in inline functions?
[ "", "c++", "header", "linker", "inline-functions", "" ]
Let's assume we've got the following Java code: ``` public class Maintainer { private Map<Enum, List<Listener>> map; public Maintainer() { this.map = new java.util.ConcurrentHashMap<Enum, List<Listener>>(); } public void addListener( Listener listener, Enum eventType ) { List<Listener> listen...
What would be wrong with doing something like the following: Defining a 'Maintainer' interface with the addListener(Listener, Enum) method. Create a DefaultMaintainer class (as above) which implements Maintainer. Then, in each Listener class, 'inject' the Maintainer interface (constructor injection might be a good c...
Slightly offtopic (as this is not about Spring) but there is a race condition in your implementation of AddListener: ``` if( ( listeners = map.get( eventType ) ) == null ) { listeners = new java.util.concurrent.CopyOnWriteArrayList<Listener>(); map.put( eventType, listeners ); } listeners.add( listener...
Map of Enums and dependency injection in Spring 2.5
[ "", "java", "spring", "enums", "maps", "" ]
I know we cannot do this at class level but at method level we can always do this. ``` var myList=new List<string> // or something else like this ``` This question came to my mind since wherever we declare variable like this. We always provide the type information at the RHS of the expression. So compiler doesn't nee...
There are technical issues with implementing this feature. The common cases seem simple but the tougher cases (e.g., fields referencing other fields in chains or cycles, expressions which contain anonymous types) are not. See Eric Lippert's blog for an in-depth explanation: [Why no var on fields?](http://blogs.msdn.co...
The compiler guys just didn't implement the support. It's entirely compiler magic, and the compiler doesn't actually put something into IL that says "figure out the type at runtime", it knows the type and builds it in, so it could've done that for members as well. It just doesn't. I'm pretty sure that if you asked a...
Why can't we declare var a = new List<string> at class level?
[ "", "c#", "" ]
So I'm using hibernate and working with an application that manages time. What is the best way to deal with times in a 24 hour clock? I do not need to worry about TimeZone issues at the beginning of this application but it would be best to ensure that this functionality is built in at the beginning. I'm using hiberna...
Store them as long ts = System.currentTimeMillis(). That format is actually TimeZone-safe as it return time in UTC. If you only need time part, well, I'm not aware of built-in type in Hib, but writing your own type Time24 is trivial -- just implement either org.hibernate.UserType or org.hibernate.CompositeUserType (lo...
I would suggest you look into using Joda, <http://joda-time.sourceforge.net/>, which offers much more intuitive and controllable time handling functionality than the core Date and Calendar implementations. JSR 310 is actually a proposition to include a new time API into java 7 that will be based largely on Joda. Joda a...
What is the best way to manage Time in a Java application?
[ "", "java", "hibernate", "" ]
How can I find out which column and value is violating the constraint? The exception message isn't helpful at all: > Failed to enable constraints. One or > more rows contain values violating > non-null, unique, or foreign-key > constraints.
There is a property called RowError you can check. See <http://dotnetdebug.net/2006/07/16/constraintexception-a-helpful-tip/> Edited to add this link showing iteration of rows to see which had errors. <http://www.devnewsgroups.net/group/microsoft.public.dotnet.framework.adonet/topic58812.aspx>
Like many people, I have my own standard data access components, which include methods to return a DataSet. Of course, if a ConstraintException is thrown, the DataSet isn't returned to the caller, so the caller can't check for row errors. What I've done is catch and rethrow ConstraintException in such methods, logging...
What triggers ConstraintException when loading DataSet?
[ "", "c#", ".net", "dataset", "" ]
I want to intercept a request in a filter/servlet and add a few parameters to it. However, the request does not expose a 'setParameter' method and the parameter map when manipulated throws an error saying it is locked. Is there an alternative I can try?
Subclass [`HttpServletRequestWrapper`](http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/servlet/http/HttpServletRequestWrapper.html) and override the `getParameter` methods. The description of this class reads: > Provides a convenient implementation of the HttpServletRequest interface that can be subclassed by deve...
I ussualy wrap the original HttpServletRequest into a new CustomHttpServletRequest that acts as a proxy to the original request and then pass this new CustomHttpServletRequest to the filter chain. In this CustomHttpServletRequest you can overide the getParameterNames, getParameter, getParameterMap methods to return an...
Is it possible to add to the available parameters of a request (HttpServletRequest)
[ "", "java", "http", "servlets", "" ]
I'm hoping to find out what tools folks use to synchronize data between databases. I'm looking for a JDBC solution that can be used as a command-line tool. There used to be a tool called Sync4J that used the SyncML framework but this seems to have fallen by the wayside.
I have heard that the Data Replication Service provided by Db4O is really good. It allows you to use Hibernate to back onto a RDBMS - I don't think it supports JDBC tho (<http://www.db4o.com/about/productinformation/drs/Default.aspx?AspxAutoDetectCookieSupport=1>) There is an open source project called Daffodil, but I...
If you have a model and DAO layer that exists already for your codebase, you can just create your own sync framework, it isn't hard. Copy data is as simple as: 1. read an object from database A 2. remove database metadata (uuid, etc) 3. insert into database B Syncing has some level of knowledge about what has been s...
What JDBC tools do you use for synchronization of data sources?
[ "", "java", "database", "jdbc", "synchronization", "" ]
I have found some libraries or web services in PHP that does the job. The problem is that the conversion is done when the page is fully loaded, I would like to **convert the page to PDF** **after some content dynamically added via AJAX** in onload event. Thank you very much, Omar
Wow, thank you everyone I didn't know that this is comunity is so active. To answer Beepcake about the project: When the page loads the app retrieves, from more than 40 servers, biological information via AJAX request, then a unique view is displayed where you can manipulate the graphic with many options. So, the coo...
You could post back `document.getElementsByTagName('html')[0].innerHTML` to the server (possibly using AJAX) and generate a PDF from that.
How can I convert my current page to pdf after some content dynamically added via AJAX?
[ "", "php", "ajax", "pdf", "" ]
See code: ``` var file1 = "50.xsl"; var file2 = "30.doc"; getFileExtension(file1); //returns xsl getFileExtension(file2); //returns doc function getFileExtension(filename) { /*TODO*/ } ```
**Newer Edit:** Lots of things have changed since this question was initially posted - there's a lot of really good information in [wallacer's revised answer](https://stackoverflow.com/a/1203361/23746) as well as [VisioN's excellent breakdown](https://stackoverflow.com/a/12900504/23746) --- **Edit:** Just because thi...
``` return filename.split('.').pop(); ``` **Edit:** This is another non-regex solution that I think is more efficient: ``` return filename.substring(filename.lastIndexOf('.')+1, filename.length) || filename; ``` There are some corner cases that are better handled by [VisioN's answer](https://stackoverflow.com/a/129...
How can I get file extensions with JavaScript?
[ "", "javascript", "file-extension", "" ]
Just wondering if there is an easy way to add the functionality to duplicate an existing listing in the admin interface? In data entry we have run into a situation where a lot of items share generic data with another item, and to save time it would be very nice to quickly duplicate an existing listing and only alter t...
You can [save as](http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.save_as) by just enabling adding this to your ModelAdmin: ``` save_as = True ``` This replaces the "Save and add another" button with a "Save as" button. "Save as" means the object will be saved as a new object (...
There's a better (but not built-in) solution here: <https://github.com/RealGeeks/django-modelclone> From their README: > Django Admin has a `save_as` feature that adds a new button to your > Change page to save a new instance of that object. > > I don't like the way this feature works because you will save an > iden...
In the Django admin interface, is there a way to duplicate an item?
[ "", "python", "django", "django-models", "django-admin", "" ]
We've used the no-longer-supported RichTextBox control as part of our (ASP.NET-based) CMS for a long time, and we'd like to replace it with something lighter-weight and with better cross-browser support. We were originally looking at various ASP.NET components, but I'm wondering if we'd be better off just using an open...
I've used [TinyMCE](http://tinymce.moxiecode.com/). Great across browsers; easy to configure to be extremely light weight and allows you to control what your user can do. Some of the plug-ins (such as the image manager) are great and easy to implement. Nice that it also support the Google Spellchecker so you don't need...
I've used [FCKeditor](http://ckeditor.com/), it's a good editor. Pretty easy to use. The newer versions have very good cross browser support.
Unobtrusive Javascript rich text editor?
[ "", "asp.net", "javascript", "jquery", "" ]
How do we decide on the best implementation of `hashCode()` method for a collection (assuming that equals method has been overridden correctly) ?
The best implementation? That is a hard question because it depends on the usage pattern. A for nearly all cases reasonable good implementation was proposed in *Josh Bloch*'s ***Effective Java*** in Item 8 (second edition). The best thing is to look it up there because the author explains there why the approach is goo...
If you're happy with the Effective Java implementation recommended by dmeister, you can use a library call instead of rolling your own: ``` @Override public int hashCode() { return Objects.hash(this.firstName, this.lastName); } ``` This requires either Guava (`com.google.common.base.Objects.hashCode`) or the stan...
Best implementation for hashCode method for a collection
[ "", "java", "hash", "equals", "hashcode", "" ]
What are the possibilities to enforce restrictions on the package dependencies in a Java build system? For example, the `myapp.server.bl.Customer` class should not be allowed to refer to the `myapp.client.ui.customlayout` package. I'm interested in either Ant-based or IDE-specific solutions. I'd like to get an error m...
I believe Checkstyle has a check for that. It's called [Import Control](http://checkstyle.sourceforge.net/config_imports.html#ImportControl "Checkstyle Documentation")
You can configure Eclipse projects to specify Access Rules. Access rules can specify "Forbidden", "Discouraged", and "Accessible" levels all with wildcard rules. You can then configure violations of either Discouraged or Forbidden to be flagged as either warnings or errors during builds. Kind of an old article on the ...
Restrict dependencies between Java packages
[ "", "java", "build-process", "dependency-management", "" ]
While writing a file using ofstream, how do I know when the file's size has reached the OS' maximum file size - more specifically linux's maximum file size - ??
First off, maximum file size is a filesystem limit, not an Operating System limit. It will even vary for a particular filesystem, based on how the filesystem was formatted. As for how you'd figure out that you'd reached the limit, your code will likely throw an exception when that happens, which you'll then be able to...
You can check if [the bad bit is set](http://www.cplusplus.com/reference/iostream/ios/bad.html). Also, using [exceptions](http://www.cplusplus.com/reference/iostream/ios/exceptions.html) you can force the stream to throw an exception, when the bad bit gets set.
How do I know I reached a file's maximum size when using ofstream?
[ "", "c++", "linux", "" ]
I have an application which is a portal application and I want to allow other users add their applications to it. In order to do this I need some way to be able to access their applications in mine. Is this possible?
You cannot put WARs inside of other WARs. You need an EAR file to contain WARs, EJBs, etc. One way to implement inter-WAR communication is to package that logic directly in the EAR. It all depends on what you're trying to do.
the way to do inter .WAR communication is by the method <http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/ServletContext.html#getContext(java.lang.String)> ServletContext.getContext(URIOfOtherWAR\_resource) I've used this succesfully for doing what you're talking about.
Is it possible to include/embed one Java EE application(war file) inside another?
[ "", "java", "jakarta-ee", "war", "" ]
I got a bunch of servlet context listeners in my Java webapp, each of them gathering some information about the environment. Some of them depend on information which is gathered by another listener. But I can't determine the order in which the listeners are registered and called, so I have to duplicate code. I unders...
All servlet containers and Java EE containers implement this part of the spec strictly. You can rely on the fact that the listeners are called in the order you specified in web.xml. You can have a Application LEVEL Data structure(HashMap) that will be updated by each Filter/Listener as it encounters the data from the ...
Why is that vague? The ordering in web.xml is very specifically the order in which they are called, it's very clearly stated in the Java EE spec. It's completely OK to rely on it.
How to determine the order of listeners in web.xml
[ "", "java", "servlets", "jakarta-ee", "" ]
I need to do a join across two different database servers (IPs 10.0.0.50 and 10.0.0.51). What's the best way?
You need to use sp\_linkedserver to create a linked server. ``` sp_addlinkedserver [ @server= ] 'server' [ , [ @srvproduct= ] 'product_name' ] [ , [ @provider= ] 'provider_name' ] [ , [ @datasrc= ] 'data_source' ] [ , [ @location= ] 'location' ] [ , [ @provstr= ] 'provider_string' ] [ , [ @catalog= ] 'catalog...
The solution I found: 1) Run a [stored proc](http://msdn.microsoft.com/en-us/library/aa259589(SQL.80).aspx) ``` exec sp_addlinkedserver @server='10.0.0.51' ``` 2) Verify that the servers were linked (lists linked servers) ``` exec sp_linkedservers ``` 3) Run the query using the format ``` [10.0.0.51].Database...
How do I create and query linked database servers in SQL Server?
[ "", "sql", "sql-server", "database", "" ]
When I type 'from' (in a [LINQ](http://en.wikipedia.org/wiki/Language_Integrated_Query) query) after importing [System.Linq namespace](http://msdn.microsoft.com/en-us/library/system.linq.aspx), it is understood as a keyword. How does this magic happen? Is 'from' a extension method on some type?
In practice, yes - LINQ keywords map to extension methods. But actually, it is more interesting; it is literally as though the compiler substitutes directly for a few key methods, i.e. ``` var qry = from cust in db.Customers where cust.IsActive select cust; ``` becomes: ``` var qry = db.Customers...
Marc Gravell has [answered the question admirably](https://stackoverflow.com/questions/190936/how-is-fromwhereselect-keywords-impemented-under-the-hood-clinq#190948), but I can't resist the temptation to mention the [weird things you can do with query expressions](http://msmvps.com/blogs/jon_skeet/archive/2008/02/29/od...
How is 'from/where/select' keywords impemented under the hood in LINQ and C#?
[ "", "c#", ".net", "linq", "" ]
Designing a new system from scratch. I'll be using the STL to store lists and maps of certain long-live objects. Question: Should I ensure my objects have copy constructors and store copies of objects within my STL containers, or is it generally better to manage the life & scope myself and just store the pointers to t...
Since people are chiming in on the efficency of using pointers. If you're considering using a std::vector and if updates are few and you often iterate over your collection and it's a non polymorphic type storing object "copies" will be more efficent since you'll get better locality of reference. Otoh, if updates are ...
This really depends upon your situation. If your objects are small, and doing a copy of the object is lightweight, then storing the data inside an stl container is straightforward and easier to manage in my opinion because you don't have to worry about lifetime management. If you objects are large, and having a defau...
Should I store entire objects, or pointers to objects in containers?
[ "", "c++", "stl", "pointers", "" ]
I have an script that receives an encrypted url and from that generates a download, the most critic par of the script is this: ``` $MimeType = new MimeType(); $mimetype = $MimeType->getType($filename); $basename = basename($filename); header("Content-type: $mimetype"); header("Content-Disposition: attachment; filename...
[This site](http://bytes.com/forum/thread554529.html) has a problem similar to yours in IE6. To summarize: > session\_start() by default sends a cache control header including "no-store". > Internet Explorer takes this a bit too literally, but doesn't have appropriate > error handling for the case, and as a result exp...
I solved it by sending the headers ``` header('Pragma: public'); header('Cache-Control: max-age=0'); ``` I didn't knew that session\_start() send headers by it's own. I found the answer in the comments section of: [Error: Internet Explorer Cannot Download FileName from WebServer](http://www.alagad.com/go/blog-entry/...
Can't download file in IE7 but there isn't any issue in Firefox, Chrome, etc..?
[ "", "php", "internet-explorer-7", "download", "" ]
How can I detect if the internet connection is offline in JavaScript?
[Almost all major browsers](https://caniuse.com/#feat=online-status) now support the [`window.navigator.onLine`](https://developer.mozilla.org/en-US/docs/Web/API/NavigatorOnLine.onLine) property, and the corresponding `online` and `offline` window events. Run the following code snippet to test it: ``` console.log('Ini...
You can determine that the connection is lost by making **failed XHR requests**. The standard approach is to **retry the request** a few times. If it doesn't go through, **alert the user** to check the connection, and **fail gracefully**. **Sidenote:** To put the entire application in an "offline" state may lead to a...
Detect if the internet connection is offline?
[ "", "javascript", "ajax", "offline", "connectivity", "internet-connection", "" ]
I want to create a script that parses or makes sense of apache's error log to see what the most recent error was. I was wondering if anyone out there has something that does this or has any ideas where to start?
There are a few things to consider first: 1. Firstly, your PHP user may not have access to Apache's log files. 2. Secondly, PHP and Apache aren't going to tell you where said log file is, 3. Lastly, Apache log files can get quite large. However, if none of these apply, you can use the normal file reading commands to ...
for anyone else looking for a sample script, i threw something together, it's got the basics: ``` <?php exec('tail /usr/local/apache/logs/error_log', $output); ?> <Table border="1"> <tr> <th>Date</th> <th>Type</th> <th>Client</th> <th>Message</th> </tr> <? foreach($output as...
How can I parse Apache's error log in PHP?
[ "", "php", "apache", "error-log", "" ]
I am totally new to `SQL`. I have a simple select query similar to this: ``` SELECT COUNT(col1) FROM table1 ``` There are some 120 records in the table and shown on the `GUI`. For some reason, this query always returns a number which is less than the actual count. Can somebody please help me?
You might have some null values in col1 column. Aggregate functions ignore nulls. try this ``` SELECT COUNT(ISNULL(col1,0)) FROM table1 ```
Try ``` select count(*) from table1 ``` **Edit:** To explain further, `count(*)` gives you the rowcount for a table, including duplicates and nulls. `count(isnull(col1,0))` will do the same thing, but *slightly* slower, since `isnull` must be evaluated for each row.
Not getting the correct count in SQL
[ "", "sql", "sql-server-2005", "t-sql", "" ]
I've got a bunch of servers running this Linux app. I'd like for them to be able to generate a GUID with a low probability of collision. I'm sure I could just pull 128 bytes out of /dev/urandom and that would probably be fine, but is there a simple & easy way to generate a GUID that is more equivalent to the Win32 one?...
This [Internet Draft](http://www.webdav.org/specs/draft-leach-uuids-guids-01.txt) describes one type of UUID in great details and I have used a similar approach with great success when I needed a UUID implementation and could not link to an existing library for architectural reasons. This [article](http://en.wikipedia...
There is [libuuid](http://linux.die.net/man/3/libuuid).
GUIDs in a C++ Linux GCC app
[ "", "c++", "linux", "gcc", "guid", "" ]
So I've got an application whose window behavior I would like to behave more like Photoshop CS. In Photoshop CS, the document windows always stay behind the tool windows, but are still top level windows. For MDI child windows, since the document window is actually a child, you can't move it outside of the main window. ...
I would imagine they've, since they're not using .NET, rolled their own windowing code over the many years of its existence and it is now, like Amazon's original [OBIDOS](http://en.wikipedia.org/wiki/Obidos_(software)), so custom to their product that off-the-shelf (aka .NET's MDI support) just aren't going to come clo...
I havn't seen anything remarkable about Photoshop CS that requries anything close to this level of hacking that can't instead be done simply by specifying the correct owner window relationships when creating windows. i.e. any window that must be shown above some other window specifies that window as its owner when bein...
Managing Window Z-Order Like Photoshop CS
[ "", "c++", "winapi", "" ]
I'm using Webbrowser control to login to HTTPS site with "untrusted certificate". but I get popup such standart window "Security Alert" about untrusted certificate: ![Security Alert window](https://i.stack.imgur.com/U01dp.jpg) I have to find this window by title and send it `Alt`+`Y` to press *Yes*: ``` int iHandle ...
This should do it: ``` public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; } ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate); ``` Obvi...
If the certificate isn't from a trusted certifying authority (the first point in the prompt) then you could install the certificate under the Trusted Root Certification Authorities on the PCs in question. You can do this under View Certificate. In some ways this could be a simpler solution as it doesn't require any c...
How to disable "Security Alert" window in Webbrowser control
[ "", "c#", "https", "browser", "certificate", "" ]
If I have a table field named 'description', what would be the SQL (using MS SQL) to get a list of records of all distinct words used in this field. For example: If the table contains the following for the 'description' field: ``` Record1 "The dog jumped over the fence." Record2 "The giant tripped on the fence." ......
I do not think you can do this with a SELECT. The best chance is to write a user defined function that returns a table with all the words and then do SELECT DISTINCT on it. --- **Disclaimer:** Function **dbo.Split** is from <http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=50648> ``` CREATE TABLE test ( id int i...
I just had a similar problem and tried using SQL CLR to solve it. Might be handy to someone ``` using System; using System.Data; using System.Data.SqlClient; using System.Data.SqlTypes; using Microsoft.SqlServer.Server; using System.Collections; using System.Collections.Generic; public partial class UserDefinedFunct...
How to get a distinct list of words used in all Field Records using MS SQL?
[ "", "sql", "sql-server", "" ]
If any of you have worked with a cool tool for viewing/querying the SQL Transaction logs, please let me know. This should show all the transactional sql statements which are committed or rolled back. For Database files, if it has some additional graphical capabilities like showing the internal Binary Tree structure of...
This is only relevant if you're talking SQL Server 2000 but RedGate produced a free tool called [SQL Log Rescue](http://www.red-gate.com/products/SQL_Log_Rescue/index.htm). Otherwise, for SQL Server 2005 [ApexSQLLog](http://www.apexsql.com/sql_tools_log.asp) from ApexSQL is the only other product I'm aware of
You can use the undocumented [DBCC LOG command.](http://searchsqlserver.techtarget.com/tip/1,289483,sid87_gci1173464,00.html)
Looking for a SQL Transaction Log file viewer
[ "", "sql", "sql-server", "logging", "transactions", "" ]
So my site uses [shadowbox](http://mjijackson.com/shadowbox/) to do display some dynamic text. Problem is I need the user to be able to copy and paste that text. Right-clicking and selecting copy works but `Ctrl`+`C` doesn't (no keyboard shortcuts do) and most people use `Ctrl`+`C`? You can see an example of what I'm ...
The best option is to disable keyboard navigation shortcuts in the shadowbox by setting the "enableKeys" option to false (see [this page](http://mjijackson.com/shadowbox/doc/api.html)). Alternatively you could do what Robby suggests and modify the shadowbox.js file, **but only do this if you need to have the shadowbox...
This problem is caused by some JavaScript which eats keyboard events. You can hit the escape key, for example, which is trapped by one of the .js files and causes the shadow box to close. Your choices are to hack through the files and find the problem, or not use shadowbox. Good luck!
Using shadowbox disables keyboard shortcuts?
[ "", "javascript", "keyboard-shortcuts", "mootools", "" ]
``` dir(re.compile(pattern)) ``` does not return pattern as one of the lists's elements. Namely it returns: ``` ['__copy__', '__deepcopy__', 'findall', 'finditer', 'match', 'scanner', 'search', 'split', 'sub', 'subn'] ``` According to the manual, it is supposed to contain > the object's attributes' names, the > nam...
For the **complete** list of attributes, the short answer is: no. The problem is that the attributes are actually defined as the arguments accepted by the `getattr` built-in function. As the user can reimplement `__getattr__`, suddenly allowing any kind of attribute, there is no possible generic way to generate that li...
That is why the new `__dir__()` method has been added in python 2.6 see: * <http://docs.python.org/whatsnew/2.6.html#other-language-changes> (scroll down a little bit) * <http://bugs.python.org/issue1591665>
How to get a complete list of object's methods and attributes?
[ "", "python", "" ]
Is it possible to have an anonymous type implement an interface? I've got a piece of code that I would like to work, but don't know how to do this. I've had a couple of answers that either say no, or create a class that implements the interface construct new instances of that. This isn't really ideal, but I'm wonderi...
No, anonymous types cannot implement an interface. From the [C# programming guide](http://msdn.microsoft.com/en-us/library/bb397696.aspx): > Anonymous types are class types that consist of one or more public read-only properties. No other kinds of class members such as methods or events are allowed. An anonymous type ...
While the answers in the thread are all true enough, I cannot resist the urge to tell you that it in fact **is possible** to have an anonymous class implement an interface, even though it takes a bit of creative cheating to get there. Back in 2008 I was writing a custom LINQ provider for my then employer, and at one p...
Can anonymous class implement interface?
[ "", "c#", "anonymous-types", "" ]
I'm trying to get into java again (it's been a few years). I never really did any GUI coding in java. I've been using Netbeans to get started with this. When using winforms in C# at work I use a usercontrols to build parts of my UI and add them to forms dynamically. I've been trying to use `JPanels` like usercontrols...
I figured it out. The comments under the accepted answer here explain it: [Dynamically added JTable not displaying](https://stackoverflow.com/questions/121715/dynamically-added-jtable-not-displaying) Basically I just added the following before the mainPanel.add() ``` mainPanel.setLayout(new java.awt.BorderLayout()); ...
`Swing/AWT` components generally have to have a layout before you add things to them - otherwise the `UI` won't know where to place the subcomponents. BFreeman has suggested `BorderLayout` which is one of the easiest ones to use and allows you to 'glue' things to the top, bottom, left, right or center of the parent. ...
How do I dynamically add Panels to other panels at runtime in Java?
[ "", "java", "swing", "" ]
I'm writing a simulator in Python, and am curious about options and opinions regarding basic 2D animations. By animation, I'm referring to rendering on the fly, not displaying prerendered images. I'm currently using matplotlib (Wxagg backend), and it's possible that I'll be able to continue using it, but I suspect it ...
I am a fan of [pyglet](http://pyglet.org) which is a completely self contained library for doing graphical work under win32, linux, and OS X. It has very low overhead, and you can see this for yourself from the tutorial on the website. It *should* play well with wxpython, or at least I seem to recall posts to the mail...
You can try pygame, its very easy to handle and similar to SDL under c++
2D animation in Python
[ "", "python", "animation", "2d", "" ]
How would you reference the models (Accord, CRV, Prius, etc) in this structure? Is this a bad structure to be able to extract the makes...then use a make to get the models...then use the model to get the options? ``` var cars = [ { "makes" : "Honda", "models" : [ {'Accord' : ["2dr",...
The structure: ``` var cars = [ { name: 'Honda', models: [ { name: 'Accord', features: ['2dr', '4dr'] }, { name: 'CRV', features: ['2dr', 'Hatchback'] }, { name: 'Pilot', features: ['base', 'superDuper'] } ]}, { name: 'Toyota', models: [ ...
cars[0].models.Accord cars[0].models.CRV cars[0].models.Pilot (See [olliej](https://stackoverflow.com/questions/180844/#180861)'s answer) Though, it may be easier to use the following access concept: ``` cars.Honda.Accord cars.Toyota.Prius ``` ...using... ``` var cars = { Honda : { Accord : ["2dr", "4dr"], ...
Referencing a javascript object literal array
[ "", "javascript", "data-structures", "" ]
I'm stuck on a fix to a legacy Visual C++ 6 app. In the C++ DLL source I have put ``` extern "C" _declspec(dllexport) char* MyNewVariable = 0; ``` which results in MyNewVariable showing up (nicely undecorated) in the export table (as shown by dumpbin /exports blah.dll). However, I can't figure out how to declare the ...
you must link against the lib generated after compiling the DLL. In the linker options of the project, you must add the `.lib` file. And yes, you should also declare the variable as: ``` extern "C" { declspec(dllimport) char MyNewVariable; } ```
extern "C" is how you remove decoration - it should work to use: extern "C" declspec(dllimport) char MyNewVariable; or if you want a header that can be used by C++ or C (with /TC switch) ``` #ifdef __cplusplus extern "C" { #endif declspec(dllimport) char MyNewVariable; #ifdef __cplusplus } #endif ``` And of course,...
Can't access variable in C++ DLL from a C app
[ "", "c++", "c", "interop", "name-decoration", "" ]
I am working on a form widget for users to enter a time of day into a text input (for a calendar application). Using JavaScript (we are using jQuery FWIW), I want to find the best way to parse the text that the user enters into a JavaScript `Date()` object so I can easily perform comparisons and other things on it. I ...
A quick solution which works on the input that you've specified: ``` function parseTime( t ) { var d = new Date(); var time = t.match( /(\d+)(?::(\d\d))?\s*(p?)/ ); d.setHours( parseInt( time[1]) + (time[3] ? 12 : 0) ); d.setMinutes( parseInt( time[2]) || 0 ); return d; } var tests = [ '1:00...
All of the examples provided fail to work for times from 12:00 am to 12:59 am. They also throw an error if the regex does not match a time. The following handles this: ``` function parseTime(timeString) { if (timeString == '') return null; var time = timeString.match(/(\d+)(:(\d\d))?\s*(p?)/i); if (time == ...
How to parse a time into a Date object from user input in JavaScript?
[ "", "javascript", "datetime", "parsing", "date", "time", "" ]
My production system occasionally exhibits a memory leak I have not been able to reproduce in a development environment. I've used a [Python memory profiler](https://stackoverflow.com/questions/110259/python-memory-profiler) (specifically, Heapy) with some success in the development environment, but it can't help me wi...
I will expand on Brett's answer from my recent experience. [Dozer package](https://pypi.org/project/Dozer/) is [well maintained](https://github.com/mgedmin/dozer), and despite advancements, like addition of `tracemalloc` to stdlib in Python 3.4, its `gc.get_objects` counting chart is my go-to tool to tackle memory leak...
Using Python's `gc` garbage collector interface and `sys.getsizeof()` it's possible to dump all the python objects and their sizes. Here's the code I'm using in production to troubleshoot a memory leak: ``` rss = psutil.Process(os.getpid()).get_memory_info().rss # Dump variables if using more than 100MB of memory if r...
How do I find what is using memory in a Python process in a production system?
[ "", "python", "memory-leaks", "coredump", "" ]
Is there a function in Python to split a string without ignoring the spaces in the resulting list? E.g: ``` s="This is the string I want to split".split() ``` gives me ``` >>> s ['This', 'is', 'the', 'string', 'I', 'want', 'to', 'split'] ``` I want something like ``` ['This',' ','is',' ', 'the',' ','string', ' ',...
``` >>> import re >>> re.split(r"(\s+)", "This is the string I want to split") ['This', ' ', 'is', ' ', 'the', ' ', 'string', ' ', 'I', ' ', 'want', ' ', 'to', ' ', 'split'] ``` Using the capturing parentheses in re.split() causes the function to return the separators as well.
I don't think there is a function in the standard library that does that by itself, but "partition" comes close The best way is probably to use regular expressions (which is how I'd do this in any language!) ``` import re print re.split(r"(\s+)", "Your string here") ```
Is there a function in Python to split a string without ignoring the spaces?
[ "", "python", "split", "" ]
I've noticed that just in the last year or so, many major websites have made the same change to the way their pages are structured. Each has moved their Javascript files from being hosted on the same domain as the page itself (or a subdomain of that), to being hosted on a differently named domain. ## It's not simply p...
Your follow-up question is essentially: Assuming a popular website is using a CDN, why would they use their own TLD like imwx.com instead of a subdomain (static.weather.com) or the CDN's domain? Well, the reason for using a domain they control versus the CDN's domain is that they retain control -- they could potential...
Limit cookie traffic? After a cookie is set on a specific domain, every request to that domain will have the cookie sent back to the server. Every request! That can add up quickly.
Why move your Javascript files to a different main domain that you also own?
[ "", "javascript", "webserver", "cdn", "provisioning", "whitelist", "" ]
So, in reading this site, it seems that the shop in which I work does a lot of things wrong and some things right. How can I improve the code that I work with from my colleagues? The only thing I can think of is to lead by example - start using Boost, etc. Any other thoughts?
You probably have to look more closely at what it is your shop does wrong and what they do right. What can you actually change there? *What can you change about your own practices that will improve your skills or that of your team?* It can be difficult to realize change in an entrenched shop. Try proposing code reviews...
Code reviews are the best way I found to improve code quality overall. Reviewing code from different individuals helping each other increases general awareness of different techniques and help propagate best practices. Hire a person more experienced than you are is also a good tool but it is a bit more tedious to imple...
Improving the quality of code?
[ "", "c++", "" ]
When using ``` $('.foo').click(function(){ alert("I haz class alertz!"); return false; }); ``` in application.js, and ``` <a href = "" class = "foo" id = "foobar_1" >Teh Foobar </a> ``` in any div that initializes with the page, when clicking "Teh Foobar" it alerts and doesn't follow the link. However...
New elements added to the document after you bind your events don't automatically get those event handlers. One way to fix this is - as John Millikin says - re-bind your events after you create new elements. The other standard way is event delegation. Because events go all the way up and down the stack through all the...
Markup returned from an AJAX call isn't present when you set up the page, so it doesn't have any onclick handlers associated with it. You'll need to hook into the Rails AJAX support so that when it loads your AJAX-powered div, it also executes your event setup code again.
JQuery selectors not finding class on elements in table created by an Ajax XHR in Ruby on Rails
[ "", "javascript", "ruby-on-rails", "ruby", "ajax", "" ]
When using regular expressions we generally, if not always use them to extract some kind of information. What I need is to replace the match value with some other value... Right now I'm doing this... ``` def getExpandedText(pattern, text, replaceValue): """ One liner... really ugly but it's only used in h...
``` sub (replacement, string[, count = 0]) ``` [sub](https://docs.python.org/howto/regex.html#search-and-replace) returns the string obtained by replacing the leftmost non-overlapping occurrences of the RE in string by the replacement replacement. If the pattern isn't found, string is returned unchanged. ``` p = ...
You want to use [re.sub](https://docs.python.org/2/library/re.html#re.sub): ``` >>> import re >>> re.sub(r'aaa...bbb', 'aaaooobbb', "hola aaaiiibbb como estas?") 'hola aaaooobbb como estas?' ``` To re-use variable parts from the pattern, use `\g<n>` in the replacement string to access the n-th `()` group: ``` >>> re...
Regular expressions but for writing in the match
[ "", "python", "regex", "" ]
I've had nothing but good luck from SO, so why not try again? I have an application that needs to show a different image based on the season of the year (spring, summer, winter, fall). I have very specific start and end dates for these seasons. What I would like from you geniuses is a method called GetSeason that tak...
Seems like just checking the month would do: ``` private static final String seasons[] = { "Winter", "Winter", "Spring", "Spring", "Summer", "Summer", "Summer", "Summer", "Fall", "Fall", "Winter", "Winter" }; public String getSeason( Date date ) { return seasons[ date.getMonth() ]; } // As stated above, getMo...
Some good answers here, but they are outdated. The java.time classes make this work much easier. # java.time The troublesome old classes bundled with the earliest versions of Java have been supplanted by the [java.time](http://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html) classes built into Java 8...
Identifying the season from the Date using Java
[ "", "java", "date", "" ]
I have multiple classes that all derive from a base class, now some of the derived classes will not be compiled depending on the platform. I have a class that allows me to return an object of the base class, however now all the names of the derived classes have been hard coded. Is there a way to determine what classes...
Are you looking for C++ runtime class registration? I found this [link](http://meat.net/2006/03/cpp-runtime-class-registration/) ([backup](http://web.archive.org/web/20100618122920/http://meat.net/2006/03/cpp-runtime-class-registration/)). That would probably accomplish what you want, I am not sure about the dynamical...
I don't know what you're really trying to accomplish, but you could put a singleton constructor in each derived class's implementation file that adds the name to a list, along with a pointer to a factory. Then the list is always up to date and can create all the compiled in classes.
C++ runtime knowledge of classes
[ "", "c++", "class", "runtime", "" ]
One thing I've started doing more often recently is **retrieving some data** at the beginning of a task **and storing it in a $\_SESSION['myDataForTheTask']**. Now it seems very convenient to do so but I don't know anything about performance, security risks or similar, using this approach. Is it something which is reg...
Well Session variables are really one of the only ways (and probably the most efficient) of having these variables available for the entire time that visitor is on the website, there's no real way for a user to edit them (other than an exploit in your code, or in the PHP interpreter) so they are fairly secure. It's a ...
I use the session variable all the time to store information for users. I haven't seen any issues with performance. The session data is pulled based on the cookie (or *PHPSESSID* if you have cookies turned off). I don't see it being any more of a security risk than any other cookie based authentication, and probably mo...
PHP: $_SESSION - What are the pros and cons of storing temporarily used data in the $_SESSION variable
[ "", "php", "session", "scope", "" ]
I'm working through previous years ACM Programming Competition problems trying to get better at solving Graph problems. The one I'm working on now is I'm given an arbitrary number of undirected graph nodes, their neighbors and the distances for the edges connecting the nodes. What I NEED is the distance between the tw...
It looks like you can use either of: * [Floyd Warshall algorithm](http://en.wikipedia.org/wiki/Floyd_Warshall) * [Johnson's algorithm](http://en.wikipedia.org/wiki/Johnson's_algorithm). I can't give you much guidance about them though - I'm no expert.
So there's an implementation of Dijkstra which runs O(VlogV + E) giving your approach a complexity of roughly V^2logV + VE. See [DADS](http://www.nist.gov/dads/HTML/dijkstraalgo.html). But perhaps more intuitive would be to run one of the all [pairs shortest path](http://www.nist.gov/dads/HTML/allPairsShortestPath.html...
How to find the distance between the two most widely separated nodes
[ "", "java", "algorithm", "graph-theory", "" ]
Ok sorry this might seem like a dumb question but I cannot figure this thing out : I am trying to parse a string and simply want to check whether it only contains the following characters : '0123456789dD+ ' I have tried many things but just can't get to figure out the right regex to use! ``` Regex oReg = new Regex...
Try this: ``` @"^[0-9dD+ ]+$" ``` The `^` and `$` at the beginning and end signify the beginning and end of the input string respectively. Thus between the beginning and then end only the stated characters are allowed. In your example, the regex matches if the string contains one of the characters even if it contains...
Oops, you forgot the boundaries, try: ``` Regex oReg = new Regex(@"^[0-9dD +]+$"); oReg.IsMatch("e4"); ``` ^ matches the begining of the text stream, $ matches the end.
Matching an (easy??) regular expression using C#'s regex
[ "", "c#", "regex", "" ]
In C# are the nullable primitive types (i.e. `bool?`) just aliases for their corresponding `Nullable<T>` type or is there a difference between the two?
If you look at the IL using [Ildasm](http://msdn.microsoft.com/en-us/library/f7dy01k1%28v=vs.100%29.aspx), you'll find that they both compile down to `Nullable<bool>`.
There is no difference between `bool? b = null` and `Nullable<bool> b = null`. The `?` is just C# compiler syntax sugar.
Is there any difference between type? and Nullable<type>?
[ "", "c#", ".net", "nullable", "" ]
I have a "numeric textbox" in C# .NET which is nothing more than a derivation of Textbox, with some added logic to prevent the user entering anything non-numeric. As part of this, I have added a Value property of type `double?` (or `Nullable<double>`). It's nullable to support the case where the user doesn't enter anyt...
Or, if you don't want the designer adding any code at all... add this to the Property. ``` [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] ```
It seems that there is an issue in Visual Studio 2008. You should create custom CodeDomSerializer to work around it: ``` public class CategoricalDataPointCodeDomSerializer : CodeDomSerializer { public override object Deserialize(IDesignerSerializationManager manager, object codeObject) { CodeStatementC...
Windows Forms Designer upset by a control with a nullable property
[ "", "c#", "winforms", "nullable", "" ]
I'm working on an application that is supposed to create products (like shipping insurance policies) when PayPal Instant Payment Notifications are received. Unfortunately, PayPal sometimes sends duplicate notifications. Furthermore, there is another third-party that is performing web-service updates simultaneously when...
It would be safer and cleaner if `insert into Policy` just hit some uniqueness table constraint on attempt to insert duplicate. Raising isolation level can lower concurrency and lead to other nasty issues like deadlocks. Another way is to always insert Policy row, then roll it back if Package has been attached to a Po...
I believe you're actually wanting Serializable isolation level. The problem is that two threads can get past the HasInsurancePolicyCheck (though I have no idea what InsurancePolicyDB.Insert would do or why it would return 0) You have many other options for this as well. One is using a message queue and processing thes...
IsolationLevel.RepeatableRead to prevent duplicates
[ "", "c#", "sql-server", "database", "transactions", "data-access-layer", "" ]
Is there any open-source, `PHP based`, role-based access control system that can be used for `CodeIgniter`?
Brandon Savage gave a presentation on his PHP package "[ApplicationACL](http://www.brandonsavage.net/projects.php)" that may or may not accomplish role-based access. [PHPGACL](http://phpgacl.sourceforge.net/) might work as well, but I can't tell you for sure. What I can tell you, however, is the [Zend\_ACL](http://fra...
Maybe I'm misunderstanding the question, but isn't the whole point of Role-Based Access Control (RBAC) to *avoid* Access Control Lists (ACLs)? > ***RBAC differs from access control lists (ACLs)** (...) in that it assigns permissions to specific operations with meaning in the organization, rather than to low-level data...
Role Based Access Control
[ "", "php", "codeigniter", "access-control", "" ]
## What should happen when I call `$user->get_email_address()`? ### Option 1: Pull the email address from the database on demand ``` public function get_email_address() { if (!$this->email_address) { $this->read_from_database('email_address'); } return $this->email_address; } ``` ### Option 2: Pu...
There really isn't a correct answer for this. Depends on how many users you're loading at once, how many text/blob fields are in your User table, whether your user table loads any associated child objects. As aaronjensen says, this pattern is called **lazy loading** - and the opposite behaviour (loading *everything* up...
Minimize the number of queries. The optimal # of queries is 0, but if you must query because it's not cached, it's 1. Querying for every property is a sure fire way to a system that will never scale, has massive contention issues, and will cause way more headaches than its worth. I should mention that there is value t...
Object-relational mapping: What's the best way to implement getters?
[ "", "php", "orm", "oop", "mapping", "" ]
I'm trying to grasp the concept of .NET Generics and actually use them in my own code but I keep running into a problem. Can someone try to explain to me why the following setup does not compile? ``` public class ClassA { ClassB b = new ClassB(); public void MethodA<T>(IRepo<T> repo) where T : ITypeEntity ...
Inheritance doesn't work the same when using generics. As Smashery points out, even if TypeA inherits from TypeB, myType<TypeA> doesn't inherit from myType<TypeB>. As such, you can't make a call to a method defined as MethodA(myType<TypeB> b) expecting a myType<TypeB> and give it a myType<TypeA> instead. The types in ...
Well this compiles ok. I basically redifined the classes to take generic parameters. This may be ok in your context. ``` public interface IRepo<TRepo> { } public interface ITypeEntity { } public class ClassA<T> where T : ITypeEntity { ClassB<T> b = new ClassB<T>(); public void MethodA(IRepo<T> repo) { ...
.NET Generic Method Question
[ "", "c#", ".net", "generics", "" ]
I'd like to track changes in inputs in a form via javascript. My intent is (but not limited) to * enable "save" button only when something has changed * alert if the user wants to close the page and something is not saved Ideas?
Loop through all the input elements, and put an `onchange` handler on each. When that fires, set a flag which lets you know the form has changed. A basic version of that would be very easy to set up, but wouldn't be smart enough to recognize if someone changed an input from "a" to "b" and then back to "a". If it were i...
Text form elements in JS expose a `.value` property and a `.defaultValue` property, so you can easily implement something like: ``` function formChanged(form) { for (var i = 0; i < form.elements.length; i++) { if(form.elements[i].value != form.elements[i].defaultValue) return(true); } return(false); } ``` ...
What is the best way to track changes in a form via javascript?
[ "", "javascript", "forms", "" ]
I'm working on a query that needs to have some data rows combined based on date ranges. These rows are duplicated in all the data values, except the date ranges are split. For example the table data may look like ``` StudentID StartDate EndDate Field1 Field2 1 9/3/2007 10/20/2007 3 True 1 ...
The following code should work. I've made a few assumptions as follows: there are no overlaps of date ranges, there are no NULL values in any of the fields, and the start date for a given row is always less than the end date. If your data doesn't fit these criteria, you'll need to adjust this method, but it should poin...
If the min()/max() solutions are not good enough (e.g. if the dates are not contiguous and you want to group separate date ranges separately), I wonder if something using Oracle's START WITH and CONNECT BY clauses would work. Which, of course, wouldn't work on every database.
Combining split date ranges in a SQL query
[ "", "sql", "database", "ms-access", "database-design", "" ]
What options exist for accessing different databases from C++? Put differently, what alternatives are there to ADO? What are the pros and cons?
1. [Microsoft ODBC](http://msdn.microsoft.com/en-us/library/ms710252.aspx). 2. The MFC ODBC classes such as [CDatabase](http://msdn.microsoft.com/en-us/library/2dhc1abk.aspx). 3. [OleDB](http://msdn.microsoft.com/en-us/library/ms722784.aspx) (via COM). 4. And you can always go through the per-RDBMS native libraries (fo...
Although this question and its answers are several years old, they are still valuable for people like me that cruise by on an evaluation trip. For this reason, I would like to add the Qt C++ framework's `QtSql` module as an option for database connectivity. Note that I am familiar with Qt in general, but have no exper...
Database abstraction layers for (Visual) C++
[ "", "c++", "database", "" ]
I'm writing a Perl script and I've come to a point where I need to parse a Java source file line by line checking for references to a fully qualified Java class name. I know the class I'm looking for up front; also the fully qualified name of the source file that is being searched (based on its path). For example find...
You also need to skip quoted strings (you can't even skip comments correctly if you don't also deal with quoted strings). I'd probably write a fairly simple, efficient, and incomplete tokenizer very similar to the one I wrote in [node 566467](http://perlmonks.org/?node_id=566467). Based on that code I'd probably just...
A Regex is probably the best solution for this, although I did find the following module in CPAN that you might be able to use * [Java::JVM::Classfile](http://search.cpan.org/~lbrocard/Java-JVM-Classfile-0.20/lib/Java/JVM/Classfile.pm) - Parses compiled class files and returns info about them. You would have to compil...
How can I identify references to Java classes using Perl?
[ "", "java", "perl", "parsing", "" ]
Suppose I have the following declaration: ``` class Over1 { protected: class Under1 { }; }; ``` I know that I could do the following: ``` class Over2 : public Over1 { protected: class Under2 : public Under1 { }; }; ``` But is there a way to declare Under2 without Over...
Using templates and explicit specializations you can do this with just one additional class declaration in Over1. ``` class Over1 { protected: class Under1 { }; template <typename T> class UnderImplementor; }; struct Under2Tag; struct Under3Tag; struct Under4Tag; template <> class Over1::UnderImplementor<...
Better than creating nested classes, you might want to look at embedding those closses into a namespace. That way, you don't need the outer class in order to get the inner class. There are some great arguments for and against in the [Google C++ Style Guide](http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml...
Inheriting from protected classes in C+++
[ "", "c++", "inheritance", "oop", "private", "" ]
At the team with which I work, we have an old codebase using PHP's ibase\_\* functions all over the code to communicate with database. We created a wrapper to it that would do something else beside just calling the original function and I did a mass search-replace in the entire code to make sure that wrapper is used in...
If I understand correct, you want to trigger an error when a built-in PHP function is used? In that case, take a look at the [Override Function](http://no.php.net/manual/en/function.override-function.php) function.
Generally speaking you can flag a method as deprecated to give your users warnings about code that will not work in future versions. I think the best way is to use [trigger\_error](http://php.net/manual/en/function.trigger-error.php) along with some [phpdoc](https://www.phpdoc.org/). ``` /** * @deprecated * * @retu...
How to deprecate a function in PHP?
[ "", "php", "deprecated", "" ]
From my small amount of experience, I've only used Ant as a build tool. Are there any other projects which are better, and why?
[Maven](http://maven.apache.org/) It is much better than ant because for most common tasks you don't have to write a complicated build.xml, maven has very good defaults and it's all convention over configuration. It has also a big central repository of libraries and it's very easy to configure it to, like, "use lates...
Ant is still a major player. In my experience, it is dominant. Plus, with Ivy, it handles some of Maven's strengths. IMO, Ant will become a framework for other tools: XML is too rigid (see link below). Maven 2 is also a major player. I know people who quite like it and bristle at criticisms that were true for Maven 1 ...
Is Ant still the best choice for a Java build tool?
[ "", "java", "ant", "build", "build-management", "" ]
I have a rather big number of source files that I need parse and extract all string literals and put them in a file as play old java constant. For exemple: ``` Label l = new Label("Cat"); ``` Would become: ``` Label l = new Label(Constants.CAT); ``` And in `Constants.java` I would have: ``` public final static S...
To complete Peter Kelley answer, you might consider for eclipse IDE the **AST** solution. You might then write an AST program which parse your source code and does what you want. A full example is available in this [eclipse corner article](http://www.eclipse.org/articles/article.php?file=Article-JavaCodeManipulation_...
Eclipse does do this automatically. Right-click the file, choose "Source", then "Externalize strings" This doesn't do exactly what you requested (having the strings in a Constants.java file as Strings) but the method used is very powerful indeed. It moves them into a properties file which can be loaded dynamically dep...
Extract all string from a java project
[ "", "java", "eclipse", "string", "gwt", "plugins", "" ]
Every so often when I'm debugging, I get this message in nice brown text on an ASP.NET error page: > *Access to the path > "c:\windows\microsoft.net\framework\(version)\Temporary ASP.NET Files\(blah)" > is denied.* I've never been able to figure out what causes it, what really fixes it, and why it happens. Often tim...
It was my understanding this can be caused by anti-virus running on the machine and intermittently locking the files.
It could happen if the Windows indexing servicing is turned on for the temporary directory. See [this article](http://blogs.msdn.com/junfeng/archive/2004/10/09/240355.aspx) for details. Run File Monitor (available at [sysinternals.com](http://www.sysinternals.com)) and put a filter on the temporary directory. When you ...
Error Message: "Access to the path c:\windows\microsoft.net\framework\(version)\Temporary ASP.NET Files\(blah) is denied." - what causes this?
[ "", "c#", ".net", "asp.net", "visual-studio-2003", "" ]
JavaScript allows functions to be treated as objects--if you first define a variable as a function, you can subsequently add properties to that function. How do you do the reverse, and add a function to an "object"? This works: ``` var foo = function() { return 1; }; foo.baz = "qqqq"; ``` At this point, `foo()` call...
You can't (as far as I know) do what you're asking, but hopefully this will clear up any confusion. First, most objects in Javascript inherit from the Object prototype. ``` // these do the same thing var foo = new Object(); var bar = {}; console.log(foo instanceof Object); // true console.log(bar instanceof Object);...
There doesn't appear to be a standard way to do it, but this works. WHY however, is the question. ``` function functionize( obj , func ) { out = func; for( i in obj ){ out[i] = obj[i]; } ; return out; } x = { a: 1, b: 2 }; x = functionize( x , function(){ return "hello world"; } ); x() ==> "hello wor...
How to convert an "object" into a function in JavaScript?
[ "", "javascript", "function", "properties", "" ]
If I am trying to determine the read speed of a drive, I can code a routine to write files to a filesystem and then read those files back. Unfortunately, this doesn't give an accurate read speed because Windows does disk read caching. Is there a way to flush the disk read cache of a drive in C# / .Net (or perhaps with...
**Why DIY?** If you only need to determine drive speed and not really interested in learning how to flush I/O buffers from .NET, you may just use DiskSpd utility from <http://research.microsoft.com/barc/Sequential_IO/>. It has random/sequential modes with and without buffer flushing. The page also has some I/O relate...
Constantin: Thanks! That link has a command-line EXE which does the testing I was looking for. I also found a link off that page to a more interesting article (in Word and PDF) on this page: [Sequential File Programming Patterns and Performance with .NET](http://research.microsoft.com/research/pubs/view.aspx?type=Tech...
How to empty/flush Windows READ disk cache in C#?
[ "", "c#", ".net", "caching", "disk", "flush", "" ]
This is an excerpt of code from a class I am working with in Java (below). Obviously the code is defining a static variable named EPSILON with the data type double. What I don't understand is the "1E-14" part. What kind of number is that? What does it mean? final double EPSILON = 1E-14;
In your case, this is equivalent to writing: ``` final double EPSILON = 0.00000000000001; ``` except you don't have to count the zeros. This is called [scientific notation](http://en.wikipedia.org/wiki/Scientific_notation) and is helpful when writing very large or very small numbers.
The "E" notation is scientific notation. You'll see it on calculators too. It means "one times (ten to the power of -14)". For another example, 2E+6 == 2,000,000.
Letters within integers. What are they?
[ "", "java", "types", "double", "int", "literals", "" ]
During my apprenticeship, I have used [NHibernate](http://nhibernate.org/ "NHibernate for .NET") for some smaller projects which I mostly coded and designed on my own. Now, before starting some bigger project, the discussion arose how to design data access and whether or not to use an ORM layer. As I am still in my app...
There's been an explosion of growth with ORMs in recent years and your more experienced coworkers may still be thinking in the "every database call should be through a stored procedure" mentality. Why would an ORM make things harder to debug? You'll get the same result whether it comes from a stored proc or from the O...
The short answer is yes, there are really good reasons. As a matter of fact there are cases where you just cannot use an ORM. Case in point, I work for a large enterprise financial institution and we have to follow a lot of security guidelines. To meet the rules and regulations that are put upon us, the only way to pa...
Are there good reasons not to use an ORM?
[ "", "c#", "orm", "enterprise", "" ]
I'm using: ``` FileInfo( System.Environment.GetFolderPath( System.Environment.SpecialFolder.ProgramFiles) + @"\MyInstalledApp" ``` In order to determine if a program is detected on a users machine (it's not ideal, but the program I'm looking for is a right old kludge of a MS-DOS application, and I co...
The function below will return the x86 `Program Files` directory in all of these three Windows configurations: * 32 bit Windows * 32 bit program running on 64 bit Windows * 64 bit program running on 64 bit windows ``` static string ProgramFilesx86() { if( 8 == IntPtr.Size || (!String.IsNullOrEmpty(Enviro...
If you're using .NET 4, there is a special folder enumeration [ProgramFilesX86](http://msdn.microsoft.com/en-us/library/system.environment.specialfolder.aspx): ``` Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86) ```
C# - How to get Program Files (x86) on Windows 64 bit
[ "", "c#", "windows", "file", "64-bit", "" ]
Is there a way to tell if an event handler has been added to an object? I'm serializing a list of objects into/out of session state so we can use SQL based session state... When an object in the list has a property changed it needs to be flagged, which the event handler took care of properly before. However now when th...
From outside the defining class, as @Telos mentions, you can only use EventHandler on the left-hand side of a `+=` or a `-=`. So, if you have the ability to modify the defining class, you could provide a method to perform the check by checking if the event handler is `null` - if so, then no event handler has been added...
I recently came to a similar situation where I needed to register a handler for an event only once. I found that you can safely unregister first, and then register again, even if the handler is not registered at all: ``` myClass.MyEvent -= MyHandler; myClass.MyEvent += MyHandler; ``` Note that doing this every time y...
Has an event handler already been added?
[ "", "c#", ".net", "asp.net", "" ]
I'm using the [zlib.NET](http://www.componentace.com/zlib_.NET.htm) library to try and inflate files that are compressed by zlib (on a Linux box, perhaps). Here's what I'm doing: ``` zlib.ZInputStream zinput = new zlib.ZInputStream(File.Open(path, FileMode.Open, FileAccess.Read)); while (stopByte != (data = zinpu...
It appears I made the mistake of assuming all virtual methods were overridden, which wasn't the case. I was using zlib.ZInputStream.ReadByte(), which is just the inherited Stream.ReadByte(), which doesn't do any inflate. I used zlib.ZInputStream.Read() instead, and it worked like it should.
Skipping the zlib header (first two bytes, `78 9C`) and then using the [`DeflateStream`](https://msdn.microsoft.com/en-us/library/system.io.compression.deflatestream.aspx) built into .net worked for me. ``` using(var input = File.OpenRead(...)) using(var output = File.Create(...)) { // if there are additional head...
How to inflate a file with zlib.NET?
[ "", "c#", ".net", "compression", "zlib", "" ]
Am looking for commercial/free recommended c# winform controls packs
**[DevExpress](http://www.devexpress.com/)** *I've tried [ComponentOne](http://www.componentone.com/), DevExpress and [Telerik](http://www.telerik.com/)*
See the following threads: * [.NET Usercontrols telerik devexpress infragistics ComponentOne whos best](https://stackoverflow.com/questions/169357/net-usercontrols-telerik-devexpress-infragistics-componentone-whos-best#170227)
recommended c# winform controls packs
[ "", "c#", "winforms", "controls", "" ]