Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I am really stumped on this one. In C# there is a hexadecimal constants representation format as below :
```
int a = 0xAF2323F5;
```
is there a binary constants representation format? | As of C#7 you can represent a binary literal value in code:
```
private static void BinaryLiteralsFeature()
{
var employeeNumber = 0b00100010; //binary equivalent of whole number 34. Underlying data type defaults to System.Int32
Console.WriteLine(employeeNumber); //prints 34 on console.
long empNumberWithLongBackingType = 0b00100010; //here backing data type is long (System.Int64)
Console.WriteLine(empNumberWithLongBackingType); //prints 34 on console.
int employeeNumber_WithCapitalPrefix = 0B00100010; //0b and 0B prefixes are equivalent.
Console.WriteLine(employeeNumber_WithCapitalPrefix); //prints 34 on console.
}
```
Further information can be found [here](https://www.codeproject.com/Articles/1156167/Csharp-Version-Introduction-to-new-language-featur). | Nope, no binary literals in C#. You can of course parse a string in binary format using Convert.ToInt32, but I don't think that would be a great solution.
```
int bin = Convert.ToInt32( "1010", 2 );
``` | C# binary constants representation | [
"",
"c#",
"binary",
"format",
"constants",
"representation",
""
] |
I need to get the keys from values that are duplicates. I tried to use array\_search and that worked fine, BUT I only got the first value as a hit.
I need to get both keys from the duplicate values, in this case 0 and 2. The search result output as an array would be good.
Is there a PHP function to do this or do I need to write some multiple loops to do it?
```
$list[0][0] = "2009-09-09";
$list[0][1] = "2009-05-05";
$list[0][2] = "2009-09-09";
$list[1][0] = "first-paid";
$list[1][1] = "1";
$list[1][2] = "last-unpaid";
echo array_search("2009-09-09",$list[0]);
``` | You want [array\_keys](http://tr.php.net/manual/en/function.array-keys.php) with the search value
```
array_keys($list[0], "2009-09-09");
```
which will return an array of the keys with the specified value, in your case [0, 2]. If you want to find the duplicates as well, you can first make a pass with [array\_unique](https://www.php.net/manual/en/function.array-unique.php), then iterate over that array using array\_keys on the original; anything which returns an array of length > 1 is a duplicate, and the result is the keys in which the duplicates are stored. Something like...
```
$uniqueKeys = array_unique($list[0])
foreach ($uniqueKeys as $uniqueKey)
{
$v = array_keys($list[0], $uniqueKey);
if (count($v) > 1)
{
foreach ($v as $key)
{
// Work with $list[0][$key]
}
}
}
``` | In [`array_search()`](http://php.net/manual/en/function.array-search.php) we can read:
> If needle is found in haystack more
> than once, the first matching key is
> returned. To return the keys for all
> matching values, use [`array_keys()`](http://tr.php.net/manual/en/function.array-keys.php) with
> the optional `search_value` parameter
> instead. | How to search Array for multiple values in PHP? | [
"",
"php",
"arrays",
"search",
"duplicates",
"key",
""
] |
This has been bothering me for a while now:
```
Could not load file or assembly 'app_code' or one of its dependencies.
The system cannot find the file specified.
```
I'm using visual studio 2008 and IIS6 and for some reason I get this weird error.
Why is it trying to load 'app\_code', and why does it fail?
Tried to resolve it/ find out more using the information in the exception
```
WRN: Assembly binding logging is turned OFF.
To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1.
Note: There is some performance penalty associated with assembly bind failure logging.
To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog].
```
But that didn't help, neither did the information in the msdn article about the Assembly Binding Log Viewer: (<http://msdn.microsoft.com/en-us/library/e74a18c4.aspx>)
Anyone can shine a light on this abomination? I'm guessing this is a newbie mistake but I have no idea where to look now. Could it be IIS 6.0 configuration issue? I am using Windows XP Professional Edition and Visual Studio 2008.
---
After getting the Assembly binding monitor up, it spews out something like:
```
LOG: This bind starts in default load context.
LOG: Using application configuration file: C:\Projects\NNNNNN\src\Trunc\Web\web.config
LOG: Using machine configuration file from c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\config\machine.config.
LOG: Post-policy reference: Microsoft.VisualStudio.Web, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
LOG: GAC Lookup was unsuccessful.
LOG: Attempting download of new URL file:///c:/WINDOWS/Microsoft.NET/Framework/v2.0.50727/Temporary ASP.NET Files/root/d94fb3b9/d76068ec/Microsoft.VisualStudio.Web.DLL.
LOG: Attempting download of new URL file:///c:/WINDOWS/Microsoft.NET/Framework/v2.0.50727/Temporary ASP.NET Files/root/d94fb3b9/d76068ec/Microsoft.VisualStudio.Web/Microsoft.VisualStudio.Web.DLL.
LOG: Attempting download of new URL file:///C:/Projects/NNNNNN/src/Trunc/Web/bin/Microsoft.VisualStudio.Web.DLL.
LOG: Attempting download of new URL file:///C:/Projects/NNNNNN/src/Trunc/Web/bin/Microsoft.VisualStudio.Web/Microsoft.VisualStudio.Web.DLL.
LOG: Attempting download of new URL file:///c:/WINDOWS/Microsoft.NET/Framework/v2.0.50727/Temporary ASP.NET Files/root/d94fb3b9/d76068ec/Microsoft.VisualStudio.Web.EXE.
LOG: Attempting download of new URL file:///c:/WINDOWS/Microsoft.NET/Framework/v2.0.50727/Temporary ASP.NET Files/root/d94fb3b9/d76068ec/Microsoft.VisualStudio.Web/Microsoft.VisualStudio.Web.EXE.
LOG: Attempting download of new URL file:///C:/Projects/NNNNNN/src/Trunc/Web/bin/Microsoft.VisualStudio.Web.EXE.
LOG: Attempting download of new URL file:///C:/Projects/NNNNNN/src/Trunc/Web/bin/Microsoft.VisualStudio.Web/Microsoft.VisualStudio.Web.EXE.
LOG: All probing URLs attempted and failed.
``` | This error was due to web.config was referencing the wrong package for a class. Clearing the mind over the weekend, and problems are solved easily. | If you use Visual Studio Performance Tools then it is possible that Visual Studio left a key in your web.config appsettings section. It causes a 32 bit library to load, which won't work if your application is loading in 64 bit mode.
Check for the following and remove it:
```
<add key="Microsoft.VisualStudio.Enterprise.AspNetHelper.VsInstrLocation" value="C:\Program Files (x86)\Microsoft Visual Studio 11.0\Team Tools\Performance Tools\vsinstr.exe"/>
``` | Could not load file or assembly 'app_code' or one of its dependencies | [
"",
"c#",
"asp.net",
"visual-studio-2008",
"iis-6",
""
] |
I am trying to use a FileDialog file chooser because I really need java app to have the native apple file chooser (I know we all hate hate the lack of portability but this is what I need). I am trying to make my file chooser allow the user to pick files that end with .ws. Here is what I tried:
```
FileDialog fd = new
FileDialog(_sharedInstance,rsc.str("480"),FileDialog.LOAD);
// fd.setFile("*.ws");
class WSFilter implements FilenameFilter {
public boolean accept(File dir, String name) {
return (name.endsWith(".ws"));
}
};
FilenameFilter wsFilter = new WSFilter();
fd.setFilenameFilter(wsFilter);
fd.setDirectory(_projectsBaseDir.getPath());
fd.setLocation(50,50);
// fd.setFile("*");
fd.setVisible(true);
```
For some reason my file chooser won't allow me to pick any files. Any ideas? | Answer was I need this call: System.setProperty("apple.awt.fileDialogForDirectories", "false"); | Why not use JFileChooser?
```
JFileChooser fileChooser = new JFileChooser(new File(filename));
fileChooser.addChoosableFileFilter(new MyFilter());
class MyFilter extends javax.swing.filechooser.FileFilter {
public boolean accept(File file) {
String filename = file.getName();
return filename.endsWith(".java");
}
public String getDescription() {
return "*.java";
}
}
``` | Using a FileDialog to choose a file of a certain extension | [
"",
"java",
"filedialog",
"filechooser",
""
] |
I need the **fastest library to resize full size images (some up to 9MB in size) to multiple sizes**.
Here's the scenerio:
* User uploads a photo
* a FileSystemWatcher is running in a service watching the drop location (on a SAN)
* When a new photo appears, the service will create 4 versions of the image at full JPEG quality:
+ 100px wide
+ 320px wide
+ 640px wide
+ 1280 wide
I'm not fussed if the library is C/C++ or anything else for that matter, as long as I can tap into it via .NET it's cool.
Also this will need to scale to possibly 1,000 **active** users.
Let me know your thoughts :) | There are a lot of articles out there showing the [basics of this](http://www.codeproject.com/KB/GDI-plus/imageresize.aspx). I've used the components from [Atalasoft](http://www.atalasoft.com/products/DotImage/) and found them to be of pretty good quality. There are nuances to resizing and working with JPEG images.
You seem to be really concerned with performance but you don't really give enough information to help us suggest good optimizations for you. Whatever you are doing, you need to do a full performance analysis and understand what is running slow. In some cases slowish, but maintainable image processing code may be OK if other things are optimized.
One solution for good performance is to queue incoming files that need to be converted. Add more machines to handle more messages in the queue, or optimize the service code to get better throughput. It's really not that difficult to handle a large number of users if you get the design right. | I recommend **[ImageResizer](http://imageresizing.net/)**:
Key features are:
* RESTful url-based image API (example: src="img.jpg?w=170")
* Intuitively crop, resize, rotate, flip, constrain, and encode
* Render PDFs into images
* 19 free plugins cover most common tasks
* Disk + Memory input/output caching
* 8-bit PNG/GIF & animated GIF processing
* Flexible text & image overlay support
* Image filtering suite (needs licence)
* High performance
* and more ....
For installing with Nuget:
```
PM> Install-Package ImageResizer.MvcWebConfig
PM> Install-Package ImageResizer.Plugins.DiskCache
PM> Install-Package ImageResizer.Plugins.PrettyGifs
```
For more information please check:
<http://imageresizing.net/docs/install/nuget> | Fastest Image Resizing in .NET | [
"",
"c#",
".net",
"image",
"image-processing",
"resize",
""
] |
I have a small (or perhaps not so small) issue with some ASP.NET/Castle Monorail sites for a product I work on. This is a fairly legacy system (written well before my time), and it uses GET requests with a considerable amount of information in the query string. We have recently run into query string length limitations, and for the amount of data we need to transfer to the server, storing the data temporarily in a cookie is also not plausible (we are already well past the 4096 byte limit per cookie, and we set a lot of cookies, so we are likely near or at the limit of cookies per domain as well.)
I am wondering if there are any alternatives, besides POST (in some cases changing to a POST request may be possible, but likely not in all), that might solve this problem. I'm hoping someone else here on StackOverflow has run into similar issues, and has some wizardly solution (i.e. compress data with javascript, encode as base64, pass to a single query string item? Just not sure if there are any libraries that can compress data with javascript in a way compatible with built-in compression classes in .NET 3.5.)
UPDATE:
Solution I ended up choosing was to POST to a temporary controller. This temp controller pulled the large list of data, stuck it in a shared Session (the production servers are in a large multi-bank server farm that does not use sticky sessions/IPs), and performed a GET to the actual controller, which pulled the data from the shared Session. Not the most performant solution, but it solved the problem. | There are several [Base64 encode plugins for jQuery](http://plugins2.jquery.com/search/node/base64+type%3Aproject_project), but that doesn't help because [Base64 generally makes the data longer](http://en.wikipedia.org/wiki/Base64), not shorter.
Depending on the data, I'd look at some other text compression techniques. [Wikipedia lists a few](http://en.wikipedia.org/wiki/Lossless_data_compression#Text):
* Context Tree Weighting method (CTW)
* Burrows-Wheeler transform (block sorting preprocessing that makes compression more efficient)
* LZ77 (used by DEFLATE)
* LZW
Here's an [LZW implementation for Javascript](http://www.marklomas.net/ch-egg/articles/lzwjs.htm).
[Huffman encoding](http://rumkin.com/tools/compression/compress_huff.php) is based on letter frequency, so it might not be appropriate for your data. You'll probably have to escape the result to make it URL-safe. | Beyond switching to POST your options are going to be limited. Base64 is going to increase the size of the data not decrease it. You mention compressing the data into a single query string item... maybe instead you could split the data into 2 separate requests using Ajax? I'm not sure if that's feasible for your situation, though. | Alternative to query string and cookies when sending data to server? | [
"",
".net",
"asp.net",
"javascript",
"query-string",
"castle-monorail",
""
] |
I was recently requested by a client to build a website for their insurance business. As part of this, they want to do some screen scraping of the quote site for one of their providers. They asked if their was an API to do this, and were told there wasn't one, but that if they could get the data from their engine they could use it as they wanted to.
My question: is it even possible to perform screen scraping on the response to a form submission to another site? If so, what are the gotchas that I should look out for. Obvious legal/ethical issues aside since they already asked for permission to do what we're planning to do.
As an aside, I would prefer to do any processing in python.
Thanks | A really nice library for screen-scraping is [mechanize](http://wwwsearch.sourceforge.net/mechanize/), which I believe is a clone of an original library written in Perl. Anyway, that in combination with the [ClientForm](http://wwwsearch.sourceforge.net/ClientForm/) module, and some additional help from either BeautifulSoup and you should be away.
I've written loads of screen-scraping code in Python and these modules turned out to be the most useful. Most of the stuff that [mechanize](http://wwwsearch.sourceforge.net/mechanize/) does could in theory be done by simply using the [urllib2](http://docs.python.org/library/urllib2.html) or [httplib](http://docs.python.org/library/httplib.html) modules from the standard library, but [mechanize](http://wwwsearch.sourceforge.net/mechanize/) makes this stuff a breeze: essentially it gives you a programmatic browser (note, it does not require a browser to work, but mearly provides you with an API that behaves like a completely customisable browser).
For post-processing, I've had a lot of success with BeautifulSoup, but [lxml.html](http://codespeak.net/lxml/lxmlhtml.html) is a good choice too.
Basically, you will be able to do this in Python for sure, and your results should be really good with the range of tools out there. | You can pass a `data` parameter to [`urllib.urlopen`](http://docs.python.org/library/urllib.html#urllib.urlopen) to send POST data with the request just like you had filled out the form. You'll obviously have to take a look at what data exactly the form contains.
Also, if the form has `method="GET"`, the request data is just part of the url given to `urlopen`.
Pretty much standard for scraping the returned HTML data is [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/). | Screen Scrape Form Results | [
"",
"python",
"forms",
"screen-scraping",
""
] |
I am debugging and I hit my break point. I hover over a variable and I get the standard drilldown. I see a Nullable prop and it is null. I right click and choose "edit value". No matter what I seem to type, I get "The value could not be set. Please check your entry."
I have tried 5/1/09, new DateTime(2009, 5, 1), {05/01/2009}... pretty much every flavor I could think of. What the heck am I doing wrong? I would like to code in the value and continue debugging with the new value.
Any suggestions?
Thanks, ~ck | DateTime.Parse("5/1/2009") | Seems easy to me. I had this line:
```
DateTime dt = DateTime.Parse("01/01/2000");
```
Hit the breakpoint, and typed this into the immediate window:
```
dt = DateTime.Parse("02/01/2010")
```
The same technique also works when editing the value in the debugger tooltip, the locals window, the autos window, the watch window and even the quick watch window. | Debugging Help - set a value in debug mode? | [
"",
"c#",
"debugging",
""
] |
I have to copy a bunch of data from one database table into another. I can't use SELECT ... INTO because one of the columns is an identity column. Also, I have some changes to make to the schema. I was able to use the export data wizard to create an SSIS package, which I then edited in Visual Studio 2005 to make the changes desired and whatnot. It's certainly faster than an INSERT INTO, but it seems silly to me to download the data to a different computer just to upload it back again. (Assuming that I am correct that that's what the SSIS package is doing). Is there an equivalent to BULK INSERT that runs directly on the server, allows keeping identity values, and pulls data from a table? (as far as I can tell, BULK INSERT can only pull data from a file)
Edit:
I do know about IDENTITY\_INSERT, but because there is a fair amount of data involved, INSERT INTO ... SELECT is kinda of slow. SSIS/BULK INSERT dumps the data into the table without regards to indexes and logging and whatnot, so it's faster. (Of course creating the clustered index on the table once it's populated is not fast, but it's still faster than the INSERT INTO...SELECT that I tried in my first attempt)
Edit 2:
The schema changes include (but are not limited to) the following:
1. Splitting one table into two new tables. In the future each will have its own IDENTITY column, but for the migration I think it will be simplest to use the identity from the original table as the identity for the both new tables. Once the migration is over one of the tables will have a one-to-many relationship to the other.
2. Moving columns from one table to another.
3. Deleting some cross reference tables that only cross referenced 1-to-1. Instead the reference will be a foreign key in one of the two tables.
4. Some new columns will be created with default values.
5. Some tables aren’t changing at all, but I have to copy them over due to the "put it all in a new DB" request. | Since so many people have looked at this question, I thought I should follow up.
I ended up sticking with the SSIS package. I executed it on the database server itself. It still went through the rigmarole of pulling data from the the sql process to the SSIS process, then sending it back. But overall it executed faster than other options I investigated.
Also, I ran into a bug: when pulling data from a view, the package would just hang. I ended up cutting and pasting the query from the view directly into the "sql query" field of the "source" object in SSIS. This only seemed to happen when the package was running on the same machine as the server. When running from a different machine, I did not run into this error.
If I had to do it all over again, I would probably generate new identity values. I would migrate the old ones to a column in the new table, use those values to associate the other tables' foreign keys, and then I would delete the column once the migration was complete and stable. On the other hand, overall the SSIS package method worked fine, so if you have to do a complex migration (splitting up tables etc.) or need to keep the identity values intact, I would recommend it.
Thanks to everyone who responded. | I think you may be interested in [Identity Insert](http://www.sqlteam.com/article/how-to-insert-values-into-an-identity-column-in-sql-server) | BULK INSERT from one table to another all on the server | [
"",
"sql",
"database",
"sql-server-2005",
"data-migration",
""
] |
I need to disable the highlighting of selected text on my web app. I have a good reason for doing this and know that this is generally a bad idea. But I need to do it anyway. It doesn't matter if I need to use CSS or JS to do it. What I'm mainly going for is the removal of the blue color given to highlighted elements. | You can use the CSS pseudo class selector `::selection` and `::-moz-selection` for Firefox.
For example:
```
::-moz-selection {
background-color: transparent;
color: #000;
}
::selection {
background-color: transparent;
color: #000;
}
.myclass::-moz-selection,
.myclass::selection { ... }
``` | The CSS3 solution:
```
user-select: none;
-moz-user-select: none;
```
There is also a webkit prefix for the user-select, but it makes some form fields impossible to focus (could be a temporary bug), so you could go with the following pseudo-class for webkit instead:
```
element::selection
``` | How can I disable highlighting in html or JS? | [
"",
"javascript",
"html",
"css",
"highlight",
""
] |
Using spring DefaultAnnotationHandlerMapping how can I lookup the Controller that would ultimately handle a given url.
I currently have this, but feels like there ought to be a cleaner way than iterating over 100s of request mappings:
```
public static Object getControllerForAction(String actionURL) {
ApplicationContext context = getApplicationContext();
AnnotationHandlerMapping mapping = (AnnotationHandlerMapping) context.getBean("annotationMapper");
PathMatcher pathMatcher = mapping.getPathMatcher();
for (Object key: mapping.getHandlerMap().keySet()) {
if (pathMatcher.match((String) key, actionURL)){
return mapping.getHandlerMap().get(key);
}
}
return null;
}
``` | For the purposes of this question, all of the interesting methods in `DefaultAnnotationHandlerMapping` and its superclasses are protected, and so not visible to external code. However, it would be trivial to write a custom subclass of `DefaultAnnotationHandlerMapping` which overrides these methods and makes them `public`.
Since you need to be able to supply a path rather than a request object, I would suggest `lookupHandler` of `AbstractUrlHandlerMapping` would be a good candidate for this. It still needs you to supply it with a request object as well as the path, but that request object is only used to pass to the validateHandler() method, which does nothing, so you could probably supply a null there. | All mappers implement `HandlerMapping` interface which has a `getHandler()` method:
```
ApplicationContext context = getApplicationContext();
AnnotationHandlerMapping mapping = (AnnotationHandlerMapping) context.getBean("annotationMapper");
Object controller = mapping.getHandler().getHandler();
```
`HandlerMapping.getHandler()` returns `HandlerExecutionChain`, calling `getHandler()` on that would return you the actual handler which - for controller mapper - would be the controller you're looking for. | How to determine Controller for given url (spring) | [
"",
"java",
"spring-mvc",
""
] |
I'm trying to login directly to Google Analytics. To explain, I have an account system and I'd like when you select an ASP.NET button for instance it re-directs you - via a silent login - to a specified Google Analytics account.
I've looked long and hard at Dave Cullen's ASP.NET library and although I can login 'silently' using HttpWebRequest, I can't then stick the user on that page. I'm having allsorts of dramas with a 'Cannot send a content-body with this verb-type' error too.
Here is the very basic code I have currently based on Dave's library;
```
string token = GoogleAnalytics.getSessionTokenClientLogin(username, password);
NameValueCollection profiles = GoogleAnalytics.getAccountInfo(token, GoogleAnalytics.mode.ClientLogin);
HttpWebRequest theRequest = (HttpWebRequest)WebRequest.Create("https://www.google.com/analytics/settings/?et=reset&hl=en_uk&et=reset&hl=en-US&et=reset&hl=en-GB");
theRequest.Headers.Add("Authorization: GoogleLogin auth=" + token);
Stream responseBody = theRequest.GetRequestStream();
Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
StreamReader readStream = new StreamReader(responseBody, encode);
```
My question therefore is; 1. can this be done? and 2. is this even the right way to do this?
Advice welcomed! | I'm not sure what the overall goal of signing someone in to Google Analytics automatically is, but if its just to display some of the data that is in Google Analytics you might want to consider using the Google Data API to pull the information that you want from Google Analytics. You could create a simple dashboard of what they really need to see without giving access to other things in Google Analytics, by logging them in you are most likely giving them access to data and tools that they just don't need?
Check out the API if it doesn't fit your needs maybe provide some more information on the overall goal is of this functionality.
<http://code.google.com/apis/analytics/> | Unless you're willing to implement a proxy server to proxy google analytics, I don't think you're going to be able to do this because you can't assign cookies to the client for another domain. | Login Remotely To Google Analytics with ASP.NET | [
"",
"c#",
"asp.net",
"google-analytics",
""
] |
My problem is in regards file copying performance. We have a media management system that requires a lot of moving files around on the file system to different locations including windows shares on the same network, FTP sites, AmazonS3, etc. When we were all on one windows network we could get away with using System.IO.File.Copy(source, destination) to copy a file. Since many times all we have is an input Stream (like a MemoryStream), we tried abstracting the Copy operation to take an input Stream and an output Stream but we are seeing a massive performance decrease. Below is some code for copying a file to use as a discussion point.
```
public void Copy(System.IO.Stream inStream, string outputFilePath)
{
int bufferSize = 1024 * 64;
using (FileStream fileStream = new FileStream(outputFilePath, FileMode.OpenOrCreate, FileAccess.Write))
{
int bytesRead = -1;
byte[] bytes = new byte[bufferSize];
while ((bytesRead = inStream.Read(bytes, 0, bufferSize)) > 0)
{
fileStream.Write(bytes, 0, bytesRead);
fileStream.Flush();
}
}
}
```
Does anyone know why this performs so much slower than File.Copy? Is there anything I can do to improve performance? Am I just going to have to put special logic in to see if I'm copying from one windows location to another--in which case I would just use File.Copy and in the other cases I'll use the streams?
Please let me know what you think and whether you need additional information. I have tried different buffer sizes and it seems like a 64k buffer size is optimal for our "small" files and 256k+ is a better buffer size for our "large" files--but in either case it performs much worse than File.Copy(). Thanks in advance! | File.Copy was build around [CopyFile](http://msdn.microsoft.com/en-us/library/aa363851%28VS.85%29.aspx) Win32 function and this function takes lot of attention from MS crew (remember this Vista-related threads about slow copy performance).
Several clues to improve performance of your method:
1. Like many said earlier remove Flush method from your cycle. You do not need it at all.
2. Increasing buffer may help, but only on file-to-file operations, for network shares, or ftp servers this will slow down instead. 60 \* 1024 is ideal for network shares, at least before vista. for ftp 32k will be enough in most cases.
3. Help os by providing your caching strategy (in your case sequential reading and writing), use FileStream constructor override with [FileOptions](http://msdn.microsoft.com/en-us/library/system.io.fileoptions.aspx) parameter (SequentalScan).
4. You can speed up copying by using asynchronous pattern (especially useful for network-to-file cases), but do not use threads for this, instead use overlapped io (BeginRead, EndRead, BeginWrite, EndWrite in .net), and do not forget set Asynchronous option in FileStream constructor (see [FileOptions](http://msdn.microsoft.com/en-us/library/system.io.fileoptions.aspx))
Example of asynchronous copy pattern:
```
int Readed = 0;
IAsyncResult ReadResult;
IAsyncResult WriteResult;
ReadResult = sourceStream.BeginRead(ActiveBuffer, 0, ActiveBuffer.Length, null, null);
do
{
Readed = sourceStream.EndRead(ReadResult);
WriteResult = destStream.BeginWrite(ActiveBuffer, 0, Readed, null, null);
WriteBuffer = ActiveBuffer;
if (Readed > 0)
{
ReadResult = sourceStream.BeginRead(BackBuffer, 0, BackBuffer.Length, null, null);
BackBuffer = Interlocked.Exchange(ref ActiveBuffer, BackBuffer);
}
destStream.EndWrite(WriteResult);
}
while (Readed > 0);
``` | Three changes will dramatically improve performance:
1. Increase your buffer size, try 1MB (well -just experiment)
2. After you open your fileStream, call fileStream.SetLength(inStream.Length) to allocate the entire block on disk up front (only works if inStream is seekable)
3. Remove fileStream.Flush() - it is redundant and probably has the single biggest impact on performance as it will block until the flush is complete. The stream will be flushed anyway on dispose.
This seemed about 3-4 times faster in the experiments I tried:
```
public static void Copy(System.IO.Stream inStream, string outputFilePath)
{
int bufferSize = 1024 * 1024;
using (FileStream fileStream = new FileStream(outputFilePath, FileMode.OpenOrCreate, FileAccess.Write))
{
fileStream.SetLength(inStream.Length);
int bytesRead = -1;
byte[] bytes = new byte[bufferSize];
while ((bytesRead = inStream.Read(bytes, 0, bufferSize)) > 0)
{
fileStream.Write(bytes, 0, bytesRead);
}
}
}
``` | File.Copy vs. Manual FileStream.Write For Copying File | [
"",
"c#",
"windows",
"performance",
""
] |
I have three tables - one for shipping rates, one for products and one for exceptions to shipping rate for particular products. Shipping is charged as follows:
Each product has a shipping price, but this price can be overridden by an exception. If no exception exists for a product, the default rate is used for the shipping rate selected by the user.
[alt text http://mi6.nu/sqljoin.png](http://mi6.nu/sqljoin.png)
I'm trying to join these tables so that if an exception exists, that price is selected, otherwise, the default price is selected but I'm having problems with the join. I need to query by product ID, and I have (line 2 is for debugging)
```
SELECT r.ID AS ShippingRateID, r.Name,
e.*, r.*
FROM shipping r LEFT JOIN shippingexceptions e ON r.ID = e.ShippingRateID
WHERE e.ProductID = 48
```
And I need returned:
```
1 Uk and Northern Ireland 1
2 EU Eire... 10
3 US and Canada 2.16
4 Rest of world 2.44
```
So if an exception exists, the exception price is used, otherwise the default price is used. I'm planning to use a CASE statement, but I need to return the data first. | First thing I notice is that you have a predicate condition on table e, which is on the "outer" side of an outer join. This will immediately turn the join into an Inner join, as the rows that would ordinarilly have been produced where there is a record on the inner side but no record on the outer side, would have all nulls in the columns from the outer table by the time the where clause predicate (WHERE e.ProductID = 48) is executed.
You need to put this predicate in the join conditions instead.
like this:
```
SELECT r.ID AS ShippingRateID, r.Name, e.*, r.*
FROM shipping r
LEFT JOIN shippingexceptions e
ON r.ID = e.ShippingRateID
And e.ProductID = 48
```
Next, as Joels answer recommended, for a simple expression, although a case would work, you don't need a case statement, Coalesce will suffice:
```
SELECT r.ID AS ShippingRateID, r.Name,
Coalesce(e.rate, defaultrate) as Rate,
e.*, r.*
FROM shipping r
LEFT JOIN shippingexceptions e
ON r.ID = e.ShippingRateID
And e.ProductID = 48
``` | Why not use a coalesce
```
SELECT r.ID AS ShippingRateID, r.Name, coalesce(e.cost, r.defaultprice)
FROM shipping r LEFT JOIN shippingexceptions e ON r.ID = e.ShippingRateID
WHERE e.ProductID = 48
```
This way, if e.rate is null, r.rate is used.
You also should put your e.ProductId on the join so it doesn't force you to select only products with exceptions
```
SELECT r.ID AS ShippingRateID, r.Name, coalesce(e.cost, r.defaultprice)
FROM shipping r LEFT JOIN shippingexceptions e ON r.ID = e.ShippingRateID and e.ProductID = 48
``` | SQL Join with CASE and WHERE | [
"",
"sql",
"sql-server",
""
] |
The following is an extract from my code:
```
public class AllIntegerIDs
{
public AllIntegerIDs()
{
m_MessageID = 0;
m_MessageType = 0;
m_ClassID = 0;
m_CategoryID = 0;
m_MessageText = null;
}
~AllIntegerIDs()
{
}
public void SetIntegerValues (int messageID, int messagetype,
int classID, int categoryID)
{
this.m_MessageID = messageID;
this.m_MessageType = messagetype;
this.m_ClassID = classID;
this.m_CategoryID = categoryID;
}
public string m_MessageText;
public int m_MessageID;
public int m_MessageType;
public int m_ClassID;
public int m_CategoryID;
}
```
I am trying to use the following in my `main()` function code:
```
List<AllIntegerIDs> integerList = new List<AllIntegerIDs>();
/* some code here that is ised for following assignments*/
{
integerList.Add(new AllIntegerIDs());
index++;
integerList[index].m_MessageID = (int)IntegerIDsSubstring[IntOffset];
integerList[index].m_MessageType = (int)IntegerIDsSubstring[IntOffset + 1];
integerList[index].m_ClassID = (int)IntegerIDsSubstring[IntOffset + 2];
integerList[index].m_CategoryID = (int)IntegerIDsSubstring[IntOffset + 3];
integerList[index].m_MessageText = MessageTextSubstring;
}
```
Problem is here: I am trying to print all elements in my List using a for loop:
```
for (int cnt3 = 0 ; cnt3 <= integerList.FindLastIndex ; cnt3++) //<----PROBLEM HERE
{
Console.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}\n", integerList[cnt3].m_MessageID,integerList[cnt3].m_MessageType,integerList[cnt3].m_ClassID,integerList[cnt3].m_CategoryID, integerList[cnt3].m_MessageText);
}
```
I want to find the last element so that I equate cnt3 in my for loop and print out all entries in the `List`. Each element in the list is an object of the class `AllIntegerIDs` as mentioned above in the code sample. How do I find the last valid entry in the List?
Should I use something like `integerList.Find(integerList[].m_MessageText == null;`?
If I use that it will need an index that will range from 0 to whatever maximum. Means I will have to use another for loop which I do not intend to use. Is there a shorter/better way? | If you just want to access the last item in the list you can do
```
if (integerList.Count > 0)
{
// pre C#8.0 : var item = integerList[integerList.Count - 1];
// C#8.0 :
var item = integerList[^1];
}
```
to get the total number of items in the list you can use the `Count` property
```
var itemCount = integerList.Count;
``` | To get the last item of a collection use **[LastOrDefault()](http://msdn.microsoft.com/en-us/library/bb301849.aspx)** and **[Last()](http://msdn.microsoft.com/en-us/library/system.linq.enumerable.last.aspx)** extension methods
```
var lastItem = integerList.LastOrDefault();
```
OR
```
var lastItem = integerList.Last();
```
Remeber to add `using System.Linq;`, or this method won't be available. | How can I find the last element in a List<>? | [
"",
"c#",
"list",
""
] |
I have a continous time dataset and I want to break it up into 15 minute blocks using sql.
**I don't want to have to create a new table to be able to do this if I can help it.**
i.e.
Time, Count
09:15, 1
09:30, 3
09:45, 0
10:00, 2
10:15, 3
.....
Does anyone have any idea of how I can do this. I presume that is use a select similar to the following:
SELECT [Some kind of data manipulation on "MyDate"]
, COUNT(ID)
FROM MyTable
GROUP BY [Some kind of data manipulation on "MyDate"] | With careful use of dateadd and datediff, this can be accomplished. My solution rounds the times down.
The first piece calculates the number of minutes between the row's date and the epoch (0) and does a mod 15 on it, giving the difference between the row's date and the closest 15 minute interval:
```
select -1 * datediff(minute, 0, mydate) % 15
from mytable
```
Next, we need to deal with just the minutes, so we use this date-part stripping technique I learned from SQL Server Magazine February 2007 (Datetime Calculations by Itzik Ben-Gan):
```
select dateadd(minute, datediff(minute, 0, mydate), 0)
from mytable
```
Then, we add the difference to the row's date column and group and count and voila!
```
select dateadd(minute, -1 * datediff(minute, 0, mydate) % 15, dateadd(minute, datediff(minute, 0, mydate), 0)), count(ID)
from mytable
group by dateadd(minute, -1 * datediff(minute, 0, mydate) % 15, dateadd(minute, datediff(minute, 0, mydate), 0))
``` | Something like this seems to work, it strips off the time portion, then readds it at the minute level, after removing minutes mod 15 - to end up with a date in 15 minute intervals, from there its a simple group by
```
create table quarterHourly (ID int identity(1, 1), created datetime)
insert into quarterHourly values ('2009-07-29 10:00:00.000') -- 10:00
insert into quarterHourly values ('2009-07-29 10:00:00.010') -- 10:00
insert into quarterHourly values ('2009-07-29 10:15:00.000') -- 10:15
insert into quarterHourly values ('2009-07-29 10:15:00.010') -- 10:15
insert into quarterHourly values ('2009-07-29 10:30:00.000') -- 10:30
insert into quarterHourly values ('2009-07-29 10:30:00.010') -- 10:30
insert into quarterHourly values ('2009-07-29 10:45:00.000') -- 10:45
insert into quarterHourly values ('2009-07-29 10:45:00.010') -- 10:45
insert into quarterHourly values ('2009-07-29 11:00:00.000') -- 11:00
insert into quarterHourly values ('2009-07-29 11:00:00.010') -- 11:00
insert into quarterHourly values ('2009-07-29 10:31:00.010') -- 10:30
insert into quarterHourly values ('2009-07-29 10:44:00.010') -- 10:30
select dateadd(mi, datediff(mi, 0, created) - datepart(mi, created) % 15, dateadd(dd, 0, datediff(dd, 0, created))), count(*)
from quarterHourly
group by dateadd(mi, datediff(mi, 0, created) - datepart(mi, created) % 15, dateadd(dd, 0, datediff(dd, 0, created)))
``` | SQL Server 2000 - Breaking a query up into 15 minute blocks | [
"",
"sql",
"sql-server",
"sql-server-2000",
""
] |
I have tried to do this in many different ways but the most obvious was this:
```
var map2 = new GMap2(document.getElementById("map2"), {size:"100%"});
```
That does not work. | [Google says](http://code.google.com/apis/maps/documentation/introduction.html):
> Unless you specify a size explicitly for the map using GMapOptions in the constructor, the map implicitly uses the size of the container to size itself.
So set the size of your map container fill all available space:
```
<div id="map2" style="width: 100%; height: 100%"></div>
``` | How about dynamically calculating the dimensions of it's parent container and explicitly setting them on the google map element? Assuming 100%/100% height don't work out. | How to get a google map to use 100% of its parent container? | [
"",
"javascript",
"css",
"api",
"google-maps",
""
] |
I am receiving a unicode message via the network, which looks like:
74 00 65 00 73 00 74 00 3F 00
I am using a BinaryReader to read the stream from my socket, but the problem is that it doesn't offer a "ReadWideString" function, or something similar to it. Anyone an idea how to deal with this?
Thanks! | Simple!
```
string str = System.Text.Encoding.Unicode.GetString(array);
```
where `array` is your array of bytes. | Strings in C# are Unicode by default. Try
```
string converted = Encoding.Unicode.GetString(data);
```
where data is a byte[] array containing your Unicode data. If your data is big endian, you can try
```
string converted = Encoding.BigEndianUnicode.GetString(data);
``` | C# read unicode? | [
"",
"c#",
"unicode",
"stream",
"ascii",
""
] |
Can anyone offer any suggestions as to why `wp-admin/options-general.php` won't load on my Wordpress installation in PHP 5.3? If I enable debugging and then have PHP report errors, I do get deprecation errors, but they don't seem relevant. Further, if I fix these errors, the page still does not load.
The top bar and several navigation boxes load, but nothing inside the central frame?
I am running dotdeb's PHP 5.3
Output with `WP_DEBUG` and `error_reporting(0)`:
```
Deprecated: Assigning the return value of new by reference is deprecated in /home/willyum/willyum.info/blog/wp-includes/cache.php on line 103
Deprecated: Assigning the return value of new by reference is deprecated in /home/willyum/willyum.info/blog/wp-includes/pomo/mo.php on line 171
Deprecated: Assigning the return value of new by reference is deprecated in /home/willyum/willyum.info/blog/wp-includes/l10n.php on line 407
Deprecated: Assigning the return value of new by reference is deprecated in /home/willyum/willyum.info/blog/wp-includes/query.php on line 61
Deprecated: Assigning the return value of new by reference is deprecated in /home/willyum/willyum.info/blog/wp-includes/theme.php on line 1133
Deprecated: Assigning the return value of new by reference is deprecated in /home/willyum/willyum.info/blog/wp-includes/taxonomy.php on line 617
``` | If I remember correctly, wordpress uses lots of [@ operator](http://www.php.net/manual/en/language.operators.errorcontrol.php) to avoid the display of errors... So, many of those are not displayed, event if `error_reporting` is activated :-(
(That's one of the reasons that @ operator is evil... )
Maybe using the [scream extension](http://pecl.php.net/package/scream) on your testing machine, to disabled the @ operator, could help ?
*Still, I've just tried wordpress on PHP 5.3, and that page seems to load fine... I'm using a 2.8.x version, btw* | Try disabling all Plugins that you have installed. If it solves the problem, then try to enable each Plugin one my one to find out the offending Plugin.
You can also use wp-devel Plugin to find out the function trace. <http://wordpress.org/extend/plugins/wp-devel/> | Wordpress and PHP 5.3 | [
"",
"php",
"wordpress",
"deprecated",
""
] |
Currently I am writing a web application using Spring Security. We have a web service which authenticates users by username and password.
**Web service:**
`String[] login(String username, String password);`
How do I configure Spring Security to pass the provided username and password to the web service?
I have written a `UserDetailsService` which only receives a username.
---
I think the problem is with your xml. Did you turned off the auto-config? And does your class extend AbstractUserDetailsAuthenticationProvider? | Extend org.acegisecurity.providers.dao.AbstractUserDetailsAuthenticationProvider
```
/**
* @author rodrigoap
*
*/
public class WebServiceUserDetailsAuthenticationProvider extends
AbstractUserDetailsAuthenticationProvider {
@Override
protected UserDetails retrieveUser(String username,
UsernamePasswordAuthenticationToken authentication)
throws AuthenticationException {
//Improve this line:
String password = authentication.getCredentials().toString();
// Invoke your webservice here
GrantedAuthority[] grantedAuth = loginWebService.login(username, password);
// create UserDetails. Warning: User is deprecated!
UserDetails userDetails = new User(username, password, grantedAuth);
return userDetails;
}
}
``` | I have written to following class:
`PncUserDetailsAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider`
Which implements the recieveUser methode:
```
@Override
protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken token) throws AuthenticationException {
try {
server = (PncUtilRemote) new InitialContext().lookup("PncUtilBean");
if (server != null) {
String password = SHA1(token.getCredentials().toString());
String[] auth = server.login(username, password);
if (auth.length > 0) {
PncUserDetails details = new PncUserDetails(username, password);
for (int i = 0; i < auth.length; i++) {
details.addAuthority(auth[i]);
}
return details;
}
}
} catch (Exception e) {
System.out.println("! " + e.getClass().getName() + " in com.logica.pnc.security.PncUserDetailsAuthenticationProvider.retrieveUser(String, UsernamePasswordAuthenticationToken): " + e.getMessage());
}
throw new BadCredentialsException("");
}
```
To enable your AuthenticationProvider you need to add some lines to your application-context.xml file:
```
<bean id="authenticationManager" class="org.springframework.security.providers.ProviderManager">
<property name="providers">
<list><ref local="PncAuthenticationProvider" /></list>
</property>
</bean>
<bean id="PncAuthenticationProvider" class="com.logica.pnc.security.PncUserDetailsAuthenticationProvider">
<security:custom-authentication-provider />
</bean>
```
It is important that you set the auto-config to false:
```
<security:http auto-config="false" />
```
Thanks to rodrigoap for pointing to the AuthenticationProvider thingy :) | Authenticate users with SpringSecurity using a WebService that requires a username and password | [
"",
"java",
"web-services",
"spring-security",
""
] |
How can I fill an array like so:
```
1 2 3 4 5 6 7 8
20 21 22 23 24 9
19 30 31 32 25 10
18 29 28 27 26 11
17 16 15 14 13 12
```
Spiral
C#
Thanks | Traverse the array starting from element (0,0) (top-left), and heading right (incrementing your column index). Keep a running counter that increments each time you fill an element, as well as upper and lower bounds on the rows and columns you have yet to fill. For an M-row by N-column matrix, your row bounds should be 0 and (M-1), and your column bounds 0 and (N-1). Go right until you hit your upper column bound, decrement your upper column bound, go down until you hit your upper row bound, decrement your upper row bound, go left until you hit your lower column bound, increment your lower column bound, go up until you hit your lower row bound, increment your lower bound, and repeat until your upper and low row or column bounds are equal (or until your running count is M\*N). | I personally made a program. Check it.
```
using System;
using System.Collections.Generic;
using System.Text;
namespace SpiralMatrix
{
class Program
{
static void Main(string[] args)
{
int m = 0, n = 0, start = 0, step = 0;
bool errorOcured = false;
Console.WriteLine("====Spiral Matrix====\n");
try
{
Console.WriteLine("Enter size of the matrix:");
Console.Write("Row (m)? ");
m = Convert.ToInt32(Console.ReadLine());
Console.Write("Column (n)? ");
n = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter the starting number: ");
start = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter step: ");
step = Convert.ToInt32(Console.ReadLine());
if (m < 0 || n < 0 || start < 0 || step < 0) throw new FormatException();
}
catch (FormatException e)
{
Console.WriteLine("Wrong input. [Details: {0}]", e.Message);
Console.WriteLine("Program will now exit...");
errorOcured = true;
}
if (!errorOcured)
{
int[,] mat = new int[m, n];
mat = initMatrix(m, n, start, step);
Console.WriteLine("\nIntial matrix generated is:");
displayMatrix(mat, m, n);
Console.WriteLine("\nSpiral Matrix generated is:");
mat = calculateSpider(mat, m, n);
displayMatrix(mat, m, n);
}
Console.Write("\nPress enter to exit...");
Console.Read();
}
private static int[,] initMatrix(int m, int n, int start, int step)
{
int[,] ret = new int[m, n];
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
ret[i, j] = start;
start += step;
}
}
return ret;
}
private static void displayMatrix(int[,] mat, int m, int n)
{
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
Console.Write("\t{0}", mat[i, j]);
}
Console.WriteLine();
}
}
private static int[,] calculateSpider(int[,] mat, int m, int n)
{
int[,] intMat;
if (m <= 2 || n <= 2)
{
if (m == 2 && n == 2)
{
int[,] t = new int[m, n];
t[0, 0] = mat[0, 0];
t[0, 1] = mat[0, 1];
t[1, 0] = mat[1, 1];
t[1, 1] = mat[1, 0];
return t;
}
else if (m == 2)
{
int[,] t = new int[m, n];
for (int i = 0; i < n; i++)
{
t[0, i] = mat[0, i];
t[1, n - 1 - i] = mat[1, i];
}
return t;
}
else if (n == 2)
{
int[,] t = new int[m, n];
int[] stMat = new int[m * n];
int c = 0;
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
stMat[c] = mat[i, j];
c++;
}
}
c = 0;
for (int i = 0; i < n; i++)
{
t[0, i] = stMat[c];
c++;
}
for (int i = 1; i < m; i++)
{
t[i, 1] = stMat[c];
c++;
}
if(m>1) t[m - 1, 0] = stMat[c];
c++;
for (int i = m - 2; i >= 1; i--)
{
t[i, 0] = stMat[c];
c++;
}
return t;
}
else return mat;
}
intMat = new int[m - 2, n - 2];
int[,] internalMatrix = new int[m - 2, n - 2]; //internal matrix
for (int i = 0; i < ((m - 2) * (n - 2)); i++)
{
internalMatrix[(m - 2) - 1 - i / (n - 2), (n - 2) - 1 - i % (n - 2)] = mat[m - 1 - (i / n), n - 1 - (i % n)];
}
intMat = calculateSpider(internalMatrix, m - 2, n - 2);
int[,] retMat = new int[m, n]; //return matrix
//copy some characters to a single dimentional array
int[] tempMat = new int[(m * n) - ((m - 2) * (n - 2))];
for (int i = 0; i < (m * n) - ((m - 2) * (n - 2)); i++)
{
tempMat[i] = mat[i / n, i % n];
}
int count = 0;
//copy fist row
for (int i = 0; i < n; i++)
{
retMat[0, i] = tempMat[count];
count++;
}
//copy last column
for (int i = 1; i < m; i++)
{
retMat[i, n - 1] = tempMat[count];
count++;
}
//copy last row
for (int i = n - 2; i >= 0; i--)
{
retMat[m - 1, i] = tempMat[count];
count++;
}
//copy first column
for (int i = m - 2; i >= 1; i--)
{
retMat[i, 0] = tempMat[count];
count++;
}
//copy others
for (int i = 1; i < m - 1; i++)
{
for (int j = 1; j < n - 1; j++)
{
retMat[i, j] = intMat[i - 1, j - 1];
}
}
return retMat;
}
}
}
``` | Spiral Algorithm in C# | [
"",
"c#",
"algorithm",
""
] |
What can I do to share code among views in CouchDB?
### Example 1 -- utility methods
Jesse Hallett [has some good utility methods](http://sitr.us/2009/06/30/database-queries-the-couchdb-way.html), including
```
function dot(attr) {
return function(obj) {
return obj[attr];
}
}
Array.prototype.map = function(func) {
var i, r = [],
for (i = 0; i < this.length; i += 1) {
r[i] = func(this[i]);
}
return r;
};
...
```
Where can I put this code so every view can access it?
### Example 2 -- constants
Similarly for constants I use in my application. Where do I put
```
MyApp = {
A_CONSTANT = "...";
ANOTHER_CONSTANT = "...";
};
```
### Example 3 -- filter of a filter:
What if I want a one view that filters by "is this a rich person?":
```
function(doc) {
if (doc.type == 'person' && doc.net_worth > 1000000) {
emit(doc.id, doc);
}
}
```
and another that indexes by last name:
```
function(doc) {
if (doc.last_name) {
emit(doc.last_name, doc);
}
}
```
How can I combine them into a "rich people by last name" view?
I sort of want the equivalent of the Ruby
```
my_array.select { |x| x.person? }.select { |x| x.net_worth > 1,000,000 }.map { |x| [x.last_name, x] }
```
How can I be DRYer? | The answer lies in [couchapp](http://github.com/couchapp/couchapp). With couchapp you can embed macros that include common library code into any of the design document sections. It is done before the design document is submitted to the server. What you need to do to do the query you ask about is reverse the keys that are emitted so you can do a range query on the "network"
```
function(doc)
{
if (doc.type == 'person')
{
emit([doc.net_worth, doc.lastname], null);
}
}
```
You don't want to include the doc you can do that with `include_docs=true` on the query parameters. And you get the doc.id for free as part of the key. Now you can do a range query on networth which would look something like this.
```
http://localhost:5984/database/_design/people/_view/by_net_worth?startkey=[1000000]&endkey=[{},{}]&include_docs=true
``` | As per [this blog post](https://caolan.org/posts/commonjs_modules_in_couchdb.html), you can add commonjs modules to the **map function** (but not the reduce function) in views in couchdb 1.1 by having a key called lib in your views object. A lot of popular javascript libraries like underscore.js adhere to the commonjs standard, so you can use them in your views by using *require("views/lib/[your module name]")*.
Say you include underscore.js as "underscore" in the lib object in views, like so:
```
views: {
lib: {
underscore: "// Underscore.js 1.1.6\n ...
}
...
[ the rest of your views go here]
}
```
, you can then add the following to your view to get access to the \_ module:
```
var _ = require("views/lib/underscore");
```
For custom libraries, all you need to do is make anything you want to share in your library a value to the global "exports" object. | How do I DRY up my CouchDB views? | [
"",
"javascript",
"couchdb",
"dry",
""
] |
I am basically creating a flat View Model for a Timesheet page (ASP.NET MVC) that has a grid for the days of the week. The WorkTime properties should either be an existing WorkTime from the database or null if there is no existing one.
There will only ever be 1 week displayed (Saturday to Friday). and I have the individual properties there so that the syntax in my view should be simpler.
```
+------+-----+-----+-----+-----+-----+-----+-----+
| Desc | Sat | Sun | Mon | Tue | Wed | Thu | Fri |
+------+-----+-----+-----+-----+-----+-----+-----+
|______|_____|_____|_____|_____|_____|_____|_____|
|______|_____|_____|_____|_____|_____|_____|_____|
|______|_____|_____|_____|_____|_____|_____|_____|
|______|_____|_____|_____|_____|_____|_____|_____|
```
All of the dates that come from and are persisted to the database have no Time element (all midnight hour) and the Saturday to Friday DateTime properties are all set already.
The properties I am setting
```
public WorkTime SaturdayWorkTime { get; private set; }
public WorkTime SundayWorkTime { get; private set; }
public WorkTime MondayWorkTime { get; private set; }
public WorkTime TuesdayWorkTime { get; private set; }
public WorkTime WednesdayWorkTime { get; private set; }
public WorkTime ThursdayWorkTime { get; private set; }
public WorkTime FridayWorkTime { get; private set; }
```
Current iteration...
```
public DateTime Saturday { get; private set; }
public DateTime Sunday { get; private set; }
public DateTime Monday { get; private set; }
public DateTime Tuesday { get; private set; }
public DateTime Wednesday { get; private set; }
public DateTime Thursday { get; private set; }
public DateTime Friday { get; private set; }
_workTimes = _workTimeRepository.GetByWorkAssignmentID(WorkAssignment.ID, Saturday, Friday);
SaturdayWorkTime = GetWorkTimeForDay(DayOfWeek.Saturday);
SundayWorkTime = GetWorkTimeForDay(DayOfWeek.Sunday);
MondayWorkTime = GetWorkTimeForDay(DayOfWeek.Monday);
TuesdayWorkTime = GetWorkTimeForDay(DayOfWeek.Tuesday);
WednesdayWorkTime = GetWorkTimeForDay(DayOfWeek.Wednesday);
ThursdayWorkTime = GetWorkTimeForDay(DayOfWeek.Thursday);
FridayWorkTime = GetWorkTimeForDay(DayOfWeek.Friday);
```
with this helper method...
```
private WorkTime GetWorkTimeForDay(DayOfWeek dow)
{
return _workTimes.FirstOrDefault(x => x.Date.DayOfWeek == dow);
}
``` | Here's a small start:
```
private WorkTime GetWorkTimeForDay(DayOfWeek dw)
{
return workTimes.FirstOrDefault(x => x.Date.DayOfWeek == dw);
}
``` | Why not create a Dictionary to store these worktimes?
```
private Dictionary<DayOfWeek, WorkTime> _workTimes;
```
Populating this dictionary, using \_workTimeRepository.GetByWorkAssignmentID, should be very simple. | C# refactor this messy code! | [
"",
"c#",
"refactoring",
""
] |
So, I have a file that sends the following:
```
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: private");
header("Content-type: application/pdf");
header("Content-disposition: inline; filename=file.pdf");
header("Content-length: 7735");
```
then I echo out the file - it is a PDF file.
Works fine in IE6 & 7 on XP (and FF for that matter)
The very same code shows nothing when running on IE8 on either XP or Vista.
There are no security warnings, etc so I don't think it has to do with that.
And, if my memory serves me correctly, this worked on IE8 a while ago.
What am I doing wrong here? Am I missing something out of the headers?
Is there a way for me to see what header information normal comes over when viewing a PDF in IE8 so I know what to emulate?
After looking at things it still works in IE8 EXCEPT when SSL is on | I'm not sure what is needed, but here is what you could do.
Put the file temporarily in a public place on your server, make syre you can download that with a direct link in IE8, Use firefox LiveHTTP headers or similar to grab all headers that the server sends. Spit them out in exactly the same way and order in your script. (And don't forget to delete the file). | Under HTTPS and IE8, those headers fix the download problem:
```
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Pragma: public");
```
Other X-something headers did not make any difference. | Problems with header() when displaying a PDF file in IE8 | [
"",
"php",
"pdf",
"header",
""
] |
I use CMake to build my application. How can I find where the python site-packages directory is located? I need the path in order to compile an extension to python.
CMake has to be able to find the path on all three major OS as I plan to deploy my application on Linux, Mac and Windows.
I tried using
```
include(FindPythonLibs)
find_path( PYTHON_SITE_PACKAGES site-packages ${PYTHON_INCLUDE_PATH}/.. )
```
however that does not work.
I can also obtain the path by running
```
python -c "from distutils.sysconfig import get_python_lib; print get_python_lib()"
```
on the shell, but how would I invoke that from CMake ?
SOLUTION:
Thanks, Alex.
So the command that gives me the site-package dir is:
```
execute_process ( COMMAND python -c "from distutils.sysconfig import get_python_lib; print get_python_lib()" OUTPUT_VARIABLE PYTHON_SITE_PACKAGES OUTPUT_STRIP_TRAILING_WHITESPACE)
```
The OUTPUT\_STRIP\_TRAILING\_WHITESPACE command is needed to remove the trailing new line. | You can execute external processes in cmake with [execute\_process](http://www.cmake.org/cmake/help/cmake2.6docs.html#command:execute_process) (and get the output into a variable if needed, as it would be here). | Slightly updated version that I used for [lcm](https://github.com/lcm-proj-lcm):
```
execute_process(
COMMAND "${PYTHON_EXECUTABLE}" -c "if True:
from distutils import sysconfig as sc
print(sc.get_python_lib(prefix='', plat_specific=True))"
OUTPUT_VARIABLE PYTHON_SITE
OUTPUT_STRIP_TRAILING_WHITESPACE)
```
This sets `PYTHON_SITE` to the appropriate prefix-relative path, suitable for use like:
```
install(
FILES ${mypackage_python_files}
DESTINATION ${PYTHON_SITE}/mypackage)
```
(Please don't install to an absolute path! Doing so bypasses `CMAKE_INSTALL_PREFIX`.) | Finding python site-packages directory with CMake | [
"",
"python",
"cmake",
""
] |
I want to make a function that detects if a method exists for given instance, what are the parameters that can be passed in and then call the method with proper parameters. I am novice and I have no idea how to do it :( | Try `hasattr`
```
>>> help(hasattr)
Help on built-in function hasattr in module __builtin__:
hasattr(...)
hasattr(object, name) -> bool
Return whether the object has an attribute with the given name.
(This is done by calling getattr(object, name) and catching exceptions.)
```
For more advanced introspection read about the `inspect` module.
But first, tell us why you need this. There's a 99% chance that a better way exists... | Python supports [duck typing](http://en.wikipedia.org/wiki/Duck_typing) - simply call the method on the instance. | How to get information about a function and call it | [
"",
"python",
""
] |
I've got a php array:
```
$toField = explode(",", $ids); //Which looks something like '24,25,26,29'
```
I want to pass this array via jQuery AJAX, with this:
```
<form id="myForm">
<input type="hidden" value="'.$toField.'">
<input type="submit" id="sendMessage" class="faceboxSubmit" name="ok" value="Send Reply"/>
</form>
```
And here's my jQuery:
```
$("#sendMessage").click(function(event){
event.preventDefault();
var senderID = <?php echo $usrID; ?>;
var receiverID = $("#toField").val();
$.ajax(
{
type: "POST",
url: "replyMessage.php",
data: "senderID=" + senderID + "&subject=" + subject + "&message=" + message + "&receiverID=" + receiverID + "&threadID=" + thread_id,
beforeSend: function() {
$("#sendingMessage").show();
},
success: function() {
alert("Success");
}
});
});
```
How can I pass the array, so that with the "replyMessage.php" page, I could take each ID from the Array, to do something like this:
```
<?php
foreach ($_POST['receiverID'] as $receiverID)
{
mysql_query //etc...
}
```
Any help is greatly appreciated! | First, you probably want to use [`implode`](http://www.php.net/implode), and not explode, to construct your `$toField` variable ;-)
```
$ids = array(24, 25, 26, 29);
$toField = implode(',', $ids);
var_dump($toField);
```
Which would give you
```
string '24,25,26,29' (length=11)
```
You then inject this in the form ; something like this would probably do :
```
<input type="hidden" value="<?php echo $toField; ?>">
```
*(Chech the HTML source of your form, to be sure ;-) )*
Then, on the PHP script that receives the data from the form when it's been submitted, you'd use [`explode`](http://php.net/explode) to extract the data as an array, from the string :
```
foreach (explode(',', $_POST['receiverID']) as $receiverID) {
var_dump($receiverID);
}
```
Which will get you :
```
string '24' (length=2)
string '25' (length=2)
string '26' (length=2)
string '29' (length=2)
```
And, now, you can use thoses ids... | ```
<form id='myform'>
<input type='hidden' name='to[]' value='1' />
<input type='hidden' name='to[]' value='2' />
.. etc ..
.. rest of you're form ..
</form>
```
jQuery change the data: .. part to:
```
data: $('#myform').serialize()
```
Then in you're PHP:
```
foreach ( $_POST [ 'to' ] as $num )
{
// do something with $num;
}
```
Something like this an option? | Pass PHP Array via jQuery Ajax | [
"",
"php",
"mysql",
"arrays",
""
] |
I have the following array (in php after executing print\_r on the array object):
```
Array (
[#weight] => 0
[#value] => Some value.
)
```
Assuming the array object is `$arr`, how do I print out "value". The following does NOT work:
```
print $arr->value;
print $val ['value'] ;
print $val [value] ;
```
So... how do you do it? Any insight into WHY would be greatly appreciated! Thanks! | ```
echo $arr['#value'];
```
The [`print_r()`](https://www.php.net/print_r) appears to be telling you that the array key is the string `#value`. | After quickly checking the docs, it looks like my comment was correct.
Try this code:
```
print $arr['#value'];
```
The reason is that the key to the array is not `value`, but `#value`. | How do I access a string-indexed element of a PHP array? | [
"",
"php",
"arrays",
"reference",
""
] |
I'm doing a website migration that involves extracting firstname and lastname from fullname. Given these were created by the end user, all kinds of permutations exist (although English and generally not too strange). Mostly I can take the first word as firstname and the last word as the lastname but have some exceptions from the occasional prefix and suffix. In going through the data and trying to get my head around all the likely exceptions I realized that this is a common problem that has been at least partially solved many times before.
Before reinventing the wheel, does anyone have any regular expressions that have worked for them or useful code? Performance is not a consideration as this is a one-time utility.
Typical values to be handled:
> Jason Briggs,
> J.D. Smith,
> John Y Citizen,
> J Scott Myers,
> Bill Jackobson III,
> Mr. John Mills
---
Update: while a common problem, the typical solution seems to involve handling the majority of cases and manually cleaning the rest.
(Given the frequency this issue must be experienced I was originally expecting to find a utility library out there but was not able to find one myself with Google) | My recommendation would be the following:
1. Split the names on the spaces.
2. Check the length of the returned array. If 2, easy split. If more, next.
3. Compare the 1st value for prefixes (i.e. Mr. Mrs. Ms. Dr.)...if so, remove it else move to next.
4. Compare the 1st value for length. If it's just 1 character, combine first 2 items in the array.
It's still not fool proof; however, it should address at least 80 per cent of your cases.
Hope this helps. | The fastest thing to do is a hybrid algorithm-human approach. You don't want to spend the time putting together a system that works 99.99% of the time because the last 5-10% of optimization will kill you. Also, you don't want to just dump all of the work on a person because most of the cases (I'm guessing) are fairly straightforward.
So, rapidly build something like what JamesEggers suggested, but catch all of the cases that appear unusual or do not fit your predefined conversions. Then, simply go through those cases manually (It shouldn't be too many).
You could go through those cases by yourself or outsource them to other users by setting up HITs in Mechanical Turk:
<http://aws.amazon.com/mturk/>
(Assuming 500 cases at $0.05 (high reward) your total cost should be $25 at most) | Separate firstname and lastname from fullname string in C# | [
"",
"c#",
"regex",
"string",
""
] |
I'm storing my Android project in a Subversion repository. After recently shuffling a bunch of stuff around I started getting tons of errors like:
```
syntax error entries /project_name/src/.svn line 1 Android AIDL Problem
syntax error don't know what to do with "" entries /project_name/src/.svn line 28 Android AIDL Problem
```
etc.
It seems as if Eclipse is trying to build the files in the .svn directories now. This setup used to work fine, how can I fix this? | It is worked for me:
* Delete your project from eclipse (not from disk).
* "File"->"New.."->"Project"->"Android Project"
* in "New Adroid Project"-Dialog selected "create project from existing source" (find your project on HDD)->"Finish"
my .classpath-file
```
<?xml version="1.0" encoding="UTF-8"?><classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="src" path="gen"/>
<classpathentry kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"/>
<classpathentry kind="output" path="bin"/></classpath>
``` | Although you can solve this problem by installing a plugin such as [Subversive](http://www.eclipse.org/subversive/documentation/gettingStarted/aboutSubversive/install.php), which has already been mentioned, you can also solve this problem without the plugin.
You can tell eclipse to ignore files stored in the `.svn` directories inside your build path. To do that, open up the project properties by right-clicking on the project and then select the `Java Build Path` option on the left. Look for the `Source` tab. There you'll see all your source folders (if you haven't changed anything this would be `gen` and `src` for Android SDK 1.5r3). Double click the `Excluded` item in the tree and add two exclusion patterns for each directory:
```
.svn/**
**/.svn/**
```
You should set the `svn:ignore` keyword of your project directory to ignore the directories, which contain automatically generated files, as they can be generated at any time and do only take up space in your repository. For a current Android SDK 1.5r3 project this would be the `bin` and the `gen` directory. If you ignore the `gen` folder this also means, that you don't need to set the exclusion pattern for this directory, as Subversion doesn't create a `.svn` directory inside ignored items.
**Edit:** As mentioned by *Henrik*, it is wise to clean the project after such a change. | Eclipse is trying to build the files in my .svn directories... how can I tell it to stop? | [
"",
"java",
"android",
"eclipse",
"svn",
""
] |
Is there any way to call a function periodically in JavaScript? | > The `setInterval()` method, repeatedly calls a function or executes a code snippet, with a fixed time delay between each call. It returns an interval ID which uniquely identifies the interval, so you can remove it later by calling clearInterval().
```
var intervalId = setInterval(function() {
alert("Interval reached every 5s")
}, 5000);
// You can clear a periodic function by uncommenting:
// clearInterval(intervalId);
```
See more @ [setInterval() @ MDN Web Docs](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval) | Please note that setInterval() is often not the best solution for periodic execution - It *really* depends on what javascript you're actually calling periodically.
*eg. If you use setInterval() with a period of 1000ms and in the periodic function you make an ajax call that occasionally takes 2 seconds to return you will be making another ajax call before the first response gets back. This is usually undesirable.*
Many libraries have periodic methods that protect against the pitfalls of using setInterval naively such as the Prototype example given by Nelson.
To achieve more robust periodic execution with a function that has a jQuery ajax call in it, consider something like this:
```
function myPeriodicMethod() {
$.ajax({
url: ...,
success: function(data) {
...
},
complete: function() {
// schedule the next request *only* when the current one is complete:
setTimeout(myPeriodicMethod, 1000);
}
});
}
// schedule the first invocation:
setTimeout(myPeriodicMethod, 1000);
```
Another approach is to use setTimeout but track elapsed time in a variable and then set the timeout delay on each invocation dynamically to execute a function as close to the desired interval as possible but never faster than you can get responses back. | Is there any way to call a function periodically in JavaScript? | [
"",
"javascript",
"dom-events",
""
] |
I'm working on a commercial project that requires a couple of files to be bundled (packed) into an archive and then compressed. Right now we have zlib in our utility library, but it doesn't look like zlib has the functionality to compress multiple files into one archive. Does anyone know of free libraries I'd be able to use for this? | Perhaps [libtar](http://www.feep.net/libtar/)? Also under a BSD license. | 7Zip has a [full SDK](http://www.7-zip.org/sdk.html) for several languages including C and C++. The compression is extremely good, albeit not very fast. The code is licensed under the LGPL. | C/C++ Packing and Compression | [
"",
"c++",
"c",
"compression",
"archive",
"zlib",
""
] |
I'm trying to implement a tree like structure using a Materialized Path model described here: <http://www.dbazine.com/oracle/or-articles/tropashko4>.
Is it possible to enforce referential integrity on the [path] field? I don't see how SQL could do it, do I have to do it manually in the DAL? | Yes, you have to enforce data integrity yourself in the DAL when you use either Materialized Path or Nested Sets solutions for hierarchical data.
Adjacency List supports referential integrity, and this is true also for a design I call "[Closure Table](https://stackoverflow.com/questions/192220/what-is-the-most-efficient-elegant-way-to-parse-a-flat-table-into-a-tree/192462#192462)" (Tropashko calls this design "transitive closure relation"). | "Materialized path" as presented by Vadim Tropashko in that article, introduces the notion of order into a relation ("Jones is the second member".).
"Materialized path" is nothing but "some form of materialized view" on the transitive closure, and therefore suffers all and exactly the same problems as any other "materialized view", except that matters are algorithmically worse precisely because of the involvement of a closure.
SQL is almost completely powerless when constraints-on-a-closure are in play. (Meaning : yes, SQL requires you to do everything yourself.) It's one of those areas where the RM shows the maximum of its almost unlimited power, but SQL fails abysmally, and where it is such a shame that the majority of people mistake SQL for being relational.
(@Bill Karwin : I'd like to be able to give you +1 for your remark on the relation between the depth of the trees and the result on performance. There are no known algorithms to compute closures that perform well in the case of trees with "crazy" depths. It's an algorithmic problem, not an SQL nor a relational one.)
EDIT
Yes, RM = Relational Model | Enforce Referential Integrity on Materialized Path? | [
"",
"sql",
"database",
"tree",
"hierarchical-data",
"referential-integrity",
""
] |
Can anyone explain to me why **xml1.Element("title")** correctly equals "`<title>Customers Main333</title>`" but **xml2.Element("title")** surprisingly equals **null**, i.e. why do I have to get the XML document as an *element* instead of a *document* in order to pull elements out of it?
```
var xml1 = XElement.Load(@"C:\\test\\smartForm-customersMain.xml");
var xml2 = XDocument.Load(@"C:\\test\\smartForm-customersMain.xml");
string title1 = xml1.Element("title").Value;
string title2 = xml2.Element("title").Value;
```
**XML:**
```
<?xml version="1.0" encoding="utf-8" ?>
<smartForm idCode="customersMain">
<title>Customers Main333</title>
<description>Generic customer form.</description>
<area idCode="generalData" title="General Data">
<column>
<group>
<field idCode="anrede">
<label>Anrede</label>
</field>
<field idCode="firstName">
<label>First Name</label>
</field>
<field idCode="lastName">
<label>Last Name</label>
</field>
</group>
</column>
</area>
<area idCode="address" title="Address">
<column>
<group>
<field idCode="street">
<label>Street</label>
</field>
<field idCode="location">
<label>Location</label>
</field>
<field idCode="zipCode">
<label>Zip Code</label>
</field>
</group>
</column>
</area>
</smartForm>
``` | The XDocument **represents the whole document, not the root node**.
Use `Root` to get the root element.
```
var title = xml2.Root.Element("title").Value;
```
should work. | This is because [`XDocument`](http://msdn.microsoft.com/en-us/library/system.xml.linq.xdocument.aspx) has an outermost layer that requires you to drill past to get to the elements. An [`XElement`](http://msdn.microsoft.com/en-us/library/system.xml.linq.xelement.aspx) targets the actual element itself. | Why does getting Elements from an XDocument result in null? | [
"",
"c#",
"linq",
"linq-to-xml",
""
] |
I have this code:
```
using ( var site = new SPSite( myUrl ) ) {
using ( var web = site.AllWebs[0] ) {
// read-only operations
}
}
```
The "myUrl" is top domain url with WSS 3.0. The authentication is set to Windows.
If I run this code from command-line under "external\_app\_user" account, all is fine. But if I run this code from webservice (outside of WSS webapplication), then result is http response "401 UNAUTHORIZED" instead of SOAP response. It's odd, because this code is in "try-catch" block, and if is any excception thrown I returned own error message in SOAP response.
The code is running on the same machine as WSS.
If I run the webservice from webbroser on the machine where web service is running, the classic windows login form is shown. If I run the webservice from webbrowser on another computer, I get only "401 UNAUTHORIZED" http response.
The web service is running under correct account. This account has access to the WSS (tested via sharepoint website). If i try get "System.Security.Principal.WindowsIdentity.GetCurrent().Name" the correct username is returned.
In web.config is set "<identity impersonate="true" userName="\_my\_username\_" password="\_my\_password\_" />.
Anyone has idea what is wrong? | I found the solution: <http://solutionizing.net/2009/01/06/elegant-spsite-elevation/> | The reason why you cannot catch the 401 is because SharePoint has custom handling for this exception, see this thread: [Cannot catch the SharePoint Access denied error](https://stackoverflow.com/questions/724679/cannot-catch-the-sharepoint-access-denied-error) (including a suggestion how to turn it off). | SPSite in web service throws 401 error | [
"",
"c#",
".net",
"asp.net",
"sharepoint",
"wss-3.0",
""
] |
Using JPA, and Hibernate as the provideer, I have a class defined like:
```
@Entity
@Table(name="partyrole")
public class PartyRole extends BaseDateRangeModel {
private static final long serialVersionUID = 1L;
private Party roleFor;
public void setRoleFor(Party roleFor) {
this.roleFor = roleFor;
}
@ManyToOne
public Party getRoleFor() {
return roleFor;
}
}
```
And I get the error in title of the question. I've tried adding `public void setType(Object type)` but that doesn't work either. The persistence.xml file is normal.
There are two classes that reference this one, but neither of them attempts to invoke `setType` either. I'd apprecaite any help!!!!
This happens at deployment time. The stack trace is at the bottom.
The Parent Class:
```
package com.nsfw.bmp.common.jpa;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.MappedSuperclass;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;
import org.hibernate.validator.AssertTrue;
import org.hibernate.validator.NotNull;
/**
* Several models are date range sensitive, this base class provides that basic
* functionality.
*
* @author jim
*
*/
@MappedSuperclass
public abstract class BaseDateRangeModel extends BasePersistentModel {
private static final long serialVersionUID = 1L;
private Date from;
private Date thru;
/**
* Determines if a model is active. A model is active if now is after or
* equal to from , and thru is either null, or after now, or equal to now.
*/
@Transient
public boolean isActive() {
Date now = new Date();
boolean afterFrom = from.before(now) || from.equals(now);
boolean beforeThru = thru == null || thru.after(now)
|| thru.equals(now);
return afterFrom && beforeThru;
}
@AssertTrue(message = "Dates are not valid the thru date must be empty, or after the fromdate.")
public boolean areDatesValid() {
if (thru == null) {
return true;
} else {
return thru.after(from);
}
}
@Temporal(TemporalType.TIMESTAMP)
@NotNull
@Column(name = "fromDate")
public Date getFrom() {
return from;
}
public void setFrom(Date from) {
this.from = from;
}
@Temporal(TemporalType.TIMESTAMP)
public Date getThru() {
return thru;
}
public void setThru(Date thru) {
this.thru = thru;
}
```
}
Its parent:
```
package com.nsfw.bmp.common.jpa;
import java.io.Serializable;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import javax.persistence.Version;
@MappedSuperclass
public abstract class BasePersistentModel implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
protected Long id;
protected Long version = 0l;
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
BasePersistentModel other = (BasePersistentModel) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (version == null) {
if (other.version != null)
return false;
} else if (!version.equals(other.version))
return false;
return true;
}
@Id
@GeneratedValue
public Long getId() {
return id;
}
@Version
public Long getVersion() {
return version;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((version == null) ? 0 : version.hashCode());
return result;
}
public void setId(Long id) {
this.id = id;
}
public void setVersion(Long version) {
this.version = version;
}
```
}
The Party class is fairly large, with a lot of mappings. This is the one asked for:
```
/**
* @return the actingAs
*/
@OneToMany(mappedBy="roleFor", targetEntity=com.nsfw.bmp.party.entity.association.PartyRole.class)
@OrderBy("from")
public List<PartyRole> getActingAs() {
return actingAs;
}
```
Here's the stack trace:
```
Caused by: org.hibernate.PropertyNotFoundException: Could not find a setter for property type in class com.nsfw.bmp.party.entity.association.PartyRole
at org.hibernate.property.BasicPropertyAccessor.createSetter(BasicPropertyAccessor.java:240)
at org.hibernate.property.BasicPropertyAccessor.getSetter(BasicPropertyAccessor.java:233)
at org.hibernate.mapping.Property.getSetter(Property.java:299)
at org.hibernate.tuple.entity.PojoEntityTuplizer.buildPropertySetter(PojoEntityTuplizer.java:272)
at org.hibernate.tuple.entity.AbstractEntityTuplizer.<init>(AbstractEntityTuplizer.java:149)
at org.hibernate.tuple.entity.PojoEntityTuplizer.<init>(PojoEntityTuplizer.java:76)
at org.hibernate.tuple.entity.EntityEntityModeToTuplizerMapping.<init>(EntityEntityModeToTuplizerMapping.java:80)
at org.hibernate.tuple.entity.EntityMetamodel.<init>(EntityMetamodel.java:325)
at org.hibernate.persister.entity.AbstractEntityPersister.<init>(AbstractEntityPersister.java:457)
at org.hibernate.persister.entity.SingleTableEntityPersister.<init>(SingleTableEntityPersister.java:131)
at org.hibernate.persister.PersisterFactory.createClassPersister(PersisterFactory.java:84)
at org.hibernate.impl.SessionFactoryImpl.<init>(SessionFactoryImpl.java:261)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1327)
at org.hibernate.cfg.AnnotationConfiguration.buildSessionFactory(AnnotationConfiguration.java:867)
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:669)
``` | Can you post your party class? I have a suspicion that this has to do with your manytoone mapping. Is there a type column in the partyRole table? | You problem might be linked to the BaseDateRangeModel class, because PartyRole extends it.
can you show us that class? | In class without a property called "type" I get org.hibernate.PropertyNotFoundException: Could not find a setter for property type in class | [
"",
"java",
"hibernate",
"jpa",
""
] |
How secure is this MySQL statement built in a PHP? Would it be vulnerable to an SQL injection?
```
$sql = sprintf("INSERT IGNORE INTO my_table VALUES(%d, %d, 1, NOW())",
mysql_escape_string($_SESSION['client']['id']),
mysql_escape_string($_POST['id']));
``` | Yes because %d only results in a number there is no need to escape the string. Using single quotes would provide a speed improvement too. So a safe and fast way is:
```
$sql = sprintf('INSERT IGNORE INTO my_table VALUES(%d, %d, 1, NOW())', $_SESSION['client']['id'], $_POST['id']);
``` | No it shouldn't be vulnerable.
Here is a detailed article on how to secure your **SQL** queries in **PHP**.
<http://www.tech-evangelist.com/2007/11/05/preventing-sql-injection-attack/> | How Secure is this MySQL statement in a PHP script? | [
"",
"php",
"mysql",
"security",
"sql-injection",
""
] |
Suppose we have following function in PHP:
```
public function testSomething()
{
$name = perform_sql_query("SELECT name FROM table WHERE id = $entity_id;");
assert($name == "some_name");
}
```
The query is syntactically correct, but since $entity\_id is undefined - the query will always search for 'id = 0', which is semantically incorrect.
I would like such functions to fail automatically, when they try to use an undefined variable. Is there such a mechanism in PHP? Or maybe there is some tool, that can be used to analyze PHP source code to find such cases?
Those undefined variables can occur anywhere in the project, so correct the decision will be to check function arguments in every function.
---
Setting an error handler helped. Now anytime an uninitialized variable is used, an exception is thrown. | One issue to consider is that for a live site, you may not want users to see errors and warnings. Some web-hosts provide an *error.log* file which logs PHP errors. Here's a custom error handler for live sites:
```
function log_error($no, $msg, $file, $line)
{
$errorMessage = "Error no $no: $msg in $file at line number $line";
file_put_contents("errors_paypal.txt",$errorMessage."\n\n",FILE_APPEND);
}
set_error_handler('log_error');
```
The great thing about this is that you can format it and dump various information you want. | PHP has several severity levels in script errors. You can define what the interpreter should consider an error: Either use the function [`error_reporting()`](http://php.net/manual/en/function.error-reporting.php) or set the [`php.ini`-directive with the same name](http://php.net/manual/en/errorfunc.configuration.php#ini.error-reporting) for that purpose.
Here is an example for configuring PHP to report *anything* which might lead to errors (this can lead to quite a lot of messages, if you are setting it for the first time, but fixing these errors will give you a much more stable application):
```
# In your PHP script:
error_reporting(E_ALL | E_STRICT);
# Or in your php.ini file:
error_reporting = E_ALL | E_STRICT
``` | How to find undefined variables in a PHP script | [
"",
"php",
"unit-testing",
""
] |
The following code does not compile.
```
int a = 1, b = 2, c = 3;
int& arr[] = {a,b,c,8};
```
**What does the C++ standard say about this?**
I know I could declare a class that contains a reference, then create an array of that class, as shown below. But I really want to know why the code above doesn't compile.
```
struct cintref
{
cintref(const int & ref) : ref(ref) {}
operator const int &() { return ref; }
private:
const int & ref;
void operator=(const cintref &);
};
int main()
{
int a=1,b=2,c=3;
//typedef const int & cintref;
cintref arr[] = {a,b,c,8};
}
```
It is possible to use `struct cintref` instead of `const int &` to simulate an array of references. | Answering to your question about standard I can cite the **C++ Standard §8.3.2/4**:
> There shall be no references to references, **no arrays of references**, and no pointers to references.
That's because references are not objects and doesn't occupy the memory so doesn't have the address. You can think of them as the aliases to the objects. Declaring an array of nothing has not much sense. | References are not objects. They don't have storage of their own, they just reference existing objects. For this reason it doesn't make sense to have arrays of references.
If you want a light-weight *object* that references another object then you can use a pointer. You will only be able to use a `struct` with a reference member as objects in arrays if you provide explicit initialization for all the reference members for all `struct` instances. References cannot be default initalized.
**Edit:** As jia3ep notes, in the standard section on declarations there is an explicit prohibition on arrays of references. | Why are arrays of references illegal? | [
"",
"c++",
"arrays",
"reference",
""
] |
How do multisets work? If a set can't have a value mapped to a key, does it only hold keys?
Also, how do associative containers work? I mean vector and deque in the memory is located sequentially it means that deleting/removing (except beginning [deque] and end [vector, deque]) are slow if they are large.
And list is a set of pointers which are not sequentially located in the memory which causes longer search but faster delete/remove.
How are sets, maps, multisets and multimaps stored and how do they work? | These 4 containers are typically all implemented using "nodes". A node is an object that stores one element. In the [multi]set case, the element is just the value; in the [multi]map case each node stores one key and its associated value. A node also stores multiple pointers to other nodes. Unlike a list, the nodes in sets and maps form a tree. You'd typically arrange it such that branches on the "left" of a certain node have values less than that node, while branches on the "right" of a certain node have values higher than that node.
Operations like finding a map key/set value are now quite fast. Start at the root node of the tree. If that matches, you're done. If the root is larger, search in the left branch. If the root is smaller than the value you're looking for, follow the pointer to the right branch. Repeat until you find a value or an empty branch.
Inserting an element is done by creating a new node, finding the location in the tree where it should be placed, and then inserting the node there by adjusting the pointers around it. Finally, there is a "rebalancing" operation to prevent your tree from ending up all out of balance. Ideally each right and left branch is about the same size. Rebalancing works by shifting some nodes from the left to the right or vice versa. E.g. if you have values {1 2 3} and your root node would be 1, you'd have 2 and 3 on the left branch and an empty right branch:
```
1
\
2
\
3
```
This is rebalanced by picking 2 as the new root node:
```
2
/ \
1 3
```
The STL containers use a smarter, faster rebalancing technique but that level of detail should not matter. It's not even specified in the standard *which* better technique should be used so implementations can differ. | There can be any implementation, as long as they match the standard specifications for those containers.
AFAIK, the associative containers are implemented as binary trees (red-black). More details... depending on the implementation. | How sets, multisets, maps and multimaps work internally | [
"",
"c++",
"data-structures",
"stl",
"dictionary",
"set",
""
] |
Below is a cubic interpolation function:
```
public float Smooth(float start, float end, float amount)
{
// Clamp to 0-1;
amount = (amount > 1f) ? 1f : amount;
amount = (amount < 0f) ? 0f : amount;
// Cubicly adjust the amount value.
amount = (amount * amount) * (3f - (2f * amount));
return (start + ((end - start) * amount));
}
```
This function will cubically interpolate between the start and end value given an amount between 0.0f - 1.0f. If you were to plot this curve, you'd end up with something like this:
> Expired Imageshack image removed
The cubic function here is:
```
amount = (amount * amount) * (3f - (2f * amount));
```
How do I adjust this to produce two produce tangents in and out?
To produce curves like this: (Linear start to cubic end)
> Expired Imageshack image removed
As one function
and like this as another: (Cubic start to linear end)
> Expired Imageshack image removed
Anyone got any ideas? Thanks in advance. | What you want is a [Cubic Hermite Spline](http://en.wikipedia.org/wiki/Cubic_Hermite_spline):

where p0 is the start point, p1 is the end point, m0 is the start tangent, and m1 is the end tangent | you could have a linear interpolation and a cubic interpolation and interpolate between the two interpolation functions.
ie.
```
cubic(t) = cubic interpolation
linear(t) = linear interpolation
cubic_to_linear(t) = linear(t)*t + cubic(t)*(1-t)
linear_to_cubic(t) = cubic(t)*t + linear(t)*(1-t)
```
where t ranges from 0...1 | Cubic/Curve Smooth Interpolation in C# | [
"",
"c#",
"math",
"linear-interpolation",
"bicubic",
""
] |
Say I have an expression like this
```
short v = ( ( p[ i++ ] & 0xFF ) << 4 | ( p[ i ] & 0xF0000000 ) >> 28;
```
with `p` being a pointer to a dynamically allocated array of 32 bit integers.
When *exactly* will `i` be incremented? I noticed that the above code delivers a different value for `v` than the following code:
```
short v = ( p[ i++ ] & 0xFF) << 4;
v |= ( p[ i ] & 0xF0000000 ) >> 28;
```
My best guess for this behaviour is that `i` is not incremented before the right side of the above `|` is evaluated.
Any insight would be appreciated!
Thanks in advance,
\Bjoern | The problem is order of evaluation:
The C++ standard does not define the order of evaluation of sub expressions. This is done so that the compiler can be as aggressive as possible in optimizations.
Lets break it down:
```
a1 a2
v = ( ( p[ i++ ] & 0xFF ) << 4 | ( p[ i ] & 0xF0000000 ) >> 28;
-----
(1) a1 = p[i]
(2) i = i + 1 (i++) after (1)
(3) a2 = p[i]
(4) t3 = a1 & 0xFF after (1)
(5) t4 = a2 & 0xF0000000 after (3)
(6) t5 = t3 << 4 after (4)
(7) t6 = t4 >> 28 after (5)
(8) t7 = t5 | t6 after (6) and (7)
(9) v = t7 after (8)
```
Now the compiler is free to re-arrange thus sub expressions as long as the above 'after' clauses are not violated. So one quick easy optimization is move 3 up one slot and then do common expression removal (1) and (3) (now beside each other) are the same and thus we can eliminate (3)
But the compiler does not have to do the optimization (and is probably better than me at it and has other tricks up its sleeve). But you can see how the value of (a1) will always be what you expect, but the value of (a2) will depend on what order the compiler decides to do the other sub-expressions.
The only guarantees that you have that the compiler can not move sub-expressions past a sequence point. Your most common sequence point is ';' (the end of the statement). There are others, but I would avoid using this knowledge as most people don't know the compiler workings that well. If you write code that uses sequence point tricks then somebody may re-factor the code to make it look more readable and now your trick has just turned into undefined be-behavior.
```
short v = ( p[ i++ ] & 0xFF) << 4;
v |= ( p[ i ] & 0xF0000000 ) >> 28;
-----
(1) a1 = p[i]
(2) i = i + 1 (i++) after (1)
(4) t3 = a1 & 0xFF after (1)
(6) t5 = t3 << 4 after (4)
(A) v = t5 after (6)
------ Sequence Point
(3) a2 = p[i]
(5) t4 = a2 & 0xF0000000 after (3)
(7) t6 = t4 >> 28 after (5)
(8) t7 = v | t6 after (7)
(9) v = t7 after (8)
```
Here everything is well defined as the write to i is sued in place and not re-read in the same expression.
Simple rule. don't use ++ or -- operators inside a larger expression.
Your code looks just as readable like this:
```
++i; // prefer pre-increment (it makes no difference here, but is a useful habit)
v = ( ( p[ i ] & 0xFF ) << 4 | ( p[ i ] & 0xF0000000 ) >> 28;
```
See this article for detailed explanation of evaluation order:
[What are all the common undefined behaviours that a C++ programmer should know about?](https://stackoverflow.com/questions/367633/what-are-all-the-common-undefined-behaviour-that-c-programmer-should-know-about/367690#367690) | i is incremented sometime before the next sequence point. The only sequence point in the expression you have given is at the end of the statement - so "sometime before the end of the statement" is the answer in this case.
That's why you shouldn't both modify an lvalue and read its value without an intervening sequence point - the result is indeterminate.
The &&, ||, comma and ? operators introduce sequence points, as well as the end of an expression and a function call (the latter means that if you do f(i++, &i), the body of f() will see the updated value if it uses the pointer to examine i). | When exactly is the postfix increment operator evaluated in a complex expression? | [
"",
"c++",
"c",
"operators",
""
] |
My background is in web programming, mostly scripting with Perl. And I've recently been tasked with creating a desktop application. I'm wondering, where can one learn such concepts like making executables, what DLLs are for, how UIs are made, what threads are, etc.
I already have C# in Depth by Jon Skeet and C# in a Nutshell. I'm not worried about learning C# itself as much as I am learning about the workflows involved with using it on the desktop, things that are typically not done in web development.
Where should I look? | One starting point would be [WindowsClient.net](http://WindowsClient.net) (Microsoft). Lots of videos too. But maybe a little less suited for the absolute beginners. | I only recently began learning C# myself - so I have quite the array(... ;) ) of links:
[C-Sharp Corner](http://www.c-sharpcorner.com/)
[CSharp Friends](http://www.csharpfriends.com/)
[CSharp Help](http://www.csharphelp.com/)
[CSharp for absolute beginners - Very good](http://www.homeandlearn.co.uk/csharp/csharp.html)
[CSharp-online](http://en.csharp-online.net)
Hope these help. | Where can I learn to build desktop applications with C#? | [
"",
"c#",
"windows",
"multithreading",
"user-interface",
"desktop",
""
] |
Is there some way to do something like this in c++, it seems sizeof cant be used there for some reason?
```
#if sizeof(wchar_t) != 2
#error "wchar_t is expected to be a 16 bit type."
#endif
``` | I think things like [BOOST\_STATIC\_ASSERT](http://www.boost.org/doc/libs/1_39_0/doc/html/boost_staticassert.html) could help. | No, this can't be done because all macro expansion (#... things) is done in the pre-processor step which does not know anything about the types of the C++ code and even does not need to know anything about the language!
It just expands/checks the #... things and nothing else!
There are some other common errors, for example:
```
enum XY
{
MY_CONST = 7,
};
#if MY_CONST == 7
// This code will NEVER be compiled because the pre-processor does not know anything about your enum!
#endif //
```
You can only access and use things in #if that are defined via command line options to the compiler or via #define. | C++ Getting the size of a type in a macro conditional | [
"",
"c++",
"macros",
"sizeof",
""
] |
I started programming in C++. It was my first language, but I have not used it in many years.
What are the new developments in the C++ world? What are the BIG things - technologies, books, frameworks, libraries, etc?
**Over the last 7-8 years what are the biggest influences on C++ programming?**
Perhaps we could do one influence per post, and that way we can vote on them. | [Boost](http://www.boost.org/):
> free peer-reviewed portable C++ source libraries.
>
> We emphasize libraries that work well with the C++ Standard Library...
>
> We aim to establish "existing practice" and provide reference implementations so that Boost libraries are suitable for eventual standardization. Ten Boost libraries are included in the [C++ Standards Committee's](http://www.open-std.org/jtc1/sc22/wg21/) Library Technical Report ([TR1](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1745.pdf)) and in the new C++11 Standard. C++11 also includes several more Boost libraries in addition to those from TR1. More Boost libraries are proposed for standardization in C++17... | "[Modern C++](https://rads.stackoverflow.com/amzn/click/com/0201704315)", STL, template metaprogramming and Generic programming.
(And yes, they're one single answer, because they're pretty closely intertwined and together represent a complete paradigm shift in C++ development. While some of them are older than 8-9 years, it's pretty much in the last years that they've really gained traction and really left "C with classes" in the dust. | Over the last 7-8 years what are the biggest influences on C++ programming? | [
"",
"c++",
""
] |
In C# & .NET, can one create a `DataView` that includes only a *proper* subset of the `DataColumn`s of a given `DataTable`?
In terms of relational algebra, one assigns a `RowFilter` in order to perform a "selection" operation (σ). How would one perform a "projection" operation (π)? | You can't do that, but you can create a copy of the table with only the columns you want :
```
DataView view = new DataView(table);
DataTable table2 = view.ToTable(false, "FirstColumn", "SecondColumn", "ThirdColumn");
```
Optionally you can return rows that have distinct values for the selected columns :
```
DataView view = new DataView(table);
DataTable table2 = view.ToTable(true, "FirstColumn", "SecondColumn", "ThirdColumn");
``` | Well I can't see any reason for "wanting" to do that... Remember, a DataView is just a list of pointers to the rows in the original table, and there is obviously no way to remove columns from the the original table... at least not without affecting every other function utilizing that table... Just only use the columns you want... | Create ADO.NET DataView showing only selected Columns | [
"",
"c#",
".net",
"datatable",
"dataview",
"datacolumn",
""
] |
When i use DatePicker, jQuery's UI plugin, in an existing .aspx page I get errors that:
```
$("#datepicker").datepicker is not a function
```
However, when I copy and paste the same code that creates and uses the datePicker to an HTML file that's also in the same directory as the aspx page, it works flawlessly. This leads me to assume that there are some JS files in the aspx page that's preventing the datePicker or maybe jQuery's UI JS files to load properly.
Can anyone confirm my beliefs or provide any tips on finding the culprit that's interfering with jQuery's UI plugins? | I struggled with a similar problem for hours. It then turned out that jQuery was included twice, once by the program that I was adding a jQuery function to and once by our in-house debugger. | If there is another library that is using the $ variable, you can do this:
```
var $j = jQuery.noConflict();
$j("#datepicker").datepicker();
```
Also make sure your javascript includes are in the correct order so the jquery core library is defined before the jquery.ui. I've had that cause issues. | jQuery UI " $("#datepicker").datepicker is not a function" | [
"",
"asp.net",
"javascript",
"jquery",
"datepicker",
""
] |
I have a file that pulls some information from the database and creates some relatively simple dynamic HTML.
The file can then be used by DOMPDF to turn it into a PDF document. DOMDPF uses GET variables to achieve the basic implementation.
```
ob_start();
include_once("report.php?id=1249642977");
require_once("dompdf/dompdf_config.inc.php");
$dompdf = new DOMPDF();
$dompdf->load_html(ob_get_contents());
$dompdf->render();
$dompdf->stream("sample.pdf", array('Attachment'=>'0'));
ob_end_clean();
```
I thought I might be able to use something ilke that to achieve the aim but unsurprisingly it didn't work.
So how can I read the HTML that gets output to the browser if you were to load the file directly, into a string for use with the DOMPDF class? | Two problems.
First, you can't call a PHP page like that using include\_once - the query string will be ignored. You have to give the id to report.php some other way.
Second, you're correctly buffering the output. However, you're passing the current output buffer to DOMPDF, telling it to generate a PDF to the output buffer, and the discarding the output buffer. You probably want something like:
```
$dompdf = new DOMPDF();
$dompdf->load_html(ob_get_clean());
$dompdf->render();
$dompdf->stream("sample.pdf", array('Attachment'=>'0'));
```
That'll get the current output buffer, discard it, and disable output buffering. The $dompdf->stream should then work. | What about using a simple HTTP request to get the HTML file and than loading it in the $dompdf object:
```
<?php
//...
$dompdf->load_html(file_get_contents("http://yoursite.net/report.php?id=1249642977"));
//...
?>
```
I don't see why you need output buffering here.. | PHP - Read dynamically generated (and echoed) HTML into a string? | [
"",
"php",
"dompdf",
""
] |
If I have a hostname such as: <http://sample.example.com> and in Javascript I do `window.location.hostname`, would I get "example.com" or "sample.example.com"?
If not, how would I be able to get sample.example.com? | Yes, `window.location.hostname` will give you subdomains as well. If this isn't working, or isn't supported by some other browser, you could quite easily parse for it:
```
// window.location.href == "http://sample.somedomain.com/somedir/somepage.html"
var domain = /:\/\/([^\/]+)/.exec(window.location.href)[1];
``` | This does the trick for me:
```
var host = window.location.host
var subdomain = host.split('.')[0]
``` | How to get a subdomain using window.location? | [
"",
"javascript",
"subdomain",
"hostname",
""
] |
Assuming the following for...
**Output:**
*The file is opened...*
Data is 'streamed' to disk. The data in memory is in a large contiguous buffer. It is written to disk in its raw form directly from that buffer. The size of the buffer is configurable, but fixed for the duration of the stream. Buffers are written to the file, one after another. No seek operations are conducted.
*...the file is closed.*
**Input:**
A large file (sequentially written as above) is read from disk from beginning to end.
---
Are there generally accepted guidelines for achieving the fastest possible sequential file I/O in C++?
Some possible considerations:
* Guidelines for choosing the optimal buffer size
* Will a portable library like boost::asio be too abstracted to expose the intricacies of a specific platform, or can they be assumed to be optimal?
* Is asynchronous I/O always preferable to synchronous? What if the application is not otherwise CPU-bound?
I realize that this will have platform-specific considerations. I welcome general guidelines as well as those for particular platforms.
*(my most immediate interest in Win x64, but I am interested in comments on Solaris and Linux as well)* | > Are there generally accepted guidelines for achieving the fastest possible sequential file I/O in C++?
Rule 0: Measure. Use all available profiling tools and get to know them. It's almost a commandment in programming that if you didn't measure it you don't know how fast it is, and for I/O this is even more true. Make sure to test under *actual work conditions* if you possibly can. A process that has no competition for the I/O system can be over-optimized, fine-tuned for conditions that don't exist under real loads.
1. Use mapped memory instead of writing to files. This isn't always faster but it allows the opportunity to optimize the I/O in an operating system-specific but relatively portable way, by avoiding unnecessary copying, and taking advantage of the OS's knowledge of how the disk actually being used. ("Portable" if you use a wrapper, not an OS-specific API call).
2. Try and linearize your output as much as possible. Having to jump around memory to find the buffers to write can have noticeable effects under optimized conditions, because cache lines, paging and other memory subsystem issues will start to matter. If you have lots of buffers look into support for *scatter-gather I/O* which tries to do that linearizing for you.
Some possible considerations:
> * Guidelines for choosing the optimal buffer size
Page size for starters, but be ready to tune from there.
> * Will a portable library like boost::asio be too abstracted to expose the intricacies
> of a specific platform, or can they be assumed to be optimal?
Don't assume it's optimal. It depends on how thoroughly the library gets exercised on your platform, and how much effort the developers put into making it fast. Having said that a portable I/O library *can* be very fast, because fast abstractions exist on most systems, and it's usually possible to come up with a general API that covers a lot of the bases. Boost.Asio is, to the best of my limited knowledge, fairly fine tuned for the particular platform it is on: there's a whole family of OS and OS-variant specific APIs for fast async I/O (e.g. [epoll](http://www.kernel.org/doc/man-pages/online/pages/man4/epoll.4.html), [/dev/epoll](http://www.xmailserver.org/linux-patches/nio-improve.html), [kqueue](http://people.freebsd.org/~jlemon/kqueue_slides/index.html), [Windows overlapped I/O](http://msdn.microsoft.com/en-us/library/aa365683(VS.85).aspx)), and Asio wraps them all.
> * Is asynchronous I/O always preferable to synchronous? What if the application is not otherwise CPU-bound?
Asynchronous I/O isn't faster in a raw sense than synchronous I/O. What asynchronous I/O does is ensure that *your* code is not wasting time waiting for the I/O to complete. It is faster in a general way than the other method of not wasting that time, namely using threads, because it will call back into your code when I/O is ready and not before. There are no false starts or concerns with idle threads needing to be terminated. | A general advice is to turn off buffering and read/write in large chunks (but not too large, then you will waste too much time waiting for the whole I/O to complete where otherwise you could start munching away at the first megabyte already. It's trivial to find the sweet spot with this algorithm, there's only one knob to turn: the chunk size).
Beyond that, for input `mmap()`ing the file shared and read-only is (if not the fastest, then) the most efficient way. Call `madvise()` if your platform has it, to tell the kernel how you will traverse the file, so it can do readahead and throw out the pages afterwards again quickly.
For output, if you already have a buffer, consider underpinning it with a file (also with `mmap()`), so you don't have to copy the data in userspace.
If `mmap()` is not to your liking, then there's `fadvise()`, and, for the really tough ones, async file I/O.
(All of the above is POSIX, Windows names may be different). | What is the Fastest Method for High Performance Sequential File I/O in C++? | [
"",
"c++",
"performance",
"file-io",
""
] |
Here is my problem, i have a class with a ave method, i want to pass a Mysql DB link to it, so i create a new object from the class, and call the saveProperty method, and in my main file i created a MySQL connection and saved the link in a var called $db so when i call the method it's link this: saveProperty($db).
but insted of saving the data i get an error:
Warning: mysql\_select\_db(): supplied argument is not a valid MySQL-Link resource in C:\wamp\www\aqaria\classes\property.php on line 75
Warning: mysql\_query(): supplied argument is not a valid MySQL-Link resource in C:\wamp\www\aqaria\classes\property.php on line 99
which means that i didn't pass the link right? but how?
here is some of my code:
```
<?php
class test
{
function saveProperty($db)
{
$sql = "<<query goes here>>"
mysql_query($sql,$db);
if(mysql_affected_rows()>0)
echo "<h3>Data was saved</h3>";
else
echo "<h3>Error saving data</h3>";
}
}
```
here is the calling code:
```
$db = mysql_connect('localhost','root','');
mysql_select_db("aqaria",$db);
$property = new Property();
$property->saveProperty($db);
```
although it would work if i added the gloabl keyword to method of the class i was wondering if i can PASS the link to the database connection? | Have you tried with a reference?
Also you might want to use $db in `mysql_affected_rows()`
```
function saveProperty(&$db)
{
$sql = "<<query goes here>>"
mysql_query($sql,$db);
if(mysql_affected_rows($db)>0)
echo "<h3>Data was saved</h3>";
else
echo "<h3>Error saving data</h3>";
}
``` | It is without doubt possible to pass db\_links around in methods.
> Warning: mysql\_select\_db(): supplied
> argument is not a valid MySQL-Link
> resource in
> C:\wamp\www\aqaria\classes\property.php
> on line 75
Check you database credentials and output with mysql\_error() | pass MySQL link to a class method | [
"",
"php",
"mysql",
"database",
"oop",
"class",
""
] |
From Python docs:
> `sys.excepthook(type, value, traceback)`
>
> This function prints out a given traceback and exception to `sys.stderr`.
>
> When an exception is raised and uncaught, the interpreter calls `sys.excepthook` with three arguments, the exception class, exception instance, and a traceback object. In an interactive session this happens just before control is returned to the prompt; in a Python program this happens just before the program exits. The handling of such top-level exceptions can be customized by assigning another three-argument function to `sys.excepthook`.
<http://docs.python.org/library/sys.html>
How do I modify this globally so the default action is to always invoke `pdb`? Is there a configuration file I can change? I don't want to wrap my code to do this. | Here's what you need
<http://ynniv.com/blog/2007/11/debugging-python.html>
Three ways, the first is simple but crude ([Thomas Heller](http://mail.python.org/pipermail/python-list/2001-April/713230.html)) - add the following to site-packages/sitecustomize.py:
```
import pdb, sys, traceback
def info(type, value, tb):
traceback.print_exception(type, value, tb)
pdb.pm()
sys.excepthook = info
```
The second is more sophisticated, and checks for interactive mode (weirdly skipping the debugging in interactive mode), from the [cookbook](http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65287):
```
# code snippet, to be included in 'sitecustomize.py'
import sys
def info(type, value, tb):
if hasattr(sys, 'ps1') or not sys.stderr.isatty():
# we are in interactive mode or we don't have a tty-like
# device, so we call the default hook
sys.__excepthook__(type, value, tb)
else:
import traceback, pdb
# we are NOT in interactive mode, print the exception...
traceback.print_exception(type, value, tb)
print
# ...then start the debugger in post-mortem mode.
pdb.pm()
sys.excepthook = info
```
And the third (which always start the debugger unless stdin or stderr are redirected) by [ynniv](http://ynniv.com/blog/2007/11/debugging-python.html)
```
# code snippet, to be included in 'sitecustomize.py'
import sys
def info(type, value, tb):
if (#hasattr(sys, "ps1") or
not sys.stderr.isatty() or
not sys.stdin.isatty()):
# stdin or stderr is redirected, just do the normal thing
original_hook(type, value, tb)
else:
# a terminal is attached and stderr is not redirected, debug
import traceback, pdb
traceback.print_exception(type, value, tb)
print
pdb.pm()
#traceback.print_stack()
original_hook = sys.excepthook
if sys.excepthook == sys.__excepthook__:
# if someone already patched excepthook, let them win
sys.excepthook = info
``` | Another option is to use ipython, which I consider a must-have tool for any python developer anyway. Instead of running your script from the shell, run it from ipython with %run. When an exception occurs, you can type %debug to debug it. (There's also an option to automatically debug any exception that occurs, but I forget what it is.) | How do I set sys.excepthook to invoke pdb globally in python? | [
"",
"python",
"debugging",
"configuration",
"pdb",
""
] |
I'm writing a collaborative project designed to allow code contributions from users. Users will be able to extend a class, add functionality etc, and submit the code back to the server for regular execution.
Is there a safe way to execute users' PHP code? A foolproof sanitizing method? What about infinite loops? Or should I offer a different scripting language? | * JailRoot for the DocumentRoot
* SafeMode ON to allow access to files
only on specific directories
* Use a per USER MPM to limit system
resources to the apache process
* Set safe php.ini settings for memmory
limit and max\_execution\_time
And as Saggi Malachi noted, this is very experimental, you have to monitor the actions on the server and have fallback szenarios, eg. cronjobs watching load average, if loadaverage is above threshold stop apache and sendmail.
Other good idea is to compile your own php und deny access to php functions which could be "exploited" by your users. | Securing against users accessing or changing files can be done with [safemode](http://www.php.net/features.safe-mode).
Securing against infinite loops require setting some amount of time the php interpreter gets to generate the site. [set\_time\_limit](http://php.net/set_time_limit)
You also need to stop users communicating with outside servers to avoid it being used as a spam sender. [allow\_url\_fopen](http://php.net/manual/en/filesystem.configuration.php#ini.allow-url-fopen)
There are probably a lot of other more serious issues. This is no easy task. | Safely executing users' PHP scripts on the server | [
"",
"php",
"linux",
""
] |
I'm having some troubles with mod\_rewrite.
On my index page (index.php) I show a blog and a single blog post page looks like this:
<http://www.mydomain.com/blog/post-title>
mod\_rewrite for this is:
```
RewriteRule ^blog/([A-Za-z0-9-]+)$ index.php?postslug=$1 [L]
```
This works like a charm.
But I also have another page called artists.php and the url should look like this:
<http://www.mydomain.com/artists/artist-name>
mod\_rewrite for this is:
```
RewriteRule ^artists/([A-Za-z0-9-]+)$ artists.php?artistslug=$1 [L]
```
This gives me a 500 internal server error and I have no clue why this happens...
Both index.php and artists.php are in the root of my website
.htaccess file:
```
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php
RewriteRule ^blog/([a-z0-9\-]+)$ index.php?postslug=$1 [L]
RewriteRule ^artists/([a-z0-9\-]+)$ artists.php?artistslug=$1 [L]
``` | Try this rule instead of your one with the two `RewriteCond`:
```
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI}.php -f
RewriteRule ^(.*)$ $1.php [L]
```
I’ve tested it myself and `%{REQUEST_FILENAME}` seems to contain the wrong value but `-f` is evaluated to *true* anyhow. | Turn on:
```
RewriteLog /path/to/file.log
RewriteLogLevel 4
``` | mod_rewrite for clean urls gives 500 internal server error | [
"",
"php",
"apache",
".htaccess",
"mod-rewrite",
""
] |
I just played around a little bit with python and threads, and realized even in a multithreaded script, DNS requests are blocking. Consider the following script:
from threading import Thread
import socket
```
class Connection(Thread):
def __init__(self, name, url):
Thread.__init__(self)
self._url = url
self._name = name
def run(self):
print "Connecting...", self._name
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setblocking(0)
s.connect((self._url, 80))
except socket.gaierror:
pass #not interested in it
print "finished", self._name
if __name__ == '__main__':
conns = []
# all invalid addresses to see how they fail / check times
conns.append(Connection("conn1", "www.2eg11erdhrtj.com"))
conns.append(Connection("conn2", "www.e2ger2dh2rtj.com"))
conns.append(Connection("conn3", "www.eg2de3rh1rtj.com"))
conns.append(Connection("conn4", "www.ege2rh4rd1tj.com"))
conns.append(Connection("conn5", "www.ege52drhrtj1.com"))
for conn in conns:
conn.start()
```
I dont know exactly how long the timeout is, but when running this the following happens:
1. All Threads start and I get my printouts
2. Every xx seconds, one thread displays finished, instead of all at once
3. The Threads finish sequentially, not all at once (timeout = same for all!)
So my only guess is that this has to do with the GIL? Obviously the threads do not perform their task concurrently, only one connection is attempted at a time.
Does anyone know a way around this?
(**asyncore** doesnt help, and I'd prefer not to use **twisted** for now)
Isn't it possible to get this simple little thing done with python?
Greetings, Tom
# edit:
I am on MacOSX, I just let my friend run this on linux, and he actually does get the results I wished to get. His socket.connects()'s return immediately, even in a non Threaded environment. And even when he sets the sockets to blocking, and timeout to 10 seconds, all his Threads finish at the same time.
Can anyone explain this? | On some systems, getaddrinfo is not thread-safe. Python believes that some such systems are FreeBSD, OpenBSD, NetBSD, OSX, and VMS. On those systems, Python maintains a lock specifically for the netdb (i.e. getaddrinfo and friends).
So if you can't switch operating systems, you'll have to use a different (thread-safe) resolver library, such as twisted's. | if it's suitable you could use the `multiprocessing` module to enable process-based parallelism
```
import multiprocessing, socket
NUM_PROCESSES = 5
def get_url(url):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setblocking(0)
s.connect((url, 80))
except socket.gaierror:
pass #not interested in it
return 'finished ' + url
def main(url_list):
pool = multiprocessing.Pool( NUM_PROCESSES )
for output in pool.imap_unordered(get_url, url_list):
print output
if __name__=="__main__":
main("""
www.2eg11erdhrtj.com
www.e2ger2dh2rtj.com
www.eg2de3rh1rtj.com
www.ege2rh4rd1tj.com
www.ege52drhrtj1.com
""".split())
``` | Python Interpreter blocks Multithreaded DNS requests? | [
"",
"python",
"multithreading",
"network-programming",
""
] |
How to achieve generic Save and Update operation using generics and reflection in C#?
I have achieved data retrieve using some reference from [here...](http://www.codeproject.com/KB/database/BusinessObjectHelper.aspx)
I don't have much time to learn technologies like NHibernate/LINQ/Entity Frameowrk, etc. for this moment. I need a quick solution for this problem for some reason. | I think you'd be better of using an ORM -- LINQ to SQL, LINQ to Entities, LINQ to nHibernate -- rather than reinventing all of this. Essentially, what you are asking advice on doing has already been done for you in these frameworks/technologies. My advice is to spend some time learning about the tools that already exist and apply your creative energy to adding value to your application, using the already developed tools for the mundane work. Unless, of course, you're looking to implement an ORM because the existing ones are inadequate for your needs. I suspect this isn't the case, otherwise you'd already know how to use reflection to do what you're asking. | Use a DBContext helper of GenericType
```
public class ContextHelper<T> : IContextHelper<T>
{
//Instantiate your own EntityFrameWork DB context here,
//Ive called the my EntityFramework Namespace 'EF' and the context is named 'Reporting'
private EF.DataContext DbContext = new EF.DataContext();
public bool Insert<T>(T row) where T : class
{
try
{
DbContext.Set<T>().Add(row);
DbContext.SaveChanges();
return true;
}
catch(Exception ex)
{
return false;
}
}
public bool Update<T>(T row) where T : class
{
try
{
DbContext.Set<T>().AddOrUpdate(row);
DbContext.SaveChanges();
return true;
}
catch (Exception ex)
{
return false;
}
}
public bool Delete<T>(T row) where T : class
{
return Update(row); //Pass an entity with IsActive = false and call update method
}
public bool AddRows<T>(T[] rows) where T : class
{
try
{
DbContext.Set<T>().AddOrUpdate(rows);
return true;
}
catch (Exception ex)
{
return false;
}
}
```
And then instantiate and call the class here
```
public class MainLogicClassExample //Catty out logi operations on objects and update DataBase
{
public void NewEmailRecipient(EF.EmailRecipient recipient)
{
// logic operation here
EntityToDB(recipient);
}
public void NewReportRecipient(EF.ReportRecipient recipient)
{
// logic operation here
EntityToDB(recipient);
}
public void UpdateEmailRecipient(EF.EmailRecipient recipient)
{
// logic operation here
UpdateEntity(recipient);
}
public void UpdateReportRecipient(EF.ReportRecipient recipient)
{
// logic operation here
UpdateEntity(recipient);
}
// call generic methods to update DB
private void EntityToDB<T>(T entity) where T : class
{
var context = new ContextHelper<T>();
context.Insert(entity);
}
private void UpdateEntity<T>(T entity) where T : class
{
var context = new ContextHelper<T>();
context.Update(entity);
}
}
```
I've added a DemoProject to gitHub here:
<https://github.com/andyf1ynn/EntityFramwork-Generic-Type-DAL> | C# - Generic CRUD operation | [
"",
"c#",
"generics",
"reflection",
"ado.net",
""
] |
In my project we have developed a project using JSF 1.2 and JBOSS 5. As part of new requirement we have to migrate it to Websphere 7. But we are facing a issue which I suspect is related to the java runtime being internally used by WAS. Its not able to autobox int/Integers , cast Strings to long implicitly. After providing the necessary checks for it finally I am stuck at the following validation exception:
/Star/employeeFormP1.jsp(226,4) '#{StarEmployeeApplicationFormBean.medicalHMO}' Can't set property 'medicalHMO' on class 'com.idea.app.bean.StarEmployeeApplicationFormBean' to value 'true'.
The following the relevant code:
```
<h:selectBooleanCheckbox id="checkbox1"
value="#{StarEmployeeApplicationFormBean.medicalHMO}"
title="click it to select or deselect"
immediate="true"
valueChangeListener="#{StarEmployeeApplicationFormBean.listHMOMedProducts}"
onchange="return submit()" />
```
Could anyone please help me on this validation exception? | JBoss 5 and WebSphere 7 are JEE5 servers, so the JSF 1.2 impl will just be using the EL implementation provided by the platform. The rules for type coercion are detailed in [the JSP 2.1 spec](http://jcp.org/en/jsr/detail?id=245):
> For example, if coercing an int to a String, "box" the int into an Integer and apply the rule for coercing an Integer to a String. Or if coercing a String to a double, apply the rule for coercing a String to a Double, then "unbox" the resulting Double, making sure the resulting Double isn’t actually null.
Based on the rules detailed in the spec, it sounds like a bug in the WebSphere implementation. If you can't find an existing [APAR/Fix Pack](http://www-01.ibm.com/software/webservers/appserv/was/support/) that addresses the issue, I'd report it. | I'm not sure exactly what the problem is. I have just a few comments:
1. "...it's not able to autobox int/Integers..." - Google tells me that WAS 7 uses JDK 5, [which does autoboxing](http://mindprod.com/jgloss/autoboxing.html). Perhaps you should check to make sure your app server is using the right version of JVM.
2. "...cast Strings to long implicitly..." - I don't believe any JVM does this.
> After providing the necessary checks
> for it finally I am stuck at the
> following validation exception:
>
> /Star/employeeFormP1.jsp(226,4)
> '#{StarEmployeeApplicationFormBean.medicalHMO}'
> Can't set property 'medicalHMO' on
> class
> 'com.idea.app.bean.StarEmployeeApplicationFormBean'
> to value 'true'.
It's hard to tell without posting some code. | Websphere 7 JSF | [
"",
"java",
"validation",
"jsf",
"websphere",
""
] |
I have downloaded the latest Eclipse IDE, Galileo, and tested it to see if it good for developing web applications in Java. I have also tried the Ganymede version of Eclipse and find that is it also good.
My Problem is that sometimes it hangs and stops responding while I am developing. Sometimes when I open a file, Eclipse hangs and does not respond for awhile. It seems that Eclipse is going slower and my job is getting slower because of the time that I am spending waiting for the response of Eclipse.
When I went to NetBeans 6.7, it was good and the performance was good. The loading is faster and the IDE responds well during my development testing.
My computer has 1 GB of RAM and a 1.6 GHz CPU.
What can you say about this? | I'm using Eclipse PDT 2.1 (also based on Galileo) for PHP development, and I've been using Eclipse-based IDE for 3 years now ; my observation is that 1 GB of RAM is generally not enough to run Eclipse + some kind of web server + DB server + browser + other stuff :-(
*I'm currently working with a 1GB of RAM machine, and it's slow as hell... Few months ago, I had a 2GB of RAM machine, and things were going really fine -- and I'm having less software running on the "new machine" than I had on the other one !*
Other things that seem to affect Eclipse's responsivness is :
* opening a project that's on a network drive (accessing the sources that are on a development server via samba, for instance)
* sometimes, using an SVN-plugin like SUbversive seems to freeze Eclipse for a couple of seconds/minutes
A nice to do with languages like PHP (might not be OK for JAVA projects, though) is to disable "automatically build" in "project"'s menu.
*As a sidenote : I've already seen questions about eclipse's speed on SO ; you might want to try so searches, to get answers faster ;-)* | This is a common concern and others have posted similar questions. There are optimizations that you can perform on your Eclipse environment. Take a look at the [solutions posted here](https://stackoverflow.com/questions/142357/what-are-the-best-eclipse-34-jvm-settings#144349). | Why is the Eclipse IDE getting slower? | [
"",
"java",
"eclipse",
"ide",
""
] |
I am currently building a new version of webservice that my company already provides. The current webservice has an input parameter of type string. In that string an entire xml doc is passed. We then validate that string against an xsd (the same xsd given to the consumer). It looks something like this:
```
[WebMethod]
public bool Upload(string xml)
{
if (ValidateXML(xml))
{
//Do something
}
}
```
I am building the next version of this service. I was under the impression that passing an XML doc as a string is not the correct way to do this. I was thinking that my service would look something like this:
```
[WebMethod]
public bool Upload(int referenceID, string referenceName, //etc...)
{
//Do something
}
```
This issue that I am having is that in actuality there are a large amount of input parameters and some of them are complex types. For example, the Upload Method needs to take in a complex object called an Allocation. This object is actually made up of several integers, decimal values, strings, and other complex objects. Should I build the webservice like so:
```
[WebMethod]
public bool Upload(int referenceID, string referenceName, Allocation referenceAllocation)
{
//Do something
}
```
Or is there a different way to do this?
Note: this Allocation object has a hierarchy in the xsd that was provided for the old service.
Could it be that the original service only took in xml to combat this problem? Is there a better way to take in complex types to a webservice?
Note: This is a C# 2.0 webservice. | I would probably use the XSD with "xsd.exe" tool to create a XML Serializable object. Then you can deal with objects instead of string parameters. It also gives you the ability to not change the signatures of the WebService.
If you change the XSD to add another parameter all you will need to do is recreate the class again using XSD.exe tool. Make good use of **partial classes** here. Separate your auto generated class from your business logic. This way you can recreate the the class definition if the XSD changes as many times as you want, but not touch your business logic.
[XML Serialization in the .NET Framework](http://msdn.microsoft.com/en-us/library/ms950721.aspx)
If you were using 3.5, you could also use LINQ to XML to quickly parse out your XML parameters. | Jon, to answer your follow-up question first: If your clients are on multiple platforms (or at least, not all on .NET), the best approach is the so-called "WSDL-first". Define the service interface in WSDL - that's where services and methods will be defined - WSDL will reference a set of XSDs defining the data-holding objects passed to and returned from those methods. You can generate C# or Java code from WSDL/XSDs.
Back to your original question. For the same of maintainability, the best practice is to defined Request and Response classes for each web methods and never pass strings, bools, integers directly. For example,
```
// in your Web service class
[WebMethod]
public UploadResponse Upload( UploadRequest request ) {
...
}
...
[Serializable]
public class UploadResponse {
public bool IsSuccessful {
get { ... }
set { ... }
}
}
[Serializable]
public class UploadRequest {
public Allocation ReferenceAllocation {
get { ... }
set { ... }
}
// define other request properties
// ...
}
```
If you defined SOAP bindings in your WSDL file, *UploadRequest* object is extracted from the SOAP message and deserialized. By the time the control reaches your WebMethod implementation, you have a deserialized *UploadRequest* object in memory with all of its properties set.
To have a method like this: public bool Upload(string xml) in a [WebService] class and parse XML inside the method implementation is definitely something you should consider moving away from. | What is right way to code input parameters with complex types for a C# .net 2.0 WebService? | [
"",
"c#",
"asp.net",
"xml",
"web-services",
""
] |
In the following code block, why do I need to declare myData in the class, then initialize myData = new string[size] in the constructor? Why is it illegal to code private string[] myData = new string[size] ?
That is, why do I need to do:
```
class IntIndexer
{
private string[] myData;
public IntIndexer(int size)
{
myData = new string[size];
for (int i = 0; i < size; i++)
{
myData[i] = "empty";
}
}
}
```
Instead of
```
class IntIndexer
{
private string[] myData = new string[size];
public IntIndexer(int size)
{
for (int i = 0; i < size; i++)
{
myData[i] = "empty";
}
}
}
``` | Because the variable "size" only exists in the constructor. | Because you do not know what size will be, or even if it exists outside the constructor.
Inline initialisers run as part of *all* constructors in the class. Adding another constructor without size would break your class if this were implemented, a confusing state of affairs.
Also even if the compiler were made smart enough to check for all this it would be a confusing abuse of scope. What if there were a constant field called size somewhere else in the class?
All these are reasons to not attempt to allow this sort of thing and there are precious little benefits to it so why bother. | C# constructor help | [
"",
"c#",
""
] |
Based on [this tutorial](http://www.htmldog.com/articles/suckerfish/dropdowns/), I've built a drop down menu for [template from Styleshout.com](http://www.styleshout.com/templates/preview/Refresh1-0/index.html). [medigerati helped me](https://stackoverflow.com/questions/1241915/why-doesnt-this-drop-down-menu-work) so that it works now - at least in Firefox 3.5 and Internet Explorer 8.
[You can see the menu in action here.](http://wp1080088.wp029.webpack.hosteurope.de/Refresh1-1/)
But unfortunately, it doesn't work well in all browsers. In Internet Explorer 6 - for example - it isn't displayed correctly.
Could you please tell me how I can improve the code to make it work in more browsers?
I hope you can help me. Thanks in advance!
HTML:
```
<ul id="nav">
<li><a href="index.html">Nav #1</a>
<ul>
<li><a href="#">Nav #1.1</a></li>
<li><a href="#">Nav #1.2</a></li>
</ul>
</li>
<li><a href="index.html">Nav #2</a>
<ul>
<li><a href="#">Nav #2.1</a></li>
<li><a href="#">Nav #2.2</a></li>
</ul>
</li>
<li><a href="index.html">Nav #3</a>
<ul>
<li><a href="#">Nav #3.1</a></li>
<li><a href="#">Nav #3.2</a></li>
</ul>
</li>
</ul>
```
CSS:
```
ul#nav li ul {
position: absolute;
left: -9999px;
top: 100%;
display: block;
width: 100px;
background-color: transparent;
}
ul#nav li {
position: relative;
float: left;
}
/* Links in the drop down lists start */
ul#nav li ul li a {
clear: left;
display: block;
text-decoration: none;
width: 100px;
background-color: #333;
}
/* Links in the drop down lists end */
/* Making visible start */
ul#nav li:hover ul, #nav li.sfhover ul {
left: auto;
}
/* Making visible end */
```
JavaScript:
```
sfHover = function() {
var sfEls = document.getElementById("nav").getElementsByTagName("LI");
for (var i=0; i<sfEls.length; i++) {
sfEls[i].onmouseover=function() {
this.className+=" sfhover";
}
sfEls[i].onmouseout=function() {
this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
}
}
}
if (window.attachEvent) window.attachEvent("onload", sfHover);
``` | Javascript event binding works differently in different browsers. Try:
```
sfHover = function() {
var sfEls = document.getElementById("nav").getElementsByTagName("LI");
for (var i=0; i<sfEls.length; i++) {
addEvent(sfEls[i], "mouseover", function() {
this.className+=" sfhover";
});
addEvent(sfEls[i], "mouseout", function() {
this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
});
}
}
function addEvent(el, name, func) {
if (el.attachEvent)
el.attachEvent("on" + name, func);
else
el.addEventListener(name, func, false);
}
addEvent(window, "load", sfHover);
```
[Quirksmode.org](http://www.quirksmode.org/js/eventSimple.html) has a lot of good articles about events. | Are you doing this as a learning exercise, or do you just want a good nav-bar type menu? If the latter, I would recommend YUI 3.0’s [MenuNav](http://developer.yahoo.com/yui/3/node-menunav/ "The MenuNav Node Plugin"), which is well-tested against all major browsers, including IE6. | Improve code for drop down menu (HTML/CSS/JavaScript) | [
"",
"javascript",
"html",
"css",
"drop-down-menu",
""
] |
I have a piece of data that is large and will probably contain quotes and double quotes.
I'm using `mysql_real_escape_string()` to store it safely.
When I pull it out to look at it, all the quotes are escaped. I tried using `str_replace` to just get rid of all the quotes, but that turns `\r\n`'s into `rn`. :(
How can I reverse it so the data comes back out the way it went in? | Do you use magic quotes?
> Note: If magic\_quotes\_gpc is enabled,
> first apply stripslashes() to the
> data. Using this function [mysql\_real\_escape\_string] on data
> which has already been escaped will
> escape the data twice. | Who says?
```
$keyword = "TEST'TEST";
$result1 = mysql_real_escape_string($keyword);
echo $result1 --> TEST\'TEST
$result2 = nl2br(stripslashes($result));
echo $result2 --> TEST'TEST
``` | reverse mysql_real_escape_string | [
"",
"php",
"mysql",
""
] |
EDIT: I would love to read reactions to Steve Reed's AOP approach. Comments to his answer are encouraged!
I'm a novice, and at some point I realized it would be helpful to know the contents of a variable during program execution. So I started doing this:
EDIT: fixed this. Used to be: var + ": " + var, which was totally wrong. Dumb typo.
```
System.err.println ( "var: " + var );
```
Later I learned that this was common practice. At least, where a debugger was unavailable or unwanted.
I use a basic text editor, and typing the print statement every time I need to debug a variable is pretty tiresome, so I thought, why not something like this:
```
void dbug ( Object obj )
{
String variableName = obj.somehowGetVariableName();
String variableContents = obj.toString();
System.out.println ( variableName +": " + variableContents );
}
```
But apparently getting the variable name is easier said than done.
[java-reflection-how-to-get-the-name-of-a-variable](https://stackoverflow.com/questions/744226/java-reflection-how-to-get-the-name-of-a-variable)
Am I stuck with:
```
System.err.println ( "var: " + var );
```
Or is there a popular shorthand version of this? | I wouldn't try and write any fancy methods around printing out debugging info. Just stick with either `LOG.debug(...)` if you are using a logger or `System.err.println(...)` otherwise.
You may wish to use `String.format("var=%s val=%s", "VarName", val)` instead of the String concatenation.
Make sure that you override the `toString` method in each of your classes to provide meaningful debug info.
At the end of the day it's often easier to fire up the debugger and take a look to see what's going on instead of having to trace through loads of logged debug lines.
The only time when i'd use your kind of debug method would be if my application maintained all of the state inside a map which I could easily print out the key value pairs (e.g. the session map in a web application). | I think that [System.err.format](http://www.devdaily.com/blog/post/java/java-string-formatted-format-output-text/) is what you want:
```
System.err.format("var: %s\n", var);
```
is a shorthand for:
```
System.err.println(String.format("var: %s", var));
``` | Looking for an easier way to write debugging print statements in Java | [
"",
"java",
"debugging",
""
] |
I have a string with a full URL including GET variables. Which is the best way to remove the GET variables? Is there a nice way to remove just one of them?
This is a code that works but is not very beautiful (I think):
```
$current_url = explode('?', $current_url);
echo $current_url[0];
```
The code above just removes all the GET variables. The URL is in my case generated from a CMS so I don't need any information about server variables. | Ok, to remove all variables, maybe the prettiest is
```
$url = strtok($url, '?');
```
See about [`strtok` here](http://php.net/manual/en/function.strtok.php).
Its the fastest (see below), and handles urls without a '?' properly.
To take a url+querystring and remove just one variable (without using a regex replace, which may be faster in some cases), you might do something like:
```
function removeqsvar($url, $varname) {
list($urlpart, $qspart) = array_pad(explode('?', $url), 2, '');
parse_str($qspart, $qsvars);
unset($qsvars[$varname]);
$newqs = http_build_query($qsvars);
return $urlpart . '?' . $newqs;
}
```
A regex replace to remove a single var might look like:
```
function removeqsvar($url, $varname) {
return preg_replace('/([?&])'.$varname.'=[^&]+(&|$)/','$1',$url);
}
```
Heres the timings of a few different methods, ensuring timing is reset inbetween runs.
```
<?php
$number_of_tests = 40000;
$mtime = microtime();
$mtime = explode(" ",$mtime);
$mtime = $mtime[1] + $mtime[0];
$starttime = $mtime;
for($i = 0; $i < $number_of_tests; $i++){
$str = "http://www.example.com?test=test";
preg_replace('/\\?.*/', '', $str);
}
$mtime = microtime();
$mtime = explode(" ",$mtime);
$mtime = $mtime[1] + $mtime[0];
$endtime = $mtime;
$totaltime = ($endtime - $starttime);
echo "regexp execution time: ".$totaltime." seconds; ";
$mtime = microtime();
$mtime = explode(" ",$mtime);
$mtime = $mtime[1] + $mtime[0];
$starttime = $mtime;
for($i = 0; $i < $number_of_tests; $i++){
$str = "http://www.example.com?test=test";
$str = explode('?', $str);
}
$mtime = microtime();
$mtime = explode(" ",$mtime);
$mtime = $mtime[1] + $mtime[0];
$endtime = $mtime;
$totaltime = ($endtime - $starttime);
echo "explode execution time: ".$totaltime." seconds; ";
$mtime = microtime();
$mtime = explode(" ",$mtime);
$mtime = $mtime[1] + $mtime[0];
$starttime = $mtime;
for($i = 0; $i < $number_of_tests; $i++){
$str = "http://www.example.com?test=test";
$qPos = strpos($str, "?");
$url_without_query_string = substr($str, 0, $qPos);
}
$mtime = microtime();
$mtime = explode(" ",$mtime);
$mtime = $mtime[1] + $mtime[0];
$endtime = $mtime;
$totaltime = ($endtime - $starttime);
echo "strpos execution time: ".$totaltime." seconds; ";
$mtime = microtime();
$mtime = explode(" ",$mtime);
$mtime = $mtime[1] + $mtime[0];
$starttime = $mtime;
for($i = 0; $i < $number_of_tests; $i++){
$str = "http://www.example.com?test=test";
$url_without_query_string = strtok($str, '?');
}
$mtime = microtime();
$mtime = explode(" ",$mtime);
$mtime = $mtime[1] + $mtime[0];
$endtime = $mtime;
$totaltime = ($endtime - $starttime);
echo "tok execution time: ".$totaltime." seconds; ";
```
shows
```
regexp execution time: 0.14604902267456 seconds; explode execution time: 0.068033933639526 seconds; strpos execution time: 0.064775943756104 seconds; tok execution time: 0.045819044113159 seconds;
regexp execution time: 0.1408839225769 seconds; explode execution time: 0.06751012802124 seconds; strpos execution time: 0.064877986907959 seconds; tok execution time: 0.047760963439941 seconds;
regexp execution time: 0.14162802696228 seconds; explode execution time: 0.065848112106323 seconds; strpos execution time: 0.064821004867554 seconds; tok execution time: 0.041788101196289 seconds;
regexp execution time: 0.14043688774109 seconds; explode execution time: 0.066350221633911 seconds; strpos execution time: 0.066242933273315 seconds; tok execution time: 0.041517972946167 seconds;
regexp execution time: 0.14228296279907 seconds; explode execution time: 0.06665301322937 seconds; strpos execution time: 0.063700199127197 seconds; tok execution time: 0.041836977005005 seconds;
```
strtok wins, and is by far the smallest code. | How about:
```
preg_replace('/\\?.*/', '', $str)
``` | Beautiful way to remove GET-variables with PHP? | [
"",
"php",
"url",
"variables",
"get",
""
] |
I am wanting to write some cross-platform library code.
I am creating a library both static and dynamic with most of the development done in Linux, I have got the static and shared library generated in Linux but now wanted to generate a Windows version of a static and dynamic library in the form of `.lib` and `.dll` using the same source code.
Is this possible? I'm a bit worried because I noticed generating Windows `.dll` files required using `_dllspec` or something similiar in your source code.
I am seeking the best and quickest solution to getting my code compiled on Windows. I don't need to do the compiling under Linux; I am happy to do it directly under Windows. Also I am using two external libraries which are Boost and Xerces XML which I have installed on both my Windows and Linux system so hopefully they shouldn't be a problem.
What I really want is to have a single source code copy that can be compiled under both Linux and Windows to generate libraries specific to each platform. I don't really care if I have to edit my code in favour of Windows or Linux as long as I can have a single source code copy. | In general, there are two issues you need to be concerned with:
1. The requirement that, on Windows, your DLL explicitly exports symbols that should be visible to the outside world (via `__declspec(dllexport)`, and
2. Being able to maintain the build system (ideally, not having to maintain a separate makefile and Microsoft Visual C++ Project/Solution)
For the first, you will need to learn about `__declspec(dllexport)`. On Windows only projects, typically this is implemented in the way I describe in my answer to [this question](https://stackoverflow.com/questions/1179103/visual-studio-2005-linker-problem/1179118#1179118). You can extend this a step further by making sure that your export symbol (such as MY\_PROJECT\_API) is defined but expands to nothing when building for Linux. This way, you can add the export symbols to your code as needed for Windows without affecting the linux build.
For the second, you can investigate some kind of cross-platform build system.
If you're comfortable with the GNU toolset, you may want to investigate [libtool](http://en.wikipedia.org/wiki/Libtool) (perhaps in conjunction with automake and autoconf).
The tools are natively supported on Linux and supported on Windows through either [Cygwin](http://www.cygwin.com/) or [MinGW/MSYS](http://www.mingw.org/). MinGW also gives you the option of cross-compiling, that is, building your native Windows binaries while running Linux. Two resources I've found helpful in navigating the Autotools (including libtool) are the ["Autobook"](http://sources.redhat.com/autobook/) (specifically the section on [DLLs and Libtool](http://sources.redhat.com/autobook/autobook/autobook_251.html#SEC251)) and [Alexandre Duret-Lutz's PowerPoint slides](http://www.lrde.epita.fr/~adl/autotools.html).
As others have mentioned, [CMake](http://www.cmake.org/) is also an option, but I can't speak for it myself. | You can pretty easily do it with #ifdef's. On Windows \_WIN32 should be defined by the compiler (even for 64 bit), so code like
```
#ifdef _WIN32
# define EXPORTIT __declspec( dllexport )
#else
# define EXPORTIT
#endif
EXPORTIT int somefunction();
```
should work OK for you. | C++ cross-platform dynamic libraries for Linux and Windows | [
"",
"c++",
"cross-platform",
"shared-libraries",
""
] |
I have a simple div which I don't want to load if the visitor loads up a certain URL.
It looks like this:
```
<?php
if( stristr($_SERVER['PHP_SELF'], 'blog') == FALSE )
{
echo "<div id="stuff"></div>";
}
?>
```
Problem is... it doesn't work... when I load up www.url.com/blog the div#stuff still shows.
Am I just lacking sleep or should the above work? What would you do to not have a div display if the url contains blog ? | Try [`$_SERVER['REQUEST_URI']`](http://docs.php.net/manual/en/reserved.variables.server.php) instead:
```
if (substr($_SERVER['REQUEST_URI'], 0, 5) !== '/blog') {
echo '<div id="stuff"></div>';
}
```
`REQUEST_URI` contains the requested URI path and query and not just the filename of the currently executing script like `PHP_SELF` does. | OP's version works for me. Provided that you fix the echo() syntax error.
```
echo "<div id=\"stuff\"></div>";
```
*tested on PHP Version 5.2.9* | Don't show this if the url contains the following | [
"",
"php",
"wordpress",
""
] |
I'd just like to know if there's a function/way to restrict input to a textbot to a formatted type e.g. a user can only enter a **date** type into a textbox; or a function similar to to the C scanset that I can use to achieve the same functionality?
Thanks | If you are writing a desktop app you could use the [`MaskedTextBox`](http://msdn.microsoft.com/en-us/library/system.windows.forms.maskedtextbox.aspx).
> The MaskedTextBox class is an enhanced
> TextBox control that supports a
> declarative syntax for accepting or
> rejecting user input. Using the Mask
> property, you can specify the
> following input without writing any
> custom validation logic in your
> application:
>
> * Required input characters.
> * Optional input characters.
> * The type of input expected at a given position in the mask; for
> example, a digit, or an alphabetic or
> alphanumeric character.
> * Mask literals, or characters that should appear directly in the
> MaskedTextBox; for example, the
> hyphens (-) in a phone number, or the
> currency symbol in a price.
> * Special processing for input characters; for example, to convert
> alphabetic characters to uppercase. | The tool that would work best in this scenario is the Masked Edit Textbox. | Can textbox input in C# be restriced to a formatted type? | [
"",
"c#",
".net",
""
] |
Given an input file of text lines, I want duplicate lines to be identified and removed. Please show a simple snippet of C# that accomplishes this. | This should do (and will copy with large files).
Note that it only removes duplicate *consecutive* lines, i.e.
```
a
b
b
c
b
d
```
will end up as
```
a
b
c
b
d
```
If you want no duplicates anywhere, you'll need to keep a set of lines you've already seen.
```
using System;
using System.IO;
class DeDuper
{
static void Main(string[] args)
{
if (args.Length != 2)
{
Console.WriteLine("Usage: DeDuper <input file> <output file>");
return;
}
using (TextReader reader = File.OpenText(args[0]))
using (TextWriter writer = File.CreateText(args[1]))
{
string currentLine;
string lastLine = null;
while ((currentLine = reader.ReadLine()) != null)
{
if (currentLine != lastLine)
{
writer.WriteLine(currentLine);
lastLine = currentLine;
}
}
}
}
}
```
Note that this assumes `Encoding.UTF8`, and that you want to use files. It's easy to generalize as a method though:
```
static void CopyLinesRemovingConsecutiveDupes
(TextReader reader, TextWriter writer)
{
string currentLine;
string lastLine = null;
while ((currentLine = reader.ReadLine()) != null)
{
if (currentLine != lastLine)
{
writer.WriteLine(currentLine);
lastLine = currentLine;
}
}
}
```
(Note that that doesn't close anything - the caller should do that.)
Here's a version that will remove *all* duplicates, rather than just consecutive ones:
```
static void CopyLinesRemovingAllDupes(TextReader reader, TextWriter writer)
{
string currentLine;
HashSet<string> previousLines = new HashSet<string>();
while ((currentLine = reader.ReadLine()) != null)
{
// Add returns true if it was actually added,
// false if it was already there
if (previousLines.Add(currentLine))
{
writer.WriteLine(currentLine);
}
}
}
``` | For small files:
```
string[] lines = File.ReadAllLines("filename.txt");
File.WriteAllLines("filename.txt", lines.Distinct().ToArray());
``` | Remove Duplicate Lines From Text File? | [
"",
"c#",
"duplicates",
""
] |
First of i am not a UI developer and this is probably a very simple problem.
What i have is a external service that I subscribe to an event, when ever that event fires a service picks this up, manipulates the data in some way then gives the UI the data to display
What i am unsure of is how to archetect this and keep the dependancy between the service which will tell the UI to update and the UI as loose as possible.
Can anyone suggest a stratagy for this or post me some links on examples or an open source project to actually look at some working code.
I am using c# and ether wpf or winforms for this.
Cheers
Colin G | How simple is this application?
The simplest solution is to have the data access/manipulation in one object, and have the UI passed as an interface into that object. With the UI interface methods, you can give data to the UI but let the UI handle displaying the data in a GUI thread-safe manner.
If it's a more complex application, I'd say it would make more sense to look into something like MVC or MVP. Or MVVM for WPF, maybe look at Bea Costa's blog for databinding examples. | My solution to this problem is to create a timer in your ui, and have your ui subscribe to the 'onTick' method. Then, at every timer tick, have the UI look at the service and figure out what data to display. | Update UI from external event | [
"",
"c#",
"wpf",
"winforms",
"user-interface",
""
] |
I'm looking for a simple commons method or operator that allows me to repeat some string *n* times. I know I could write this using a for loop, but I wish to avoid for loops whenever necessary and a simple direct method should exist somewhere.
```
String str = "abc";
String repeated = str.repeat(3);
repeated.equals("abcabcabc");
```
**Related to:**
[repeat string javascript](https://stackoverflow.com/questions/202605/repeat-string-javascript)
[Create NSString by repeating another string a given number of times](https://stackoverflow.com/questions/260945/create-nsstring-by-repeating-another-string-a-given-number-of-times)
**Edited**
I try to avoid for loops when they are not completely necessary because:
1. They add to the number of lines of code even if they are tucked away in another function.
2. Someone reading my code has to figure out what I am doing in that for loop. Even if it is commented and has meaningful variables names, they still have to make sure it is not doing anything "clever".
3. Programmers love to put clever things in for loops, even if I write it to "only do what it is intended to do", that does not preclude someone coming along and adding some additional clever "fix".
4. They are very often easy to get wrong. For loops involving indexes tend to generate off by one bugs.
5. For loops often reuse the same variables, increasing the chance of really hard to find scoping bugs.
6. For loops increase the number of places a bug hunter has to look. | # `String::repeat`
```
". ".repeat(7) // Seven period-with-space pairs: . . . . . . .
```
[New in Java 11](https://bugs.openjdk.java.net/browse/JDK-8197594) is the method [`String::repeat`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#repeat(int)) that does exactly what you asked for:
```
String str = "abc";
String repeated = str.repeat(3);
repeated.equals("abcabcabc");
```
Its [Javadoc](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#repeat(int)) says:
```
/**
* Returns a string whose value is the concatenation of this
* string repeated {@code count} times.
* <p>
* If this string is empty or count is zero then the empty
* string is returned.
*
* @param count number of times to repeat
*
* @return A string composed of this string repeated
* {@code count} times or the empty string if this
* string is empty or count is zero
*
* @throws IllegalArgumentException if the {@code count} is
* negative.
*
* @since 11
*/
``` | Here is the shortest version (Java 1.5+ required):
```
repeated = new String(new char[n]).replace("\0", s);
```
Where `n` is the number of times you want to repeat the string and `s` is the string to repeat.
No imports or libraries needed. | Simple way to repeat a string | [
"",
"java",
"string",
""
] |
Given the following table:
```
Length | Width | Color | ID
===========================
18 | 18 | blue | 1
---------------------------
12 | 12 | red | 1
---------------------------
```
I want to produce a single column/row:
```
SIZES
=================
18 x 18, 12 x 12,
```
I can do this in SQL as follows:
```
DECLARE @SIZES VARCHAR(8000)
SELECT @SIZES = COALESCE(@SIZES, '') + Convert(varchar(80), [Length]) + ' x ' +
Convert(varchar(80), [Width]) + ', '
FROM table
where ID = 1
GROUP BY [Length], [Width]
ORDER BY [Length], [Width]
SELECT SIZES = @SIZES
```
But I cannot figure out how to do this in LINQ.
The closest I got was:
```
from t in table
where id == 1
group t by new {
t.Length,
t.Width
} into g
orderby g.Key.Length, g.Key.Width
select new {
SIZES = (Convert.ToInt32(g.Key.Length) + " x " +
Convert.ToInt32(g.Key.Width) + ", ")
}
```
Which produces one column and two rows:
```
SIZES
========
18 x 18,
12 X 12,
```
The converts are unimportant to the problem. The columns are defined as floats though all are integers. The key is the COALESCE function I cannot figure out how to do that in LINQ. | I don't think LINQ to SQL supports this T-SQL trick. The COALESCE isn't really the issue (as Mehrdad points out the equivalent in C# is ??) -- it's the fact that SQL Server aggregates each result via string concatenation into the variable @SIZES. AFAIK LINQ to SQL can't construct this type of query.
This will yield your desired result, but the string concatenation is performed on your side, not on the SQL server side. That probably doesn't matter.
```
var query =
from t in table
where id == 1
group t by new {
t.Length,
t.Width
} into g
orderby g.Key.Length, g.Key.Width
select new {
SIZES = (Convert.ToInt32(g.Key.Length) + " x " +
Convert.ToInt32(g.Key.Width) + ", ")
};
var result = string.Join(string.Empty, query.Select(r => r.SIZES).ToArray());
``` | Try `??` ([null coalesce operator](http://weblogs.asp.net/scottgu/archive/2007/09/20/the-new-c-null-coalescing-operator-and-using-it-with-linq.aspx)) like:
```
t.Length ?? 0
``` | LINQ to SQL C# COALESCE | [
"",
"sql",
"linq",
"coalesce",
""
] |
I have a python list which holds a few email ids accepted as unicode strings:
```
[u'one@example.com',u'two@example.com',u'three@example.com']
```
This is assigned to `values['Emails']` and `values` is passed to render as html.
The Html renders as this:
> Emails: [u'one@example.com',u'two@example.com',u'three@example.com']
I would like it to look like this:
> Emails: [ one@example.com, two@example.com, three@example.com ]
How can I do this in the server script?
Is there a simple way to achieve this in the HTML itself? | The easiest way for you to do it would be to iterate over your email list. e.g.
```
{% for email in Emails %}
email,
{% endfor %}
```
This way you (or a designer) will have a lot more control of the layout.
Have a look at the [template documentation](http://docs.djangoproject.com/en/dev/topics/templates/#topics-templates) for more details. | In Python:
```
'[%s]' % ', '.join(pythonlistwithemails)
```
In bare HTML it is impossible... you'd have to use javascript. | Dropping the Unicode markers in Html output | [
"",
"python",
"html",
"django",
"unicode",
"html-lists",
""
] |
I'm trying to install the first service I wrote using:
```
installutil XMPPMonitor.exe
```
I get the following message:
```
Running a transacted installation.
Beginning the Install phase of the installation.
See the contents of the log file for the E:\Documents\Projects\XMPPMonitor\XMPPMonitor\bin\Debug\XMPPMonitor.exe assembly's progress.
The file is located at E:\Documents\Projects\XMPPMonitor\XMPPMonitor\bin\Debug\XMPPMonitor.InstallLog.
The Install phase completed successfully, and the Commit phase is beginning.
See the contents of the log file for the E:\Documents\Projects\XMPPMonitor\XMPPMonitor\bin\Debug\XMPPMonitor.exe assembly's progress.
The file is located at E:\Documents\Projects\XMPPMonitor\XMPPMonitor\bin\Debug\XMPPMonitor.InstallLog.
The Commit phase completed successfully.
The transacted install has completed.
```
But I'm not setting the service listed when I run services.msc. Am I missing something? | Make sure you correctly created and configured the [ServiceInstaller](http://msdn.microsoft.com/en-us/library/system.serviceprocess.serviceinstaller.aspx) and [ServiceProcessInstaller](http://msdn.microsoft.com/en-us/library/system.serviceprocess.serviceprocessinstaller.aspx). These are what installutil uses to actually register each service within the process. | I asked a similar question recently : [C#: Running and Debugging a Windows Service](https://stackoverflow.com/questions/711241/c-running-and-debugging-a-windows-service)
Apparently the problem was because I did not have an **Installer** attached to the service.
[Here](http://arcanecode.wordpress.com/2007/05/23/windows-services-in-c-adding-the-installer-part-3/) is the tutorial I used to add a Service Installer and so on. | Installing .NET Windows Service | [
"",
"c#",
".net",
""
] |
im having some problem with this code:
```
if (count($_POST)) {
$username = mysql_real_escape_string($_POST['username']);
$passwd = mysql_real_escape_string($_POST['passwd']);
mysql_query("INSERT INTO users (username, password)
VALUES ($username, $passwd)");
}
<form method="post">
<p><input type="text" name="username" /></p>
<p><input type="password" name="passwd" /></p>
<p><input type="submit" value="Register me!" /></p>
</form>
```
i am connected to db
the users column ID is auto\_increment
I get this when adding or die mysql\_error in sql statement: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' )' at line 2 | You're missing quotes around the inserted values:
```
mysql_query("INSERT INTO users (username, password)
VALUES ('$username', '$passwd')");
``` | surround both with single quotes
```
mysql_query("INSERT INTO users (username, password)
VALUES ('$username', '$passwd')");
``` | INSERT INTO wont work! | [
"",
"sql",
"mysql",
""
] |
I have 2 regular Tables "Tasks" and "Employees" and one junction table EmployeeTasks simplified they look like this
**Tasks**
* TaskID
* ProjectID
* Duration
**Employee**
* EmployeeID
* EmployeeName
**EmployeeTasks**
* EmployeeID
* TaskID
I am trying to find a tsql query that based on a common project ID would deliver a summary of the total time spent and number of tasks done by each employee. Similar to this:
```
"Employee" | "Number of Tasks" | "Time Spent"
----------------------------------------
John | 5 | 123
Sam | 4 | 72
``` | ```
SELECT E.EmployeeName, COUNT(T.TaskID) AS [Number of Tasks], SUM(T.Duration) as [Time Spent]
FROM Employee E, EmployeeTasks ET, Tasks T
WHERE ET.EmployeeID = E.EmployeeID AND ET.TaskID = T.TaskID
GROUP BY E.EmployeeName
``` | try this:
```
Select EmployeeName,
Count(et.TaskId) NumTasks,
Sum(T.Duration) TimeSpent
From Employees E
Left Join (EmployeeTasks eT Join Tasks T
On T.TaskId = eT.TaskId)
On eT.EmployeeId = E.EmployeeId
Where ProjectId = @ProjectId
Group By EmployeeName
```
and this will do it for all employees-Project combinations
```
Select EmployeeName, ProjectId,
Count(et.TaskId) NumTasks,
Sum(T.Duration) TimeSpent
From Employees E
Left Join (EmployeeTasks eT Join Tasks T
On T.TaskId = eT.TaskId)
On eT.EmployeeId = E.EmployeeId
Group By EmployeeName, ProjectId
``` | SQL select sum from other table as a column via junction table | [
"",
"sql",
"sql-server-2005",
"t-sql",
""
] |
I want to write some text that contains whitespace characters such as `newline` and `tab` into an xml file so I use
```
Element element = xmldoc.createElement("TestElement");
element.appendChild(xmldoc.createCDATASection(somestring));
```
but when I read this back in using
```
Node vs = xmldoc.getElementsByTagName("TestElement").item(0);
String x = vs.getFirstChild().getNodeValue();
```
I get a string that has no newlines anymore.
When i look directly into the xml on disk, the newlines seem preserved. so the problem occurs when reading in the xml file.
How can I preserve the newlines?
Thanks! | I don't know how you parse and write your document, but here's an enhanced code example based on yours:
```
// creating the document in-memory
Document xmldoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
Element element = xmldoc.createElement("TestElement");
xmldoc.appendChild(element);
element.appendChild(xmldoc.createCDATASection("first line\nsecond line\n"));
// serializing the xml to a string
DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
DOMImplementationLS impl =
(DOMImplementationLS)registry.getDOMImplementation("LS");
LSSerializer writer = impl.createLSSerializer();
String str = writer.writeToString(xmldoc);
// printing the xml for verification of whitespace in cdata
System.out.println("--- XML ---");
System.out.println(str);
// de-serializing the xml from the string
final Charset charset = Charset.forName("utf-16");
final ByteArrayInputStream input = new ByteArrayInputStream(str.getBytes(charset));
Document xmldoc2 = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(input);
Node vs = xmldoc2.getElementsByTagName("TestElement").item(0);
final Node child = vs.getFirstChild();
String x = child.getNodeValue();
// print the value, yay!
System.out.println("--- Node Text ---");
System.out.println(x);
```
The serialization using LSSerializer is the W3C way to do it ([see here](http://xerces.apache.org/xerces2-j/faq-dom.html#faq-3)). The output is as expected, with line separators:
```
--- XML ---
<?xml version="1.0" encoding="UTF-16"?>
<TestElement><![CDATA[first line
second line ]]></TestElement>
--- Node Text ---
first line
second line
``` | You need to check the type of each node using node.getNodeType(). If the type is CDATA\_SECTION\_NODE, you need to concat the CDATA guards to node.getNodeValue. | How to preserve newlines in CDATA when generating XML? | [
"",
"java",
"xml",
"newline",
"w3c",
"cdata",
""
] |
How do I get the current username in .NET using C#? | ```
string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
``` | If you are in a network of users, then the username will be different:
```
Environment.UserName
- Will Display format : 'Username'
```
rather than
```
System.Security.Principal.WindowsIdentity.GetCurrent().Name
- Will Display format : 'NetworkName\Username'
```
Choose the format you want. | How do I get the current username in .NET using C#? | [
"",
"c#",
".net",
""
] |
I am trying to use jquery appendTo in order to copy an element into another container.
The object is indeed appended but, it is removed from the source.
Is there a way I can append the element while leaving the source element where it is?
call it copy call it clone call it whatever you feel like.
Here is my current code:
```
jQuery(document).ready(function()
{
jQuery('#button').appendTo('#panel'); //button should appear ALSO in panel.
});
``` | Close, but not close enough. The code below will `clone()` the element and then append it in `#panel`.
```
jQuery(document).ready(function()
{
jQuery('#button').clone().appendTo('#panel');
});
```
Note that it is against standards to have an `ID` used twice in the same page. So, to fix this:
```
jQuery(document).ready(function()
{
jQuery('#button').clone().attr('id', 'newbutton').appendTo('#panel');
});
``` | Simply call the `clone()` method on your selected jQuery object before appending it:
```
$('#button').clone().appendTo('#panel');
```
If you need to also clone all the event handlers attached to the selected elements, pass boolean `true` as a parameter to the `clone()` method.
Also, you may will want to change the `id` attribute of the selected element...
That is as easy as:
```
$('#button').clone().attr('id', 'button-clone').appendTo('#panel');
``` | jQuery cloneTo instead of appendTo? | [
"",
"javascript",
"jquery",
"html",
"clone",
""
] |
In many books is said that the reason for which Java's generic use erasure is
to have compatibility with legacy code.
Ok, very good but can anyone show me some simple examples where some
generic code interact with old legacy code and vice-versa? | Here's an example that wouldn't be possible without *type erasure*:
```
public static void main(String[] args) {
List<String> newList = legacyMethod();
for (String s : newList) {
System.out.println(s);
}
}
public static List legacyMethod() {
List oldList = new ArrayList();
oldList.add("a");
oldList.add("b");
oldList.add("c");
return oldList;
}
``` | Having compatibility with the legacy code means that it should be able to run on the new version of JVM without compilation. Let's say you are having some legacy library without source code. This ensures that you'll be able to run it on Java 5. Your new code will be able to call legacy code without problems. | Generics erasure and legacy code | [
"",
"java",
"generics",
""
] |
I wrote this code:
```
public class FileViewer extends JPanel implements ActionListener {
/**
*
*/
private static final long serialVersionUID = 1L;
JFileChooser chooser;
FileNameExtensionFilter filter = null;
JEditorPane pane = null;
JTextField text = null;
JButton button;
JTextArea o = null;
URL url;
public FileViewer(JTextArea o) {
this.o = o;
setLayout(new FlowLayout(FlowLayout.RIGHT));
JTextField text = new JTextField("file...", 31);
text.setColumns(45);
text.revalidate();
text.setEditable(true);
button = new JButton("Browse");
add(text);
add(button);
filter = new FileNameExtensionFilter("html", "html");
chooser = new JFileChooser();
chooser.addChoosableFileFilter(filter);
button.addActionListener(this);
}
public void paintComponent(Graphics g) {
super.paintComponents(g);
Graphics2D graphic = (Graphics2D) g;
graphic.drawString("HTML File:", 10, 20);
}
public void actionPerformed(ActionEvent event) {
int returnVal = 0;
if (event.getSource() == button) {
returnVal = chooser.showOpenDialog(FileViewer.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
text.setToolTipText(chooser.getSelectedFile().getName());
} else
o.append("Open command cancled by user.");
}
}
}
```
But in the line: `text.setToolTipText(chooser.getSelectedFile().getName());` a NullPointerException is thrown!
**EDIT**
I have fixed the problem which I have mentioned above but it doesn't work correctly (it doesn't write the name of the file in the text!) :-( | Answering your other point:
```
text.setToolTipText(chooser.getSelectedFile().getName());
```
Was this the intended behaviour? The filename will only appear as a tooltip when you mouse over the text field. To put text directly into a JTextField you should call `setText()` instead. | You've declared `text` globally and assigned `NULL` to it. In your constructor for `FileViewer` you declare it again with `new`, but this declaration is local. The variable referenced in `actionPerformed()` is the global one, which is still `NULL`, so you get the exception. If you change
```
JTextField text = new JTextField("file...", 31);
```
to
```
text = new JTextField("file...", 31);
```
that should fix it. | What's wrong with this code? | [
"",
"java",
"swing",
"nullpointerexception",
""
] |
Suppose you have 3 modules, a.py, b.py, and c.py:
a.py:
```
v1 = 1
v2 = 2
etc.
```
b.py:
```
from a import *
```
c.py:
```
from a import *
v1 = 0
```
Will c.py change v1 in a.py and b.py? If not, is there a way to do it? | All that a statement like:
```
v1 = 0
```
can do is bind the name `v1` to the object `0`. It can't affect a different module.
If I'm using unfamiliar terms there, and I guess I probably am, I strongly recommend you read Fredrik Lundh's excellent article [Python Objects: Reset your brain](http://effbot.org/zone/python-objects.htm). | The `from ... import *` form is basically intended for handy interactive use at the interpreter prompt: you'd be well advised to never use it in other situations, as it will give you nothing but problems.
In fact, the in-house style guide at my employer goes further, recommending to always import a module, never contents from within a module (a module from within a package is OK and in fact recommended). As a result, in our codebase, references to imported things are always qualified names (`themod.thething`) and never barenames (which always refer to builtin, globals of this same module, or locals); this makes the code much clearer and more readable and avoids all kinds of subtle anomalies.
Of course, if a module's name is too long, an `as` clause in the import, to give it a shorter and handier alias for the purposes of the importing module, is fine. But, with your one-letter module names, that won't be needed;-).
So, if you follow the guideline and always import the module (and not things from inside it), `c.v1` will always be referring to the same thing as `a.v1` and `b.v1`, both for getting AND setting: here's one potential subtle anomaly avoided right off the bat!-)
Remember the very last bit of the Zen of Python (do `import this` at the interpreter prompt to see it all):
```
Namespaces are one honking great idea -- let's do more of those!
```
Importing the whole module (not bits and pieces from within it) preserves its integrity as a namespace, as does always referring to things inside the imported module by qualified (dotted) names. It's one honking great idea: do more of that!-) | Python imports: Will changing a variable in "child" change variable in "parent"/other children? | [
"",
"python",
"import",
""
] |
I am looking a Tool on How to Find CPU Utilization of a Single Thread within a Process in VC++.
It would be great full if any one could provide me a tool.
Also it could be better if you guys provide how to do programmatically.
Thank you in Advance. | Perhaps using [GetThreadTimes](http://msdn.microsoft.com/en-us/library/ms683237%28VS.85%29.aspx) would help ?
To elaborate if the thread belongs to another executable, that would be something (not tested) in the lines of:
```
// Returns true if thread times could be queried and its results are usable,
// false otherwise. Error handling is minimal, considering throwing detailed
// exceptions instead of returning a simple boolean.
bool get_remote_thread_times(DWORD thread_id, FILETIME & kernel_time, FILETIME & user_time)
{
FILETIME creation_time = { 0 };
FILETIME exit_time = { 0 };
HANDLE thread_handle = OpenThread(THREAD_QUERY_INFORMATION, FALSE, thread_id);
if (thread_handle == INVALID_HANDLE) return false;
bool success = GetThreadTimes(thread_handle, &creation_time, &exit_time, &kernel_time, &user_time) != 0;
CloseHandle(thread_handle);
return success;
}
``` | try using process explorer.. (tool).. pretty useful..
<http://download.cnet.com/Process-Explorer/3000-2094_4-10223605.html> | How to Find CPU Utilization of a Single Thread within a Process | [
"",
"c++",
"c",
"multithreading",
"cpu",
"cpu-usage",
""
] |
I am developing in C#.net and I believe I need to use generics for the problem I have however I don’t know where to start.
Here are the steps I need to do:
1. Get ID from user – DONE
2. Query database table using ID - DONE
3. Pull back one row - DONE
4. Create a object type dependant on ID
5. Populate object dependant on type
Different appointments require different information being pulled back (populated) from the database. For example one appointment might only require the users forename/surname where another may require forename/surname/dob.
I want the child class to execute first and then call the parent method. The issue is myAppointment is still be treated as a Appointment object not a DoctorAppointment/OtherAppointment once it has gone through the Switch statement. Where myAppointment is declared I actually dont know what type of object is it going to be
Here is the code I currently have:
```
tblAppointment getAppointment = (from getApp in dc.tblAppointments
where getApp.appID == Id
select getApp).SingleOrDefault();
// Needs to be set the something. I really want this be to set to a generic type as I don’t really know what type it will be until it has been through the switch statement
Appointment myAppointment = null;
switch (getAppointment.tblAppointment.appTypeID)
{
case 2:
{
// Changes myAppointment from Appointment to DoctorsAppointment
myAppointment = new DoctorsAppointment();
}
break;
case 1:
{
myAppointment = new OtherAppointment();
}
break;
default:
break;
}
// I want this to set myAppointment to DoctorsAppointment.Populate(getAppointment)
return myAppointment.Populate(getAppointment);
```
Appointment is parent class.
DoctorsAppointment/OtherAppointment are child classes.
The Populate within the child classes require a parameter whereas the parent class doesn’t. The error I am currently recieveing is:
```
No overload for method 'Populate' takes '1' arguments
```
Hopefully I have explained myself enough.
Thanks,
Clare | Suggest you take one of the inheritance answers above
I thought it was worth asking if you are using LINQ to SQL? The kind of functionality you need is partially implemented for you if you have one table, that stores different kinds of objects.
See [here](http://blogs.microsoft.co.il/blogs/bursteg/archive/2007/10/01/linq-to-sql-inheritance.aspx) for an example | One solution is to, in parent class Appointment, make method like this:
```
public virtual void Populate( getAppointment)
{
// does nothing
}
```
And then in child classes:
```
public override void Populate( getAppointment)
{
// do what you need
}
``` | Incorporating Generics | [
"",
"c#",
".net",
"generics",
""
] |
I am creating a contextmenu that should contain a listing of all folders, subfolders, and files in a chosen folder. I want the menu to open the files and folders when they are clicked, but the click event doesn't register if the menuitem has subitems.
```
void Foo(string Title)
{
MenuItem = new MenuItem(Title);
MenuItem.Click += new EventHandler(MenuItem_Click);
ContextMenu.MenuItems.Add(MenuItem);
}
void MenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show("This box will only show when menuitems without subitems are clicked");
}
```
How can I make the click event fire even if the menuitem has subitems? | It sounds like a menu may not be the most appropriate UI widget here. I believe the reason you don't get a click event raised is that menu items with submenus are assumed to *only* expand their children when clicked, rather than executing any other action.
That's likely to be the assumption of the user, too.
This behaviour is mentioned in the documentation for [`MenuItem.Click`](http://msdn.microsoft.com/en-us/library/system.windows.forms.menuitem.click.aspx):
> Note: If the MenuItems property for the
> MenuItem contains any items, this
> event is not raised. This event is not
> raised for parent menu items. | If you launched your popup from a toolstrip, you can subclass the toolstrip and add this code.
```
override protected void OnItemClicked(ToolStripItemClickedEventArgs e)
{
if (this.Items.Count == 0)
base.OnItemClicked(e);
// else do nothing
}
```
However, the ContextMenu class does not have OnItemClicked, but it has onPopup. I have not tried it but you could try subclassing the ContextMenu
```
public class MyContextMenu : ContextMenu
{
override protected void OnPopUp(EventArgs e)
{
if (this.MenuItems.Count == 0)
base.OnPopUp(e);
// else do nothing
}
}
```
if that does not work then, you could override the two show methods
```
public class MyContextMenu : ContextMenu
{
override protected void Show (Control c, Point p)
{
if (this.MenuItems.Count == 0)
base.Show (c, p) ;
// else do nothing
}
override protected void (Control c, Point p, LeftRightAlignment z)
{
if (this.MenuItems.Count == 0)
base.Show (c, p, z) ;
// else do nothing
}
}
``` | Get click event on a menuitem with subitems (C#) | [
"",
"c#",
"events",
"click",
"menuitem",
""
] |
How can I make a simple server(simple as in accepting a connection and print to terminal whatever is received) accept connection from multiple ports or a port range?
Do I have to use multiple threads, one for each bind call. Or is there another solution?
The simple server can look something like this.
```
def server():
import sys, os, socket
port = 11116
host = ''
backlog = 5 # Number of clients on wait.
buf_size = 1024
try:
listening_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listening_socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
listening_socket.bind((host, port))
listening_socket.listen(backlog)
except socket.error, (value, message):
if listening_socket:
listening_socket.close()
print 'Could not open socket: ' + message
sys.exit(1)
while True:
accepted_socket, adress = listening_socket.accept()
data = accepted_socket.recv(buf_size)
if data:
accepted_socket.send('Hello, and goodbye.')
accepted_socket.close()
server()
```
EDIT:
This is an example of how it can be done. Thanks everyone.
```
import socket, select
def server():
import sys, os, socket
port_wan = 11111
port_mob = 11112
port_sat = 11113
sock_lst = []
host = ''
backlog = 5 # Number of clients on wait.
buf_size = 1024
try:
for item in port_wan, port_mob, port_sat:
sock_lst.append(socket.socket(socket.AF_INET, socket.SOCK_STREAM))
sock_lst[-1].setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
sock_lst[-1].bind((host, item))
sock_lst[-1].listen(backlog)
except socket.error, (value, message):
if sock_lst[-1]:
sock_lst[-1].close()
sock_lst = sock_lst[:-1]
print 'Could not open socket: ' + message
sys.exit(1)
while True:
read, write, error = select.select(sock_lst,[],[])
for r in read:
for item in sock_lst:
if r == item:
accepted_socket, adress = item.accept()
print 'We have a connection with ', adress
data = accepted_socket.recv(buf_size)
if data:
print data
accepted_socket.send('Hello, and goodbye.')
accepted_socket.close()
server()
``` | I'm not a python guy, but the function you are interested in is "select". This will allow you to watch multiple sockets and breaks out when activity occurs on any one of them.
Here's a [python example that uses select](http://code.activestate.com/recipes/531824/). | Since Python's got so much overhead, multithreaded apps are a big point of debate. Then there's the whole blocking-operation-GIL issue too. Luckily, the Python motto of *"If it seems like a big issue, someone's probably already come up with a solution (or several!)"* holds true here. My favorite solution tends to be the microthread model, specifically [`gevent`](http://www.gevent.org/).
Gevent is an event-driven single-thread concurrency library that handles most issues for you out of the box via monkey-patching. `gevent.monkey.patch_socket()` is a function that replaces the normal socket calls with non-blocking variants, polling and sleeping to allow the switch to other greenlets as need be. If you want more control, or it's not cutting it for you, you can easily manage the switching with select and `gevent`'s cooperative yield.
Here's a simple example.
```
import gevent
import socket
import gevent.monkey; gevent.monkey.patch_socket()
ALL_PORTS=[i for i in xrange(1024, 2048)]
MY_ADDRESS = "127.0.0.1"
def init_server_sock(port):
try:
s=socket.socket()
s.setblocking(0)
s.bind((MY_ADDRESS, port))
s.listen(5)
return s
except Exception, e:
print "Exception creating socket at port %i: %s" % (port, str(e))
return False
def interact(port, sock):
while 1:
try:
csock, addr = sock.accept()
except:
continue
data = ""
while not data:
try:
data=csock.recv(1024)
print data
except:
gevent.sleep(0) #this is the cooperative yield
csock.send("Port %i got your message!" % port)
csock.close()
gevent.sleep(0)
def main():
socks = {p:init_server_sock(p) for p in ALL_PORTS}
greenlets = []
for k,v in socks.items():
if not v:
socks.pop(k)
else:
greenlets.append(gevent.spawn(interact, k, v))
#now we've got our sockets, let's start accepting
gevent.joinall(greenlets)
```
That would be a super-simple, completely untested server serving plain text `We got your message!` on ports 1024-2048. Involving select is a little harder; you'd have to have a manager greenlet which calls select and then starts up the active ones; but that's not massively hard to implement.
Hope this helps! The nice part of the greenlet-based philosophy is that the select call is actually part of their hub module, as I recall, which will allow you to create a much more scalable and complex server more easily. It's pretty efficient too; there are a couple benchmarks floating around. | How to make server accepting connections from multiple ports? | [
"",
"python",
"network-programming",
""
] |
I'm used to thinking of all initialization of globals/static-class-members as happening before the first line of main(). But I recently read somewhere that the standard allows initialization to happen later to "assist with dynamic loading of modules." I could see this being true when dynamic linking: I wouldn't expect a global initialized in a library to be initialized before I dlopen'ed the library. However, within a grouping of statically linked together translation units (my app's direct .o files) I would find this behavior very unintuitive. Does this only happen lazily when dynamically linking or can it happen at any time? (or was what I read just wrong? ;) | The standard has the following in 3.6.2/3:
> It is implementation-defined whether or not the dynamic initialization (8.5, 9.4, 12.1, 12.6.1) of an object of
> namespace scope is done before the first statement of main. If the initialization is deferred to some point
> in time after the first statement of main, it shall occur before the first use of any function or object defined
> in the same translation unit as the object to be initialized.
~~But o~~ Of course you can ~~never officially~~ tell when the initialization takes place ~~since the initialization will occur before you access the variable!~~ as follows:
```
// t1.cc
#include <iostream>
int i1 = 0;
int main () {
std::cout << i1 << std::endl
// t2.cc
extern int i1;
int i2 = ++i1;
```
I can conform that g++ 4.2.4 at least appears to perform the initialization of 'i2' before main. | The problem that one wanted to solve with that rule is the one of dynamic loading. The allowance isn't restricted to dynamic loading and formally could happen for other cases. I don't know an implementation which use it for anything else than dynamic loading. | How lazy can C++ global initialization be? | [
"",
"c++",
"static",
"initialization",
"global-variables",
"dynamic-linking",
""
] |
Currently I am using the below method to open the users outlook email account and populate an email with the relevant content for sending:
```
public void SendSupportEmail(string emailAddress, string subject, string body)
{
Process.Start("mailto:" + emailAddress + "?subject=" + subject + "&body="
+ body);
}
```
I want to however, be able to populate the email with an attached file.
something like:
```
public void SendSupportEmail(string emailAddress, string subject, string body)
{
Process.Start("mailto:" + emailAddress + "?subject=" + subject + "&body="
+ body + "&Attach="
+ @"C:\Documents and Settings\Administrator\Desktop\stuff.txt");
}
```
However this does not seem to work.
Does anyone know of a way which will allow this to work!?
Help greatly appreciate.
Regards. | mailto: doesn't officially support attachments. I've heard Outlook 2003 will work with this syntax:
```
<a href='mailto:name@domain.com?Subject=SubjTxt&Body=Bod_Txt&Attachment=""C:\file.txt"" '>
```
A better way to handle this is to send the mail on the server using [System.Net.Mail.Attachment](http://msdn.microsoft.com/en-us/library/system.net.mail.attachment.aspx).
```
public static void CreateMessageWithAttachment(string server)
{
// Specify the file to be attached and sent.
// This example assumes that a file named Data.xls exists in the
// current working directory.
string file = "data.xls";
// Create a message and set up the recipients.
MailMessage message = new MailMessage(
"jane@contoso.com",
"ben@contoso.com",
"Quarterly data report.",
"See the attached spreadsheet.");
// Create the file attachment for this e-mail message.
Attachment data = new Attachment(file, MediaTypeNames.Application.Octet);
// Add time stamp information for the file.
ContentDisposition disposition = data.ContentDisposition;
disposition.CreationDate = System.IO.File.GetCreationTime(file);
disposition.ModificationDate = System.IO.File.GetLastWriteTime(file);
disposition.ReadDate = System.IO.File.GetLastAccessTime(file);
// Add the file attachment to this e-mail message.
message.Attachments.Add(data);
//Send the message.
SmtpClient client = new SmtpClient(server);
// Add credentials if the SMTP server requires them.
client.Credentials = CredentialCache.DefaultNetworkCredentials;
try {
client.Send(message);
}
catch (Exception ex) {
Console.WriteLine("Exception caught in CreateMessageWithAttachment(): {0}",
ex.ToString() );
}
data.Dispose();
}
``` | If you want to access the default email client then you can use MAPI32.dll (works on Windows OS only).
Take a look at the following wrapper:
<http://www.codeproject.com/KB/IP/SendFileToNET.aspx>
Code looks like this:
```
MAPI mapi = new MAPI();
mapi.AddAttachment("c:\\temp\\file1.txt");
mapi.AddAttachment("c:\\temp\\file2.txt");
mapi.AddRecipientTo("person1@somewhere.com");
mapi.AddRecipientTo("person2@somewhere.com");
mapi.SendMailPopup("testing", "body text");
// Or if you want try and do a direct send without displaying the mail dialog
// mapi.SendMailDirect("testing", "body text");
``` | C# MailTo with Attachment? | [
"",
"c#",
"attachment",
"mailto",
""
] |
I need to gather some system information for the application I'm developing. The memory available and the CPU load are easy to get using C#. Unfortunately, the CPU temperature it's not that easy. I have tried using WMI, but I couldn't get anything using
```
Win32_TemperatureProbe
```
or
```
MSAcpi_ThermalZoneTemperature
```
How can I do this? I'm wondering how monitoring programs, as SiSoftware Sandra, can get that information...
Here is the code of the class:
```
public class SystemInformation
{
private System.Diagnostics.PerformanceCounter m_memoryCounter;
private System.Diagnostics.PerformanceCounter m_CPUCounter;
public SystemInformation()
{
m_memoryCounter = new System.Diagnostics.PerformanceCounter();
m_memoryCounter.CategoryName = "Memory";
m_memoryCounter.CounterName = "Available MBytes";
m_CPUCounter = new System.Diagnostics.PerformanceCounter();
m_CPUCounter.CategoryName = "Processor";
m_CPUCounter.CounterName = "% Processor Time";
m_CPUCounter.InstanceName = "_Total";
}
public float GetAvailableMemory()
{
return m_memoryCounter.NextValue();
}
public float GetCPULoad()
{
return m_CPUCounter.NextValue();
}
public float GetCPUTemperature()
{
//...
return 0;
}
}
``` | I'm pretty sure it's manufacturer dependent, since they will be accessed through an I/O port. If you have a specific board you're trying to work with, try looking through the manuals and/or contacting the manufacturer.
If you want to do this for a lot of different boards, I'd recommend contacting someone at something like SiSoftware or be prepared to read a *lot* of motherboard manuals.
As another note, not all boards have temperature monitors.
You also might run into problems getting privileged access from the kernel. | > For others who may come by here, maybe take a look at : <http://openhardwaremonitor.org/>
Follow that link and at first you might think, "Hey, that's an *application*, and that is why it was removed. The question was how to do this from C# code, not to find an application that can tell me the temperature..." This is where it shows you are not willing to invest enough time in reading what "Open Hardware Monitor" also is.
They also include a data interface. Here is the description:
> **Data Interface**
> The Open Hardware Monitor publishes all sensor data to
> WMI (Windows Management Instrumentation). This allows other
> applications to read and use the sensor information as well. A
> preliminary documentation of the interface can be found [here (click)](http://openhardwaremonitor.org/wordpress/wp-content/uploads/2011/04/OpenHardwareMonitor-WMI.pdf).
When you download it, it contains the OpenHardwareMonitor.exe application, and you're not looking for that one. It also contains the OpenHardwareMonitorLib.dll, and you're looking for that one.
It is mostly, if not 100%, just a wrapper around the WinRing0 API, which you could choose to wrap yourself if you feel like it.
I have tried this out from a C# application myself, and it works. Although it was still in beta, it seemed rather stable. It is also open source, so it could be a good starting point instead.
---
Update as of 2023-06-26
As noted in the comments, it looks like the project is no longer maintained, but that there is a maintained fork here:
<https://github.com/LibreHardwareMonitor/LibreHardwareMonitor> | How can I get the CPU temperature? | [
"",
"c#",
".net",
"wmi",
""
] |
Hey all, I've got a query in need of optimizing. It works but its a dog, performance wise.
It reads like this:
```
SELECT *
FROM (
SELECT *
FROM views
WHERE user_id = '1'
ORDER BY
page DESC
) v
GROUP BY
v.session
```
I'm tracking views to different pages, and I want to know the highest page per session, in order to know how far they've clicked through (they're required to view every page all the way to the end) in any given session.
Basically what I'm trying to do is ORDER the results before the GROUP. Which the above achieves, at significant cost.
Anyone who can slap me over the head with how to do this? Thanks guys!
**Update:**
The Explain:
```
"1" "PRIMARY" "<derived2>" "ALL" \N \N \N \N "3545" "Using temporary; Using filesort"
"2" "DERIVED" "views" "index" \N "page" "5" \N "196168" "Using where"
```
The schema:
```
ID int(8) unsigned (NULL) NO PRI (NULL) auto_increment select,insert,update,references
page int(8) (NULL) YES MUL (NULL) select,insert,update,references
user_id int(8) (NULL) YES (NULL) select,insert,update,references
session int(8) (NULL) YES (NULL) select,insert,update,references
created datetime (NULL) NO select,insert,update,references
```
Index Info:
```
views 0 PRIMARY 1 ID A 196008 (NULL) (NULL) BTREE
views 1 page 1 page A 259 (NULL) (NULL) YES BTREE
``` | > I'm tracking views to different pages, and I want to know the highest page per session, in order to know how far they've clicked through (they're required to view every page all the way to the end) in any given session.
Ordering before grouping is a highly unreliable way to do this.
`MySQL` extends `GROUP BY` syntax: you can use ungrouped and unaggregated fields in `SELECT` and `ORDER BY` clauses.
In this case, a random value of `page` is output per each `session`.
[**Documentation**](http://dev.mysql.com/doc/refman/5.0/en/group-by-hidden-columns.html) explicitly states that you should never make any assumptions on which value exactly will it be:
> Do not use this feature if the columns you omit from the `GROUP BY` part are not constant in the group. The server is free to return any value from the group, so the results are indeterminate unless all values are the same.
However, in practice, the values from the first row scanned are returned.
Since you are using an `ORDER BY page DESC` in your subquery, this row happens to be the rows with a maximal `page` per session.
You shouldn't rely on it, since this behaviour is undocumented and if some other row will be returned in next version, it will not be considered a bug.
But you don't even have to do such nasty tricks.
Just use aggregate functions:
```
SELECT MAX(page)
FROM views
WHERE user_id = '1'
GROUP BY
session
```
This is documented and clean way to do what you want.
Create a composite index on `(user_id, session, page)` for the query to run faster.
If you need all columns from your table, not only the aggregated ones, use this syntax:
```
SELECT v.*
FROM (
SELECT DISTINCT user_id, session
FROM views
) vo
JOIN views v
ON v.id =
(
SELECT id
FROM views vi
WHERE vi.user_id = vo.user_id
AND vi.session = vo.session
ORDER BY
page DESC
LIMIT 1
)
```
This assumes that `id` is a `PRIMARY KEY` on `views`. | I think your subquery is unnecessary. You would receive the same results from this much simpler (and faster) query:
```
SELECT *
FROM views
WHERE user_id = '1'
GROUP BY session
ORDER BY page DESC
```
Also, you should have an index on every field you're either grouping, ordering or "where-ing" by. In this case, you need an index on user\_id, session and page. | How to optimize MySQL query (group and order) | [
"",
"sql",
"mysql",
"optimization",
""
] |
This is my solution for sphere's online judge [palin problem](https://www.spoj.pl/problems/PALIN/). It runs fine on Netbeans, but the judge is rejecting my answer saying it gives a RuntimeError. I tried it on JCreator and it says:
```
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:468)
at java.lang.Integer.parseInt(Integer.java:497)
at Main.main(Main.java:73)
```
I'm not passing an empty string for it to parse, why is this?
The code:
```
import java.io.*;
import java.util.*;
class Main {
public static int firstPalinLargerThanNum(int num){
int foundPalin =0;
int evalThisNum = ++num;
while (true){
if (isPalin(evalThisNum))
break;
evalThisNum++;
}
foundPalin = evalThisNum;
return foundPalin;
}
public static boolean isPalin(int evalThisNum){
boolean isItPalin = false;
int dig=0;
int rev=0;
int n = evalThisNum;
while (evalThisNum > 0)
{
dig = evalThisNum % 10;
rev = rev * 10 + dig;
evalThisNum = evalThisNum / 10;
}
if (n == rev) {
isItPalin=true;
}
return isItPalin;
}
public static void main(String args[]) throws java.lang.Exception{
BufferedReader r1 = new BufferedReader(new InputStreamReader(System.in));
/*BufferedReader r1 = new BufferedReader (new FileReader(new File ("C:\\Documents and Settings\\Administrator\\My Documents\\NetBeansProjects\\Sphere\\src\\sphere\\sphere\\PALIN_INPUT.txt")));*/
String read = r1.readLine();
int numberOfTestCases = Integer.parseInt(read);
for (int i=0; i<numberOfTestCases;i++){
read = r1.readLine();
if (read!=null){
int num = Integer.parseInt(read);
System.out.println(firstPalinLargerThanNum(num));
}
}
}
}
```
Input:
```
2
808
2133
```
line 73 is: `int num = Integer.parseInt(read);` | You will get that error if you hit `<Enter>` when the program is expecting a number.
Suppose your input is
```
2
3
<Enter>
```
You will receive the error you have indicated after processing the number 3, as you have told your routine to iterate twice.
As an aside, on top of error handling around the number parsing, you might also want to introduce a `trim()` to the `readLine()` method calls:
```
String read = r1.readLine().trim();
```
This will allow you to handle gracefully the input in the event that the user to put in whitespace around the numbers. | Just a wild guess: Could there be a problem with different end-of-line separators.
E.g. your program actually gets `2<CR><LF>808<CR><LF>2133<CR><LF>`, thinks that the line ends at the `<CR>` and processes the line.
Now when it tries to process the next line it finds `<LF>` which makes it think it read an empty String. | why's this program giving a runtime error on jcreator but not on netbeans? | [
"",
"java",
"runtime-error",
""
] |
I am trying to insert items into a listbox in my asp.net C# application
I concatenate some values and put whitespace in between them but it doesn't show up in the listbox.
```
ListItem lt = new ListItem();
lt.Text = ItemName + " " + barcode + " " + price; // problem
lt.Value = barcode;
lstMailItems.Items.Add(lt);
```
i even tried
```
lt.Text = ItemName + "\t\t" + barcode + "\t\t" + price; // problem
lt.Text = ItemName + "& nbsp;" + barcode + "& nbsp;" + price; //   shows up as text
```
but that even doesn't seem to work. How can I put whitespace between these strings so that it shows up in the listbox as well | ```
string spaces = Server.HtmlDecode(" ");
lt.Text = ItemName + spaces + barcode + spaces + price; // works
``` | I had the same issue and the above answers led me to this which worked for me.
```
string space = " ";
space = Server.HtmlDecode(space);
line = line.Replace(" ", space);
ClassCodeListBox.Items.Add(line);
``` | Insert whitespace between characters in listbox | [
"",
"c#",
"asp.net",
"listbox",
""
] |
Is there a standard nice way to call a blocking method with a timeout in Java? I want to be able to do:
```
// call something.blockingMethod();
// if it hasn't come back within 2 seconds, forget it
```
if that makes sense.
Thanks. | You could use an Executor:
```
ExecutorService executor = Executors.newCachedThreadPool();
Callable<Object> task = new Callable<Object>() {
public Object call() {
return something.blockingMethod();
}
};
Future<Object> future = executor.submit(task);
try {
Object result = future.get(5, TimeUnit.SECONDS);
} catch (TimeoutException ex) {
// handle the timeout
} catch (InterruptedException e) {
// handle the interrupts
} catch (ExecutionException e) {
// handle other exceptions
} finally {
future.cancel(true); // may or may not desire this
}
```
If the `future.get` doesn't return in 5 seconds, it throws a `TimeoutException`. The timeout can be configured in seconds, minutes, milliseconds or any unit available as a constant in `TimeUnit`.
See the [JavaDoc](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Future.html) for more detail. | You could wrap the call in a `FutureTask` and use the timeout version of get().
See <http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/FutureTask.html> | How do I call some blocking method with a timeout in Java? | [
"",
"java",
"concurrency",
""
] |
As part of some code logic, the component downloads the user uploaded files to a specific directory.
I am using
```
System.IO.File.Delete(file1);
System.IO.File.Delete(file2);
```
to delete the files. I don't think the local system account IUSR account has permissions to do that.
What are the best practices to handle deletion of files in ASP.NET? | 1. Make a folder that is **outside** your web application to store the files (i.e. when you republish the site, it is not affected)
2. Give that folder appropriate permissions for the IUSR account (or whatever application pool identity you're running under)
3. Store that folder's path in your web.config so you don't have to change code for it. | Delete the file before saving it will refresh automatically
System.IO.File.Delete(filepath);
fupedit.SaveAs(Server.MapPath(filePath)); | ASP.NET Deleting files on the file system? | [
"",
"c#",
"asp.net",
""
] |
I want a variable like $ that is sort of special, but I'm already using jQuery, so $ is taken. | If you want a special variable like $ but $ is already taken by jQuery, why not use something that starts with $, like $a or similar? Just make sure it's one that jQuery doesn't also define. | Unfortunately, older javascript supports letters, numbers, underscores, and $ in identifiers. In javascript 1.5 and later you can use Unicode characters, but that would be a very bad idea as they can be a pain to enter into most editors, and certainly aren't something you would want to have to type very often.
[Source](https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Variables) | What unusual characters in addition to $ are allowed in JavaScript identifiers? | [
"",
"javascript",
"syntax",
""
] |
I am pretty new to Python world and trying to learn it.
This is what I am trying to achieve: I want to create a Car class, its constructor checks for the input to set the object carName as the input. I try to do this by using the java logic but I seem to fail :)
```
class Car():
carName = "" #how can I define a non assigned variable anyway like "String carName;" in java
def __self__(self,input):
self.carName = input
def showName():
print carName
a = Car("bmw")
a.showName()
``` | derived from object for [new-style class](http://docs.python.org/reference/datamodel.html#new-style-and-classic-classes)
use `__init__` to initialize the new instance, not `__self__`
`__main__` is [helpful too](http://docs.python.org/library/__main__.html).
```
class Car(object):
def __init__(self,input):
self.carName = input
def showName(self):
print self.carName
def main():
a = Car("bmw")
a.showName()
if __name__ == "__main__":
main()
``` | You don't define a variable, and you use **init** and self.
Like this:
```
class Car(Object):
def __init__(self,input):
self.carName = input
def showName(self):
print self.carName
a = Car("bmw")
a.showName()
``` | Python object creation | [
"",
"python",
"class",
"object",
""
] |
1. is there any way to check if an email is active without sending it an email? (meaning that it does not get returned)
2. if i have 20,000 emails in my email list, and i do decide to send all of them an email, how can automatically cross out the email address that got returned? | These days, you can't know if the email address is valid. The domain is about as far as you'll get and you can do a reverse lookup on that to see if that is valid. But it won't tell you about the user.
What you need is something to process the bounces from your mail out and write some sort of script to perhaps update the list. There are many tools under Linux for this type of purpose such as procmail. Theres a port of that for windows I think. | Sending an email and requesting the user click some sort of activation link is the best way to determine if the email address is valid, and being used by someone. If you just want to see if the email is valid whether or not its registerd or active, use a Regex.
As for crossing them out, where are the emails stored? If its in a database, just set an activation key and a flag saying whether the link has been visited or not. | how do you check if email address is working? | [
"",
"php",
"vb.net",
""
] |
I have a response XML something like this -
```
<Response> <aa> <Fromhere> <a1>Content</a1> <a2>Content</a2> </Fromhere> </aa> </Response>
```
I want to extract the whole content from `<Fromhere>` to `</Fromhere>` in a string. Is it possible to do that through any string function or through XML parser?
Please advice. | You could try an XPath approach for simpleness in XML parsing:
```
InputStream response = new ByteArrayInputStream("<Response> <aa> "
+ "<Fromhere> <a1>Content</a1> <a2>Content</a2> </Fromhere> "
+ "</aa> </Response>".getBytes()); /* Or whatever. */
DocumentBuilder builder = DocumentBuilderFactory
.newInstance().newDocumentBuilder();
Document doc = builder.parse(response);
XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xpath.compile("string(/Response/aa/FromHere)");
String result = (String)expr.evaluate(doc, XPathConstants.STRING);
```
Note that I haven't tried this code. It may need tweaking. | Through an XML parser. Using string functions to parse XML is a bad idea...
Beside the Sun tutorials pointed out above, you can check [the DZone Refcardz on Java and XML](http://refcardz.dzone.com/refcardz/using-xml-java), I found it was a good, terse explanation how to do it.
But well, there is probably plenty of Web resources on the topic, including on this very site. | Java:XML Parser | [
"",
"java",
"xml",
""
] |
In my application I want to extract the latest date shown in web page. I am using *System.Xml.Linq.XDocument* class to extract content. But I am not able to extract pubdate of feed. Here is my code but its giving exception.
```
System.Xml.Linq.XDocument feeddata =
System.Xml.Linq.XDocument.Load(
"http://feeds2.feedburner.com/plasticsnews/plasticsinformation/plastopedia");
var maxPubDates = (from feeds in feeddata.Descendants("Feeds")select feeds );
DateTime maxDate = maxPubDates.Max(feed => (DateTime) feed.Element("pubDate"));
``` | Actually the line:
```
var maxPubDates = (from feeds in feeddata.Descendants("Feeds") select feeds);
```
is not returning anything, as there is no descendant with tag "Feeds".
Change it to this line and you will get right results:
```
var maxPubDates = (from item in feeddata.Descendants("item") select item);
``` | Use
```
feeddata.Descendants("item")
```
instead of
```
feeddata.Descendants("Feeds")
``` | how to extract maximum date from web page in dot net window application | [
"",
"c#",
".net",
"linq-to-xml",
""
] |
I'm trying to write some portable C++ library code that will initially rely on Boost.Regex, and then move to TR1 as compilers support it, and eventually to the C++0x specification after things get moved from the std::tr1 namespace to std. Here is some pseudo-code for what I'd like to do with the preprocessor:
```
if( exists(regex) ) // check if I can #include <regex>
{
#include <regex> // per TR1
if( is_namespace(std::tr1) ) // are we on TR1 or C++0x?
{
using std::tr1::regex;
} else
{
using std::regex;
}
} else // fall-back to boost
{
#include <boost/regex.hpp>
using boost::regex;
}
```
Granted, all of that would need to be in preprocessor directives, but if I knew how to accomplish that I wouldn't be asking here. :) | You can't do it without relying on a third party thing *before* preprocessing. Generally, things like `autoconf` can be used to accomplish this.
They work by generating another header file with `#define` directives that indicate existence of headers/libraries you want to use. | You can't do it. The preprocessing phase of C++ happens before the compilation phase, so C++ language conditional constructs cannot usefully be placed around preprocessor directives like #include.
If you need conditional compilation, then the way to do it is to use #ifdef. Something like:
```
#ifdef BOOST_BUILD
#include "somebooststuff.h"
using namespace boost;
#else
#include "somestdstuff.h"
using namespace std;
#endif
```
where BOOST\_BUILD is a preprocessor symbol you define in your makefile or whatever. | Determine compile-time existence of include files in C++ | [
"",
"c++",
"c++11",
"boost",
"c-preprocessor",
"tr1",
""
] |
The problem: I want to be able to FIFO queue outgoing messages. For update/deletion reasons, I also want to be able to access every message in the queue based upon an object ID.
I've currently implemented a solution where data is pushed into a deque, and an iterator to that data is kept. The iterator, keyed by an object ID, is then placed into a map. This was fine in the one place that I did it, but I now find myself wanting to do this elsewhere.
Am I over-complicating the problem? Is there a data structure out there that does this already? | Why not make the deque a deque of IDs and the map a map from ID to object. Then when you access an ID in the deque, you look up the ID in the map. If the IDs are globally unique, you only need one map to service all the deques. | I have used [Boost.MultiIndex](http://www.boost.org/doc/libs/1_39_0/libs/multi_index/index.html) to do something very similar. Using it, you can have a container that has the data just once, but it can be accessed through two (or more!)
facades: one that looks like a list, and another one that behaves as a map. When you erase an element using one facade (e.g., pop from the list), the other view will be updated seamlessly. | How to implement a queued map? | [
"",
"c++",
"algorithm",
"stl",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.