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 tried the [Jacob Java COM Bridge](http://danadler.com/jacob/) but that doesn't seem as straightforward or simple to use, and I couldn't get it to retrieve cell values (even though this is the library underlying Scriptom). Are there alternatives?
|
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 easy. I have a great book on learning COM, but don't have the name handy right now...
You want to learn about the IDispatch interface (this is what most of Excel's COM interface is developed around). It's a nasty, nasty interface (one of those viral things that you can do so much with it that it becomes impossible to tell what is actually happening) - but learning it is key.
If you are having issues in just one area (i.e. getting a value from a cell), you could grab the source for Scriptom and see what they do (open source, after all!).
Another suggestion is to try to implement some test cases of your code in VBA and make sure that you are correctly thinking through all the return values. When we were doing Excel automation in one of our Java apps, we implemented the general algorithm from Word's VBA, worked through the problem cases, etc... After that, transferring over to Jacob was pretty straightforward.
* K
|
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 with the database causes an error.
Has anyone every gotten NHibernate working with an in memory database? Is it even possible? The connection string I'm using is this:
```
Data Source=:memory:;Version=3;New=True
```
|
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. Close the session at the end of your test (maybe in a [TearDown] method).
|
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 using MSTest):
* Configure NHibernate (Fluently) to use SQLite with the following connection string:
```
FullUri=file:memorydb.db?mode=memory&cache=shared
```
* Use that configuration to create a hbm2ddl.**SchemaExport** object, and execute it on a separate connection (but with that same connection string again).
* Leave that connection open, and referenced by a static field, until *AssemblyCleanup*, at which point it is closed and disposed of. This is because SQLite needs at least one active connection to be held on the in-memory database to know it's still required and avoid tidying up.
Before each test runs, a new session is created, and the test runs in a transaction which is rolled back at the end.
Here is an example of the test assembly-level code:
```
[TestClass]
public static class SampleAssemblySetup
{
private const string ConnectionString = "FullUri=file:memorydb.db?mode=memory&cache=shared";
private static SQLiteConnection _connection;
[AssemblyInitialize]
public static void AssemblyInit(TestContext context)
{
var configuration = Fluently.Configure()
.Database(SQLiteConfiguration.Standard.ConnectionString(ConnectionString))
.Mappings(m => m.FluentMappings.AddFromAssembly(Assembly.Load("MyMappingsAssembly")))
.ExposeConfiguration(x => x.SetProperty("current_session_context_class", "call"))
.BuildConfiguration();
// Create the schema in the database
// Because it's an in-memory database, we hold this connection open until all the tests are finished
var schemaExport = new SchemaExport(configuration);
_connection = new SQLiteConnection(ConnectionString);
_connection.Open();
schemaExport.Execute(false, true, false, _connection, null);
}
[AssemblyCleanup]
public static void AssemblyTearDown()
{
if (_connection != null)
{
_connection.Dispose();
_connection = null;
}
}
}
```
And a base class for each unit test class/fixture:
```
public class TestBase
{
[TestInitialize]
public virtual void Initialize()
{
NHibernateBootstrapper.InitializeSession();
var transaction = SessionFactory.Current.GetCurrentSession().BeginTransaction();
}
[TestCleanup]
public virtual void Cleanup()
{
var currentSession = SessionFactory.Current.GetCurrentSession();
if (currentSession.Transaction != null)
{
currentSession.Transaction.Rollback();
currentSession.Close();
}
NHibernateBootstrapper.CleanupSession();
}
}
```
Resource management could improve, I admit, but these are unit tests after all (suggested improvements welcome!).
|
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 should I start? What language should I do it in? I was thinking PHP might be able to do this or even a greasemonkey script possibly?
Thanks a lot.
|
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. The issue was that I couldn't authenticate to access the report parameters because of the hard-coded and less-than-script-friendly way I was required to log in to the site. However, I presume that your site is internal to your organisation, so it may be possible to bypass/rework the security requirements in order to access the data. If this is the case, then you should be able to use one of the screen scraping methods outlined above.
If not, you may need to incorporate the actual login procedure into your script or application, download and capture any cookies that may be set and incorporate them into your data request.
|
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() > y.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 through it.
|
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)
Although this may not happen in real world scenarios...
during our load tests, we are getting System.Data.Linq.ChangeConflictException exceptions.
Wrapping up the submit inside a transacion is not helping either.
Can't we force LINQ to get a lock on the row for the entire duration of the update operation?
Is there any other way to get over this?
|
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 middle) it should be OK.
In particular, with a serializable isolation level, nobody can update data that you have a read lock on (i.e. anything you have queried). The only problem is that this might lead to deadlock scenarios if different queries are reading data in different orders. AFAIK, there is no way to get LINQ-to-SQL to issue the (UPDLOCK) hint, which is a shame.
Either a TransactionScope or a SqlTransaction would do, as long as they are set as serializable isolation (which is the default for TransactionScope).
|
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.com/default.aspx?showNum=118)
|
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 the corresponding .aspx (or .master) file, even after restarting the whole IDE. The Solution Explorer entry looks in a way like this:
```
- Main.aspx
Main.aspx.cs
Main.aspx.designer.cs
```
Can I make Visual Studio file the designer-file below the aspx-file in any way? I strongly hope there is a simpler way than manually creating each file and copying and pasting the contents into each file by hand.
|
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 Web Site or Web Project](https://stackoverflow.com/questions/10798/aspnet-web-site-or-web-project).
In a web site I can't even use YonahW's solution, because I can't just put files into the proper web site directory without causing them to be added to the web site automatically. Thanks to you anyway, YonahW. :-)
|
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 use of pinvoke, which I am not really comfortable with.
Thanks
Just to clearify: I don't want to embedded a new instance of Windows Media Player in my app, but instead control/read the "real" full version of Windows Media Player, started seperatly by the user
|
I had this <https://social.msdn.microsoft.com/Forums/vstudio/en-US/dbd43d7e-f3a6-4087-be06-df17e76b635d/windows-media-player-remoting-in-c?forum=clr> in my bookmarks but have NOT tested it in anyway. Just a pointer in the right direction. It's nothing official and will require a bit of digging, but you should get a fairly simple wrapper (which will still use PInvoke under the hood - but you won't see it) around Windows Media Player.
Hope that helps.
Oh, I misunderstood. I thought you were talking about controlling the currently running Windows Media Player instance. If you are hosting Windows Media Player yourself then WMPLib is certainly the better solution.
|
Just add a reference to wmp.dll (\windows\system32\wmp.dll)
```
using WMPLib;
```
And then you can instantiate a media player
```
var Player = new WindowsMediaPlayer();
// Load a playlist or file and then get the title
var title = Player.controls.currentItem.name;
```
See [Creating the Windows Media Player Control Programmatically](http://msdn.microsoft.com/en-us/library/bb262248(VS.85).aspx) for more information
|
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 instances, we're struggling to overcome this without having to add a notable chunk to development time estimates.
I've worked with MVC before - via Struts in Java - and found that in that instance, I was able to keep HTML pages exactly as I'd wanted them to be. *(This viewpoint is based on the "best case" static HTML I typically developed beforehand, then handed over to the Java programmers to fill in the holes.)*
This worked out really well and we were able to produce some of the "best" web pages from a CMS that I've seen. Could .NET MVC give me the separation I need, or would it be a false economy to put aside valuable development time to test this?
If .NET MVC isn't going to give me this fine-grained control over separation, any recommendations for .NET coding practices, libraries, etc. which might would be really helpful.
|
The ASP.NET MVC Framework would give you a much more familiar separation. Because there is no viewstate, etc in the MVC Framework you won't have to worry about JavaScript being dumped into your pages. The only JavaScript calls you see will be ones that you manually add.
You can, for the most part, separate HTML / CSS / JS like you would in a different framework.
|
Depending on the view engine you're going to use. yes.
But you can easilly check this by looking at the page-source for stack-overflow. It's not zen-garden but it's pretty clean.
Some more clarification:
The rendering of the pages is done by the view engine. You can use the standard view engine or existing ones like nVelocity or Brail, just like with monorail.
<http://www.chadmyers.com/Blog/archive/2007/11/28/testing-scottgu-alternate-view-engines-with-asp.net-mvc-nvelocity.aspx>
As the view engine is responsible for creating HTML what comes out depends on your choice. But most view engines are better in this respect than vanilla ASP.Net
|
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 `throw ex`.
---
If there is a need to rethrow an exception that comes from somewhere else (AggregateException, TargetInvocationException) or perhaps another thread, you also shouldn't rethrow it directly. Rather there is the [ExceptionDispatchInfo](https://learn.microsoft.com/en-us/dotnet/api/system.runtime.exceptionservices.exceptiondispatchinfo) that preserves all the necessary information.
```
try
{
methodInfo.Invoke(...);
}
catch (System.Reflection.TargetInvocationException e)
{
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(e.InnerException).Throw();
throw; // just to inform the compiler that the flow never leaves the block
}
```
|
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 chained exceptions to report, each reporting more detail.
|
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 with the functions I want to test, imports ten other files which is part of our software and not python core libs.
I want to be able to run the unit tests as separately as possible and for now I am only going to test functions that does not depend on things from the files that are being imported.
### EDIT
Thanks for all the answers.
I didn't really know what I wanted to do from the start but now I think I know.
Problem was that some imports was only possible when the whole application was running because of some third-party auto-magic. So I had to make some stubs for these modules in a directory which I pointed out with sys.path
Now I can import the file which contains the functions I want to write tests for in my unit-test file without complaints about missing modules.
|
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, wantedModules):
def inner(moduleName, *args, **kwargs):
if moduleName in wantedModules:
print "IMPORTING MODULE", moduleName
self.real_import(*args, **kwargs)
else:
print "NOT IMPORTING MODULE", moduleName
return inner
def mock_import(self, moduleName, wantedModules):
__builtins__.__import__ = self.wrapper(wantedModules)
try:
__import__(moduleName, globals(), locals(), [], -1)
finally:
__builtins__.__import__ = self.real_import
```
And in your test code, instead of writing `import myModule`, write:
```
wrapper = ImportWrapper(__import__)
wrapper.mock_import('myModule', [])
```
The second argument to `mock_import` is a list of module names you *do* want to import in inner module.
This example can be modified further to e.g. import other module than desired instead of just not importing it, or even mocking the module object with some custom object of your own.
|
"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 various project directories onto a `PYTHONPATH` that you can use for testing. We have a rather complex path, in Windows we manage it like this
```
@set Part1=c:\blah\blah\blah
@set Part2=c:\some\other\path
@set that=g:\shared\stuff
set PYTHONPATH=%part1%;%part2%;%that%
```
We keep each piece of the path separate so that we (a) know where things come from and (b) can manage change when we move things around.
Since the `PYTHONPATH` is searched in order, we can control what gets used by adjusting the order on the path.
Once you have "everything", it becomes a question of trust.
Either
* you trust something (i.e., the Python code base) and just import it.
Or
* You don't trust something (i.e., your own code) and you
1. test it separately and
2. mock it for stand-alone testing.
Would you test the Python libraries? If so, you've got a lot of work. If not, then, you should perhaps only mock out the things you're actually going to test.
|
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 machine, I get a "What do you want to do with the \*.php file?" dialog. The dialog is the browser's open/save dialog
I'm just trying to get the output of phpinfo() to make sure everything is up and running...
I already tried to mess around a bit with the Apache conf file, but since I don't know much about what I'm doing, I reinstalled everything again and the problem is still there. I kinda get the feeling it must have something to do with the PHP thingy isn't correctly installed.
When i try to get the output of phpinfo as in:
```
<pre><?php
phpinfo();
?></pre>
```
I get the browser's "Open/Save" dialog for the \*.php file.
|
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 Group\Apache2\conf\httpd.conf`
|
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/xampp.html) and install Postgres after all is set up and running with the web server and php.
|
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 App Engine; it is only used as a stub for the Images API in your local environment. Only the transforms provided in the images API are available on App Engine.
The community has been asking for full [PIL](http://www.pythonware.com/products/pil/index.htm) support for some time, but it looks like we'll have to wait.
|
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 metadata['has_alpha'] else 3
pixel_position = point[0] + point[1] * w
print pixels[
pixel_position * pixel_byte_width :
(pixel_position + 1) * pixel_byte_width]
```
|
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, virtual methods, etc.
4. dynamic (de)allocation of memory
What rules (of thumb?) do you use to decide whether or not to unwind a performance critical loop? What other optimisation do you consider in these cases?
|
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 make the decision anymore and I may end up with less than optimal code. E.g. exactly the opposite I tried to achieve.
There are several cases where I do unroll performance critical loops by hand, but I only do this if I know that the compiler will - after manual unrolling - be able to use architectural specific feature such as SSE or MMX instructions. Then, and only then I do it.
Btw - modern CPUs are very efficient at executing well predictable branches. This is exactly what a loop is. The loop overhead is so small these days that it rarely makes a difference. Memory latency effects that may occur due to the increase in code-size will however make a difference.
|
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));
```
results in: "1999-11-30",
huh? i went from 0000-00-00 to 1999-11-30 ???
I know i could do comparison to see if the date is either of those values is equal to the date i have but it isn't a very robust way to check. Is there a good way to check to see if i have a valid date? Anyone have a good function to check this?
Edit:
People are asking what i'm running:
Running PHP 5.2.5 (cli) (built: Jul 23 2008 11:32:27) on Linux localhost 2.6.18-53.1.14.el5 #1 SMP Wed Mar 5 11:36:49 EST 2008 i686 i686 i386 GNU/Linux
|
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 true;
}
}
return false;
}
?>
```
|
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'))
string: '2012-02-29'
>> date('Y-m-d', strtotime('2012-02-00'))
string: '2012-01-31'
>> date('Y-m-d', strtotime('2012-01-00'))
string: '2011-12-31'
>> date('Y-m-d', strtotime('2012-00-00'))
string: '2011-11-30'
```
|
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. But, my Ant experience is somewhat limited so that doesn't help me much. (Most of the Java work I have done was just deployed as a jar file).
I have looked into Cruise Control before, and I understand that phpUnderControl is a plug-in for CC. But, Phing says it also works with CC. So I am not clear on the overlap here. Do I need both Phing and phpUnderControl to work with CruiseControl, or are they mutually exlclusive?
What I need exactly is something that can:
* Check out source from SVN
* Install the database from SQL file
* Generate some local configuration files from a series of templates and an ini file
* Run all of our unit tests (currently ST, but easy to convert to PHPUnit) and send an email to the dev team if any tests break (with a stack trace of course)
* Generate API documentation for the application and put it somewhere
* Run a test coverage report
Now, we have just about all of this in one form or another. But, it'd be nice to have it all automated and bundled together in one process.
|
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 phpDocumentor, PHP\_CodeSniffer, and PHPUnit whenever we do a check in. Since it's all based off of the build.xml file you can run just about any software you want through it.
|
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.Web.UI.UserControl {
// Attribute to prevent property from showing in VS Property Window?
public bool SampleProperty { get; set; }
// other stuff
}
```
|
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_column FROM my_table where search_column IN (?)
```
Using `preparedStatement.setString( 1, "'A', 'B', 'C'" );` is essentially a non-working attempt at a workaround of the reasons for using `?` in the first place.
What workarounds are available?
|
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 search_column = ?`, execute it for each value and UNION the results client-side. Requires only one prepared statement. Slow and painful.
* Prepare `SELECT my_column FROM my_table WHERE search_column IN (?,?,?)` and execute it. Requires one prepared statement per size-of-IN-list. Fast and obvious.
* Prepare `SELECT my_column FROM my_table WHERE search_column = ? ; SELECT my_column FROM my_table WHERE search_column = ? ; ...` and execute it. [Or use `UNION ALL` in place of those semicolons. --ed] Requires one prepared statement per size-of-IN-list. Stupidly slow, strictly worse than `WHERE search_column IN (?,?,?)`, so I don't know why the blogger even suggested it.
* Use a stored procedure to construct the result set.
* Prepare N different size-of-IN-list queries; say, with 2, 10, and 50 values. To search for an IN-list with 6 different values, populate the size-10 query so that it looks like `SELECT my_column FROM my_table WHERE search_column IN (1,2,3,4,5,6,6,6,6,6)`. Any decent server will optimize out the duplicate values before running the query.
None of these options are ideal.
The best option if you are using JDBC4 and a server that supports `x = ANY(y)`, is to use `PreparedStatement.setArray` as described in [Boris's anwser](https://stackoverflow.com/questions/178479/preparedstatement-in-clause-alternatives/10240302#10240302).
There doesn't seem to be any way to make `setArray` work with IN-lists, though.
---
Sometimes SQL statements are loaded at runtime (e.g., from a properties file) but require a variable number of parameters. In such cases, first define the query:
```
query=SELECT * FROM table t WHERE t.column IN (?)
```
Next, load the query. Then determine the number of parameters prior to running it. Once the parameter count is known, run:
```
sql = any( sql, count );
```
For example:
```
/**
* Converts a SQL statement containing exactly one IN clause to an IN clause
* using multiple comma-delimited parameters.
*
* @param sql The SQL statement string with one IN clause.
* @param params The number of parameters the SQL statement requires.
* @return The SQL statement with (?) replaced with multiple parameter
* placeholders.
*/
public static String any(String sql, final int params) {
// Create a comma-delimited list based on the number of parameters.
final StringBuilder sb = new StringBuilder(
String.join(", ", Collections.nCopies(possibleValue.size(), "?")));
// For more than 1 parameter, replace the single parameter with
// multiple parameter placeholders.
if (sb.length() > 1) {
sql = sql.replace("(?)", "(" + sb + ")");
}
// Return the modified comma-delimited list of parameters.
return sql;
}
```
For certain databases where passing an array via the JDBC 4 specification is unsupported, this method can facilitate transforming the slow `= ?` into the faster `IN (?)` clause condition, which can then be expanded by calling the `any` method.
|
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()) {
while(rs.next()) {
// do some...
}
}
```
or
```
final PreparedStatement statement = connection.prepareStatement(
"SELECT my_column FROM my_table " +
"where search_column IN (SELECT * FROM unnest(?))"
);
final String[] values = getValues();
statement.setArray(1, connection.createArrayOf("text", values));
try (ResultSet rs = statement.executeQuery()) {
while(rs.next()) {
// do some...
}
}
```
|
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. Custom functions - See various solutions in the notes section: <http://php.net/manual/en/ref.mail.php>
|
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", that's 6 mutually exclusive events, although calculating the probability of a clash gets a little harder than P(A or B) = P(A) + P(B), as obviously it includes numbers and from the code below, you can see it works out whether to use a number or letter using 50/50.
I'm interested in the clash rate and if the code below is a realistic simulation of anticipated clash rate you'd get from generating a hash. On average I get 40-50 clashes per million, however bare in mind the uid wouldn't be generated a million times at once, but probably only around 10-1000 times a minute.
What is the probability of a clash each time, and can anyone suggest a better way of doing it?
```
static Random _random = new Random();
public static void main()
{
// Size of the key, 6
HashSet<string> set = new HashSet<string>();
int clashes = 0;
for (int n=0;n < 1000000;n++)
{
StringBuilder builder = new StringBuilder();
for (int i =0;i < 7;i++)
{
if (_random.NextDouble() > 0.5)
{
builder.Append((char)_random.Next(97,123));
}
else
{
builder.Append(_random.Next(0,9).ToString());
}
}
if (set.Contains(builder.ToString()))
{
clashes++;
Console.WriteLine("clash: (" +n+ ")" +builder.ToString());
}
set.Add(builder.ToString());
_random.Next();
//Console.Write(builder.ToString());
}
Console.WriteLine("Clashes: " +clashes);
Console.ReadLine();
}
```
**UPDATE:**
[Here's the resulting article](http://www.yetanotherchris.me/home/2009/3/3/friendly-unique-id-generation-part-1.html) from this question
I really asked two questions here so I was cheating. The answer I was after was rcar's, however Sklivvz's is also the answer to the 2nd part (an alternative). Is it possible to make a custom unique id generator in a database, or would it be client side (which would be 2 possible reads first)?
The general idea I was after was using Ids in databases or other stores that can be used by phone or printed material, not a giant 16 byte guid.
**UPDATE 2:** I put the formula for two mutually exclusive events above instead of 2 independent ones (as getting an 'a' the first time doesn't mean you can't get an 'a' the second time). Should've been P(A and B) = P(A) x P(B)
|
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, around 1.7% after 10 million IDs, and around 16% after 100 million.
1000 IDs/minute works out to about 43 million/month, so as Sklivvz pointed out, using some incrementing ID is probably going to be a better way to go in this case.
EDIT:
To explain the math, he's essentially flipping a coin and then picking a number or letter 6 times. There's a 0.5 probability that the coin flip matches, and then 50% of the time there's a 1/10 chance of matching and a 50% chance of a 1/26 chance of matching. That happens 6 times independently, so you multiply those probabilities together.
|
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 URLs would be:
```
http://example.com/1
http://example.com/2
...
http://example.com/2W
...
```
|
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 Henry Jones Chicago 1899
```
I need to find the 3 oldest persons, but only one of every city.
If it would just be the three oldest, it would be...
* Henry Jones / Chicago
* Mac Taylor / New York
* Egon Spengler / New York
However since both Egon Spengler and Mac Taylor are located in New York, Egon Spengler would drop out and the next one (Sarah Connor / Los Angeles) would come in instead.
Any elegant solutions?
**Update:**
Currently a variation of PConroy is the best/fastest solution:
```
SELECT P.*, COUNT(*) AS ct
FROM people P
JOIN (SELECT MIN(Birthyear) AS Birthyear
FROM people
GROUP by City) P2 ON P2.Birthyear = P.Birthyear
GROUP BY P.City
ORDER BY P.Birthyear ASC
LIMIT 10;
```
His original query with "IN" is extremly slow with big datasets (aborted after 5 minutes), but moving the subquery to a JOIN will speed it up a lot. It took about 0.15 seconds for approx. 1 mio rows in my test environment. I have an index on "City, Birthyear" and a second one just on "Birthyear".
Note: This is related to...
* [Selecting unique rows in a set of two possibilities](https://stackoverflow.com/questions/150610/selecting-unique-rows-in-a-set-of-two-possibilities)
* [SQL Query to get latest price](https://stackoverflow.com/questions/49404/sql-query-to-get-latest-price)
|
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 the oldest in their city (Egon Spengler drops out..)
```
SELECT Name, City, Birthyear, COUNT(*) AS ct
FROM table
WHERE Birthyear IN (SELECT MIN(Birthyear)
FROM table
GROUP by City)
GROUP BY City
ORDER BY Birthyear DESC LIMIT 3;
+-----------------+-------------+------+----+
| name | city | year | ct |
+-----------------+-------------+------+----+
| Henry Jones | Chicago | 1899 | 1 |
| Mac Taylor | New York | 1955 | 1 |
| Sarah Connor | Los Angeles | 1959 | 1 |
+-----------------+-------------+------+----+
```
**Edit** - added `GROUP BY City` to outer query, as people with same birth years would return multiple values. Grouping on the outer query ensures that only one result will be returned per city, if more than one person has that minimum `Birthyear`. The `ct` column will show if more than one person exists in the city with that `Birthyear`
|
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
```
String large = ... // read 10k string
String small = large.substring(...) // extrakt a few chars
large = null; // large String object no longer reachable,
// but 10k char[] still alive, as long as small lives
```
might cause unexpected memory usage.
|
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 a lot of Heap left.
So it shouldn't be a concern unless you are interning all of these strings. If it becomes a concern, it would be possible to have your own Map implementation to store these strings, so you don't use the internal mechanism.
I checked the implementation of the intern() method and it is native, so it does not seem to be straightforward to measure the memory consumption, or to see the contents of the pool.
You can use this flag to increase the PermSize if you run out of memory:
```
-XX:MaxPermSize=64m
```
|
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" />
</Children>
</Abc:CustomControlUno>
```
You'd need the code in the control to be along the lines of:
```
[ParseChildren(true)]
[PersistChildren(true)]
[ToolboxData("<{0}:CustomControlUno runat=server></{0}:CustomControlUno>")]
public class CustomControlUno : WebControl, INamingContainer
{
private Control1ChildrenCollection _children;
[PersistenceMode(PersistenceMode.InnerProperty)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public Control1ChildrenCollection Children
{
get
{
if (_children == null)
{
_children = new Control1ChildrenCollection();
}
return _children;
}
}
}
public class Control1ChildrenCollection : List<Control1Child>
{
}
public class Control1Child
{
public int IntegerProperty { get; set; }
}
```
|
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>
</IfNotDiscount>
</wc:PriceInfo>
```
In the code I then set the `HasDiscount` property of the control to a boolean, which decides which clause is rendered.
The big difference from Rob's solution, is that the clauses within the control really can hold arbitrary HTML/ASPX code.
And here is the code for the control:
```
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebUtilities
{
[ToolboxData("<{0}:PriceInfo runat=server></{0}:PriceInfo>")]
public class PriceInfo : WebControl, INamingContainer
{
private readonly Control ifDiscountControl = new Control();
private readonly Control ifNotDiscountControl = new Control();
public bool HasDiscount { get; set; }
[PersistenceMode(PersistenceMode.InnerProperty)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public Control IfDiscount
{
get { return ifDiscountControl; }
}
[PersistenceMode(PersistenceMode.InnerProperty)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public Control IfNotDiscount
{
get { return ifNotDiscountControl; }
}
public override void RenderControl(HtmlTextWriter writer)
{
if (HasDiscount)
ifDiscountControl.RenderControl(writer);
else
ifNotDiscountControl.RenderControl(writer);
}
}
}
```
|
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_started/windows.html#library-naming) because this is generally not possible any other way (the executable could have been created in any number of languages, by any number of compiler versions, after all).
---
(Added much later): [Turns out GCC has this feature in 4.3 if asked for when you compile the code](http://dberkholz.wordpress.com/2007/10/12/new-gcc-hotness/?referer=sphere_related_content/):
> A new command-line switch -frecord-gcc-switches ... causes the command line that was used to invoke the compiler to be recorded into the object file that is being created. The exact format of this recording is target and binary file format dependent, but it usually takes the form of a note section containing ASCII text.
|
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 actual titles linked to the table with the global id.
I just want to have something like this
```
ID TITLE
1 Array("english title", "nederlandse titel");
```
I'm using PHP/MSYQL, so if it would be doable could you please explain in these languages.
Oh yeah I figured that I could format it funky and use the split function to turn it into an array again. But I wonder if I could just store it as an array right away, I case the user might type something with the same formatting (one out of a million)
|
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 want to support and if that number will change in the future.
**edit:** a good point mentioned by [dcousineau](https://stackoverflow.com/users/20265/dcousineau) (see comments)
> Sometimes the serialized output, even after escaping, throws characters into the query that screws things up. You may want to wrap your serialize() in base64\_encode() calls and then use base64\_decode() before you unserialize.
adjusted code for those situations:
```
$title = base64_encode(serialize($array) );
$title = unserialize(base64_decode($mysql_data) );
```
|
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, select, etc
cons: limited number of languages, adding more is an ALTER TABLE
Given our two choices, you usually should should pick the first one. Unless you're dealing with just an obscene amount of transactions that cannot be parallelized, or you absosmurfly can ensure that you will never add languages, the extra flexibility in schema layout will save you headaches in the long run.
|
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 ch = stream.get()) != -1) ...
```
The compiler (VC++ 9.0) does not like it at all.
Is this compliant behavior? Is there a reason for it?
**EDIT**: I found I can do this:
```
while (int ch = stream.get() != -1) ...
```
but because of precedence rules, that's interpreted as:
```
while (int ch = (stream.get() != -1)) ...
```
which is not what I want.
|
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 condition to declare a variable, however, they have done so by adding a new grammar rule called 'condition' that can be an expression or a declarator with an initializer. The result is that just because you are in the condition of an `if`, `for`, `while`, or `switch` does not mean that you can declare a variable inside an expression.
|
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 like expression, but it's a different syntactical entity.
When you write
```
while(int i = 1) {
}
```
, that's perfectly fine. "int i=1" is a declaration. However, what you want is
```
while ( (int i = 1) + 3) {
}
```
This is a very different animal. You want an expression inside while(), where one of the terms of the expression is a declaration. Now, declaration is a statement, and as such cannot be part of expression. That's why what you need to be done cannot be done.
(after writing the whole rant, I noticed that 2 other people wrote the same thing. Oh well, the more the merrier.)
|
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 schedule or if something failed/broken, i need to run them a couple times.
The problem with this is that I also have some external notifications set into the tasks (posting to twitter, sending an email, etc) that I DONT want to happen everytime I run the script manually.
I'm using php5 (if it matters), its a fairly standard linux server environment.
Any ideas?
|
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 in. In my environment, the following environment variables are set when running a script manually that aren't present when running from cron:
* TERM
* SSH\_CLIENT
* SSH\_TTY
* SSH\_CONNECTION
There are others too. So for example if you always use SSH to access the box, then the following line would detect if the script is running from cron:
`$cron = !isset($_ENV['SSH_CLIENT']);`
|
```
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_html (www)` create a directory called `CISYSTEM`, and inside that directory create a directory from the version you're using, `202`, `210` etc.
```
/CISYSTEM
/202
/210
/another_CI_version
/projekt_application
/models
/views
/controllers
/private_assets
/public_html
/projekt
index.php
.htaccess
css
img
js
lib
```
The beauty of this directory structure is it adds another layer of security and makes it dead-easy to upgrade/swap out your CI core. Plus, you're not supposed to make changes to the core - having a single directory where your core is stored and having all projects reference it keeps things DRY.
All this directory shuffling requires you to reroute a few things though. Luckily, CodeIgniter makes it easy -- all changes can be made in the `index.php` file.
Open `index.php` and reroute a couple things:
Change: `$system_path = 'system';`
To: `$system_path = '../../CISYSTEM/210';`
Change: `$application_folder = 'application';`
To: `$application_folder = '../../projekt_application';`
---
Also, I see a lot of people talking about using `site_url()` in the other answers. I recommend a less verbose way of using `site_url()`... you don't have to call it every time if you make use of HTML's `<base>` element:
`<base href="<?= site_url();?>">`
Just include that in your application's `<head>` and you can call your controllers directly... as in:
`<a href='controllername/functionname'>Some Action</a>`
Cheers
|
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):
<http://tartarus.org/~martin/PorterStemmer/php.txt>
This works, up to a point, but doesn't return "real" words. The example above is stemmed to "commun".
I've tried "Snowball" (suggested within another Stack Overflow thread).
<http://snowball.tartarus.org/demo.php>
For my example (community / communities), Snowball stems to "communiti".
**Question**
Are there any other stemming algorithms that will do this? Has anyone else solved this problem?
*My current thinking is that I could use a stemming algorithm to avoid duplicates and then pick the shortest word I encounter to be the actual word to display.*
|
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 back to real words. I can basically see two potential ways to do this:
1. Locate or create a large dictionary which maps each possible stem back to an actual word. (e.g., communiti -> community)
2. Create a function which compares each stem to a list of the words that were reduced to that stem and attempts to determine which is most similar. (e.g., comparing "communiti" against "community" and "communities" in such a way that "community" will be recognized as the more similar option)
Personally, I think the way I would do it would be a dynamic form of #1, building up a custom dictionary database by recording every word examined along with what it stemmed to and then assuming that the most common word is the one that should be used. (e.g., If my body of source text uses "communities" more often than "community", then map communiti -> communities.) A dictionary-based approach will be more accurate in general and building it based on the stemmer input will provide results customized to your texts, with the primary drawback being the space required, which is generally not an issue these days.
|
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 lemmatizers for English, I've only used `morpha` though.
*Morpha* is just a big lex-file which you can compile into an executable.
Usage example:
```
$ cat test.txt
Community
Communities
$ cat test.txt | ./morpha -uc
Community
Community
```
You can get morpha from <http://www.informatics.sussex.ac.uk/research/groups/nlp/carroll/morph.html>
|
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 problems.
1. *PDO mssql:*
```
$dbh = new PDO ('mssql:host='.$mssql_server.';dbname='.$mssql_db, $mssql_login, $mssql_pwd);
```
in which case a result of a simple query like that:
```
SELECT field1 FROM tbl1 WHERE id=1
```
shows `field1` data truncated to 255 bytes.
2. *PDO odbc:*
```
$dbh = new PDO ('odbc:DSN=myDSN;UID='.$mssql_login.';PWD='.$mssql_pwd);
```
in which case a result of the same query shows full not truncated data but with question marks instead of Russian symbols.
---
Notes:
* In the SQL Management Studio data is not truncated and Russian symbols are displayed properly as well.
* We have Windows 2003 Enterprise Edition SP2
So what should we choose as a connection method and how to fix corresponding issues?
|
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.getSystemColor(SWT.COLOR_LIST_BACKGROUND);
```
Note that you do not need to dispose these colors because SWT created them.
|
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'm afraid that this is a fragile solution because as far as I know, the compiler doesn't guarantee inlining, even when you specify the `inline` keyword. If this is not true, please correct me.
**Anyway, what happens to static variables inside this function? How many copies do I end up with?**
|
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++14 (n3797)
>
> When a name has internal linkage , the entity it denotes can be referred to by names from other scopes in the same translation unit.
>
> 3.5/2 - C++14 (n3797)
If you declare this static function in a header, then all the compilation units including this header will have their own copy of the function.
The thing is, if there are static variables inside that function, each compilation unit including this header will also have their own, personal version.
## inline function?
Declaring it inline makes it a candidate for inlining (it does not mean a lot nowadays in C++, as the compiler will inline or not, sometimes ignoring the fact the keyword inline is present or absent):
> A function declaration (8.3.5, 9.3, 11.3) with an inline specifier declares an inline function. The inline specifier indicates to the implementation that inline substitution of the function body at the point of call is to be preferred to the usual function call mechanism. An implementation is not required to perform this inline substitution at the point of call; however, even if this inline substitution is omitted, the other rules for inline functions defined by 7.1.2 shall still be respected.
>
> 7.1.2/2 - C++14 (n3797)
In a header, its has an interesting side effect: The inlined function can be defined multiple times in the same module, and the linker will simply join "them" into one (if they were not inlined for compiler's reason).
For static variables declared inside, the standard specifically says there one, and only one of them:
> A static local variable in an extern inline function always refers to the same object.
>
> 7.1.2/4 - C++98/C++14 (n3797)
(functions are by default extern, so, unless you specifically mark your function as static, this applies to that function)
This has the advantage of "static" (i.e. it can be defined in a header) without its flaws (it exists at most once if it is not inlined)
## static local variable?
Static local variables have no linkage (they can't be referred to by name outside their scope), but has static storage duration (i.e. it is global, but its construction and destruction obey to specific rules).
## static + inline?
Mixing inline and static will then have the consequences you described (even if the function is inlined, the static variable inside won't be, and you'll end with as much static variables as you have compilation units including the definition of your static functions).
## Answer to author's additional question
> Since I wrote the question I tried it out with Visual Studio 2008. I tried to turn on all the options that make VS act in compliance with standards, but it's possible that I missed some. These are the results:
>
> When the function is merely "inline", there is only one copy of the static variable.
>
> When the function is "static inline", there are as many copies as there are translation units.
>
> The real question is now whether things are supposed to be this way, or if this is an idiosyncrasy of the Microsoft C++ compiler.
So I suppose you have something like that:
```
void doSomething()
{
static int value ;
}
```
You must realise that the static variable inside the function, simply put, a global variable hidden to all but the function's scope, meaning that only the function it is declared inside can reach it.
Inlining the function won't change anything:
```
inline void doSomething()
{
static int value ;
}
```
There will be only one hidden global variable. The fact the compiler will try to inline the code won't change the fact there is only one global hidden variable.
Now, if your function is declared static:
```
static void doSomething()
{
static int value ;
}
```
Then it is "private" for each compilation unit, meaning that every CPP file including the header where the static function is declared will have its own private copy of the function, including its own private copy of global hidden variable, thus as much variables as there are compilation units including the header.
Adding "inline" to a "static" function with a "static" variable inside:
```
inline static void doSomething()
{
static int value ;
}
```
has the same result than not adding this "inline" keyword, as far as the static variable inside is concerned.
**So the behaviour of VC++ is correct, and you are mistaking the real meaning of "inline" and "static".**
|
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 regardless of the source file they were called from.
Think like a compiler for a moment - how could it be otherwise? Each compilation unit (source file) is independent of the others, and can be compiled separately; each one must therefore create a copy of the variable, thinking it is the only one. The linker has the ability to reach across those boundaries and adjust the references for both variables and functions.
|
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> listeners;
if( ( listeners = map.get( eventType ) ) == null ) {
listeners = new java.util.concurrent.CopyOnWriteArrayList<Listener>();
map.put( eventType, listeners );
}
listeners.add( listener );
}
}
```
This code snippet is nothing but a bit improved listener pattern where each listener is telling what type of event it is interested in, and the provided method maintains a concurrent map of these relationships.
Initially, I wanted this method to be called via my own annotation framework, but bumped into a brick wall of various annotation limitations (e.g. you can't have *java.lang.Enum* as annotation param, also there's a set of various classloader issues) therefore decided to use Spring.
Could anyone tell me how do I Spring\_ify\_ this? What I want to achive is:
1. Define *Maintainer* class as a Spring bean.
2. Make it so that all sorts of listeners would be able to register themselves to *Maintainer* via XML by using *addListener* method. Spring doc nor Google are very generous in examples.
Is there a way to achieve this easily?
|
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 choice). The listener can then register itself with the Maintainer.
other than that, I'm not 100% clear on exactly what your difficulty is with Spring at the moment! :)
|
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 );
```
If two threads call this method at the same time (for an event type that previously had no listeners), map.get( eventType ) will return null in both threads, each thread will create its own CopyOnWriteArrayList (each containing a single listener), one thread will replace the list created by the other, and the first listener will be forgotten.
To fix this, change:
```
private Map<Enum, List<Listener>> map;
...
map.put( eventType, listeners );
```
to:
```
private ConcurrentMap<Enum, List<Listener>> map;
...
map.putIfAbsent( eventType, listeners );
listeners = map.get( eventType );
```
|
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 need to do type guessing. (correct me if i am wrong).
so question remains WHY NOT at class level while its allowed at method level
|
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.com/ericlippert/archive/2009/01/26/why-no-var-on-fields.aspx)
|
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 an actual compiler guy on the C# compiler team, you'd get something official, but there's no magic happening here and it should be possible to do the same for members fields.
|
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 hibernate as well, just as an fyi
|
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 (load=nullSafeGet and store=nullSafeSet methods in them).
See <http://docs.jboss.org/hibernate/core/3.3/reference/en/html/mapping.html#mapping-types-custom>
But I'd still save absolute time anyway. May help in future.
P.S. That's all presuming storing Date is out of question for some reason. TimeZone in Date sometimes gets in the way, really. ;)
|
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 also offers both timezone dependent Time handling and timezone independent time handling which eases difficulties when dealing with intervals.
|
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 row error details, as in the following example (which uses Log4Net for logging):
```
...
try
{
adapter.Fill(dataTable); // or dataSet
}
catch (ConstraintException)
{
LogErrors(dataTable);
throw;
}
...
private static void LogErrors(DataSet dataSet)
{
foreach (DataTable dataTable in dataSet.Tables)
{
LogErrors(dataTable);
}
}
private static void LogErrors(DataTable dataTable)
{
if (!dataTable.HasErrors) return;
StringBuilder sb = new StringBuilder();
sb.AppendFormat(
CultureInfo.CurrentCulture,
"ConstraintException while filling {0}",
dataTable.TableName);
DataRow[] errorRows = dataTable.GetErrors();
for (int i = 0; (i < MAX_ERRORS_TO_LOG) && (i < errorRows.Length); i++)
{
sb.AppendLine();
sb.Append(errorRows[i].RowError);
}
_logger.Error(sb.ToString());
}
```
|
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 developers wishing to adapt the request to a Servlet.
In the filter, wrap the request in an instance of your subclass.
|
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 any parameters you want.
This is an example of the filter:
```
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletRequest customRequest = new CustomHttpServletRequest(httpRequest);
customRequest.addParameter(xxx, "xxx");
chain.doFilter(customRequest, response);
}
```
|
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 haven't investigated it at all. (<https://daffodilreplicator.dev.java.net/>)
The one I am currently considering using is called SymmetricDS (<http://symmetricds.sourceforge.net/>)
There are others, they each do it slightly differently. Some use triggers, some poll, some use intercepting JDBC drivers. You need to decide what technical limitations you are under to determine which one you really want to use.
Wikipedia provides a nice overview of different techniques (<http://en.wikipedia.org/wiki/Multi-master_replication>) and also provides a link to another alternative DBReplicator (<http://dbreplicator.org/>).
|
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 synced already. You can either do it at runtime by getting a list of uuids from TableInA and TableInB and working out which entries are new, or you can have a table of items that need to be synced (populate with a trigger upon insert/update in TableInA), and run from that. Your tool can be a TimerTask so databases are kept synced at the time granularity that you desire.
However there is probably some tool out there that does it all without any of this implementation faff, and each implementation would be different based on business needs anyway. In addition at the database level there will be replication tools.
|
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 cool thing will be to print when the user makes his own version of the graphic. I think that the best solution is to POST the entire HTML with *document.getElementsByTagName('html')[0].innerHTML* as RoBorg has said and then generate the PDF with a library such as *dompdf*
|
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 this is the accepted answer; [wallacer's answer](https://stackoverflow.com/a/1203361/23746) is indeed much better:
```
return filename.split('.').pop();
```
---
My old answer:
```
return /[^.]+$/.exec(filename);
```
Should do it.
**Edit:** In response to PhiLho's comment, use something like:
```
return (/[.]/.exec(filename)) ? /[^.]+$/.exec(filename) : undefined;
```
|
```
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/12900504/1249581) below, particularly files with no extension (`.htaccess` etc included).
It's very performant, and handles corner cases in an arguably better way by returning `""` instead of the full string when there's no dot or no string before the dot. It's a very well crafted solution, albeit tough to read. Stick it in your helpers lib and just use it.
**Old Edit:**
A safer implementation if you're going to run into files with no extension, or hidden files with no extension (see VisioN's comment to Tom's answer above) would be something along these lines
```
var a = filename.split(".");
if( a.length === 1 || ( a[0] === "" && a.length === 2 ) ) {
return "";
}
return a.pop(); // feel free to tack .toLowerCase() here if you want
```
If `a.length` is one, it's a visible file with no extension ie. *file*
If `a[0] === ""` and `a.length === 2` it's a hidden file with no extension ie. *.htaccess*
This should clear up issues with the slightly more complex cases. In terms of performance, I think this solution is [a little slower than regex](https://stackoverflow.com/a/12900504/1249581) in most browsers. However, for most common purposes this code should be perfectly usable.
|
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 the changed data. Using a better model structure would be one way of reducing the duplication of the data, but there may be situation where the duplicated data needs to be changed on an individual basis in the future.
|
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 (with a new ID), rather than the old 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
> identical copy of the original object (if you don't get validation
> errors) as soon as you click that link, and if you forget to make the
> small changes that you wanted in the new object you will end up with a
> duplicate of the existing object.
>
> On the other hand, django-modelclone offers an intermediate view, that
> basically pre-fills the form for you. So you can modify and then save
> a new instance. Or just go away without side effects.
|
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-source, all-Javascript solution instead.
I'm a recent convert to jQuery, and I've been amazed at what can be done purely on the client side with very compact add-ons like [Flexigrid](http://www.webplicity.net/flexigrid/) and of course [the excellent WMD](http://wmd-editor.com/). I've done a little poking around for all-Javascript editors, and this is what I've found so far:
* [Batiste jQueryEditor](http://batiste.dosimple.ch/blog/posts/2007-09-11-1/rich-text-editor-jquery.html)
* [Xinha](http://xinha.webfactional.com/)
* [YUI Rich Text Editor](http://developer.yahoo.com/yui/editor/)
* [Tiny MCE](http://tinymce.moxiecode.com/)
* [FCKeditor](http://www.fckeditor.net/demo/skins?skin=office2003)
After a superficial review, Tiny MCE looks like a good choice; but I'd be interested in hearing from people in the SO community who have actually used these. Let me know what you think.
|
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 any libraries installed on your server.
|
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 good.
### A short version
1. Create a `int result` and assign a **non-zero** value.
2. For *every field* `f` tested in the `equals()` method, calculate a hash code `c` by:
* If the field f is a `boolean`:
calculate `(f ? 0 : 1)`;
* If the field f is a `byte`, `char`, `short` or `int`: calculate `(int)f`;
* If the field f is a `long`: calculate `(int)(f ^ (f >>> 32))`;
* If the field f is a `float`: calculate `Float.floatToIntBits(f)`;
* If the field f is a `double`: calculate `Double.doubleToLongBits(f)` and handle the return value like every long value;
* If the field f is an *object*: Use the result of the `hashCode()` method or 0 if `f == null`;
* If the field f is an *array*: see every field as separate element and calculate the hash value in a *recursive fashion* and combine the values as described next.
3. Combine the hash value `c` with `result`:
```
result = 37 * result + c
```
4. Return `result`
This should result in a proper distribution of hash values for most use situations.
|
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 standard library in Java 7 (`java.util.Objects.hash`) but works the same way.
|
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 message in the build indicating that a (custom) package dependency rule has been violated and the build aborted. I also would like to maintain the dependencies in a list, preferably in a text file, outside of the Ant scripts or IDE project files.
(I don't know Maven but I've read it here it has better support for module dependency management)
|
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 idea (details may be out of date):
<http://www.eclipsezone.com/eclipse/forums/t53736.html>
If you're using Eclipse (or OSGi) plugins, then the "public" parts of the plugin/module are explicitly defined and this is part of the model.
|
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 relate back to the OS error codes.
Note that the actual limit is [pretty darn big](http://en.wikipedia.org/wiki/Ext2#File_system_limits) for a "typical" EXT2 filesystem - in the Terabytes. You'll likely never reach it, in practice. If you seriously are accumulating Terabytes of data, you might want to consider whether there's a more reasonable way to store it, rather than a single gigantic file.
|
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 understand that the listeners are registered in the order their order in web.xml but this sounds a bit vague to me, too vague to rely on it.
Do you have a hint how I can solve my problem?
|
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 requests. This will let each Listener update only what is essential. You can put the common code in a base Listener so that there is no code duplication.
|
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' ]
```
More information available on [MSDN](http://msdn.microsoft.com/en-us/library/ms190479.aspx).
|
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].DatabaseName.dbo.TableName
```
|
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.Where(cust => cust.IsActive);
```
(if we had a non-trivial select, it would add .Select(...some projection...)
Different LINQ kewords map to different methods - i.e. there is OrderBy, GroupBy, ThenBy, OrderByDescending, etc.
In the case of `IEnumerable<T>`/`IQueryable<T>`, this then resolves these via extension methods (typically courtesy of `Enumerable`/`Queryable`)- however, if your queryable objects declared their own Where/OrderBy/etc then these would get used in preference.
Jon Skeet covers this a lot more in the latter parts of [C# in Depth](http://www.manning.com/skeet/). I've also seen [an example of Jon's](http://msmvps.com/blogs/jon_skeet/archive/2008/02/29/odd-query-expressions.aspx) where he discusses some really bizarre implications of this - such as calling static methods on a type.
|
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/odd-query-expressions.aspx). The compiler really doesn't care very much how it finds a "Select" member, or "Where" etc.
The way that the compiler translates the code into "C# 3.0 without query expressions" before doing normal compilation is really beautiful - it's a wonderful way of introducing new functionality into the language but only having an impact in one isolated portion of the specification.
|
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 those objects in my STL containers?
I realize this is somewhat short on details, but I'm looking for the "theoretical" better answer if it exists, since I know both of these solutions are possible.
Two very obvious disadvantage to playing with pointers:
1) I must manage allocation/deallocation of these objects myself in a scope beyond the STL.
2) I cannot create a temp object on the stack and add it to my containers.
Is there anything else I'm missing?
|
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 common storing pointers will save the copy/relocation costs.
|
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 default constructor doesn't make sense, or copies of objects are expensive, then storing with pointers is probably the way to go.
If you decide to use pointers to objects, take a look at the [Boost Pointer Container Library](http://www.boost.org/doc/libs/1_35_0/libs/ptr_container/doc/ptr_container.html). This boost library wraps all the STL containers for use with dynamically allocated objects.
Each pointer container (for example ptr\_vector) takes ownership of an object when it is added to the container, and manages the lifetime of those objects for you. You also access all the elements in a ptr\_ container by reference. This lets you do things like
```
class BigExpensive { ... }
// create a pointer vector
ptr_vector<BigExpensive> bigVector;
bigVector.push_back( new BigExpensive( "Lexus", 57700 ) );
bigVector.push_back( new BigExpensive( "House", 15000000 );
// get a reference to the first element
MyClass& expensiveItem = bigList[0];
expensiveItem.sell();
```
These classes wrap the STL containers and work with all of the STL algorithms, which is really handy.
There are also facilities for transferring ownership of a pointer in the container to the caller (via the release function in most of the containers).
|
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=\"$basename\"");
header('Content-Length: '. filesize($filename));
if ( @readfile($filename)===false ) {
header("HTTP/1.0 500 Internal Server Error");
loadErrorPage('500');
}
```
Downloads works as charm in any Browser except IE, I have seen problems related to 'no-cache' headers but I don't send anything like that, they talk about utf-8 characters, but there is not any `utf-8 characters`(and the $filename has not any utf-8 characteres neither).
|
[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 explodes cryptically when you
> attempt to save the output page to disk.
>
> Before session\_start(), add "session\_cache\_limiter('none');", or look up that
> function and tweak the limiter as appropriate (probably 'private' is closer to
> the mark).
I realize the code snippet you posted does not include a call to `session_start();`, but I figured I'd share this possible solution in case you do have a call to it and just didn't show us.
|
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/error-internet-explorer-cannot-download-filename-from-webserver)
|
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('Initially ' + (window.navigator.onLine ? 'on' : 'off') + 'line');
window.addEventListener('online', () => console.log('Became online'));
window.addEventListener('offline', () => console.log('Became offline'));
document.getElementById('statusCheck').addEventListener('click', () => console.log('window.navigator.onLine is ' + window.navigator.onLine));
```
```
<button id="statusCheck">Click to check the <tt>window.navigator.onLine</tt> property</button><br /><br />
Check the console below for results:
```
Try setting your system or browser in offline/online mode and check the log or the `window.navigator.onLine` property for the value changes.
Note however this quote from [Mozilla Documentation](https://developer.mozilla.org/en-US/docs/Web/API/NavigatorOnLine.onLine):
> In Chrome and Safari, if the browser is not able to connect to a local area network (LAN) or a router, it is offline; all other conditions return `true`. So while **you can assume that the browser is offline when it returns a `false` value**, **you cannot assume that a `true` value necessarily means that the browser can access the internet**. You could be getting false positives, such as in cases where the computer is running a virtualization software that has virtual ethernet adapters that are always "connected." Therefore, if you really want to determine the online status of the browser, you should develop additional means for checking.
>
> In Firefox and Internet Explorer, switching the browser to offline mode sends a `false` value. Until Firefox 41, all other conditions return a `true` value; since Firefox 41, on OS X and Windows, the value will follow the actual network connectivity.
(emphasis is my own)
This means that if `window.navigator.onLine` is `false` (or you get an `offline` event), you are guaranteed to have no Internet connection.
If it is `true` however (or you get an `online` event), it only means the system is connected to some network, at best. It does not mean that you have Internet access for example. To check that, you will still need to use one of the solutions described in the other answers.
I initially intended to post this as an update to [Grant Wagner's answer](https://stackoverflow.com/a/189457/525036), but it seemed too much of an edit, especially considering that the 2014 update was already [not from him](https://stackoverflow.com/posts/189457/revisions).
|
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 lot of error-prone work of handling state.. wireless connections may come and go, etc. So your best bet may be to just fail gracefully, preserve the data, and alert the user.. allowing them to eventually fix the connection problem if there is one, and to continue using your app with a fair amount of forgiveness.
**Sidenote:** You could check a reliable site like google for connectivity, but this may not be entirely useful as just trying to make your own request, because while Google may be available, your own application may not be, and you're still going to have to handle your own connection problem. Trying to send a ping to google would be a good way to confirm that the internet connection itself is down, so if that information is useful to you, then it might be worth the trouble.
**Sidenote**: *Sending a Ping* could be achieved in the same way that you would make any kind of two-way ajax request, but sending a ping to google, in this case, would pose some challenges. First, we'd have the same cross-domain issues that are typically encountered in making Ajax communications. One option is to set up a server-side proxy, wherein we actually `ping` google (or whatever site), and return the results of the ping to the app. This is a **catch-22** because if the internet connection is actually the problem, we won't be able to get to the server, and if the connection problem is only on our own domain, we won't be able to tell the difference. Other cross-domain techniques could be tried, for example, embedding an iframe in your page which points to google.com, and then polling the iframe for success/failure (examine the contents, etc). Embedding an image may not really tell us anything, because we need a useful response from the communication mechanism in order to draw a good conclusion about what's going on. So again, determining the state of the internet connection as a whole may be more trouble than it's worth. You'll have to weight these options out for your specific app.
|
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 do it.
The easiest way to get the last error is
```
$contents = @file('/path/to/error.log', FILE_SKIP_EMPTY_LINES);
if (is_array($contents)) {
echo end($contents);
}
unset($contents);
```
There's probably a better way of doing this that doesn't oink up memory, but I'll leave that as an exercise for the reader.
One last comment: PHP also has an ini setting to redirect PHP errors to a log file: `error_log = /path/to/error.log`
You can set this in httpd.conf or in an .htaccess file (if you have access to one) using the php\_flag notation:
```
php_flag error_log /web/mysite/logs/error.log
```
|
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 $line) {
// sample line: [Wed Oct 01 15:07:23 2008] [error] [client 76.246.51.127] PHP 99. Debugger->handleError() /home/gsmcms/public_html/central/cake/libs/debugger.php:0
preg_match('~^\[(.*?)\]~', $line, $date);
if(empty($date[1])) {
continue;
}
preg_match('~\] \[([a-z]*?)\] \[~', $line, $type);
preg_match('~\] \[client ([0-9\.]*)\]~', $line, $client);
preg_match('~\] (.*)$~', $line, $message);
?>
<tr>
<td><?=$date[1]?></td>
<td><?=$type[1]?></td>
<td><?=$client[1]?></td>
<td><?=$message[1]?></td>
</tr>
<?
}
?>
</table>
```
|
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? Specifically, one that takes into account space (well, MAC address), time, and randomness? I don't want to call off the box for it, I just want something like [CreateGuid()](http://msdn.microsoft.com/en-us/library/aa713311.aspx)
|
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.org/wiki/Universally_Unique_Identifier) provides a good overview.
|
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. In CS, though, you can move your image to a different monitor fine, which is a big advantage over docked applications like Visual Studio, and over regular MDI applications.
Anyway, here's my research so far. I've tried to intercept the WM\_MOUSEACTIVATE message, and use the DeferWindowPos commands to do my own ordering of the window, and then return MA\_NOACTIVATEANDEAT, but that causes the window to not be activated properly, and I believe there are other commands that "activate" a window without calling WM\_MOUSEACTIVATE (like SetFocus() I think), so that method probably won't work anyway.
I believe Windows' procedure for "activating" a window is
1. notify the unactivated window with the WM\_NCACTIVATE and WM\_ACTIVATE messages
2. move the window to the top of the z-order (sending WM\_POSCHANGING, WM\_POSCHANGED and repaint messages)
3. notify the newly activated window with WM\_NCACTIVATE and WM\_ACTIVATE messages.
It seems the cleanest way to do it would be to intercept the first WM\_ACTIVATE message, and somehow notify Windows that you're going to override their way of doing the z-ordering, and then use the DeferWindowPos commands, but I can't figure out how to do it that way. It seems once Windows sends the WM\_ACTIVATE message, it's already going to do the reordering its own way, so any DeferWindowPos commands I use are overridden.
Right now I've got a basic implementation quasy-working that makes the tool windows topmost when the app is activated, but then makes them non-topmost when it's not, but it's very quirky (it sometimes gets on top of other windows like the task manager, whereas Photoshop CS doesn't do that, so I think Photoshop somehow does it differently) and it just seems like there would be a more intuitive way of doing it.
Anyway, does anyone know how Photoshop CS does it, or a better way than using topmost?
|
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 close.
I don't like answering without a real answer, but likely **you'd have to spend a lot of time and effort to get something similar** if Photoshop-like is truly your goal. Is it worth your time? Just remember *many* programmers over *many* years and versions have come together to get Photoshop's simple-seeming windowing behavior to work just right and to feel natural to you.
It looks like you're already having to delve pretty deep into Win32 API functions and values to even glimpse at a "solution" and that should be your first red flag. Is it eventually possible? Probably. But depending on your needs and your time and a lot of other factors only you could decide, it may not be practical.
|
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 being created - if you have multiple document windows, each one gets its own set of owned child windows that you can dynamically show and hide as the document window gains and looses activation.
|
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:

I have to find this window by title and send it `Alt`+`Y` to press *Yes*:
```
int iHandle = NativeWin32.FindWindow(null, "Security Alert");
NativeWin32.SetForegroundWindow(iHandle);
System.Windows.Forms.SendKeys.Send("Y%");
```
but user can see a flickering of this window.
How can I ignore this alert?
Or disable this "untrusted certificate" check in Webbrowser control?
|
This should do it:
```
public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
return true;
}
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate);
```
Obviously, blindingly allowing certificates is a security risk. Be careful.
|
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 code changes that accept any and all certificates. It does however require the certificate to be installed wherever the application is used.
|
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."
...
```
The SQL record output would be:
```
"The","giant","dog","jumped","tripped","on","over","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 identity(1, 1) not null,
description varchar(50) not null
)
INSERT INTO test VALUES('The dog jumped over the fence')
INSERT INTO test VALUES('The giant tripped on the fence')
CREATE FUNCTION dbo.Split
(
@RowData nvarchar(2000),
@SplitOn nvarchar(5)
)
RETURNS @RtnValue table
(
Id int identity(1,1),
Data nvarchar(100)
)
AS
BEGIN
Declare @Cnt int
Set @Cnt = 1
While (Charindex(@SplitOn,@RowData)>0)
Begin
Insert Into @RtnValue (data)
Select
Data = ltrim(rtrim(Substring(@RowData,1,Charindex(@SplitOn,@RowData)-1)))
Set @RowData = Substring(@RowData,Charindex(@SplitOn,@RowData)+1,len(@RowData))
Set @Cnt = @Cnt + 1
End
Insert Into @RtnValue (data)
Select Data = ltrim(rtrim(@RowData))
Return
END
CREATE FUNCTION dbo.SplitAll(@SplitOn nvarchar(5))
RETURNS @RtnValue table
(
Id int identity(1,1),
Data nvarchar(100)
)
AS
BEGIN
DECLARE My_Cursor CURSOR FOR SELECT Description FROM dbo.test
DECLARE @description varchar(50)
OPEN My_Cursor
FETCH NEXT FROM My_Cursor INTO @description
WHILE @@FETCH_STATUS = 0
BEGIN
INSERT INTO @RtnValue
SELECT Data FROM dbo.Split(@description, @SplitOn)
FETCH NEXT FROM My_Cursor INTO @description
END
CLOSE My_Cursor
DEALLOCATE My_Cursor
RETURN
END
SELECT DISTINCT Data FROM dbo.SplitAll(N' ')
```
|
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 UserDefinedFunctions
{
private class SplitStrings : IEnumerable
{
private List<string> splits;
public SplitStrings(string toSplit, string splitOn)
{
splits = new List<string>();
// nothing, return empty list
if (string.IsNullOrEmpty(toSplit))
{
return;
}
// return one word
if (string.IsNullOrEmpty(splitOn))
{
splits.Add(toSplit);
return;
}
splits.AddRange(
toSplit.Split(new string[] { splitOn }, StringSplitOptions.RemoveEmptyEntries)
);
}
#region IEnumerable Members
public IEnumerator GetEnumerator()
{
return splits.GetEnumerator();
}
#endregion
}
[Microsoft.SqlServer.Server.SqlFunction(FillRowMethodName = "readRow", TableDefinition = "word nvarchar(255)")]
public static IEnumerable fnc_clr_split_string(string toSplit, string splitOn)
{
return new SplitStrings(toSplit, splitOn);
}
public static void readRow(object inWord, out SqlString word)
{
string w = (string)inWord;
if (string.IsNullOrEmpty(w))
{
word = string.Empty;
return;
}
if (w.Length > 255)
{
w = w.Substring(0, 254);
}
word = w;
}
};
```
|
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 the indexes, that will be awesome but I guess I am asking for too much huh..
|
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 talking about [here](http://mjijackson.com/shadowbox/).
Just go to the "web" examples and click "inline". Notice keyboard shortcuts do work on the "this page" example. The only difference between the two I see is the player js files they use. "Inline" uses the html.js player and "this page" uses iframe.js. Also, I believe it uses the mootools library. Any ideas?
|
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 keyboard navigation**. I think that you want to search for this block of code and modify it so that it only cancels the default event if one of the shortcuts is used (I've added some line breaks and indention):
```
var handleKey = function(e) {
var code = SL.keyCode(e);
SL.preventDefault(e);
if (code == 81 || code == 88 || code == 27) {
SB.close()
} else {
if (code == 37) {
SB.previous()
} else {
if (code == 39) {
SB.next()
} else {
if (code == 32) {
SB[(typeof slide_timer == "number" ? "pause" : "play")]()
}
}
}
}
};
```
I think you could change it to look more like this:
```
var handleKey = function(e) {
switch (SL.keyCode(e)) {
case 81:
case 88:
case 27:
SB.close()
SL.preventDefault(e);
break;
case 37:
SB.previous()
SL.preventDefault(e);
break;
case 39:
SB.next()
SL.preventDefault(e);
break;
case 32:
SB[(typeof slide_timer == "number" ? "pause" : "play")]()
SL.preventDefault(e);
break;
}
};
```
This should prevent the shadowbox event handler from swallowing any keystrokes that it doesn't care about.
|
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
> names of its class's attributes, and
> recursively of the attributes of its
> class's base classes.
It says also that
> The list is not necessarily complete.
Is there a way to get the **complete** list? I always assumed that dir returns a complete list but apparently it does not...
Also: is there a way to list only attributes? Or only methods?
*Edit: this is actually a bug in python -> supposedly it is fixed in the 3.0 branch (and perhaps also in 2.6)*
|
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 list. The `dir` function returns the keys in the `__dict__` attribute, i.e. all the attributes accessible if the `__getattr__` method is not reimplemented.
For the second question, it does not really make sense. Actually, methods are callable attributes, nothing more. You could though filter callable attributes, and, using the `inspect` module determine the class methods, methods or functions.
|
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 wondering if there is a mechanism to create a thin dynamic class on top of an interface which would make this simple.
```
public interface DummyInterface
{
string A { get; }
string B { get; }
}
public class DummySource
{
public string A { get; set; }
public string C { get; set; }
public string D { get; set; }
}
public class Test
{
public void WillThisWork()
{
var source = new DummySource[0];
var values = from value in source
select new
{
A = value.A,
B = value.C + "_" + value.D
};
DoSomethingWithDummyInterface(values);
}
public void DoSomethingWithDummyInterface(IEnumerable<DummyInterface> values)
{
foreach (var value in values)
{
Console.WriteLine("A = '{0}', B = '{1}'", value.A, value.B);
}
}
}
```
I've found an article [Dynamic interface wrapping](http://channel8.msdn.com/Posts/Adding-some-dynamic-to-C-interface-wrapping/) that describes one approach. Is this the best way of doing this?
|
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 cannot be cast to any interface or type except for object.
|
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 point I needed to be able to tell "my" anonymous classes from other anonymous ones, which meant having them implement an interface that I could use to type check them. The way we solved it was by using aspects (we used [PostSharp](https://www.postsharp.net/)), to add the interface implementation directly in the IL. So, in fact, **letting anonymous classes implement interfaces is doable**, you just need to bend the rules slightly to get there.
|
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 in C#. I created a `JPanel` form called `BlurbEditor`. This has a few simple controls on it. I am trying to add it to another panel at run time on a button event.
Here is the code that I thought would work:
```
mainPanel.add(new BlurbEditor());
mainPanel.revalidate();
//I've also tried all possible combinations of these too
//mainPanel.repaint();
//mainPanel.validate();
```
This unfortunately is not working. What am I doing wrong?
|
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.
There are others such as `FlowLayout` which is like a `textarea` - it adds components left-to-right at the top of the parent and wraps onto a new row when it gets to the end.
The `GridBagLayout` which has always been notorious for being impossible to figure out, but does give you nearly all the control you would need. A bit like those `HTML` tables we used to see with bizarre combinations of rowspan, colspan, width and height attributes - which never seemed to look quite how you wanted them.
|
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 won't be able to sufficiently scale in terms of performance or capabilities.
Requirements are:
* Cross-platform (Linux, MacOS X,
Windows)
* Low complexity overhead
* Plays well with wxpython (at least won't step on each other's toes unduly)
* Interactivity. Detect when objects are clicked on, moused over, etc.
Note that high performance isn't on the list, but the ability to handle ~100 bitmap objects on the screen would be good.
Your thoughts?
|
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 mailing list about wxpython and pyglet being used together.
It however does not offer selection of objects via mouse clicks - this you will have to handle yourself. Generally speaking for a 2D application this is not too difficult to do.
[mactorii](https://github.com/freespace/mactorii) is an OS X application of mine written in pure python+pyglet, and has some basic animation (scrolling) and click detection. It doesn't use wxpython, but perhaps it will give you an idea of what is involved. Note however mactorii is using the old pyglet api, so the run loop I have in there is obsolete. I will get around to updating it one day... :P
|
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","4dr"]} ,
{'CRV' : ["2dr","Hatchback"]} ,
{'Pilot' : ["base","superDuper"] }
]
},
{
"makes" : "Toyota",
"models" : [
{'Prius' : ["green","reallyGreen"]} ,
{'Camry' : ["sporty","square"]} ,
{'Corolla' : ["cheap","superFly"] }
]
}
];
```
Thanks
|
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: [
{ name: 'Prius', features: ['green', 'superGreen'] },
{ name: 'Camry', features: ['sporty', 'square'] },
{ name: 'Corolla', features: ['cheap', 'superFly'] }
]}
];
```
I wrote about the traversal and everything else [here](https://stackoverflow.com/questions/180451/using-javascript-and-jquery-to-populate-related-select-boxes-with-array-structu#180926).
|
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"],
CRV : ["2dr", "Hatchback"],
Pilot : ["base", "superDuper"]
},
Toyota : {
Prius : ["green", "reallyGreen"],
Camry : ["sporty", "square"],
Corolla : ["cheap", "superFly"]
}
};
```
|
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 variable so that I can access it in a C source file. I have tried various things, including
```
_declspec(dllimport) char* MyNewVariable;
```
but that just gives me a linker error:
unresolved external symbol "\_\_declspec(dllimport) char \* MyNewVariable" (\_\_imp\_?MyNewVariable@@3PADA)
```
extern "C" _declspec(dllimport) char* MyNewVariable;
```
as suggested by Tony (and as I tried before) results in a different expected decoration, but still hasn't removed it:
unresolved external symbol \_\_imp\_\_MyNewVariable
How do I write the declaration so that the C++ DLL variable is accessible from the C app?
---
## The Answer
As identified by botismarius and others (many thanks to all), I needed to link with the DLL's .lib. To prevent the name being mangled I needed to declare it (in the C source) with no decorators, which means I needed to use the .lib file.
|
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, link with the import library generated by the dll doing the export.
|
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 tried the `parse()` method and it is a little too picky for my needs. I would expect it to be able to successfully parse the following example input times (in addition to other logically similar time formats) as the same `Date()` object:
* 1:00 pm
* 1:00 p.m.
* 1:00 p
* 1:00pm
* 1:00p.m.
* 1:00p
* 1 pm
* 1 p.m.
* 1 p
* 1pm
* 1p.m.
* 1p
* 13:00
* 13
I am thinking that I might use regular expressions to split up the input and extract the information I want to use to create my `Date()` object. What is the best way to do this?
|
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 pm','1:00 p.m.','1:00 p','1:00pm','1:00p.m.','1:00p','1 pm',
'1 p.m.','1 p','1pm','1p.m.', '1p', '13:00','13', '1a', '12', '12a', '12p', '12am', '12pm', '2400am', '2400pm', '2400',
'1000', '100', '123', '2459', '2359', '2359am', '1100', '123p',
'1234', '1', '9', '99', '999', '9999', '99999', '0000', '0011', '-1', 'mioaw' ];
for ( var i = 0; i < tests.length; i++ ) {
console.log( tests[i].padStart( 9, ' ' ) + " = " + parseTime(tests[i]) );
}
```
It should work for a few other varieties as well (even if a.m. is used, it'll still work - for example). Obviously this is pretty crude but it's also pretty lightweight (much cheaper to use that than a full library, for example).
> Warning: The code doe not work with 12:00 AM, etc.
|
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 == null) return null;
var hours = parseInt(time[1],10);
if (hours == 12 && !time[4]) {
hours = 0;
}
else {
hours += (hours < 12 && time[4])? 12 : 0;
}
var d = new Date();
d.setHours(hours);
d.setMinutes(parseInt(time[3],10) || 0);
d.setSeconds(0, 0);
return d;
}
var tests = [
'1:00 pm','1:00 p.m.','1:00 p','1:00pm','1:00p.m.','1:00p','1 pm',
'1 p.m.','1 p','1pm','1p.m.', '1p', '13:00','13', '1a', '12', '12a', '12p', '12am', '12pm', '2400am', '2400pm', '2400',
'1000', '100', '123', '2459', '2359', '2359am', '1100', '123p',
'1234', '1', '9', '99', '999', '9999', '99999', '0000', '0011', '-1', 'mioaw' ];
for ( var i = 0; i < tests.length; i++ ) {
console.log( tests[i].padStart( 9, ' ' ) + " = " + parseTime(tests[i]) );
}
```
This will work for strings which contain a time anywhere inside them. So "abcde12:00pmdef" would be parsed and return 12 pm. If the desired outcome is that it only returns a time when the string only contains a time in them the following regular expression can be used provided you replace "time[4]" with "time[6]".
```
/^(\d+)(:(\d\d))?\s*((a|(p))m?)?$/i
```
|
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 with things I can't reproduce, and I'm reluctant to instrument our production system with Heapy because it takes a while to do its thing and its threaded remote interface does not work well in our server.
What I think I want is a way to dump a snapshot of the production Python process (or at least gc.get\_objects), and then analyze it offline to see where it is using memory. [How do I get a core dump of a python process like this?](https://stackoverflow.com/questions/141802/how-do-i-dump-an-entire-python-process-for-later-debugging-inspection) Once I have one, how do I do something useful with it?
|
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 leaks. Below I use `dozer > 0.7` which has not been released at the time of writing (well, because I contributed a couple of fixes there recently).
# Example
Let's look at a non-trivial memory leak. I'll use [Celery](http://www.celeryproject.org/) 4.4 here and will eventually uncover a feature which causes the leak (and because it's a bug/feature kind of thing, it can be called mere misconfiguration, cause by ignorance). So there's a Python 3.6 *venv* where I `pip install celery < 4.5`. And have the following module.
*demo.py*
```
import time
import celery
redis_dsn = 'redis://localhost'
app = celery.Celery('demo', broker=redis_dsn, backend=redis_dsn)
@app.task
def subtask():
pass
@app.task
def task():
for i in range(10_000):
subtask.delay()
time.sleep(0.01)
if __name__ == '__main__':
task.delay().get()
```
Basically a task which schedules a bunch of subtasks. What can go wrong?
I'll use [`procpath`](https://pypi.org/project/Procpath/) to analyse Celery node memory consumption. `pip install procpath`. I have 4 terminals:
1. `procpath record -d celery.sqlite -i1 "$..children[?('celery' in @.cmdline)]"` to record the Celery node's process tree stats
2. `docker run --rm -it -p 6379:6379 redis` to run Redis which will serve as Celery broker and result backend
3. `celery -A demo worker --concurrency 2` to run the node with 2 workers
4. `python demo.py` to finally run the example
(4) will finish under 2 minutes.
Then I use [sqliteviz](https://github.com/lana-k/sqliteviz) ([pre-built version](https://lana-k.github.io/sqliteviz/)) to visualise what `procpath` has recorder. I drop the `celery.sqlite` there and use this query:
```
SELECT datetime(ts, 'unixepoch', 'localtime') ts, stat_pid, stat_rss / 256.0 rss
FROM record
```
And in sqliteviz I create a line chart trace with `X=ts`, `Y=rss`, and add split transform `By=stat_pid`. The result chart is:
[](https://i.stack.imgur.com/US20P.png)
This shape is likely pretty familiar to anyone who fought with memory leaks.
# Finding leaking objects
Now it's time for `dozer`. I'll show non-instrumented case (and you can instrument your code in similar way if you can). To inject Dozer server into target process I'll use [Pyrasite](https://pypi.org/project/pyrasite/) (update: try a fork, [Pyrasite-ng](https://pypi.org/project/pyrasite-ng/), if Pyrasite doesn't work). There are two things to know about it:
* To run it, [ptrace](http://man7.org/linux/man-pages/man2/ptrace.2.html) has to be configured as "classic ptrace permissions": `echo 0 | sudo tee /proc/sys/kernel/yama/ptrace_scope`, which is may be a security risk
* There are non-zero chances that your target Python process will crash
With that caveat I:
* `pip install https://github.com/mgedmin/dozer/archive/3ca74bd8.zip` (that's to-be 0.8 I mentioned above)
* `pip install pillow` (which `dozer` uses for charting)
* `pip install pyrasite`
After that I can get Python shell in the target process:
```
pyrasite-shell 26572
```
And inject the following, which will run Dozer's WSGI application using stdlib's `wsgiref`'s server.
```
import threading
import wsgiref.simple_server
import dozer
def run_dozer():
app = dozer.Dozer(app=None, path='/')
with wsgiref.simple_server.make_server('', 8000, app) as httpd:
print('Serving Dozer on port 8000...')
httpd.serve_forever()
threading.Thread(target=run_dozer, daemon=True).start()
```
Opening `http://localhost:8000` in a browser there should see something like:
[](https://i.stack.imgur.com/5hDUb.png)
After that I run `python demo.py` from (4) again and wait for it to finish. Then in Dozer I set "Floor" to 5000, and here's what I see:
[](https://i.stack.imgur.com/VoTDD.png)
Two types related to Celery grow as the subtask are scheduled:
* `celery.result.AsyncResult`
* `vine.promises.promise`
`weakref.WeakMethod` has the same shape and numbers and must be caused by the same thing.
# Finding root cause
At this point from the leaking types and the trends it may be already clear what's going on in your case. If it's not, Dozer has "TRACE" link per type, which allows tracing (e.g. seeing object's attributes) chosen object's referrers (`gc.get_referrers`) and referents (`gc.get_referents`), and continue the process again traversing the graph.
But a picture says a thousand words, right? So I'll show how to use [`objgraph`](https://pypi.org/project/objgraph/) to render chosen object's dependency graph.
* `pip install objgraph`
* `apt-get install graphviz`
Then:
* I run `python demo.py` from (4) again
* in Dozer I set `floor=0`, `filter=AsyncResult`
* and click "TRACE" which should yield
[](https://i.stack.imgur.com/GRp77.png)
Then in Pyrasite shell run:
```
objgraph.show_backrefs([objgraph.at(140254427663376)], filename='backref.png')
```
The PNG file should contain:
[](https://i.stack.imgur.com/TrU1M.png)
Basically there's some `Context` object containing a `list` called `_children` that in turn is containing many instances of `celery.result.AsyncResult`, which leak. Changing `Filter=celery.*context` in Dozer here's what I see:
[](https://i.stack.imgur.com/sIplB.png)
So the culprit is `celery.app.task.Context`. Searching that type would certainly lead you to [Celery task page](https://docs.celeryproject.org/en/stable/reference/celery.app.task.html). Quickly searching for "children" there, here's what it says:
> `trail = True`
>
> If enabled the request will keep track of subtasks started by this task, and this information will be sent with the result (`result.children`).
Disabling the trail by setting `trail=False` like:
```
@app.task(trail=False)
def task():
for i in range(10_000):
subtask.delay()
time.sleep(0.01)
```
Then restarting the Celery node from (3) and `python demo.py` from (4) yet again, shows this memory consumption.
[](https://i.stack.imgur.com/CzTin.png)
Problem solved!
|
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 rss > 100 * 1024 * 1024:
memory_dump()
os.abort()
def memory_dump():
dump = open("memory.pickle", 'wb')
xs = []
for obj in gc.get_objects():
i = id(obj)
size = sys.getsizeof(obj, 0)
# referrers = [id(o) for o in gc.get_referrers(obj) if hasattr(o, '__class__')]
referents = [id(o) for o in gc.get_referents(obj) if hasattr(o, '__class__')]
if hasattr(obj, '__class__'):
cls = str(obj.__class__)
xs.append({'id': i, 'class': cls, 'size': size, 'referents': referents})
cPickle.dump(xs, dump)
```
Note that I'm only saving data from objects that have a `__class__` attribute because those are the only objects I care about. It should be possible to save the complete list of objects, but you will need to take care choosing other attributes. Also, I found that getting the referrers for each object was extremely slow so I opted to save only the referents. Anyway, after the crash, the resulting pickled data can be read back like this:
```
with open("memory.pickle", 'rb') as dump:
objs = cPickle.load(dump)
```
## Added 2017-11-15
The Python 3.6 version is here:
```
import gc
import sys
import _pickle as cPickle
def memory_dump():
with open("memory.pickle", 'wb') as dump:
xs = []
for obj in gc.get_objects():
i = id(obj)
size = sys.getsizeof(obj, 0)
# referrers = [id(o) for o in gc.get_referrers(obj) if hasattr(o, '__class__')]
referents = [id(o) for o in gc.get_referents(obj) if hasattr(o, '__class__')]
if hasattr(obj, '__class__'):
cls = str(obj.__class__)
xs.append({'id': i, 'class': cls, 'size': size, 'referents': referents})
cPickle.dump(xs, dump)
```
|
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 parallelization
Now, there is a well known technique of spreading the components of your page across multiple domains to parallelize downloading. [Yahoo recommends it](http://developer.yahoo.com/performance/rules.html#split) as do many others. For instance, **www.example.com** is where your HTML is hosted, then you put images on **images.example.com** and javascripts on **scripts.example.com**. This gets around the fact that most browsers limit the number of simultaneous connections per server in order to be good net citizens.
The above is *not* what I am talking about.
## It's not simply redirection to a content delivery network (or maybe it is--see bottom of question)
What I am talking about is hosting Javascripts specifically on an entirely different domain. Let me be specific. Just in the last year or so I've noticed that:
**youtube.com** has moved its .JS files to **ytimg.com**
**cnn.com** has moved its .JS files to **cdn.turner.com**
**weather.com** has moved its .JS files to **j.imwx.com**
Now, I know about content delivery networks like [Akamai](http://www.akamai.com) who specialize in outsourcing this for large websites. (The name "cdn" in Turner's special domain clues us in to the importance of this concept here).
But note with these examples, each site has its own specifically registered domain for this purpose, and its not the domain of a content delivery network or other infrastructure provider. In fact, if you try to load the home page off most of these script domains, they usually redirect back to the main domain of the company. And if you reverse lookup the IPs involved, they *sometimes* appear point to a CDN company's servers, sometimes not.
## Why do I care?
Having formerly worked at two different security companies, I have been made paranoid of malicious Javascripts.
As a result, I follow the practice of whitelisting sites that I will allow Javascript (and other active content such as Java) to run on. As a result, to make a site like **cnn.com** work properly, I have to manually put **cnn.com** into a list. It's a pain in the behind, but I prefer it over the alternative.
When folks used things like **scripts.cnn.com** to parallelize, that worked fine with appropriate wildcarding. And when folks used subdomains off the CDN company domains, I could just permit the CDN company's main domain with a wildcard in front as well and kill many birds with one stone (such as \*.edgesuite.net and \*.akamai.com).
Now I have discovered that (as of 2008) this is not enough. Now I have to poke around in the source code of a page I want to whitelist, and figure out what "secret" domain (or domains) that site is using to store their Javascripts on. In some cases I've found I have to permit three different domains to make a site work.
## Why did all these major sites start doing this?
EDIT: OK [as "onebyone" pointed out](https://stackoverflow.com/questions/160376/why-move-your-javascript-files-to-a-different-main-domain-that-you-also-own#160451), it does appear to be related to CDN delivery of content. So let me modify the question slightly based on his research...
Why is **weather.com** using **j.imwx.com** instead of **twc.vo.llnwd.net**?
Why is **youtube.com** using **s.ytimg.com** instead of **static.cache.l.google.com**?
There has to a reasoning behind this.
|
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 potentially even change CDNs entirely and only have to change a DNS record, versus having to update links in 1000s of pages/applications.
So, why use nonsense domain names? Well, a big thing with helper files like .js and .css is that you want them to be cached downstream by proxies and people's browsers as much as possible. If a person hits gmail.com and all the .js is loaded out of their browser cache, the site appears much snappier to them, and it also saves bandwidth on the server end (everybody wins). The problem is that once you send HTTP headers for really aggressive caching (i.e. cache me for a week or a year or forever), these files aren't ever reliably loaded from the server any more and you can't make changes/fixes to them because things will break in people's browsers.
So, what companies have to do is stage these changes and actually change the URLs of all of these files to force people's browsers to reload them. Cycling through domains like "a.imwx.com", "b.imwx.com" etc. is how this gets done.
By using a nonsense domain name, the Javascript developers and their Javascript sysadmin/CDN liaison counterparts can have their own domain name/DNS that they're pushing these changes through, that they're accountable/autonomous for.
Then, if any sort of cookie-blocking or script-blocking starts happening on the TLD, they just change from one nonsense TLD to kyxmlek.com or whatever. They don't have to worry about accidentally doing something evil that has countermeasure side effects on all of \*.google.com.
|
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 (on your code first), which could lead to discussion.
For tangible items, I'd look at [Scott Meyers](http://www.aristeia.com/)' Effective C++, etc. Develop your skillset and you will either help improve others around you or move on to a shop that will. Also, look at the Gang of Four's [Design Patterns](https://rads.stackoverflow.com/amzn/click/com/0201633612) book.
|
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 implement.
|
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, when using the same code in application.js, and
```
<a href = "" class = "foo" id = "foobar_1" >Teh Foobar </a>
```
is being returned into a div by a
```
form_remote_tag
```
when clicked, "Teh Foobar" fails to alert, and functions as a link.
What is happening, and how do I get around it?
|
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 their parent elements, you can bind an event to an element that will be an ancestor of all your target elements.
For instance, this jQuery code would work (your syntax may vary for other JavaScript libraries):
```
$(document).ready(function() {
$('body').click(function(event) {
if ($(event.target).is('.foo')) { // <- this is the magic
alert('Something of class foo was clicked.');
return false;
}
});
});
```
Now when you click something of class foo this event will get fired unless something in between catches the event and cancels the bubbling. Actually, event will be called when almost anything is clicked - the "if" statement just filters out which events deserve the alert.
|
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 here.
"""
return text.replace(text[text.find(re.findall(pattern, text)[0]):], replaceValue) + \
text[text.find(re.findall(pattern, text)[0]) + len(replaceValue):]
```
so if I do sth like
```
>>> getExpandedText("aaa(...)bbb", "hola aaaiiibbb como estas?", "ooo")
'hola aaaooobbb como estas?'
```
It changes the (...) with 'ooo'.
Do you guys know whether with python regular expressions we can do this?
thanks a lot guys!!
|
```
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 = re.compile( '(blue|white|red)')
>>> p.sub( 'colour', 'blue socks and red shoes')
'colour socks and colour shoes'
>>> p.sub( 'colour', 'blue socks and red shoes', count=1)
'colour socks and red shoes'
```
|
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.sub( "(svcOrdNbr +)..", "\g<1>XX", "svcOrdNbr IASZ0080")
'svcOrdNbr XXSZ0080'
```
|
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 takes a date as input and returns a String value of Spring, Summer, Winter or Fall. Here are the date ranges and their associated seasons:
Spring:3/1-4/30
Summer:5/1-8/31
Fall:9/1-10/31
Winter: 11/1-2/28
Can someone provide a working method to return the proper season?
Thanks everyone!
|
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, getMonth() is deprecated, but if you start with a Date,
// you'd have to convert to Calendar before continuing with new Java,
// and that's not fast.
```
|
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 and later. See [Oracle Tutorial](http://docs.oracle.com/javase/tutorial/datetime/TOC.html). Much of the functionality has been back-ported to Java 6 & 7 in [ThreeTen-Backport](http://www.threeten.org/threetenbp/) and further adapted to Android in [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP).
## `Month`
Given that seasons are defined here using whole months, we can make use of the handy [`Month`](http://docs.oracle.com/javase/8/docs/api/java/time/Month.html) [enum](http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html). Such enum values are better than mere integer values (1-12) because they are type-safe and you are guaranteed of valid values.
## `EnumSet`
An [`EnumSet`](http://docs.oracle.com/javase/8/docs/api/java/util/EnumSet.html) is a fast-performing and compact-memory way to track a subset of enum values.
```
EnumSet<Month> spring = EnumSet.of( Month.MARCH , Month.APRIL );
EnumSet<Month> summer = EnumSet.of( Month.MAY , Month.JUNE , Month.JULY , Month.AUGUST );
EnumSet<Month> fall = EnumSet.of( Month.SEPTEMBER , Month.OCTOBER );
EnumSet<Month> winter = EnumSet.of( Month.NOVEMBER , Month.DECEMBER , Month.JANUARY , Month.FEBRUARY );
```
As an example, we get the current moment for a particular time zone.
```
ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.now( zoneId );
```
Ask that date-time value for its `Month`.
```
Month month = Month.from( zdt );
```
Look for which season `EnumSet` has that particular Month value by calling [`contains`](http://docs.oracle.com/javase/8/docs/api/java/util/Set.html#contains-java.lang.Object-).
```
if ( spring.contains( month ) ) {
…
} else if ( summer.contains( month ) ) {
…
} else if ( fall.contains( month ) ) {
…
} else if ( winter.contains( month ) ) {
…
} else {
// FIXME: Handle reaching impossible point as error condition.
}
```
## Define your own “Season” enum
If you are using this season idea around your code base, I suggest defining your own enum, “Season”.
The basic enum is simple: `public enum Season { SPRING, SUMMER, FALL, WINTER; }`. But we also add a static method `of` to do that lookup of which month maps to which season.
```
package work.basil.example;
import java.time.Month;
public enum Season {
SPRING, SUMMER, FALL, WINTER;
static public Season of ( final Month month ) {
switch ( month ) {
// Spring.
case MARCH: // Java quirk: An enum switch case label must be the unqualified name of an enum. So cannot use `Month.MARCH` here, only `MARCH`.
return Season.SPRING;
case APRIL:
return Season.SPRING;
// Summer.
case MAY:
return Season.SUMMER;
case JUNE:
return Season.SUMMER;
case JULY:
return Season.SUMMER;
case AUGUST:
return Season.SUMMER;
// Fall.
case SEPTEMBER:
return Season.FALL;
case OCTOBER:
return Season.FALL;
// Winter.
case NOVEMBER:
return Season.WINTER;
case DECEMBER:
return Season.WINTER;
case JANUARY:
return Season.WINTER;
case FEBRUARY:
return Season.WINTER;
default:
System.out.println ( "ERROR." ); // FIXME: Handle reaching impossible point as error condition.
return null;
}
}
}
```
Or use the switch expressions feature ([JEP 361](https://openjdk.java.net/jeps/361)) of Java 14.
```
package work.basil.example;
import java.time.Month;
import java.util.Objects;
public enum Season
{
SPRING, SUMMER, FALL, WINTER;
static public Season of ( final Month month )
{
Objects.requireNonNull( month , "ERROR - Received null where a `Month` is expected. Message # 0ac03df9-1c5a-4c2d-a22d-14c40e25c58b." );
return
switch ( Objects.requireNonNull( month ) )
{
// Spring.
case MARCH , APRIL -> Season.SPRING;
// Summer.
case MAY , JUNE , JULY , AUGUST -> Season.SUMMER;
// Fall.
case SEPTEMBER , OCTOBER -> Season.FALL;
// Winter.
case NOVEMBER , DECEMBER , JANUARY , FEBRUARY -> Season.WINTER;
}
;
}
}
```
Here is how to use that enum.
```
ZoneId zoneId = ZoneId.of ( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.now ( zoneId );
Month month = Month.from ( zdt );
Season season = Season.of ( month );
```
Dump to console.
```
System.out.println ( "zdt: " + zdt + " | month: " + month + " | season: " + season );
```
> zdt: 2016-06-25T18:23:14.695-04:00[America/Montreal] | month: JUNE | season: SUMMER
|
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 have been compiled, at run-time preferably, so that I can remove the linking and instead provide dynamically loadable libraries instead.
|
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 dynamically loaded modules and whether or not you can register them using the same method.
|
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 regularly done by programmers with more expertise or is it more of an amateur thing to do?
**For example:**
```
if (!isset($_SESSION['dataentry']))
{
$query_taskinfo = "SELECT participationcode, modulearray, wavenum FROM mng_wave WHERE wave_id=" . mysql_real_escape_string($_GET['wave_id']);
$result_taskinfo = $db->query($query_taskinfo);
$row_taskinfo = $result_taskinfo->fetch_row();
$dataentry = array("pcode" => $row_taskinfo[0], "modules" => $row_taskinfo[1], "data_id" => 0, "wavenum" => $row_taskinfo[2], "prequest" => FALSE, "highlight" => array());
$_SESSION['dataentry'] = $dataentry;
}
```
|
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 good way of storing settings that can be changed by the user, as you can read the settings from database once at the beginning of a session and it is available for that entire session, you only need to make further database calls if the settings are changed and of course, as you show in your code, it's trivial to find out whether the settings already exist or whether they need to be extracted from database.
I can't think of any other way of storing temporary variables securely (since cookies can easily be modified and this will be undesirable in most cases) so $\_SESSION would be the way to go
|
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 more secure than storing the actual data in the users cookie.
Just to let you know though, you do have a security issue with your SQL statement:
```
SELECT participationcode, modulearray, wavenum FROM mng_wave WHERE wave_id=".$_GET['wave_id'];
```
You should **NEVER, I REPEAT NEVER**, take user provided data and use it to run a SQL statement without first sanitizing it. I would wrap it in quotes and add the function `mysql_real_escape_string()`. That will protect you from most attacks. So your line would look like:
```
$query_taskinfo = "SELECT participationcode, modulearray, wavenum FROM mng_wave WHERE wave_id='".mysql_real_escape_string($_GET['wave_id'])."'";
```
|
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 two farthest nodes from eachother (the weight distance, not by # of nodes away).
Now, I do have Dijkstra's algorithm in the form of:
```
// Dijkstra's Single-Source Algorithm
private int cheapest(double[] distances, boolean[] visited)
{
int best = -1;
for (int i = 0; i < size(); i++)
{
if (!visited[i] && ((best < 0) || (distances[i] < distances[best])))
{
best = i;
}
}
return best;
}
// Dijkstra's Continued
public double[] distancesFrom(int source)
{
double[] result = new double[size()];
java.util.Arrays.fill(result, Double.POSITIVE_INFINITY);
result[source] = 0; // zero distance from itself
boolean[] visited = new boolean[size()];
for (int i = 0; i < size(); i++)
{
int node = cheapest(result, visited);
visited[node] = true;
for (int j = 0; j < size(); j++)
{
result[j] = Math.min(result[j], result[node] + getCost(node, j));
}
}
return result;
}
```
With this implementation I can give it a particular node and it will give me a list of all the distances from that node. So, I could grab the largest distance in that list of distances but I can't be sure that any particular node is one of the two furthest ones at either end.
So the only solution I can think of is to run this Dijkstra's algorithm on every node, go through each returned list of distances and looking for the largest distance. After exhausting each node returning it's list of distances I should have the value of the largest distance between any two nodes (the "road" distance between the two most widely seperated villages). There has got to be an easier way to do this because this seems really computationally expensive. The problem says that there could be sample inputs with up to 500 nodes so I wouldn't want it to take prohibitively long. Is this how I should do it?
Here is a sample input for the problem:
Total Nodes: 5
Edges:
Nodes 2 - Connect - Node 4. Distance/Weight 25
Nodes 2 - Connect - Node 5. Distance/Weight 26
Nodes 3 - Connect - Node 4. Distance/Weight 16
Nodes 1 - Connect - Node 4. Distance/Weight 14
The answer to this sample input is "67 miles". Which is the length of the road between the two most widely separated villages.
So should I do it how I described or is there a much simpler and much less computationally expensive way?
|
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) algorithms like Floyd-Warshall or Johnsons. Unfortunately they're all roughly O(V^3) for dense graphs (close to the complete graph where E = V^2).
|
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(@"[\d dD+]+");
oReg.IsMatch("e4");
```
will return true even though e is not allowed...
I've tried many strings, including Regex("[1234567890 dD+]+")...
It always works on [Regex Pal](http://regexpal.com/) but not in C#...
Please advise and again i apologize this seems like a very silly question
|
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 other characters as well.
@comments: Thanks, I fixed the missing `+` and space.
|
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 anything.
The control works fine when run, but the Windows Forms designer doesn't seem to like dealing with it much. When the control is added to a form, the following line of code is generated in InitializeComponent():
```
this.numericTextBox1.Value = 1;
```
Remember 'Value' is of type `Nullable<double>`. This generates the following warning whenever I try to reopen the form in the Designer:
```
Object of type 'System.Int32' cannot be converted to type 'System.Nullable`1[System.Double]'.
```
As a result, the form cannot be viewed in the Designer until I manually remove that line and rebuild - after which it's regenerated as soon as I save any changes. Annoying.
Any suggestions?
|
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)
{
CodeStatementCollection collection = codeObject as CodeStatementCollection;
if (collection != null)
{
foreach (CodeStatement statement in collection)
{
CodeAssignStatement codeAssignment = statement as CodeAssignStatement;
if (codeAssignment != null)
{
CodePropertyReferenceExpression properyRef = codeAssignment.Left as CodePropertyReferenceExpression;
CodePrimitiveExpression primitiveExpression = codeAssignment.Right as CodePrimitiveExpression;
if (properyRef != null && properyRef.PropertyName == "Value" && primitiveExpression != null && primitiveExpression.Value != null)
{
primitiveExpression.Value = Convert.ToDouble(primitiveExpression.Value);
break;
}
}
}
}
return base.Deserialize(manager, codeObject);
}
}
```
Then you should apply it by using the [DesignerSerializer](http://msdn.microsoft.com/en-us/library/system.componentmodel.design.serialization.designerserializerattribute.aspx) attribute on your class.
|
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 they get updates from PayPal as well.
Here is a basic diagram of the database tables involved.
```
// table "package"
// columns packageID, policyID, other data...
//
// table "insurancepolicy"
// columns policyID, coverageAmount, other data...
```
Here is a basic diagram of what I want to do:
```
using (SqlConnection conn = new SqlConnection(...))
{
sqlTransaction sqlTrans = conn.BeginTransaction(IsolationLevel.RepeatableRead);
// Calls a stored procedure that checks if the foreign key in the transaction table has a value.
if (PackageDB.HasInsurancePolicy(packageID, conn))
{
sqlTrans.Commit();
return false;
}
// Insert row in foreign table.
int policyID = InsurancePolicyDB.Insert(coverageAmount, conn);
if (policyID <= 0)
{
sqlTrans.Rollback();
return false;
}
// Assign foreign key to parent table. If this fails, roll back everything.
bool assigned = PackageDB.AssignPolicyID(packageID, policyID, conn);
if (!assigned)
{
sqlTrans.Rollback();
return false;
}
}
```
If there are two (or more) threads (or processes or applications) doing this at the same time, I want the first thread to lock the "package" row while it has no policyID, until the policy is created and the policyID is assigned to the package table. Then the lock would be released after the policyID is assigned to the package table. It is my hope that the other thread which is calling this same code will pause when it reads the package row to make sure it doesn't have a policyID first. When the first transaction's lock is released, it is my hope that the second transaction will see the policyID is there and therefore return without inserting any rows into the policy table.
Note: Because of the CRUD database design, each the stored procedures involved either Read (select), Create (insert), or Update.
Is this the right use of RepeatableRead transaction isolation?
Thanks.
|
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 Policy already:
```
begin tran (read committed)
/* tentatively insert new Policy */
insert Policy
/* attach Package to Policy if it's still free */
update Package
set Package.policy_id = @policy_id
where Package.package_id = @package_id and Package.policy_id is null
if @@rowcount > 0
commit
else
rollback
```
This works best when conflicts are rare, which seems to be your case.
|
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 these requests serially yourself. Another is to use [sp\_getapplock](http://msdn.microsoft.com/en-us/library/ms189823.aspx) and lock on some key unique to that package. That way you don't lock any more rows or tables than you must.
|
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://framework.zend.com/manual/en/zend.acl.html) component of the Zend Framework will do role-based setups (however you'll have to subclass to check multiple roles at once). Granted the pain of this is you'll have to pull out Zend\_ACL, I do not believe it has any external dependencies, from the monolithic download (or SVN checkout).
The nice thing about Zend\_ACL is though its storage agnostic. You can either rebuild it every time or it's designed to be serialized (I use a combination of both, serialize for the cache and rebuild from the DB).
|
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 objects. For example, an access control list could be used to grant or deny write access to a particular system file, but it would not say in what ways that file could be changed. In an RBAC-based system, an operation might be to create a 'credit account' transaction in a financial application (...). The assignment of permission to perform a particular operation is meaningful because the operations are fine-grained and themselves have meaning within the application.*
> (Quote: [Wikipedia](http://en.wikipedia.org/wiki/Role-based_access_control))
I don't know the specifics on Zend\_ACL or the other implementations mentioned, but if they are ACL-based, I would not recommend using them for role-based authorization.
|
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: Pull the email address (and the other User attributes) from the database on object creation
```
public function __construct(..., $id = 0) {
if ($id) {
$this->load_all_data_from_db($id);
}
}
public function get_email_address() {
return $this->email_address;
}
```
My basic question is whether it's best to minimize the number of database queries, or whether it's best to minimize the amount of data that gets transferred from the database.
Another possibility is that it's best to load the attributes that you'll need the most / contain the least data at object creation and everything else on demand.
A follow-up question: What do ORM abstraction frameworks like Activerecord do?
|
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 front just in case you need it) is known as **eager loading**.
That said, there is a third option you might want to consider, which is lazy-loading the entire User object when any of its properties are accessed:
```
public function get_email_address() {
if (!$this->email_address) {
$this->load_all_data_from_db($this->id)
}
return $this->email_address;
}
```
Advantages of this approach are that you can create a collection of users (e.g. a list of all users whose passwords are blank, maybe?) based on their IDs only, without the memory hit of fully loading every single user, but then you only require a single database call for each user to populate the rest of the user fields.
|
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 to lazy loading (which is what you're talking about in step 1) *if* it's unlikely that you will need the data being lazily loaded. If you can though, it's best to be explicit, and fetch exactly or nearly exactly what you need. The less time you spend querying, the less time your connection is open and the more scalable your system is.
|
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
{
b.MethodB(repo);
}
}
public class ClassB
{
IRepo<ITypeEntity> repo;
public void MethodB(IRepo<ITypeEntity> repo)
{
this.repo = repo;
}
}
```
I get the following error:
cannot convert from IRepo<'T> to IRepo<'ITypeEntity>
MethodA gets called with a IRepo<'DetailType> object parameter where DetailType inherits from ITypeEntity.
I keep thinking that this should compile as I'm constraining T within MethodA to be of type ITypeEntity.
Any thoughts or feedback would be extremely helpful.
Thanks.
**Edit:** Nick R has a great suggestion but unfortunately in my context, I don't have the option of making ClassA Generic. ClassB could be though.
|
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 question have to match exactly. Thus, the following won't compile:
```
myType<TypeA> a; // This should be a myType<TypeB>, even if it contains only TypeA's
public void MethodB(myType<TypeB> b){ /* do stuff */ }
public void Main()
{
MethodB(a);
}
```
So in your case, you would need to pass in an IRepo<ITypeEntity> to MethodB, even if it only contains DetailTypes. You'd need to do some conversion between the two. If you were using a generic IList, you might do the following:
```
public void MethodA<T>(IList<T> list) where T : ITypeEntity
{
IList<T> myIList = new List<T>();
foreach(T item in list)
{
myIList.Add(item);
}
b.MethodB(myIList);
}
```
I hope this is helpful.
|
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)
{
b.MethodB(repo);
}
}
public class ClassB<T> where T : ITypeEntity
{
IRepo<T> repo;
public void MethodB(IRepo<T> repo)
{
this.repo = 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 important to catch that case, then it'd still be possible, but would take a bit more work.
Here's a basic example in jQuery:
```
$("#myForm")
.on("input", function() {
// do whatever you need to do when something's changed.
// perhaps set up an onExit function on the window
$('#saveButton').show();
})
;
```
|
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);
}
```
For checkboxes and radio buttons see whether `element.checked != element.defaultChecked`, and for HTML `<select />` elements you'll need to loop over the `select.options` array and check for each option whether `selected == defaultSelected`.
You might want to look at using a framework like [jQuery](http://jquery.com/) to attach handlers to the `onchange` event of each individual form element. These handlers can call your `formChanged()` code and modify the `enabled` property of your "save" button, and/or attach/detach an event handler for the document body's `beforeunload` event.
|
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 10/21/2007 6/12/2008 3 True
2 10/10/2007 3/20/2008 4 False
3 9/3/2007 11/3/2007 8 True
3 12/15/2007 6/12/2008 8 True
```
The result of the query should have the split date ranges combined. The query should combine date ranges with a gap of only one day. If there is more than a one day gap, then the rows shouldn't be combined. The rows that don't have a split date range should come through unchanged. The result would look like
```
StudentID StartDate EndDate Field1 Field2
1 9/3/2007 6/12/2008 3 True
2 10/10/2007 3/20/2008 4 False
3 9/3/2007 11/3/2007 8 True
3 12/15/2007 6/12/2008 8 True
```
What would be the SELECT statement for this query?
|
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 point you in the right direction.
You can use subqueries instead of the views, but that can be cumbersome so I used the views to make the code clearer.
```
CREATE VIEW dbo.StudentStartDates
AS
SELECT
S.StudentID,
S.StartDate,
S.Field1,
S.Field2
FROM
dbo.Students S
LEFT OUTER JOIN dbo.Students PREV ON
PREV.StudentID = S.StudentID AND
PREV.Field1 = S.Field1 AND
PREV.Field2 = S.Field2 AND
PREV.EndDate = DATEADD(dy, -1, S.StartDate)
WHERE PREV.StudentID IS NULL
GO
CREATE VIEW dbo.StudentEndDates
AS
SELECT
S.StudentID,
S.EndDate,
S.Field1,
S.Field2
FROM
dbo.Students S
LEFT OUTER JOIN dbo.Students NEXT ON
NEXT.StudentID = S.StudentID AND
NEXT.Field1 = S.Field1 AND
NEXT.Field2 = S.Field2 AND
NEXT.StartDate = DATEADD(dy, 1, S.EndDate)
WHERE NEXT.StudentID IS NULL
GO
SELECT
SD.StudentID,
SD.StartDate,
ED.EndDate,
SD.Field1,
SD.Field2
FROM
dbo.StudentStartDates SD
INNER JOIN dbo.StudentEndDates ED ON
ED.StudentID = SD.StudentID AND
ED.Field1 = SD.Field1 AND
ED.Field2 = SD.Field2 AND
ED.EndDate > SD.StartDate AND
NOT EXISTS (SELECT * FROM dbo.StudentEndDates ED2 WHERE ED2.StudentID = SD.StudentID AND ED2.Field1 = SD.Field1 AND ED2.Field2 = SD.Field2 AND ED2.EndDate < ED.EndDate AND ED2.EndDate > SD.StartDate)
GO
```
|
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 (for example, the [SQL Server native library](http://msdn.microsoft.com/en-us/library/ms722784.aspx))
5. [DAO](http://msdn.microsoft.com/en-us/library/aa163992.aspx) (don't).
6. 3rd party ORM providers.
I would recommend going through ODBC or OleDB by default. Native libraries really restrict you, DAO is no fun, there aren't a lot of great 3rd-party ORM for C++/Windows.
|
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 experience with `QtSql` in particular.
**Pros (just a few that should also apply if you just choose Qt for its QtSql module):** Qt is cross-platform. In my experience, Qt is well-designed, pretty intuitive to use, and extremely well documented. It has been around for a long time, is maintained by an active community and backed by Nokia, so it won't become unavailable over night. Since 2009, Qt has been licensed under the LGPL, so it is a real no-cost option even for commercial applications.
**Cons:** Qt is not small. You will introduce new types such as `QString` to your project. Qt is licenced under the LGPL, so you need to acknowledge its use even in commercial apps.
|
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 all valid references to foo.bar.Baz inside the com/bob/is/YourUncle.java file.
At this moment the cases I can think of that it needs to account for are:
1. The file being parsed is in the same package as the search class.
find foo.bar.Baz references in foo/bar/Boing.java
2. It should ignore comments.
```
// this is a comment saying this method returns a foo.bar.Baz or Baz instance
// it shouldn't count
/* a multiline comment as well
this shouldn't count
if I put foo.bar.Baz or Baz in here either */
```
3. In-line fully qualified references.
```
foo.bar.Baz fb = new foo.bar.Baz();
```
4. References based off an import statement.
```
import foo.bar.Baz;
...
Baz b = new Baz();
```
What would be the most efficient way to do this in Perl 5.8? Some fancy regex perhaps?
```
open F, $File::Find::name or die;
# these three things are already known
# $classToFind looking for references of this class
# $pkgToFind the package of the class you're finding references of
# $currentPkg package name of the file being parsed
while(<F>){
# ... do work here
}
close F;
# the results are availble here in some form
```
|
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 dig through the non-comment/non-string chunks looking for `\bimport\b` and `\b\Q$toFind\E\b` matches. Perhaps similar to:
```
if( m[
\G
(?:
[^'"/]+
| /(?![/*])
)+
]xgc
) {
my $code = substr( $_, $-[0], $+[0] - $-[0] );
my $imported = 0;
while( $code =~ /\b(import\s+)?\Q$package\E\b/g ) {
if( $1 ) {
... # Found importing of package
while( $code =~ /\b\Q$class\E\b/g ) {
... # Found mention of imported class
}
last;
}
... # Found a package reference
}
} elsif( m[ \G ' (?: [^'\\]+ | \\. )* ' ]xgc
|| m[ \G " (?: [^"\\]+ | \\. )* " ]xgc
) {
# skip quoted strings
} elsif( m[\G//.*]gc ) {
# skip C++ comments
```
|
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 compile the files before you could use this.
Also, remember that it can be tricky to catch all possible variants of a multi-line comment with a regex.
|
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 Over2?
Since you would have to extend Over1 to use any derivative of Under1 this may seem silly, but in this situation there might be 30 different flavors of Under. I can either:
* Put them all inside Over1 : Not
attractive since Over2 may only use
1 or 2 of them
* Put them each in
their own version of Over : Not
attractive since then you will have
to multiply inherit from almost the
same class.
* Find a way to create
children of Under1 without creating
children of Over1
So is this possible?
Thanks.
|
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<Under2Tag> : public Over1::Under1
{
};
template <>
class Over1::UnderImplementor<Under3Tag> : public Over1::Under1
{
};
template <>
class Over1::UnderImplementor<Under4Tag> : public Over1::Under1
{
};
```
Hope this helps.
|
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 instead.
Now, how do we prevent usage of ibase\_\* functions in the future?
Preferably, I'd like to still have them available, but make it throw a NOTICE or WARNING when it is used.
A solution in pure PHP (not needing to compile a custom version of PHP) is preferred.
|
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
*
* @return $this
*/
public function oldMethod()
{
trigger_error('Method ' . __METHOD__ . ' is deprecated', E_USER_DEPRECATED);
return $this;
}
```
The `@deprecated` phpdoc is important because many IDEs like [PHPStorm](https://www.jetbrains.com/phpstorm/) recognise it and strike the method name if you try to use it, so you notice that is deprecated before actually running your code.
It will look more or less like this:
[](https://i.stack.imgur.com/eiMB5.png)
Beside the phpdoc you can make sure the user gets a warning by triggering the right error at runtime. Just make sure you use the right constant (i.e. `E_USER_DEPRECATED`).
`E_DEPRECATED` is instead used internally by PHP thus you should **not** be using it. More information [here](http://php.net/manual/en/errorfunc.constants.php#errorfunc.constants.errorlevels.e-deprecated-error).
|
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 latest stable commons-whatever". Maven will then download the latest stable version for you (no more checking in jars into VCS) and if a new upstream stable version is released, it will download it as well. Of course, it's just as easy to lock it to some specific version should you need that.
It is also well integrated both with Netbeans and Eclipse (m2eclipse plugin) so the IDE honors whatever settings (including dependencies) you declare in the pom.xml file.
There are also some downsides to maven: some plugins are rather poorly documented, integration with both IDEs is not really perfect, and that in different ways, some error messages may be hard to understand.
|
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 (it has come a long way).
Groovy is offering some cool stuff in the build space, because they build on Ant. Gant is used in Grails, but may be subsumed into Gradle. These can be used for Java as well.
At the risk of pimping my own blog, [here is a post](http://codetojoy.blogspot.com/2008/10/ant-vs-maven-episode-2-gant-or-gradle.html) about Gant and Gradle. Here is a link to the [very current debate](http://www.nabble.com/Gant-and-Gradle-td19810302.html) about their future.
|
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 String CAT = "Cat";
```
**I do not want the strings to be externalized in a property text file.**
One reason is for consistency and code readability.
The other is that our client code uses `GWT`, which does not support Java property text file mechanism.
I could write some sort of parser (using ant replace task maybe)?
But I wondered if an `IDE` already does this sort of thing automatically.
|
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_AST/index.html), also more details in the [eclipse help](http://help.eclipse.org/help33/index.jsp?topic=/org.eclipse.jdt.doc.isv/reference/api/org/eclipse/jdt/core/dom/ASTParser.html).
And you can find some examples in [Listing 5 of the section "Implementation of in-place translation" of **Automating the embedding of Domain Specific Languages in Eclipse JDT**](http://www.eclipse.org/articles/Article-AutomatingDSLEmbeddings/#implementation_in_place), alongside [multiple examples in GitHub projects](https://github.com/search?q=%22org.eclipse.jdt.core.dom.ASTVisitor%22&ref=cmdform&type=Code).
|
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 depending on your locale. Having them in a separate Java source file as you suggest means you'll either have ALL languages in your application at once or you'll ship different applications depending on locale.
We use it for our applications where even the basic stuff has to ship in English and Japanese - our more complicated applications ship with 12 languages - we're not a small software development company by any means :-).
If you *do* want them in a Java file, despite the shortcomings already mentioned, it's a lot easier to write a program to morph the properties file into a Java source file than it is to try and extract the strings from free-form Java source.
All you then need to do is modify the Accessor class to use the in-built strings (in the separate class) rather than loading them at run time.
|
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 times the path after the "Temporary ASP.NET Files" portion (the "(blah)") does not exist, so I'm not sure why it's looking there.
Sometimes an IISRESET fixes it, and sometimes it doesn't.
Sometimes an aspnet\_regiis fixes it, and sometimes it doesn't.
Sometimes a reboot fixes it, and sometimes it doesn't.
For what it's worth I ran into this today with some .NET 1.1 code (yes, still maintaining some - hoping to upgrade it soon) and I'm not sure if I've ever seen it with .NET 2.0 and above.
Does anyone know what causes this and what should fix it? I assume it has multiple possible causes but I'm just curious if someone could shed some light on it.
|
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 get the access error, see what application is causing the issue. It will most likely be the virus scan - exclude this directory from the scan and see if the problem is resolved.
|
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()` calls the function, and `foo.baz` has the value "qqqq".
However, if you do the property assignment part first, how do you subsequently assign a function to the variable?
```
var bar = { baz: "qqqq" };
```
What can I do now to arrange for `bar.baz` to have the value "qqqq" *and* `bar()` to call the function?
|
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); // true
```
Second, functions **ARE** objects in Javascript. Specifically, they are objects that inherit from the Function prototype, which itself inherits from the Object prototype. Check out [Function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) on MDN for more information.
```
// various ways of creating functions
var foo = new Function();
var bar = function(){};
function baz(){};
// all functions are Function objects, and therefore Object objects
console.log(foo instanceof Function); // true
console.log(foo instanceof Object); // true
```
If you create a value that is an Object object first, you can't (as far as I know) convert it to a Function object later. What you CAN do however is create a new function, copy the properties from your old object to this function, and then reassign that function to the same variable, discarding the old object.
You can quickly copy the properties of one object to another with [`Object.assign(target, source)`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign).
```
var foo = { baz: "qqqq" };
var bar = function () { return 1; }; // create a new function
Object.assign(bar, foo); // copy the properties of foo to it
foo = bar; // assign the function to foo
console.log(foo instanceof Function); // true
console.log(foo()); // 1
console.log(foo.baz); // "qqqq"
```
But this isn't something you would typically do in practice. It's generally not recommended to add properties to a standard object like functions in the first place.
Finally, anticipating a possible question, you can't change the body of a function after it has been created. The function body is stored internally and not exposed as a property.
|
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 world"
```
There is simply no other way to acheive this,
doing
```
x={}
x()
```
WILL return a "type error". because "x" is an "object" and you can't change it. its about as sensible as trying to do
```
x = 1
x[50] = 5
print x[50]
```
it won't work. 1 is an integer. integers don't have array methods. you can't make it.
|
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 Win32 API calls) so that I can read the files directly from the drive without them being cached?
|
**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 related research reports you might find useful.
|
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=Technical%20Report&id=841)
EDIT 2024: It seems that Microsoft has taken down the original page. Here is a link to the Wayback machine copy of it: <https://web.archive.org/web/20150328142042/http://research.microsoft.com/apps/pubs/default.aspx?id=64538>
In this article, it talks about Un-buffered File Performance (iow, no read/write caching -- just raw disk performance.)
Quoted directly from the article:
> There is no simple way to disable
> FileStream buffering in the V2 .NET
> framework. One must invoke the Windows
> file system directly to obtain an
> un-buffered file handle and then
> ‘wrap’ the result in a FileStream as
> follows in C#:
```
[DllImport("kernel32", SetLastError=true)]
static extern unsafe SafeFileHandle CreateFile(
string FileName, // file name
uint DesiredAccess, // access mode
uint ShareMode, // share mode
IntPtr SecurityAttributes, // Security Attr
uint CreationDisposition, // how to create
uint FlagsAndAttributes, // file attributes
SafeFileHandle hTemplate // template file
);
SafeFileHandle handle = CreateFile(FileName,
FileAccess.Read,
FileShare.None,
IntPtr.Zero,
FileMode.Open,
FILE_FLAG_NO_BUFFERING,
null);
FileStream stream = new FileStream(handle,
FileAccess.Read,
true,
4096);
```
> Calling CreateFile() with the
> FILE\_FLAG\_NO\_BUFFERING flag tells the
> file system to bypass all software
> memory caching for the file. The
> ‘true’ value passed as the third
> argument to the FileStream constructor
> indicates that the stream should take
> ownership of the file handle, meaning
> that the file handle will
> automatically be closed when the
> stream is closed. After this
> hocus-pocus, the un-buffered file
> stream is read and written in the same
> way as any other.
|
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 apprenticeship and still consider myself a beginner in enterprise programming, I did not really try to push in my opinion, which is that using an object relational mapper to the database can ease development quite a lot. The other coders in the development team are much more experienced than me, so I think I will just do what they say. :-)
However, I do not completely understand two of the main reasons for not using NHibernate or a similar project:
1. One can just build one’s own data access objects with SQL queries and copy those queries out of Microsoft SQL Server Management Studio.
2. Debugging an ORM can be hard.
So, of course I could just build my data access layer with a lot of `SELECT`s etc, but here I miss the advantage of automatic joins, lazy-loading proxy classes and a lower maintenance effort if a table gets a new column or a column gets renamed. (Updating numerous `SELECT`, `INSERT` and `UPDATE` queries vs. updating the mapping config and possibly refactoring the business classes and DTOs.)
Also, using NHibernate you can run into unforeseen problems if you do not know the framework very well. That could be, for example, trusting the Table.hbm.xml where you set a string’s length to be automatically validated. However, I can also imagine similar bugs in a “simple” SqlConnection query based data access layer.
Finally, are those arguments mentioned above really a good reason not to utilise an ORM for a non-trivial database based enterprise application? Are there probably other arguments they/I might have missed?
(I should probably add that I think this is like the first “big” .NET/C# based application which will require teamwork. Good practices, which are seen as pretty normal on Stack Overflow, such as unit testing or continuous integration, are non-existing here up to now.)
|
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 ORM.
I guess the only real detriment that I can think of with an ORM is that the security model is a little less flexible.
**EDIT:** I just re-read your question and it looks they are copy and pasting the queries into inline sql. This makes the security model the same as an ORM, so there would be absolutely no advantage over this approach over an ORM. If they are using unparametrized queries then it would actually be a security risk.
|
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 pass audits is to keep data access within stored procedures. Now some may say that's just plain stupid, but honestly it isn't. Using an ORM tool means the tool/developer can insert, select, update or delete whatever he or she wants. Stored procedures provide a lot more security, especially in environments when dealing with client data. I think this is the biggest reason to consider. Security.
|
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 couldn't think of another method).
On Windows XP and 32-bit versions of Windows Vista this works fine. However, on x64 Windows Vista the code returns the x64 Program Files folder, whereas the application is installed in Program Files x86. Is there a way to programatically return the path to Program Files x86 without hard wiring "C:\Program Files (x86)"?
|
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(Environment.GetEnvironmentVariable("PROCESSOR_ARCHITEW6432"))))
{
return Environment.GetEnvironmentVariable("ProgramFiles(x86)");
}
return Environment.GetEnvironmentVariable("ProgramFiles");
}
```
|
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 the objects are deserialized it isn't getting the event handler.
In an fit of mild annoyance, I just added the event handler to the Get property that accesses the object. It's getting called now which is great, except that it's getting called like 5 times so I think the handler just keeps getting added every time the object is accessed.
It's really safe enough to just ignore, but I'd rather make it that much cleaner by checking to see if the handler has already been added so I only do so once.
Is that possible?
EDIT: I don't necessarily have full control of what event handlers are added, so just checking for null isn't good enough.
|
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. If not, then maybe and you can loop through the values in
[Delegate.GetInvocationList](http://msdn.microsoft.com/en-us/library/system.delegate.getinvocationlist.aspx). If one is equal to the delegate that you want to add as event handler, then you know it's there.
```
public bool IsEventHandlerRegistered(Delegate prospectiveHandler)
{
if ( this.EventHandler != null )
{
foreach ( Delegate existingHandler in this.EventHandler.GetInvocationList() )
{
if ( existingHandler == prospectiveHandler )
{
return true;
}
}
}
return false;
}
```
And this could easily be modified to become "add the handler if it's not there". If you don't have access to the innards of the class that's exposing the event, you may need to explore `-=` and `+=`, as suggested by @Lou Franco.
However, you may be better off reexamining the way you're commissioning and decommissioning these objects, to see if you can't find a way to track this information yourself.
|
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 you register your handler will ensure that your handler is registered only once.
Sounds like a pretty good practice to me :)
|
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 = zinput.ReadByte()))
{
// check data here
}
zinput.Close();
```
The data bytes match the compressed data bytes, so I must be doing something wrong.
|
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 headers before the zlib header, you can skip them:
// input.Seek(xxx, SeekOrigin.Current);
if (input.ReadByte() != 0x78 || input.ReadByte() != 0x9C)//zlib header
throw new Exception("Incorrect zlib header");
using (var deflateStream = new DeflateStream(decryptedData, CompressionMode.Decompress, true))
{
deflateStream.CopyTo(output);
}
}
```
|
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",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.