Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I've been struggling with a piece of C# code and although I have found a solution to the problem, it is by no means ideal (see DoSomething\_WorksButNotIdeal() below).
What I would like to do is instead of having the if, else statement (which is potentially massive depending on what types I want to support) just have a generic cast, but I can't get it to work. I've tried to demonstrate this in the DoSomething\_HelpMe() method.
Is there anyway of achieving this? Any help is greatly appreciated.
```
public interface ITag
{
string TagName { get; }
Type Type { get; }
}
public interface ITag<T> : ITag
{
T InMemValue { get; set; }
T OnDiscValue { get; set; }
}
public class Tag<T> : ITag<T>
{
public Tag(string tagName)
{
TagName = tagName;
}
public string TagName { get; private set; }
public T InMemValue { get; set; }
public T OnDiscValue { get; set; }
public Type Type{ get{ return typeof(T);} }
}
public class MusicTrack
{
public MusicTrack()
{
TrackTitle = new Tag<string>("TrackTitle");
TrackNumber = new Tag<int>("TrackNumber");
Tags = new Dictionary<string, ITag>();
Tags.Add(TrackTitle.TagName, TrackTitle);
Tags.Add(TrackNumber.TagName, TrackNumber);
}
public IDictionary<string,ITag> Tags;
public ITag<string> TrackTitle { get; set; }
public ITag<int> TrackNumber { get; set; }
}
public static class Main
{
public static void DoSomething_WorksButNotIdeal()
{
MusicTrack track1 = new MusicTrack();
MusicTrack track2 = new MusicTrack();
// Set some values on the tracks
foreach (ITag tag in track1.Tags.Values)
{
Type type = tag.Type;
if (type == typeof(string))
{
((ITag<string>) tag).InMemValue = ((ITag<string>)track2.Tags[tag.TagName]).OnDiscValue;
}
else if (type == typeof(int))
{
((ITag<int>)tag).InMemValue = ((ITag<int>)track2.Tags[tag.TagName]).OnDiscValue;
}
else if (type == typeof(bool))
{
((ITag<bool>)tag).InMemValue = ((ITag<bool>)track2.Tags[tag.TagName]).OnDiscValue;
}
// etc etc
else
{
throw new Exception("Unsupported type.");
}
}
}
public static void DoSomething_HelpMe()
{
MusicTrack track1 = new MusicTrack();
MusicTrack track2 = new MusicTrack();
// Set some values on the tracks
foreach (ITag tag in track1.Tags.Values)
{
Type type = tag.Type;
// THIS OBVIOUSLY DOESN'T WORK BUT I'M JUST TRYING TO DEMONSTRATE WHAT
// I'D IDEALLY LIKE TO ACHIEVE
((ITag<typeof(type)>)tag).InMemValue = ((ITag<typeof(type)>)track2.Tags[tag.TagName]).OnDiscValue;
}
}
}
``` | Any reason that you can't have:
```
public interface ITag
{
string TagName { get; }
Type Type { get; }
object InMemValue { get; set; }
object OnDiscValue { get; set; }
}
```
and use `ITag<T>` to make it more specific?
```
public interface ITag<T> : ITag
{
new T InMemValue { get; set; }
new T OnDiscValue { get; set; }
}
```
Then your method can just use `ITag`. You'd need something like (int `Tag<T>`):
```
object ITag.InMemValue
{
get { return InMemValue; }
set { InMemValue = (T)value; }
}
object ITag.OnDiscValue
{
get { return OnDiscValue; }
set { OnDiscValue = (T)value; }
}
```
---
(edit)
Another option would be a method on the non-generic `ITag`:
```
void CopyValueFrom(ITag tag);
```
(maybe a bit more specific about what it copies to/from)
Your concrete implementation (`Tag<T>`) would have to assume that the `ITag` is actually an `ITag<T>` and cast:
```
public void CopyFromTag(ITag tag) {
ITag<T> from = tag as ITag<T>;
if(from==null) throw new ArgumentException("tag");
this.TheFirstProperty = from.TheSecondProperty;
}
``` | The simplest way to solve it is to resolve the type where you have the information, namely inside the `Tag<T>` implementation, so add the following to your existing types (only showing the additions!)
```
public interface ITag
{
void CopyFrom(bool sourceIsMem, ITag sourceTag, bool targetIsMem);
}
public class Tag<T> : ITag<T>
{
public void CopyFrom(bool sourceIsMem, ITag sourceTag, bool targetIsMem)
{
ITag<T> castSource = sourceTag as ITag<T>;
if (castSource == null)
throw new ArgumentException(
"Source tag is of an incompatible type", "sourceTag");
if (targetIsMem)
InMemValue = sourceIsMem ?
castSource.InMemValue : castSource.OnDiscValue;
else
OnDiscValue = sourceIsMem ?
castSource.InMemValue : castSource.OnDiscValue;
}
}
```
Note that you really should use `enum` types for the `sourceIsMem` and `targetIsMem` instead, because a `bool` is really ugly and hard to read in the invocation as the following fragment will show.
This is how you would make your routine work now:
```
public static void DoSomething_HelpMe()
{
MusicTrack track1 = new MusicTrack();
MusicTrack track2 = new MusicTrack();
// Set some values on the tracks
foreach (ITag tag in track1.Tags.Values)
tag.CopyFrom(false, track2.Tags[tag.TagName], true);
}
``` | C# Casting and Generics | [
"",
"c#",
"generics",
"casting",
""
] |
In C#.NET, I want to fetch data from an URL and save it to a file in binary.
Using HttpWebRequest/Streamreader to read into a string and saving using StreamWriter works fine with ASCII, but non-ASCII characters get mangled because the Systems thinks it has to worry about Encodings, encode to Unicode or from or whatever.
What is the easiest way to GET data from an URL and saving it to a file, binary, as-is?
```
// This code works, but for ASCII only
String url = "url...";
HttpWebRequest request = (HttpWebRequest)
WebRequest.Create(url);
// execute the request
HttpWebResponse response = (HttpWebResponse)
request.GetResponse();
// we will read data via the response stream
Stream ReceiveStream = response.GetResponseStream();
StreamReader readStream = new StreamReader( ReceiveStream );
string contents = readStream.ReadToEnd();
string filename = @"...";
// create a writer and open the file
TextWriter tw = new StreamWriter(filename);
tw.Write(contents.Substring(5));
tw.Close();
``` | Minimalist answer:
```
using (WebClient client = new WebClient()) {
client.DownloadFile(url, filePath);
}
```
Or in PowerShell (suggested in an anonymous edit):
```
[System.Net.WebClient]::WebClient
$client = New-Object System.Net.WebClient
$client.DownloadFile($URL, $Filename)
``` | Just don't use any StreamReader or TextWriter. Save into a file with a raw FileStream.
```
String url = ...;
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);
// execute the request
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
// we will read data via the response stream
Stream ReceiveStream = response.GetResponseStream();
string filename = ...;
byte[] buffer = new byte[1024];
FileStream outFile = new FileStream(filename, FileMode.Create);
int bytesRead;
while((bytesRead = ReceiveStream.Read(buffer, 0, buffer.Length)) != 0)
outFile.Write(buffer, 0, bytesRead);
// Or using statement instead
outFile.Close()
``` | How to GET data from an URL and save it into a file in binary in C#.NET without the encoding mess? | [
"",
"c#",
".net",
"http",
"encoding",
"binary",
""
] |
I'm practising the "Switch Loop" in a program. And I'm making a code where a user can input the integer and after the user will input the integer it will also display what the user just typed in. Now I'm trying to implement where the program will ask the user to input the number again by selecting the Y/N.
I already included it here in my code but if I type characters the first time the program asks me to type an integer, the program will execute the catch part. How can I make it that if the user will type a character it will also display the message again, "please enter the integer:"
```
int enterYourNumber;
char shortLetter;
try
{
Console.WriteLine("Please enter the integer: ");
enterYourNumber = Convert.ToInt32(Console.ReadLine());
WriteNumber(enterYourNumber);
Console.WriteLine("Do you still want to enter a number? Y/N");
shortLetter = Convert.ToChar(Console.ReadLine());
while (shortLetter == 'y' || shortLetter == 'Y')
{
Console.WriteLine("Please enter the integer: ");
enterYourNumber = Convert.ToInt32(Console.ReadLine());
WriteNumber(enterYourNumber);
Console.WriteLine("Do you still want to enter a number? Y/N");
shortLetter = Convert.ToChar(Console.ReadLine());
}
}
catch
{
Console.WriteLine("Please enter an integer not a character");
}
}
public static void WriteNumber(int wordValue)
{
switch (wordValue)
{
case 1:
Console.WriteLine("You have entered number one");
break;
case 2:
Console.WriteLine("You have entered number two");
break;
case 3:
Console.WriteLine("You have entered number three");
break;
default:
Console.WriteLine("You have exceeded the range of number 1-3 ");
break;
}
```
This is what I did; I don't know why I'm getting an error. The new method seems not to work:
```
int enterYourNumber;
char shortLetter;
do
{
enterYourNumber = GetNumber();
WriteNumber(enterYourNumber);
Console.WriteLine("Do you still want to enter a number? Y/N");
shortLetter = Convert.ToChar(Console.ReadLine());
}
while (shortLetter == 'y' || shortLetter == 'Y')
{
Console.WriteLine("Please enter the integer: ");
enterYourNumber = Convert.ToInt32(Console.ReadLine());
WriteNumber(enterYourNumber);
Console.WriteLine("Do you still want to enter a number? Y/N");
shortLetter = Convert.ToChar(Console.ReadLine());
}
}
public static int GetNumber()
{
bool done = false;
int value;
while ( !done )
{
Console.WriteLine("Please enter the integer: ");
try
{
value = Convert.ToInt32(Console.ReadLine());
done = true;
}
catch
{
Console.WriteLine("Please enter an integer not a character");
}
}
}
```
## Update
Bill, this is the example you gave and it seems I'm still getting an error:
```
public static void Main(string[] args)
{
int enterYourNumber;
char shortLetter;
do
{
enteryourNumber = GetNumber();
WriteNumber(enteryourNumber);
Console.WriteLine("Do you still want to enter a number? Y/N");
shortLetter = Convert.ToChar(Console.ReadLine());
}
while (shortLetter == 'y' || shortLetter == 'Y');
}
public static int GetNumber()
{
bool done = false;
int value;
while (!done)
{
Console.WriteLine("Please enter the integer: ");
try
{
value = Convert.ToInt32(Console.ReadLine());
done = true;
}
catch
{
Console.WriteLine("Please enter an integer not a character");
}
Console.WriteLine("Please enter the integer: ");
enterYourNumber = Convert.ToInt32(Console.ReadLine());
WriteNumber(enterYourNumber);
Console.WriteLine("Do you still want to enter a number? Y/N");
shortLetter = Convert.ToChar(Console.ReadLine());
}
}
public static void WriteNumber(int wordValue)
{
switch (wordValue)
{
case 1:
Console.WriteLine("You have entered number one");
break;
case 2:
Console.WriteLine("You have entered number two");
break;
case 3:
Console.WriteLine("You have entered number three");
break;
default:
Console.WriteLine("You have exceeded the range of number 1-3 ");
break;
}
}
}
}
```
## Update
This response is for Robert. This is what I did now, but if I enter "N" it will not exit the program. It still asked the same question.
```
public static void Main(string[] args)
{
int enterYourNumber;
char shortLetter;
bool validEntry;
while (true)
{
do
{
Console.WriteLine("Please enter an integer: ");
string numberString = Console.ReadLine();
validEntry = int.TryParse(numberString, out enterYourNumber);
WriteNumber(enterYourNumber);
if (!validEntry)
{
Console.WriteLine("Entry must be an integer");
}
} while (!validEntry);
Console.WriteLine("Do you still want to enter a number? Y/N");
shortLetter = Convert.ToChar(Console.ReadLine());
}
}
public static void WriteNumber(int wordValue)
{
switch (wordValue)
{
case 1:
Console.WriteLine("You have entered number one");
break;
case 2:
Console.WriteLine("You have entered numbered two");
break;
case 3:
Console.WriteLine("You have entered numbered three");
break;
default:
Console.WriteLine("You have exceeded the range of number 1-3");
break;
}
}
}
}
```
## Update
Robert and Bill, here is what I got now. How can I improve this?
```
public static void Main(string[] args)
{
int intEnterYourNumber;
char charShortLetter;
string strUserInput;
do
{
do
{
Console.WriteLine("Please enter the integer: ");
strUserInput = Console.ReadLine();
} while (!int.TryParse(strUserInput, out intEnterYourNumber));
WriteNumber(intEnterYourNumber);
Console.WriteLine("Do you still want to enter a number? Y/N");
charShortLetter = Convert.ToChar(Console.ReadLine().ToUpper());
} while (charShortLetter == 'Y');
}
public static void WriteNumber(int wordValue)
{
switch (wordValue)
{
case 1:
Console.WriteLine("You have entered number one");
break;
case 2:
Console.WriteLine("You have entered numbered two");
break;
case 3:
Console.WriteLine("You have entered numbered three");
break;
default:
Console.WriteLine("You have exceeded the range of number 1-3");
break;
}
}
``` | Move the try/catch block inside the loop. Robert Harvey's suggestion of the do/while loop is good, too.
```
int enterYourNumber;
char shortLetter;
do
{
try
{
Console.WriteLine("Please enter the integer: ");
enterYourNumber = Convert.ToInt32(Console.ReadLine());
WriteNumber(enterYourNumber);
}
catch( FormatException )
{
Console.WriteLine("Please enter an integer not a character");
}
shortLetter = '\0';
do
{
try
{
Console.WriteLine("Do you still want to enter a number? Y/N");
shortLetter = Convert.ToChar(Console.ReadLine());
}
catch( FormatException )
{
Console.WriteLine("Please enter a single character");
}
}
while ( shortLetter == '\0' )
}
while (shortLetter == 'y' || shortLetter == 'Y')
}
public static void WriteNumber(int wordValue)
{
switch (wordValue)
{
case 1:
Console.WriteLine("You have entered number one");
break;
case 2:
Console.WriteLine("You have entered number two");
break;
case 3:
Console.WriteLine("You have entered number three");
break;
default:
Console.WriteLine("You have exceeded the range of number 1-3 ");
break;
}
``` | I think your code would be easier to learn and understand if you **did not use exceptions to test your numbers**. Try using **int.TryParse()** instead ([TryParse()](http://msdn.microsoft.com/en-us/library/f02979c7.aspx) on MSDN). TryParse() returns *true* (or *false*) depending on whether the entered number was valid:
```
int number;
bool validEntry = int.TryParse(enterYourNumber, out number);
if (!validEntry)
{
Console.WriteLine("Entry must be an integer.");
}
```
Also, **learn about the do...while loop** ([link](http://msdn.microsoft.com/en-us/library/370s1zax(VS.80).aspx)). a do..while loop is similar to a regular while loop except a do-while loop is executed once before the conditional expression is evaluated.
```
bool validEntry;
int enteredNumber;
do
{
Console.Write("Please enter the integer: ");
string numberString = Console.ReadLine();
validEntry = int.TryParse(numberString, out enteredNumber);
if (!validEntry)
{
Console.WriteLine("Entry must be an integer.");
}
} while (!validEntry);
```
Wrap the whole thing in another while loop ("Do you still want to enter a number (Y/N)?") and you're done. | switch statement | [
"",
"c#",
"switch-statement",
""
] |
What packages do you use to handle command line options, settings and config files?
I'm looking for something that reads **user-defined options** from the command line and/or from config files.
The options (settings) should be dividable into different groups, so that I can pass different (subsets of) options to different objects in my code.
I know of `boost::program_options`, but I can't quite get used to the `API`. Are there light-weight alternatives?
(BTW, do you ever use a global options object in your code that can be read from anywhere? Or would you consider that evil?) | Well, you're not going to like my answer. I use `boost::program_options`. The interface takes some getting used to, but once you have it down, it's amazing. Just make sure to do boatloads of unit testing, because if you get the syntax wrong you **will** get runtime errors.
And, yes, I store them in a singleton object (read-only). I don't think it's evil in that case. It's one of the few cases I can think of where a singleton is acceptable. | At Google, we use [gflags](http://code.google.com/p/google-gflags/). It doesn't do configuration files, but for flags, it's a lot less painful than using getopt.
```
#include <gflags/gflags.h>
DEFINE_string(server, "foo", "What server to connect to");
int main(int argc, char* argv[]) {
google::ParseCommandLineFlags(&argc, &argv, true);
if (!server.empty()) {
Connect(server);
}
}
```
You put the `DEFINE_foo` at the top of the file that needs to know the value of the flag. If other files also need to know the value, you use `DECLARE_foo` in them. There's also pretty good support for testing, so unit tests can set different flags independently. | How do you handle command line options and config files? | [
"",
"c++",
"command-line-arguments",
"configuration-files",
""
] |
I have a project that will send an email with certain data to a gmail account. I think that it will probably be easier to read the Atom feed rather than connect through POP.
The url that I should be using according to Google is:
```
https://gmail.google.com/gmail/feed/atom
```
The question/problem is: how do I authenticate the email account I want to see? If I do it in Firefox, it uses the cookies.
I'm also uncertain how exactly to "download" the XML file that this request should return (I believe the proper term is stream).
**Edit 1:**
I am using .Net 3.5. | This is what I used in Vb.net:
```
objClient.Credentials = New System.Net.NetworkCredential(username, password)
```
objClient is of type System.Net.WebClient.
You can then get the emails from the feed using something like this:
```
Dim nodelist As XmlNodeList
Dim node As XmlNode
Dim response As String
Dim xmlDoc As New XmlDocument
'get emails from gmail
response = Encoding.UTF8.GetString(objClient.DownloadData("https://mail.google.com/mail/feed/atom"))
response = response.Replace("<feed version=""0.3"" xmlns=""http://purl.org/atom/ns#"">", "<feed>")
'Get the number of unread emails
xmlDoc.LoadXml(response)
node = xmlDoc.SelectSingleNode("/feed/fullcount")
mailCount = node.InnerText
nodelist = xmlDoc.SelectNodes("/feed/entry")
node = xmlDoc.SelectSingleNode("title")
```
This should not be very different in C#. | .NET framework 3.5 provides native classes to read feeds. [This](http://predicatet.blogspot.com/2008/11/read-rss-or-atom-feed-natively-with-c.html) articles describes how to do it.
I haven't used it tho, but there must be some provision for authentication to a URL. You can check that out. I too will do it, and post the answer back.
If you are not using framework 3.5, then you can try [Atom.NET](http://atomnet.sourceforge.net/index.html). I have used it once, but its old. You can give it a try if it meets your needs.
EDIT: This is the code for assigning user credentials:
```
XmlUrlResolver resolver = new XmlUrlResolver();
resolver.Credentials = new NetworkCredential("abc@abc.com", "password");
XmlReaderSettings settings = new XmlReaderSettings();
settings.XmlResolver = resolver;
XmlReader reader = XmlReader.Create("https://gmail.google.com/gmail/feed/atom", settings);
``` | Reading Atom feed of gmail account from C# | [
"",
"c#",
"xml",
"gmail",
"atom-feed",
""
] |
Wondering if it is possible to replace the desktop (ie. icons, wallpaper) with a WPF Window, Frame or something that I can interact with using WPF and C#? I also don't want it to hide when Show Desktop is clicked.
I'm guessing I'll need to use some Win32 APIs or something? Anyone have any examples, or can anyone point me in the right direction?
Thanks | [How do I Create a Borderless Window in WPF?](http://learnwpf.com/Posts/Post.aspx?postId=e9cb689c-e6af-407a-b28c-d38f2f2f555c)
Check
1. [3D gadgets for your WPF Desktop](http://www.codeproject.com/KB/WPF/3d-gadget-WPF.aspx) | Check out [Baby Smash!](http://www.hanselman.com/babysmash/) it's a WPF application that sounds like it does most of what you'll want. I believe you can get the source too. | Replace Desktop with WPF Application | [
"",
"c#",
"wpf",
"integration",
"desktop",
""
] |
Without a possibility to access .htaccess I find myself in a creative impasse. **There is no mod\_rewriting for me.** Nevertheless, I want to be able to do the nice stuff like:
```
http://www.example.com/Blog/2009/12/10/
http://www.example.com/Title_Of_This_Page
```
**What are my alternatives?**
In respond to the answers:
* I'm building with php5
* I don't have access to .htaccess
* `http://www.example.com/index.php/Blog/` is a known technique but I don't prefer it. Is shows the php so to say.
* How would I create extensionless PHP-files? Would this do the trick?
* How much would using the custom 404 technique hurt performance? | If you've the permissions to set custom error documents for your server you could use this to redirect 404 requests.
E.g. for Apache (<http://httpd.apache.org/docs/2.0/mod/core.html#errordocument>)
```
ErrorDocument 404 /index.php
```
In the index.php you then can proceed your request by using data from the $\_SERVER array. | You can also have urls like
```
http://domain.com/index.php/Blog/Hello_World
```
out of the box with PHP5. You can then read the URL parameters using
```
echo $_SERVER['PATH_INFO'];
```
Remember to validate/filter the PATH\_INFO and all other request variables before using them in your application. | Pretty URLs without mod_rewrite, without .htaccess | [
"",
"php",
"html",
"url",
".htaccess",
"mod-rewrite",
""
] |
I have a date of the form specified by RFC 2822 -- say `Fri, 15 May 2009 17:58:28 +0000`, as a string. Is there a quick and/or standard way to get it as a `datetime` object in Python 2.5? I tried to produce a strptime format string, but the +0000 timezone specifier confuses the parser. | The problem is that parsedate will ignore the offset.
Do this instead:
```
from email.utils import parsedate_tz
print parsedate_tz('Fri, 15 May 2009 17:58:28 +0700')
``` | I'd like to elaborate on previous answers. `email.utils.parsedate` and `email.utils.parsedate_tz` both return tuples, since the OP needs a `datetime.datetime` object, I'm adding these examples for completeness:
```
from email.utils import parsedate
from datetime import datetime
import time
t = parsedate('Sun, 14 Jul 2013 20:14:30 -0000')
d1 = datetime.fromtimestamp(time.mktime(t))
```
Or:
```
d2 = datetime.datetime(*t[:6])
```
Note that `d1` and `d2` are both naive datetime objects, there's no timezone information stored. If you need aware datetime objects, check the `tzinfo` `datetime()` arg.
Alternatively you could use the [dateutil](https://pypi.python.org/pypi/python-dateutil) module | How to parse a RFC 2822 date/time into a Python datetime? | [
"",
"python",
"parsing",
"datetime",
"time",
"python-2.5",
""
] |
I have been developing a **parser** that takes **JavaScript** as input and creates a compressed version of that JavaScript as output.
I found initially that the parser failed when attempting to read the input JavaScript. I believe this has something to do with the fact that **Visual Studio 2008** saves its files by default as **UTF-8**. And when doing so, VS includes a couple of **hidden characters at the start of the UTF-8 file**.
As a workaround, I used Visual Studio to save the file as **code page 1252**. After doing so, my parser was able to read the input JavaScript.
Note that I need to use special European characters that include accents.
**So, here are my questions:**
1. Should I use code page 1252 or UTF-8?
2. Why does Visual Studio save files as UTF-8 by default?
3. If I choose to save files as 1252 will that lead to problems?
4. It appears to me that Eclipse saves files as code page 1252 by default. Does that sound right? | UTF-8 is a better option as it really support *all* known characters, while with 1252 you might end up with characters that you need missing from it (even in European languages).
Apparently, VS2008 saves UTF-8 with a [byte order mark](http://en.wikipedia.org/wiki/Byte-order_mark) - it should be possible to either switch that off, or have the parser recognize it, or strip the BOM somewhere in between. | utf-8 has byte order mark (BOM) signature at the beginning of a file which some editors, and obviously libraries don't understand... <http://en.wikipedia.org/wiki/Byte-order_mark>
if you can get around it, UTF-8 is preferred today by all means. try stripping that first bytes of BOM before giving the JS code to that parser, or find an option in your IDE if it can not write that
1252 doesn't cause this issue and you won't have problems with it, but you'll output your web in an outdated format, i wouldn't do it today, there was a lot of encoding mess on the web in the past with iso vs. win codepages for different languages... | UTF-8 vs code page 1252 in Visual Studio 2008 for HTML and JavaScript that includes European characters | [
"",
"javascript",
"html",
"visual-studio",
"utf-8",
"codepages",
""
] |
Continuing my reverse engineering education I've often wanted to be able to copy portions of x86 assembly code and call it from a high level language of my choice for testing.
Does anyone know of a method of calling a sequence of x86 instructions from within a C# method? I know that this can be done using C++ but I'm curious if it can be done in C#?
Note: I'm not talking about executing MSIL instructions. I'm talking about executing a series of raw x86 assembly instructions. | Just to counter Brian's claim, rewritten code from leppie's answer [link](http://androidbutnotparanoid.blogspot.com/2009/05/dynamically-generating-and-executing.html):
```
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace DynamicX86
{
class Program
{
const uint PAGE_EXECUTE_READWRITE = 0x40;
const uint MEM_COMMIT = 0x1000;
[DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr VirtualAlloc(IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect);
private delegate int IntReturner();
static void Main(string[] args)
{
List<byte> bodyBuilder = new List<byte>();
bodyBuilder.Add(0xb8);
bodyBuilder.AddRange(BitConverter.GetBytes(42));
bodyBuilder.Add(0xc3);
byte[] body = bodyBuilder.ToArray();
IntPtr buf = VirtualAlloc(IntPtr.Zero, (uint)body.Length, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
Marshal.Copy(body, 0, buf, body.Length);
IntReturner ptr = (IntReturner)Marshal.GetDelegateForFunctionPointer(buf, typeof(IntReturner));
Console.WriteLine(ptr());
}
}
}
``` | Yes, see my detailed answer [here](https://stackoverflow.com/a/39620743/3902603)
The main part is: **(Without any P/Invoke or external reference)**
```
public static unsafe int? InjectAndRunX86ASM(this Func<int> del, byte[] asm)
{
if (del != null)
fixed (byte* ptr = &asm[0])
{
FieldInfo _methodPtr = typeof(Delegate).GetField("_methodPtr", BindingFlags.NonPublic | BindingFlags.Instance);
FieldInfo _methodPtrAux = typeof(Delegate).GetField("_methodPtrAux", BindingFlags.NonPublic | BindingFlags.Instance);
_methodPtr.SetValue(del, ptr);
_methodPtrAux.SetValue(del, ptr);
return del();
}
else
return null;
}
```
Which can be used as follows:
```
Func<int> del = () => 0;
byte[] asm_bytes = new byte[] { 0xb8, 0x15, 0x03, 0x00, 0x00, 0xbb, 0x42, 0x00, 0x00, 0x00, 0x03, 0xc3 };
// mov eax, 315h
// mov ebx, 42h
// add eax, ebx
// ret
int? res = del.InjectAndRunX86ASM(asm_bytes); // should be 789 + 66 = 855
```
---
**EDIT:** The newest version of C# (C#9) introduces the concept of 'delegate pointers', which allows you to do the following:
```
byte[] asm = {
0x8D, 0x04, 0x11, // lea eax, [rcx+rdx]
0xC3 // ret
};
void* buffer = VirtualAlloc(null, asm.Length, 0x1000, 4);
var func = (delegate*<int, int, int>)buffer;
int dummy;
Marshal.Copy(asm, 0, (nint)buffer, asm.Length);
VirtualProtect(buffer, asm.Length, 0x20, &dummy);
Console.WriteLine(func(42, 378)); // call 'func' with (42, 378), which computes '420'
VirtualFree(buffer, 0, 0x8000);
```
You can find a complete example here: <https://gist.github.com/Unknown6656/a42a810d4283208c3c21c632fb16c3f9> | Is it possible to execute an x86 assembly sequence from within C#? | [
"",
"c#",
"assembly",
""
] |
I have a java application running on linux machine. I run the java application using the following:
```
java myapp -Xdebug -Xrunjdwp:server=y,transport=dt_socket,address=4000, suspend=n
```
I have opened port 4000 for TCP on this Linux machine. I use eclipse from Windows XP machine and try to connect to this application. I have opened the port in windows also.
Both machines are on the LAN but I can't seem to connect the debugger to the Java application. What am I doing wrong? | **Edit:** I noticed that some people are cutting and pasting the invocation here. The answer I originally gave was relevant for the OP only. Here's a more modern invocation style (including using the more conventional port of 8000):
```
java -agentlib:jdwp=transport=dt_socket,server=y,address=8000,suspend=n
<other arguments>
```
**Note:** With `address=8000` (as used above), the debug server will only listen on `localhost` (see [What are Java command line options to set to allow JVM to be remotely debugged?](https://stackoverflow.com/questions/138511/)). If you want the server to listen on all interfaces, to be able to debug across the network, use `address=*:8000`. Obviously only do this on a restricted, trusted network...
Original answer follows.
---
Try this:
```
java -Xdebug -Xrunjdwp:server=y,transport=dt_socket,address=4000,suspend=n myapp
```
Two points here:
1. No spaces in the `runjdwp` option.
2. Options come before the class name. Any arguments you have after the class name are arguments to your program! | For JDK 1.3 or earlier :
```
-Xnoagent -Djava.compiler=NONE -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=6006
```
For JDK 1.4
```
-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=6006
```
For newer JDK :
```
-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=6006
```
Please change the port number based on your needs.
From [java technotes](http://docs.oracle.com/javase/6/docs/technotes/guides/jpda/conninv.html#Invocation)
> From 5.0 onwards the -agentlib:jdwp option is used to load and specify
> options to the JDWP agent. For releases prior to 5.0, the -Xdebug and
> -Xrunjdwp options are used (the 5.0 implementation also supports the -Xdebug and -Xrunjdwp options but the newer -agentlib:jdwp option is preferable as the JDWP agent in 5.0 uses the JVM TI interface to the
> VM rather than the older JVMDI interface)
One more thing to note, from [JVM Tool interface documentation](http://docs.oracle.com/javase/7/docs/technotes/guides/jvmti):
> JVM TI was introduced at JDK 5.0. JVM TI replaces the Java Virtual Machine Profiler Interface (JVMPI) and the Java Virtual Machine Debug Interface (JVMDI) which, as of JDK 6, are no longer provided. | Remote debugging a Java application | [
"",
"java",
"debugging",
"remote-debugging",
""
] |
WCF offers two options for ResponseFormat attribute in WebGet annotation in ServiceContract.
```
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebGet(UriTemplate = "greet/{value}", BodyStyle = WebMessageBodyStyle.Bare)]
string GetData(string value);
[OperationContract]
[WebGet(UriTemplate = "foo", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)]
string Foo();
```
The options for ResponseFormat are WebMessageFormat.Json and WebMessageFormat.Xml. Is it possible to write my own web message format? I would like that when client calls foo() method he gets raw string - without json or xml wrappers. | [`WebGetAttribute`](http://msdn.microsoft.com/en-us/library/system.servicemodel.web.webgetattribute.aspx) is shipped by Microsoft, and I don't think you can extend [`WebMessageFormat`](http://msdn.microsoft.com/en-us/library/system.servicemodel.web.webgetattribute.responseformat.aspx). However you could probably extend the [`WebHttpBinding`](http://msdn.microsoft.com/en-us/library/system.servicemodel.webhttpbinding.aspx) that uses `WebGetAttribute`. You could add your own attribute like
```
[WebGet2(UriTemplate = "foo", ResponseFormat = WebMessageFormat2.PlainText)]
string Foo();
```
In general, customizing the message layout in WCF is called custom message encoder/encoding. Microsoft provides an example: [Custom Message Encoder: Compression Encoder](http://msdn.microsoft.com/en-us/library/ms751458.aspx). Also another common extension people do is to extend behavior to add custom error handling, so you could look for some example in that direction. | Try using
```
BodyStyle = WebMessageBodyStyle.Bare
```
Then return a System.IO.Stream from your function.
Here's some code I use to return an image out of a database, but accessible via a URL:
```
[OperationContract()]
[WebGet(UriTemplate = "Person/{personID}/Image", BodyStyle = WebMessageBodyStyle.Bare)]
System.IO.Stream GetImage(string personID);
```
Implementation:
```
public System.IO.Stream GetImage(string personID)
{
// parse personID, call DB
OutgoingWebResponseContext context = WebOperationContext.Current.OutgoingResponse;
if (image_not_found_in_DB)
{
context.StatusCode = System.Net.HttpStatusCode.Redirect;
context.Headers.Add(System.Net.HttpResponseHeader.Location, url_of_a_default_image);
return null;
}
// everything is OK, so send image
context.Headers.Add(System.Net.HttpResponseHeader.CacheControl, "public");
context.ContentType = "image/jpeg";
context.LastModified = date_image_was_stored_in_database;
context.StatusCode = System.Net.HttpStatusCode.OK;
return new System.IO.MemoryStream(buffer_containing_jpeg_image_from_database);
}
```
In your case, to return a raw string, set the ContentType to something like "text/plain" and return your data as a stream. At a guess, something like this:
```
return new System.IO.MemoryStream(ASCIIEncoding.Default.GetBytes(string_to_send));
``` | WCF ResponseFormat For WebGet | [
"",
"c#",
"wcf",
"webget",
"responseformat",
""
] |
I've been writing .NET software for years but have started to dabble a bit in Java. While the syntax is similar the methodology is often different so I'm asking for a bit of help in these concept translations.
**Properties**
I know that properties are simply abstracted get\_/set\_ methods - the same in C#. But, what are the commonly accepted naming conventions? Do you use 'get\_' with an underscode or just 'get' by itself.
**Constructors**
In C# the base constructor is called automatically. Is this also true in Java?
**Events**
Like properties, events in .NET are abstracted add\_/remove\_/fire\_ methods that work on a Delegate object. Is there an equivalent in Java? If I want to use some sort of subscriber pattern do you simply define an interface with an Invoke/Run method and collect objects or is there some built-in support for this pattern?
**Update:** One more map:
**String Formatting**
Is there an equivalent to String.Format? | [Java from a C# developer's perspective](http://www.25hoursaday.com/csharpvsjava.html)
Dare Obasanjo has updated his original 10 year old article with a version 2:
[C# from a Java Developer's Perspective v2.0](http://www.25hoursaday.com/weblog/2007/04/30/CFromAJavaDevelopersPerspectiveV20.aspx)
Although for you its the other way round :) | To answer your specific questions:
**Properties**
By convention, Java uses "`get`" or "`set`" followed by the variable name in upper camel case. For example, "`getUserIdentifier()`". booleans often will use "`is`" instead of "`get`"
**Constructors**
In Java, superclass constructors are called first, descending down the type hierarchy.
**Events**
By convention (this is the one you'll get the least agreement on...different libraries do it slightly differently), Java uses methods named like "`addEventTypeListener(EventTypeListener listener)`" and "`removeEventTypeListener(EventTypeListener listener)`", where EventType is a semantic name for the type of event (like MouseClick for addMouseClickListener) and `EventTypeListener` is an interface (usually top-level) that defines the methods available on the receivers - obviously one or more of those references is essentially a "fire" method.
Additionally, there is usually an Event class defined (for example, "`MouseClickEvent`"). This event class contains the data about the event (perhaps x,y coordinates, etc) and is usually an argument to the "fire" methods. | Java equivalent of .NET constructs | [
"",
"java",
".net",
""
] |
I am manually displaying a System.Windows.Forms.Tooltip on a control using the show method, but how can I detect if a tooltip is currently shown?
If I need to change the method for showing it to find out, that is fine. | You could try ToolTip.GetToolTip(control), and check if the returned value is not an empty string, like this:
```
if (!string.IsNullOrEmpty(myToolTip.GetToolTip(myControl)))
{
// Victory!
}
``` | I had so much trouble with the builtin tooltip that I built my own with a timer and tracking MouseMoved. | Detect if Tooltip is shown? | [
"",
"c#",
"winforms",
"tooltip",
"visibility",
""
] |
In my includes folder I have a function...
```
function storelistingUno() {
$itemnum=mysql_real_escape_string($_POST['itemnum']);
$msrp=mysql_real_escape_string($_POST['msrp']);
$edprice=mysql_real_escape_string($_POST['edprice']); //This value has to be the same as in the HTML form file
$itemtype=mysql_real_escape_string($_POST['itemtype']);
$box=mysql_real_escape_string($_POST['box']);
$box2=mysql_real_escape_string($_POST['box2']);
$box25=mysql_real_escape_string($_POST['box25']);
$box3=mysql_real_escape_string($_POST['box3']);
$box4=mysql_real_escape_string($_POST['box4']);
$box5=mysql_real_escape_string($_POST['box5']);
$box6=mysql_real_escape_string($_POST['box6']);
$box7=mysql_real_escape_string($_POST['box7']);
$box8=mysql_real_escape_string($_POST['box8']);
$itemcolor=mysql_real_escape_string($_POST['itemcolor']);
$link=mysql_real_escape_string($_POST['link']);
$test = "yes!";
}
```
I reference this in about 8 pages and I decided it would be easier to just make a function out of it and only touch this from now on. So I referenced `storelistingUno();` in my code, but I don't think it worked, because I tried to execute `echo $test;` and nothing happened. Do I need to return something?
Thanks. | Look into [extract()](http://us.php.net/extract). You can do something like this:
```
<?php
function getEscapedArray()
{
$keys = array('itemnum', 'msrp', 'edprice', 'itemtype', 'box', 'box2', 'box25', 'box3', 'box4', 'box5', 'box6', 'box7', 'box8', 'itemcolor', 'link');
$returnValues = array();
foreach ($keys as $key) {
$returnValues[$key] = mysql_real_escape_string($_POST[$key]);
}
$returnValues['test'] = 'yes!';
return $returnValues;
}
extract(getEscapedArray());
echo $test;
```
Although - Its still not the best way to do this. The best would be to just use the return from that function as the array.
```
$parsedVals = getEscapedArray();
echo $parsedVals["test"];
``` | $test is a local variable in that function - you either need to make it global (by putting `global $test;` at the start of the function or using `$GLOBALS['test']` instead of just `$test` or return the value.
Are you thinking of using that function to just escape the values? Maybe you could make it perform the query too, then you wouldn't have to return / use globals.
Edit:
A different way would be to include the code instead of using a function - not recommended though... | Storing and accessing a snippet of code in a function | [
"",
"php",
""
] |
I have a simple question to ask. I have a UTF 16 text file to read wich starts with FFFE. What are the C++ tools to deal with this kind of file? I just want to read it, filter some lines, and display the result.
It looks simple, but I just have experience in work with plain ascci files and I'm in the hurry. I'm using VS C++, but I'm not want to work with managed C++.
Regards
Here a put a very simple example
```
wifstream file;
file.open("C:\\appLog.txt", ios::in);
wchar_t buffer[2048];
file.seekg(2);
file.getline(buffer, bSize-1);
wprintf(L"%s\n", buffer);
file.close();
``` | You can use [fgetws](https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/fgets-fgetws), which reads 16-bit characters. Your file is in little-endian,byte order. Since x86 machines are also little-endian you should be able to handle the file without much trouble. When you want to do output, use [fwprintf](https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/fprintf-fprintf-l-fwprintf-fwprintf-l).
Also, I agree more information could be useful. For instance, you may be using a library that abstracts away some of this. | Since you are in the hurry, use ifstream in binary mode and do your job. I had the same problems with you and this saved my day. *(it is not a recommended solution, of course, its just a hack)*
```
ifstream file;
file.open("k:/test.txt", ifstream::in|ifstream::binary);
wchar_t buffer[2048];
file.seekg(2);
file.read((char*)buffer, line_length);
wprintf(L"%s\n", buffer);
file.close();
``` | Read Unicode files C++ | [
"",
"c++",
"visual-c++",
"unicode",
"file",
"utf-16",
""
] |
The php page is called page.php; this pages has 2 submit forms on it: form1 and form2. When one of the form's submit button is pressed what in the HTML header with identify which form was submitted? | I don't believe that it does post any identification. The easiest way to have your code know which form posted is to put a hidden field in each form identifying the form like this:
```
<form id="form1">
<input type="hidden" name="formName" value="form1"/>
<input type="submit" value="submit" />
</form>
<form id="form2">
<input type="hidden" name="formName" value="form2"/>
<input type="submit" value="submit" />
</form>
``` | As mentioned in che's comment on Jacob's answer:
```
<form id="form1">
<input type="submit" value="submit" name="form1" />
</form>
<form id="form2">
<input type="submit" value="submit" name="form2" />
</form>
```
And then in your form handling script:
```
if(isset($_POST['form1']){
// do stuff
}
```
This is what I use when not submitting forms via ajax. | How does a HTML form identify itself in POST header? | [
"",
"php",
"post",
"header",
""
] |
How can I add a custom filter to django admin (the filters that appear on the right side of a model dashboard)? I know its easy to include a filter based on a field of that model, but what about a "calculated" field like this:
```
class NewsItem(models.Model):
headline = models.CharField(max_length=4096, blank=False)
byline_1 = models.CharField(max_length=4096, blank=True)
dateline = models.DateTimeField(help_text=_("date/time that appears on article"))
body_copy = models.TextField(blank=False)
when_to_publish = models.DateTimeField(verbose_name="When to publish", blank=True, null=True)
# HOW CAN I HAVE "is_live" as part of the admin filter? It's a calculated state!!
def is_live(self):
if self.when_to_publish is not None:
if ( self.when_to_publish < datetime.now() ):
return """ <img alt="True" src="/media/img/admin/icon-yes.gif"/> """
else:
return """ <img alt="False" src="/media/img/admin/icon-no.gif"/> """
is_live.allow_tags = True
```
---
```
class NewsItemAdmin(admin.ModelAdmin):
form = NewsItemAdminForm
list_display = ('headline', 'id', 'is_live')
list_filter = ('is_live') # how can i make this work??
``` | Thanks to gpilotino for giving me the push into the right direction for implementing this.
I noticed the question's code is using a datetime to figure out when its live . So I used the DateFieldFilterSpec and subclassed it.
```
from django.db import models
from django.contrib.admin.filterspecs import FilterSpec, ChoicesFilterSpec,DateFieldFilterSpec
from django.utils.encoding import smart_unicode
from django.utils.translation import ugettext as _
from datetime import datetime
class IsLiveFilterSpec(DateFieldFilterSpec):
"""
Adds filtering by future and previous values in the admin
filter sidebar. Set the is_live_filter filter in the model field attribute
'is_live_filter'. my_model_field.is_live_filter = True
"""
def __init__(self, f, request, params, model, model_admin):
super(IsLiveFilterSpec, self).__init__(f, request, params, model,
model_admin)
today = datetime.now()
self.links = (
(_('Any'), {}),
(_('Yes'), {'%s__lte' % self.field.name: str(today),
}),
(_('No'), {'%s__gte' % self.field.name: str(today),
}),
)
def title(self):
return "Is Live"
# registering the filter
FilterSpec.filter_specs.insert(0, (lambda f: getattr(f, 'is_live_filter', False),
IsLiveFilterSpec))
```
To use you can put the above code into a filters.py, and import it in the model you want to add the filter to | you have to write a custom FilterSpec (not documentend anywhere).
Look here for an example:
<http://www.djangosnippets.org/snippets/1051/> | Custom Filter in Django Admin on Django 1.3 or below | [
"",
"python",
"django",
"django-admin",
""
] |
I have a login page. In my web.config I setup a loginUrl so that if a user tries to go to an "Authorized" page and are not authorized they will get redirected to the login page.
Now I noticed when this happens and the user gets redirected from a "Authorized" page the url from the page they are getting redirected from gets appended to the login url.
So that way when they do login I can use that I can send them back to the page they where trying to get too.
So this is how the Url would look:
<http://localhost:2505/CMS_Account/LogOn?ReturnUrl=%2fCMS_Home%2fIndex>
So I am trying to capture the ReturnUrl querystring part as a parameter in my View.
But I can't get it took work.
So I found out if I change my Form for the login to this:
```
<% using (Html.BeginForm()) ........
```
Then I can capture the ReturnURl for some reason no problem.
However how I have it right now I have this:
```
<% using (Html.BeginForm("Login","Authentication",FormMethod.Post,new { id = "frm_Login"})) .....
```
Once I try to pass the parameters into the BeginForm it stops capturing the ReturnUrl.
I don't know why it stops. Some people say that it is because I am using the default route and somehow if you don't put anything in the beingForm it magically can figure out the ReturnUrl with the default url.
Soon as you put something in BeginForm it seems to get dumb and you need to give it a route to tell it what to do.
I don't know how to write this route though. I tried quite a few different combinations and they all failed and everyone who tells me right a route never tell me how it should look like.
So I don't know what to try anymore.
What I tried
```
routes.MapRoute(
"CMS_Account", // Route name
"CMS_Account/{action}/{ReturnUrl}", // URL with parameters
new { controller = "CMS_Account", action = "LogOn",} // Parameter defaults
);
routes.MapRoute(
"CMS_Account", // Route name
"CMS_Account/{action}/{ReturnUrl}", // URL with parameters
new { controller = "CMS_Account", action = "LogOn", ReturnUrl = ""} // Parameter defaults
);
routes.MapRoute(
"CMS_Account", // Route name
"{controller}/{action}/{ReturnUrl}", // URL with parameters
new { controller = "CMS_Account", action = "LogOn", ReturnUrl = ""} // Parameter defaults
);
routes.MapRoute(
"CMS_Account", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "CMS_Account", action = "LogOn", id = ""} // Parameter defaults
);
routes.MapRoute(
"CMS_Account", // Route name
"{controller}/{action}/", // URL with parameters
new { controller = "CMS_Account", action = "LogOn"} // Parameter defaults
);
``` | You don't need to change your routes. The cool thing with the routing engine is that if you add an additional route value that isn't declared in the route itself, the routing engine will throw it on the end as a get variable.
E.g. Have you tried putting the ReturnUrl into BeginFrom?
Controller as Dennis suggested:
```
public ActionResult LogOn(string ReturnURL) {
ViewData["ReturnURL"] = ReturnURL;
return View();
}
```
Then in your view you'll need to use the BeginForm(string action, string controller, object routeValues, FormMethod method, object htmlAttributes) overload. E.g.
```
Html.BeginForm("Login",
"Authentication",
new { @returnUrl = ViewData["ReturnUrl"] },
FormMethod.Post,
new { @id = "frm_Login" })
```
HTHs,
Charles
EDIT: Just on a side note, the other way around it would be to put the ReturnUrl into a hidden input field - after initial getting it from the querystring. This means the value is then in your post collection and you don't have to worry about getting it back into your querystring. | You don't need to alter your routes.
The easiest way to get the ReturnURL parameter (or any other query string parameter) is to add it to your `LogOn` action like so:
```
public ActionResult LogOn(string ReturnURL) {
ViewData["ReturnURL"] = ReturnURL;
return View();
}
``` | Having trouble with Asp.net MVC passing in a querystring as a parameter | [
"",
"c#",
"asp.net-mvc",
""
] |
I'm looking to see if there is an official enumeration for months in the .net framework.
It seems possible to me that there is one, because of how common the use of month is, and because there are other such enumerations in the .net framework.
For instance, there is an enumeration for the days in the week, System.DayOfWeek, which includes Monday, Tuesday, etc..
I'm wondering if there is one for the months in the year, i.e. January, February, etc?
Does anyone know? | There isn't, but if you want the name of a month you can use:
```
CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName (DateTime.Now.Month);
```
which will return a string representation (of the current month, in this case). Note that `GetMonth` takes arguments from 1 to 13 - January is 1, 13 is a blank string. | No, there isn't. | Is there a predefined enumeration for Month in the .NET library? | [
"",
"c#",
".net",
"datetime",
"enumeration",
""
] |
In a web app I am working on, the user can create a zip archive of a folder full of files. Here here's the code:
```
files = torrent[0].files
zipfile = z.ZipFile(zipname, 'w')
output = ""
for f in files:
zipfile.write(settings.PYRAT_TRANSMISSION_DOWNLOAD_DIR + "/" + f.name, f.name)
downloadurl = settings.PYRAT_DOWNLOAD_BASE_URL + "/" + settings.PYRAT_ARCHIVE_DIR + "/" + filename
output = "Download <a href=\"" + downloadurl + "\">" + torrent_name + "</a>"
return HttpResponse(output)
```
But this has the nasty side effect of a long wait (10+ seconds) while the zip archive is being downloaded. Is it possible to skip this? Instead of saving the archive to a file, is it possible to send it straight to the user?
I do beleive that torrentflux provides this excat feature I am talking about. Being able to zip GBs of data and download it within a second. | Check this [Serving dynamically generated ZIP archives in Django](https://stackoverflow.com/questions/67454/serving-dynamically-generated-zip-archives-in-django) | As mandrake says, constructor of HttpResponse accepts iterable objects.
Luckily, ZIP format is such that archive can be created in single pass, central directory record is located at the very end of file:

(Picture from [Wikipedia](http://en.wikipedia.org/wiki/Zip_%28file_format%29#Structure))
And luckily, `zipfile` indeed doesn't do any seeks as long as you only add files.
Here is the code I came up with. Some notes:
* I'm using this code for zipping up a bunch of JPEG pictures. There is no point *compressing* them, I'm using ZIP only as container.
* Memory usage is O(size\_of\_largest\_file) not O(size\_of\_archive). And this is good enough for me: many relatively small files that add up to potentially huge archive
* This code doesn't set Content-Length header, so user doesn't get nice progress indication. It *should be possible* to calculate this in advance if sizes of all files are known.
* Serving the ZIP straight to user like this means that resume on downloads won't work.
So, here goes:
```
import zipfile
class ZipBuffer(object):
""" A file-like object for zipfile.ZipFile to write into. """
def __init__(self):
self.data = []
self.pos = 0
def write(self, data):
self.data.append(data)
self.pos += len(data)
def tell(self):
# zipfile calls this so we need it
return self.pos
def flush(self):
# zipfile calls this so we need it
pass
def get_and_clear(self):
result = self.data
self.data = []
return result
def generate_zipped_stream():
sink = ZipBuffer()
archive = zipfile.ZipFile(sink, "w")
for filename in ["file1.txt", "file2.txt"]:
archive.writestr(filename, "contents of file here")
for chunk in sink.get_and_clear():
yield chunk
archive.close()
# close() generates some more data, so we yield that too
for chunk in sink.get_and_clear():
yield chunk
def my_django_view(request):
response = HttpResponse(generate_zipped_stream(), mimetype="application/zip")
response['Content-Disposition'] = 'attachment; filename=archive.zip'
return response
``` | Create zip archive for instant download | [
"",
"python",
"django",
"zip",
"archive",
""
] |
I was told that using javascript to submit in either asp or asp.net causes a faster submit. Is this true or is there no significant difference? | There should be a slight overhead doing it with Javascript, and it depends on client machine performance. | I wouldn't think so? Your browser would have the extra overhead of executing your JS (depending on how complicated your JS is) and then submitting the form. I would want to think that submitting a form the classic way is faster than submitting the form using JS.
And, your server side technology should not really matter (asp/asp.net/jsp/whateva)- it is unrelated to JS. | Is submitting a form in javascript significantly faster than server-side submitting? | [
"",
"asp.net",
"javascript",
"asp-classic",
""
] |
I'm designing a personal project which is largely database driven. I'm trying to come up with a good design for how to handle database interop, and I'd like the input of the experienced minds here at StackOverflow.
Is the following good design, or is there a more standard way of handling communication with the database?
**EDIT**
I was mainly looking for feedback on whether it was usual to break up the connection details into their own base class, with subclasses for logical units/classes.
To that end, I've modified the code below to add a retrieval method to complement the insertion method in the original question. I've also modified it to show that it takes/returns (depending on the method) business objects.
For instance, in the example we use the Employee class throughout the application, but have an EmployeeDb class (inherited from Database) which handles its persistence to/from the database.
I like this because it keeps storage implementation details out of the business objects, but dislike it because it strongly couples the Employee and EmployeeDB classes.
```
// Abstract Base Class to handle specifics of the database connection
abstract class Database : IDisposable
{
protected OleDbConnection m_Conn;
public bool Open()
{
// Open a connection to the database
}
public void Dispose()
{
if (m_Conn != null)
{
m_Conn.Dispose();
}
}
}
// Specific classes for each table, with methods for CRUD functions
class EmployeeDB : Database
{
public bool AddTestData(Employee emp)
{
// Construct SQL to add Employee class members to the DB, breaking
// them out into their component tables as needed
}
public List<Employee> GetEmployeeByProject(string project)
{
// Retrieve recordset of all employees on the project,
// breaking them out into instances of the Employee class
// Add each new Employee object to a list, and return the list
// to the caller.
}
}
// Specific classes for each table (or logical unit, since obviously
// most of the time we'll need to join a few tables to get what
// we want), with methods for CRUD functions
void AddSomethingToTheDatabase()
{
using (TestDataDB td = new TestDataDB())
{
td.Open(Application.StartupPath);
string NewID = td.AddTestData(txtAddMe.Text);
}
}
``` | Are you sure you don't want to try an [Object Relational Mapper](http://en.wikipedia.org/wiki/Object-relational_mapping)?
Maybe [Linq to SQL](http://weblogs.asp.net/scottgu/archive/2007/05/19/using-linq-to-sql-part-1.aspx) or [nHibernate](https://www.hibernate.org/343.html)? | There are lots of ways of doing this, and the vast majority of OO folks will disagree with mine.
I suggest you take a more relational approach, and instead of having classes for tables, have classes for relations. In relational theory, the result of a query is a relation just like the relations that were used in the query; in fact you never see anything but results of queries, since even to get the contents of a table you need to `SELECT * FROM x`, which is applying the identity function to it.
So do your queries using the relational language you already have at your disposal (building up a framework to write the queries for you, if you need to go that far), and the results of queries should be your classes or, if you're not working in a language where it's easy to create new classes on the fly, some other sort of structure (such as objects). Then you simply use those results directly. | Modelling database tables into classes | [
"",
"c#",
".net",
"database",
""
] |
I have an ASP.NET App that uses a .NET library. I want to enable logging to somewhere to check later the error messages.
I will log ASP.NET app and .NET library, to the same place or to different places. I don't know how to do it.
I prefer to use System.Diagnostics. from .NET Framework instead of 3rd party frameworks, but I don't know if this is the better solution.
I want to log error messages and, sometimes, custom messages.
Thank you! | There are plenty logging frameworks for .NET, If you want to have powerful and flexible logging in your application then you should use [one of 3rd party frameworks](https://stackoverflow.com/questions/126540/what-is-your-net-logging-framework-of-choice), I prefer log4net. There are also several ways for doing this using only classes of .Net Framework.
For example you can use these approaches:
1. The simplest way will be creation of your personal implementation of logger, for example you can just use File.AppendAllText at the place you want to log something to somewhere. If you want to use SQL database as a storage for your log entries you can use SqlCommand class filled with appropriate insert query or you can define another way of logging. But this way isn't recommended because there are many chances that others who will support your code will know usage of well known frameworks & practices and there aren't any chances that they will know your implementation, so they probably will need to read bigger amount of code.
2. You can use EventLog class. We have used it to log critical errors (like unhandled exceptions) happened in our services and ASP.NET applications. It will allow you to have unconditional logging to system wide storage. That storage will be accessible from Microsoft Management Console (mmc) and that storage will be configurable.
3. You can also use something like Debug.WriteLine or Trace.WriteLine for logging. In that case you will have ability to configure log listeners via editing of web.config file. You will have ability to enable or disable of logging, change ways of logging (log to file, to event log or to something else). | I have been using [ELMAH](http://code.google.com/p/elmah/) for about a year now, and it's been a great tool. ELMAH captures any unhandled exception in your .NET app, and can log to a db, xml, or send an email to you with stack trace info.
This [dotnetslackers](http://dotnetslackers.com/articles/aspnet/ErrorLoggingModulesAndHandlers.aspx) [article](http://dotnetslackers.com/articles/aspnet/ErrorLoggingModulesAndHandlers.aspx) was a great start to get me up and running. I've used ELMAH in about 6 projects over the past year with great results. Configuration is easy. It's all done by referencing the .dll in your web project, then setting values in the web.config file. The debug info captured is very detailed. You get the full stack trace and a capture of all server variables for the request at the time. | .NET Debug log | [
"",
"c#",
"logging",
""
] |
I'm starting a C++ project using OpenGL and Qt for the UI in eclipse. I would like to create a UI where a portion of the window contains a frame for OpenGL rendering and the rest would contain other Qt widgets such as buttons and so on.
I haven't used Qt or the GUI editor in eclipse before and I'm wondering what the best approach would be? Should I create the UI by hand coding or would it be easier to use eclipse's GUI designer - I had a quick look at this and there doesn't seem to be an OpenGL widget built in.
Thanks | If you are using Qt Designer (which I think is available via Eclipse Integration), you can place a base QWidget in the layout and then "promote" that widget to a QGLWidget. To do this:
1. Add the QWidget to the desired place in the layout
2. Right-click on the widget
3. Select "Promote To"
4. Enter QGLWidget as the class name and as the header
5. Hit *Add*
6. Select the QGLWidget from the list of promoted widgets at the top of the dialog
7. Hit *Promote*
This way you don't have to go through the placeholder route and create an additional layer. | Why won't you use [Qt Eclipse Integration](http://www.qtsoftware.com/developer/eclipse-integration)? It works flawlessly, enables you to edit UIs directly from Eclipse. | Designing a Qt + OpenGL application in Eclipse | [
"",
"c++",
"eclipse",
"user-interface",
"qt",
"opengl",
""
] |
In my particular case:
```
callback instanceof Function
```
or
```
typeof callback == "function"
```
does it even matter, what's the difference?
**Additional Resource:**
JavaScript-Garden [typeof](http://bonsaiden.github.com/JavaScript-Garden/#types.typeof) vs [instanceof](http://bonsaiden.github.com/JavaScript-Garden/#types.instanceof) | ### Use `instanceof` for custom types:
```
var ClassFirst = function () {};
var ClassSecond = function () {};
var instance = new ClassFirst();
typeof instance; // object
typeof instance == 'ClassFirst'; // false
instance instanceof Object; // true
instance instanceof ClassFirst; // true
instance instanceof ClassSecond; // false
```
### Use `typeof` for simple built in types:
```
'example string' instanceof String; // false
typeof 'example string' == 'string'; // true
'example string' instanceof Object; // false
typeof 'example string' == 'object'; // false
true instanceof Boolean; // false
typeof true == 'boolean'; // true
99.99 instanceof Number; // false
typeof 99.99 == 'number'; // true
function() {} instanceof Function; // true
typeof function() {} == 'function'; // true
```
### Use `instanceof` for complex built in types:
```
/regularexpression/ instanceof RegExp; // true
typeof /regularexpression/; // object
[] instanceof Array; // true
typeof []; //object
{} instanceof Object; // true
typeof {}; // object
```
And the last one is a little bit tricky:
```
typeof null; // object
``` | Both are similar in functionality because they both return type information, however I personally prefer `instanceof` because it's comparing actual types rather than strings. Type comparison is less prone to human error, and it's technically faster since it's comparing pointers in memory rather than doing whole string comparisons. | What is the difference between typeof and instanceof and when should one be used vs. the other? | [
"",
"javascript",
"instanceof",
"typeof",
""
] |
I'd like to set up eclipse with a bunch of plugins and DB connection configurations, etc and re-zip it up so my team-mates and new starters can all be working on the same platform easily.
It seems that installing plugins is fine, but when I add in custom jars (e.g. ivy2, ojdbc, etc) they all save with full, absolute paths which probably dont exist on others machines (particularly if they unzip in a different location to me).
Anyway, I'm hoping that this idea is not silly and am working if this sort of process is documented somewhere or if anyone has any tips in general.
Thanks, | I would recommend against requiring all developers to place eclipse in the same location. There are times when some developers may want to try an alternate version of eclipse to explore a technology that requires a different set of plugins or a different eclipse base version.
Let developers install eclipse where they would like.
However, for jars that you need to run plugins (external dependencies that you need to configure for proper plugin usage):
Hardwire a directory *for those jars* (as opposed to the entire eclipse dir), like c:\eclipse-helpers or something.
---
To deal with third-party library dependencies (in the code you're developing), you have a few good choices:
1. Create project(s) to hold the third-party libs and check them into your source version control system (which you *are* using, right?). You can then add the libs to the build path(s) of the project(s) - make sure you mark them for export in the "order and export" tab of the build path page. You can then simply add these third-party projects as project dependencies.
2. Reference the third-party jars as CLASSPATH *variables* when adding them to the build path of your projects. This allows other developers to store the dependencies in different locations. Perhaps define a CLASSPATH variable (in eclipse's Window->Preferences->Java->Build Path->Classpath Variables) called THIRD\_PARTY\_JARS; each developer can map it to a different path where they want to hold their deps.
3. Reference the third-party jars as a "user library" (Window->Preferences->Java->Build Path->User library). This is similar to classpath variables, but acts as an explicit set of jars.
4. Include the third-party jars directly in your projects. Use this option only if you need the deps in a single location. | Although not exactly in line with the direction of the question, you could use [Yoxos OnDemand](http://eclipsesource.com/en/yoxos/yoxos-ondemand/). It allows you to "roll-your-own" Eclipse distro and download it as a zip. They add in their own perspective where you can add more plugins (direct from their repo), or update the plugins that you have.
Although I've never used the feature, you can make make your own stacks and name them, allowing anyone to go to the site later and download it (with the most up-to-date versions of the plugins). Also, dependencies for plugins are resolved automatically if need be. | how to repackage eclipse for my team | [
"",
"java",
"eclipse",
"ide",
""
] |
Is there a better way to engineer a `sleep` in JavaScript than the following `pausecomp` function ([taken from here](http://www.sean.co.uk/a/webdesign/javascriptdelay.shtm))?
```
function pausecomp(millis)
{
var date = new Date();
var curDate = null;
do { curDate = new Date(); }
while(curDate-date < millis);
}
```
This is not a duplicate of [Sleep in JavaScript - delay between actions](https://stackoverflow.com/questions/758688/sleep-in-javascript-delay-between-actions); I want a *real sleep* in the middle of a function, and not a delay before a piece of code executes. | ## 2017 — 2021 update
Since 2009 when this question was asked, JavaScript has evolved significantly. All other answers are now obsolete or overly complicated. Here is the current best practice:
```
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
```
Or as a one-liner:
```
await new Promise(r => setTimeout(r, 2000));
```
As a function:
```
const sleep = ms => new Promise(r => setTimeout(r, ms));
```
or in Typescript:
```
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
```
use it as:
```
await sleep(<duration>);
```
### Demo:
```
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function demo() {
for (let i = 0; i < 5; i++) {
console.log(`Waiting ${i} seconds...`);
await sleep(i * 1000);
}
console.log('Done');
}
demo();
```
Note that,
1. `await` can only be executed in functions prefixed with the `async` keyword, or at the top level of your script in [an increasing number of environments](https://stackoverflow.com/questions/46515764/how-can-i-use-async-await-at-the-top-level/56590390#56590390).
2. `await` only pauses the current `async` function. This means it does not block the execution of the rest of the script, which is what you want in the vast majority of the cases. If you do want a blocking construct, see [this answer](https://stackoverflow.com/questions/951021/what-is-the-javascript-version-of-sleep/56406126#56406126) using [`Atomics`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Atomics)`.wait`, but note that most browsers will not allow it on the browser's main thread.
Two new JavaScript features (as of 2017) helped write this "sleep" function:
* [Promises, a native feature of ES2015](https://ponyfoo.com/articles/es6-promises-in-depth) (aka ES6). We also use [arrow functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) in the definition of the sleep function.
* The [`async/await`](https://ponyfoo.com/articles/understanding-javascript-async-await) feature lets the code explicitly wait for a promise to settle (resolve or reject).
## Compatibility
* promises are supported [in Node v0.12+](http://node.green/#Promise) and [widely supported in browsers](http://caniuse.com/#feat=promises), except IE
* `async`/`await` landed in V8 and has been [enabled by default since Chrome 55](https://developers.google.com/web/fundamentals/getting-started/primers/async-functions) (released in Dec 2016)
+ it landed [in Node 7 in October 2016](https://blog.risingstack.com/async-await-node-js-7-nightly/)
+ and also landed [in Firefox Nightly in November 2016](https://blog.nightly.mozilla.org/2016/11/01/async-await-support-in-firefox/)
If for some reason you're using Node older than 7 (which reached [end of life in 2017](https://github.com/nodejs/Release#end-of-life-releases)), or are targeting old browsers, `async`/`await` can still be used via [Babel](https://babeljs.io/) (a tool that will [transpile](https://www.stevefenton.co.uk/2012/11/compiling-vs-transpiling/) JavaScript + new features into plain old JavaScript), with the [`transform-async-to-generator`](https://babeljs.io/docs/en/babel-plugin-transform-async-to-generator) plugin. | (See the [updated answer for 2016](https://stackoverflow.com/a/39914235/11236))
I think it's perfectly reasonable to want to perform an action, wait, and then perform another action. If you are used to writing in multi-threaded languages, you probably have the idea of yielding execution for a set amount of time until your thread wakes up.
The issue here is that JavaScript is a single-thread event-based model. While in a specific case, it might be nice to have the whole engine wait for a few seconds, in general it is bad practice. Suppose I wanted to make use of your functions while writing my own? When I called your method, my methods would all freeze up. If JavaScript could somehow preserve your function's execution context, store it somewhere, then bring it back and continue later, then sleep could happen, but that would basically be threading.
So you are pretty much stuck with what others have suggested -- you'll need to break your code up into multiple functions.
Your question is a bit of a false choice, then. There is no way to sleep in the way you want, nor should you pursue the solution you suggest. | What is the JavaScript version of sleep()? | [
"",
"javascript",
"sleep",
""
] |
I'd like to find out the arity of a method in Python (the number of parameters that it receives).
Right now I'm doing this:
```
def arity(obj, method):
return getattr(obj.__class__, method).func_code.co_argcount - 1 # remove self
class Foo:
def bar(self, bla):
pass
arity(Foo(), "bar") # => 1
```
I'd like to be able to achieve this:
```
Foo().bar.arity() # => 1
```
**Update**: Right now the above function fails with built-in types, any help on this would also be appreciated:
```
# Traceback (most recent call last):
# File "bla.py", line 10, in <module>
# print arity('foo', 'split') # =>
# File "bla.py", line 3, in arity
# return getattr(obj.__class__, method).func_code.co_argcount - 1 # remove self
# AttributeError: 'method_descriptor' object has no attribute 'func_co
``` | Module `inspect` from Python's standard library is your friend -- see [the online docs](http://docs.python.org/library/inspect.html)! `inspect.getargspec(func)` returns a tuple with four items, `args, varargs, varkw, defaults`: `len(args)` is the "primary arity", but arity can be anything from that to infinity if you have `varargs` and/or `varkw` not `None`, and some arguments may be omitted (and defaulted) if `defaults` is not `None`. How you turn that into a single number, beats me, but presumably you have your ideas in the matter!-)
This applies to Python-coded functions, but not to C-coded ones. Nothing in the Python C API lets C-coded functions (including built-ins) expose their signature for introspection, except via their docstring (or optionally via **annotations** in Python 3); so, you *will* need to fall back to docstring parsing as a last ditch if other approaches fail (of course, the docstring might be missing too, in which case the function will remain a mystery). | Use a decorator to decorate methods e.g.
```
def arity(method):
def _arity():
return method.func_code.co_argcount - 1 # remove self
method.arity = _arity
return method
class Foo:
@arity
def bar(self, bla):
pass
print Foo().bar.arity()
```
Now implement `_arity` function to calculate arg count based on your needs | How to find out the arity of a method in Python | [
"",
"python",
"metaprogramming",
""
] |
I have an ASP.NET app with a three layer architecture:
* Presentation layer: ASP.NET
* Bussiness Layer: C# library.
* Data Access Layer: C# library with
ADO.Net Entity Framework objects.
Some methods on Bussiness layer would return ADO.NET entity objects but, data access layer is not visible at Presentation layer I can't do that.
My question is: On a design view, Is it correct to expose Entity Objects in the Presentation Layer? I think I only have to link Data Layer library with ASP.NET app.
Thank you! | I suggest that you look into the concepts of View objects...or Data Transfer Objects (DTO). You might consider using a tool like AutoMapper or similar which will create a view specific domain object out of your entities. In general you may have screens that need an entity present to perform its work. But more often than not you will need to pass several different entities. In this case you are better off creating one DTO that contains all of these entities. By doing this you are adding a layer of separation between your presentation layer and your business layer. Often times your entities have more power than you might want to expose to your presentation layer. And...vice versa. Frequently you may need to get some UI messages out to the presentation layer based on some validation flagged in your business layer. Rather than make your ui more complex than it needs to be (by passing in your full entities) you can only pass in what the UI needs in the form of the DTO. Also, there is never a need for your business objects to care about anything specific to the presentation layer. I suggest that you not databind directly to anything as far back as the data access layer. Technically your presentation layer should know as little as possible about your business layer. In the case of MVP or MVC this is very easy to achieve by disconnecting the front end and the back end by way of this additional separation! | It's absolutely desirable to have your entity objects available for use and consumption in your presentation tier. That's what all the work is for.
* Binding collection of objects to a grid/listview/dropdown
* Splashing a single object (i.e. customer) onto a form for read/update/delete
This makes your life easier by far. Otherwise you'd have to pass string after int after double after string between your presentation and business layers.
These may be Entity objects or even your own POCO objects that were hydrated from the Entity objects.
I would even go so far as to say that your Entites should be in their own assembly separate from the DAL. | Three tier architecture question | [
"",
"c#",
"entity-framework",
"three-tier",
""
] |
I've always wanted to be able to use the line below but the C# compiler won't let me. To me it seems obvious and unambiguos as to what I want.
```
myString.Trim({'[', ']'});
```
I can acheive my goal using:
```
myString.Trim(new char[]{'[', ']'});
```
So I don't die wondering is there any other way to do it that is closer to the first approach? | The `string.Trim(...)` method actually takes a `params` argument, so, why do you not just call:
```
myString.Trim('[', ']');
``` | Others have concentrated on the specific example (and using the fact that it's a parameter array is the way to go), but you may be interested in C# 3's implicit typing. You *could* have written:
```
myString.Trim(new[] {'[', ']'});
```
Not *quite* as compact as you were after, as you still need to express the concept of "I want to create an array" unless you're writing a variable initializer, but the type of the array is inferred from the contents.
The big use case for this is anonymous types:
```
var skeets = new[] {
new { Name="Jon", Age=32 },
new { Name="Holly", Age=33 },
new { Name="Tom", Age=5 },
new { Name="Robin", Age=3 },
new { Name="William", Age=3 }
};
```
Here you *couldn't* write the name of the type, because it doesn't have a name (that's expressible in C#).
One other point to make about your specific example - if you're going to use this frequently (i.e. call the `Trim` method often) you may want to avoid creating a new array each time anyway:
```
private static readonly char[] SquareBrackets = {'[', ']'};
public void Whatever() {
...
foo = myString.Trim(SquareBrackets);
...
}
``` | Minimalist array creation in c# | [
"",
"c#",
"arrays",
""
] |
For an application we are working on I need to generate sample credit card numbers which pass the Luhn algorithm but which are also unique, so we cannot use the sample credit card numbers.
We need to be able to generate around 300 card numbers at a time, and ideally i would be able to do this when generating my input data.
Many Thanks | Create random numbers, then calculate the checksum number.
You can find more information at [Wikipedia - Luhn](http://en.wikipedia.org/wiki/Luhn), both details about the algorithm and links to different implementations. | From what I see you just need to ensure that when running through the algorithm you get a result of 0 (mod 10). So you can pick any number of random digits (or sequential if you like) and just add one last digit which will ensure that the number is valid. | Does anyone know where there is c# code or a dll which can generate sample credit card numbers | [
"",
"c#",
".net",
"credit-card",
"luhn",
""
] |
The default Django's `User` model has some fields, and validation rules, that I don't really need. I want to make registration as simple as possible, i.e. require either email or username, or phone number - all those being unique, hence good as user identifiers.
I also don't like default character set for user name that is validated in Django user model. I'd like to allow any character there - why not?
I used user-profile django application before to add a profile to user - but this time I'd rather make the class mimimal. But I still want to use the `User` class, as it gives me an easy way to have parts of site restricted only for users logged in.
How do I do it? | Rather than modify the User class directly or do subclassing, you can also just repurpose the existing fields.
For one site I used the "first\_name" field as the "publicly displayed name" of a user and stuff a slugified version of that into the "username" field (for use in URLs). I wrote a custom auth backend to allow people to log in using their "public name" or their email address, and I enforce the uniqueness of both of those at registration time. This plays nicely with other reusable apps and doesn't introduce extra tables or queries.
For another site I didn't want usernames at all, just unique emails. In order to satisfy Django's need for a unique username, I just hashed the email address and used that as the username (you have to base64-encode the hash to squeeze it under 30 characters). Custom auth backend to allow login with email.
If backwards-compatibility weren't an issue, there are a lot of improvements I'd love to see made to django.contrib.auth and the User model to make them more flexible. But there's quite a lot you can do inside the current constraints with a little creativity. | **I misread the question. Hope this post is helpful to anyone else.**
```
#in models.py
from django.db.models.signals import post_save
class UserProfile(models.Model):
user = models.ForeignKey(User)
#other fields here
def __str__(self):
return "%s's profile" % self.user
def create_user_profile(sender, instance, created, **kwargs):
if created:
profile, created = UserProfile.objects.get_or_create(user=instance)
post_save.connect(create_user_profile, sender=User)
#in settings.py
AUTH_PROFILE_MODULE = 'YOURAPP.UserProfile'
```
This will create a userprofile each time a user is saved if it is created.
You can then use
```
user.get_profile().whatever
```
Here is some more info from the docs
<http://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information-about-users> | How to change default django User model to fit my needs? | [
"",
"python",
"django",
"django-models",
""
] |
I'm starting to design a config and settings component for an application.
I need an easy way to read dictionary style settings and also a way to store simple arrays into a persistence level.
is there a commonly used component already available ? (something like log4net for logging)
what options should I look into ? | Take a look at App.Config and the [ConfigurationManager class](http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.aspx). | You don't really need to do that: .NET BCL already [has](http://msdn.microsoft.com/en-us/library/system.configuration.aspx) everything you need. | config and settings component for C# | [
"",
"c#",
""
] |
I am debugging [codeplex simple project](http://www.codeplex.com/sl2videoplayer). I am using
* VSTS 2008
* C#
* Windows Vista x86 Enterprise.
I have not modified any code of this codeplex project, and just press F5 to run VideoPlayerWeb project.
The current issue I met with is error message --
> Unable to connect to ASP.Net Development Server.
Here is my screen snapshots when clicking F5. Any ideas what is wrong?
[](https://i.stack.imgur.com/xggYG.jpg)
[](https://i.stack.imgur.com/fC9g0.jpg) | I had this problem with VS 2010, and it was as simple as terminating the "WebDev.WebServer40.EXE" process. Although the icon was no longer showing in the system tray, the process was still running. | Could be a number of things...try these (check the last one first)...
* Disable IPv6
* Make sure there isnt an edit in the
hosts file for localhost
* Check firewall/virus settings to allow connections to/from
devenv.exe
* If you can preview in the browser
make sure the URL in the browser uses
the same port number as the port
number shown in the ASP.NET dev
server taskbar icon.
* Try setting a fixed, predefined port
in project properties
I got these from a couple of forums elsewhere, hopefully they can help. Good luck. Let us know what works and some more about your environment (firewall, anti virus etc) can help as well. | Unable to connect to ASP.Net Development Server issue | [
"",
"c#",
"asp.net",
"visual-studio-2008",
"debugging",
""
] |
Using the update command, I want to change the `type_name` for a specific entry in the database, but it is changing the `type_name` for all the entries with the same `type_id`.
I need it to only change that individual entry's `type_name`, and not the `type_name` that is associated with all the entries with the same `type_id`.
I have an update query:
```
$sql = 'UPDATE photos
LEFT JOIN types
ON photos.type_id = types.type_id
SET photos.photo_title = $_POST['photo_title'],
types.type_name = $_POST['type_name']
WHERE photos.photo_id = 3';
```
Here's the form I'm using:
```
<form name="form1" method="post" action="">
<input name="photo_title" type="text" value=""/>
<textarea name="type_name"></textarea>
<input type="submit" name="update" value="Update entry" />
</form>
```
Here's my database structure:
TABLE photos
* photo\_id PRIMARY KEY
* photo\_title
* type\_id FOREIGN KEY
TABLE types
* type\_id PRIMARY KEY
* type\_name | What is happening is that your join is producing the wrong set of data. You're joining the photos and types on type\_id.
Now what you seem to be describing is that the types column may contain multiple rows with the same type\_\_\_id. What does this mean? It means that your join will produce multiple pairs of `(photos,types)` for each photo (specifically, for each photo, the join will produce n rows, where n is the number of rows in types having the same type\_id as the photo).
As for how to fix this, you should take a look at your database design. You seem to expect a unique row in types for each photo. How is this relationship expressed? That will enable you to get a proper `ON` clause for your join.
**UPDATE**
After looking at the table structure, it seems your database is expressing things slightly differently. As it stands you can have multiple photos with the same type (i.e. their typeid in the photos table is the same). Thus it is a bit meaningless to speak of changing the typename of just one such photo. You're merely updating the typename for a particular type, that happens to be the type of the photo whose name you were also updating.
Now what exactly are you trying to achieve, here?
* If you are trying to re categorize a particular photo, then you instead want to either create a new entry in the types table and point your photo to that new record, or find an existing photo with a matching name and point the photo at that record. (I presume you already have such code in your photo insertion logic. This should be similar)
* If you are trying to update the type description for a photo and all other photos with that type, then what you have will work just fine. | I'm surprised that MySQL allows this, but it looks like you're updating the name in the type table. You're probably looking to update the type\_id of a single row in the photos table.
You could do that like this:
```
UPDATE photos
SET photos.photo_title = $_POST['photo_title'],
photos.type_id = (
select type_id
from types
where type_name = $_POST['type_name']
)
WHERE photos.photo_id = 3
```
Or alternatively:
```
UPDATE photos
LEFT JOIN types ON types.type_id = $_POST['type_name']
SET photos.photo_title = $_POST['photo_title'],
photos.type_id = types.type_id
WHERE photos.photo_id = 3
```
Before you run this query, you could make sure the type\_name exists:
```
REPLACE INTO types (type_name) VALUES ($_POST['type_name'])
``` | Why is my Update command updating all of the fields that have the same ID? | [
"",
"php",
"mysql",
"database",
""
] |
I found solutions for Windows Forms with AppDomain but what would be the equivalent for a WPF `Application` object? | One method:
```
System.AppDomain.CurrentDomain.BaseDirectory
```
Another way to do it would be:
```
System.IO.Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName)
``` | Here is another:
```
System.Reflection.Assembly.GetExecutingAssembly().Location
``` | Getting the application's directory from a WPF application | [
"",
"c#",
".net",
"wpf",
""
] |
my question is rather a design question.
In Python, if code in your "constructor" fails, the object ends up not being defined. Thus:
```
someInstance = MyClass("test123") #lets say that constructor throws an exception
someInstance.doSomething() # will fail, name someInstance not defined.
```
I do have a situation though, where a lot of code copying would occur if i remove the error-prone code from my constructor. Basically my constructor fills a few attributes (via IO, where a lot can go wrong) that can be accessed with various getters. If I remove the code from the contructor, i'd have 10 getters with copy paste code something like :
1. is attribute really set?
2. do some IO actions to fill the attribute
3. return the contents of the variable in question
I dislike that, because all my getters would contain a lot of code. Instead of that I perform my IO operations in a central location, the constructor, and fill all my attributes.
Whats a proper way of doing this? | I'm not a Python developer, but in general, it's best to avoid complex/error-prone operations in your constructor. One way around this would be to put a "LoadFromFile" or "Init" method in your class to populate the object from an external source. This load/init method must then be called separately after constructing the object. | There is a difference between a constructor in C++ and an `__init__` method
in Python. In C++, the task of a constructor is to construct an object. If it fails,
no destructor is called. Therefore if any resources were acquired before an
exception was thrown, the cleanup should be done before exiting the constructor.
Thus, some prefer two-phase construction with most of the construction done
outside the constructor (ugh).
Python has a much cleaner two-phase construction (construct, then
initialize). However, many people confuse an `__init__` method (initializer)
with a constructor. The actual constructor in Python is called `__new__`.
Unlike in C++, it does not take an instance, but
returns one. The task of `__init__` is to initialize the created instance.
If an exception is raised in `__init__`, the destructor `__del__` (if any)
will be called as expected, because the object was already created (even though it was not properly initialized) by the time `__init__` was called.
Answering your question:
> In Python, if code in your
> "constructor" fails, the object ends
> up not being defined.
That's not precisely true. If `__init__` raises an exception, the object is
created but not initialized properly (e.g., some attributes are not
assigned). But at the time that it's raised, you probably don't have any references to
this object, so the fact that the attributes are not assigned doesn't matter. Only the destructor (if any) needs to check whether the attributes actually exist.
> Whats a proper way of doing this?
In Python, initialize objects in `__init__` and don't worry about exceptions.
In C++, use [RAII](http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization).
---
**Update** [about resource management]:
In garbage collected languages, if you are dealing with resources, especially limited ones such as database connections, it's better not to release them in the destructor.
This is because objects are destroyed in a non-deterministic way, and if you happen
to have a loop of references (which is not always easy to tell), and at least one of the objects in the loop has a destructor defined, they will never be destroyed.
Garbage collected languages have other means of dealing with resources. In Python, it's a [with statement](http://www.python.org/dev/peps/pep-0343/). | Bad Practice to run code in constructor thats likely to fail? | [
"",
"python",
"oop",
"exception",
"constructor",
""
] |
I am building some Postgres tables from Python dictionaries where the {'key': 'value'} pairs correspond to column 'key' and field 'value'. These are generated from .dbf files -- I now pipe the contents of the .dbf files into a script that returns a list of dicts like:
```
{'Warngentyp': '', 'Lon': '-81.67170', 'Zwatch_war': '0', 'State':...
```
Currently I am putting these into a sqlite database with no type declarations, then dumping it to a .sql file, manually editing the schema, and importing to Postgres.
I would love to be able to infer the correct type declarations, basically iterate over a list of strings like ['0', '3', '5'] or ['ga', 'ca', 'tn'] or ['-81.009', '135.444', '-80.000'] and generate something like 'int', 'varchar(2)', 'float'. (I would be equally happy with a Python, Postgres, or SQLite tool.)
Is there a package that does this, or a straightforward way to implement it? | YOU DON'T NEED TO INFER THE TYPE DECLARATIONS!!!
You can derive what you want directly from the .dbf files. Each column has a name, a type code (C=Character, N=Number, D=Date (yyyymmdd), L=Logical (T/F), plus more types if the files are from Foxpro), a length (where relevant), and a number of decimal places (for type N).
Whatever software that you used to dig the data out of the .dbf files needed to use that information to convert each piece of data to the appropriate Python data type.
Dictionaries? Why? With a minor amount of work, that software could be modified to produce a CREATE TABLE statement based on those column definitions, plus an INSERT statement for each row of data.
I presume you are using one of the several published Python DBF-reading modules. Any one of them should have the facilities that you need: open a .dbf file, get the column names, get the column type etc info, get each row of data. If you are unhappy with the module that you are using, talk to me; I have an unpublished one that as far as reading DBFs goes, combines the better features of the others, avoids the worst features, is as fast as you'll get with a pure Python implementation, handles all the Visual Foxpro datatypes and the \_NullFlags pseudo-column, handles memoes, etc etc.
HTH
=========
Addendum:
When I said you didn't need to infer types, you hadn't made it plain that you had a bunch of fields of type C which contained numbers.
FIPS fields: some are with and some without leading zeroes. If you are going to use them, you face the '012' != '12' != 12 problem. I'd suggest stripping off the leading zeroes and keeping them in integer columns, restoring leading zeroes in reports or whatever if you really need to. Why are there 2 each of state fips and county fips?
Population: in the sample file, almost all are integer. Four are like 40552.0000, and a reasonable number are blank/empty. You seem to regard population as important, and asked "Is it possible that some small percentage of population fields contain .... ?" Anything is possible in data. Don't wonder and speculate, investigate! I'd strongly advise you to sort your data in population order and eyeball it; you'll find that multiple places in the same state share the same population count. E.g. There are 35 places in New York state whose pop'n is stated as 8,008,278; they are spread over 6 counties. 29 of them have a PL\_FIPS value of 51000; 5 have 5100 -- looks like a trailing zero problem :-(
Tip for deciding between float and int: try anum = float(chars) *first*; if that succeeds, check if int(anum) == anum.
ID: wonderful "unique ID"; 59 cases where it's not an int -- several in Canada (the website said "US cities"; is this an artifact of some unresolved border dispute?), some containing the word 'Number', and some empty.
Low-hanging fruit: I would have thought that deducing that population was in fact integer was 0.1 inches above the ground :-)
There's a serious flaw in that if all([int(value) ... logic:
```
>>> all([int(value) for value in "0 1 2 3 4 5 6 7 8 9".split()])
False
>>> all([int(value) for value in "1 2 3 4 5 6 7 8 9".split()])
True
>>>
```
You evidently think that you are testing that all the strings can be converted to int, but you're adding the rider "and are all non-zero". Ditto float a few lines later.
IOW if there's just one zero value, you declare that the column is not integer.
Even after fixing that, if there's just one empty value, you call it varchar.
What I suggest is: count how many are empty (after normalising whitespace (which should include NBSP)), how many qualify as integer, how many non-integer non-empty ones qualify as float, and how many "other". Check the "other" ones; decide whether to reject or fix; repeat until happy :-)
I hope some of this helps. | Don't use eval. If someone inserts bad code, it can hose your database or server.
Instead use these
```
def isFloat(s):
try:
float(s)
return True
except (ValueError, TypeError), e:
return False
str.isdigit()
```
And everything else can be a varchar | Inferring appropriate database type declarations from strings in Python | [
"",
"python",
"sqlite",
"postgresql",
"types",
""
] |
I'm using [Janrain's PHP-OpenID 2.1.3](http://www.openidenabled.com/php-openid/), and I've managed to get it working with all the providers I have tried except for Google and Yahoo. The major difference here seems to be that Google and Yahoo, unlike most other providers, don't use a user-specific URL, but rather have the user discovery framework all on their end - which throws the default Janrain framework for a loop then it tries to begin the auth request.
From what I've seen it looks like it's probably the YADIS discovery that is throwing the error, which should be able to be bypassed since the discovery is on Google or Yahoo's end, but I'm not sure. This is all a big informal learning experience for me, and I haven't had any luck finding documentation that can help me on this one. Any tips would be greatly appreciated.
**Edit:** the specific problem I am having is that when the begin() function is called for the Google or Yahoo URL, I get a null return. This function is found in Auth/OpenID/Consumer.php for reference. | Ok, I finally got to fix the library... I explained everything [here](http://sourcecookbook.com/en/recipes/60/janrain-s-php-openid-library-fixed-for-php-5-3-and-how-i-did-it) (you can also download the php-openid library after my changes).
I needed to do what Paul Tarjan suggested but, also, I needed to modify the `Auth_OpenID_detectMathLibrary` and add the `static` keyword to a lot of functions. After that It seems to work perfectly although it is not an ideal solution... I think that someone should rewrite the whole library in PHP 5... | I had the same problem on Windows XP. Fixed by activating curl extension. To do this uncomment in php.ini the line
```
extension=php_curl.dll
```
by removing the **;** in front of it if any. Restart apache.
Also on windows to work properly you need to define Auth\_OpenID\_RAND\_SOURCE as null since in windows you don't have a random source. You can do this by adding the line
```
define('Auth_OpenID_RAND_SOURCE', null);
```
in CryptUtil.php before the first code line
```
if(!defined('Auth_OpenID_RAND_SOURCE')){
```
Even if the curl is not enabled the API should work by using instead the Auth\_Yadis\_PlainHTTPFetcher to communicat via HTTP. In the case of Google and Yahoo you need https, so it only works if open\_ssl is enabled (Auth\_Yadis\_PlainHTTPFetcher::supportsSSL must return true). | Janrain's PHP-OpenID and Google/Yahoo | [
"",
"php",
"openid",
"yahoo",
"janrain",
""
] |
User should be redirected to the Login page after registration and after logout. In both cases there must be a message displayed indicating relevant messages.
Using the `django.contrib.auth.views.login` how do I send these {{ info }} messages.
A possible option would be to copy the `auth.views` to new registration module and include all essential stuff. But that doesn't seem DRY enough.
What is the best approach.
### Update: Question elaboration:
For normal cases when you want to indicate to some user the response of an action you can use
```
request.user.message_set.create()
```
This creates a message that is displayed in one of the templates and automatically deletes.
However this message system only works for logged in users who continue to have same session id. In the case of registration, the user is not authenticated and in the case of logout since the session changes, this system cannot be used.
Add to that, the built in `login` and `logout` functions from `django.contrib.auth.views` return a 'HttpResponseRedirect' which make it impossible to add another variable to the template.
I tried setting things on the request object itself
```
request.info='Registered'
```
and check this in a **different view**
```
try:
info = request.info:
del request.info
except:
info = ''
#later
render_to_response('app/file',{'info':info})
```
Even this didn't work.
Clearly I can define a registered.html and add this static message there, but I was being lazy to write another template and trying to implement it DRY.
I realized that the cases were different for "registered" message and "logged out" message. And the DRY approach I used, I shall write as an answer. | I think the best solution to this problem is to use a "flash"-type session-based messaging system. There are several floating around: [django-flash](http://djangoflash.destaquenet.com/) seems really nice, I use [django-session-messages](http://code.google.com/p/django-session-messages/) which is very simple. Hopefully by the time we get to Django 1.2 this'll be baked-in. | If the messages are static you can use your own templates for those views:
```
(r'^accounts/login/$', 'django.contrib.auth.views.login', {'template_name': 'myapp/login.html'}
```
From the [docs](http://docs.djangoproject.com/en/dev/topics/auth/). | django Authentication using auth.views | [
"",
"python",
"django",
"authentication",
"django-authentication",
""
] |
I need a callback function that is almost exactly the same for a series of gui events. The function will behave slightly differently depending on which event has called it. Seems like a simple case to me, but I cannot figure out this weird behavior of lambda functions.
So I have the following simplified code below:
```
def callback(msg):
print msg
#creating a list of function handles with an iterator
funcList=[]
for m in ('do', 're', 'mi'):
funcList.append(lambda: callback(m))
for f in funcList:
f()
#create one at a time
funcList=[]
funcList.append(lambda: callback('do'))
funcList.append(lambda: callback('re'))
funcList.append(lambda: callback('mi'))
for f in funcList:
f()
```
The output of this code is:
```
mi
mi
mi
do
re
mi
```
I expected:
```
do
re
mi
do
re
mi
```
Why has using an iterator messed things up?
I've tried using a deepcopy:
```
import copy
funcList=[]
for m in ('do', 're', 'mi'):
funcList.append(lambda: callback(copy.deepcopy(m)))
for f in funcList:
f()
```
But this has the same problem. | The problem here is the `m` variable (a reference) being taken from the surrounding scope.
Only parameters are held in the lambda scope.
To solve this you have to create another scope for lambda:
```
def callback(msg):
print msg
def callback_factory(m):
return lambda: callback(m)
funcList=[]
for m in ('do', 're', 'mi'):
funcList.append(callback_factory(m))
for f in funcList:
f()
```
In the example above, lambda also uses the surounding scope to find `m`, but this
time it's `callback_factory` scope which is created once per every `callback_factory`
call.
Or with [functools.partial](http://docs.python.org/library/functools.html#functools.partial):
```
from functools import partial
def callback(msg):
print msg
funcList=[partial(callback, m) for m in ('do', 're', 'mi')]
for f in funcList:
f()
``` | When a lambda is created, it doesn't make a copy of the variables in the enclosing scope that it uses. It maintains a reference to the environment so that it can look up the value of the variable later. There is just one `m`. It gets assigned to every time through the loop. After the loop, the variable `m` has value `'mi'`. So when you actually run the function you created later, it will look up the value of `m` in the environment that created it, which will by then have value `'mi'`.
One common and idiomatic solution to this problem is to capture the value of `m` at the time that the lambda is created by using it as the default argument of an optional parameter. You usually use a parameter of the same name so you don't have to change the body of the code:
```
for m in ('do', 're', 'mi'):
funcList.append(lambda m=m: callback(m))
``` | Scope of lambda functions and their parameters? | [
"",
"python",
"lexical-closures",
""
] |
Why is it that I can't have 008 or 009 be keys for a Python dict, but 001-007 are fine?
Example:
```
some_dict = {
001: "spam",
002: "eggs",
003: "foo",
004: "bar",
008: "anything", # Throws a SyntaxError
009: "nothing" # Throws a SyntaxError
}
```
**Update**: Problem solved. I wasn't aware that starting a literal with a zero made it octal. That seems really odd. Why zero? | In python and some other languages, if you start a number with a 0, the number is interpreted as being in octal (base 8), where only 0-7 are valid digits. You'll have to change your code to this:
```
some_dict = {
1: "spam",
2: "eggs",
3: "foo",
4: "bar",
8: "anything",
9: "nothing" }
```
Or if the leading zeros are really important, use strings for the keys. | Python takes 008 and 009 as octal numbers, therefore...invalid.
You can only go up to 007, then the next number would be 010 (8) then 011 (9). Try it in a Python interpreter, and you'll see what I mean. | Why are 008 and 009 invalid keys for Python dicts? | [
"",
"python",
"dictionary",
"python-2.x",
""
] |
I'm compiling from csc.exe (well, CruiseControl is...), and I need to reference a DLL in the GAC. I do not have the correct version of this DLL as a simple file, but there is a correct version in the GAC.
However, you can't reference assemblies in the GAC with csc -- you have to have the path to the actual file.
I've found some references that claim you can reverse engineer the path to the actual file, but I haven't been able to get them work. I fired up Fusion logging, and I can see where the runtime is getting the file from, but using a filepath to that location in my reference does not work.
So, how do you provide csc with a reference to an assembly version that only exists in the GAC? | I had a similar problem. The solution I used was to open a command prompt and change directory to something like the following (change it depending on which assembly you want):
```
C:\WINDOWS\assembly\GAC_MSIL\System.Web.Extensions\3.5.0.0__31bf3856ad364e35\
```
You can then copy the DLL in this directory somewhere outside the GAC. | I'd recommend using Nant or MSBuild and just use the .csproj file generated by visual studio. Then simply get CruiseControl to use your Nant script. Below is an extract from a Nant script I wrote,
```
<csc target="library" output="${basedir}/bin/${basename}.dll" debug="${debug}" optimize="true">
<sources>
<include name="src/app/**/*.cs"/>
</sources>
<references refid="My.Assemblies" />
</csc>
```
and the references
```
<assemblyfileset id="My.Assemblies"><include name="System.dll"></include>
<include name="System.Configuration.dll"></include>
<include name="System.Core.dll"></include>
<include name="System.Data.dll"></include>
<include name="System.Data.DataSetExtensions.dll"></include>
<include name="System.Drawing.dll"></include>
<include name="System.EnterpriseServices.dll"></include>
<include name="System.Web.dll"></include>
<include name="System.Web.Extensions.dll"></include>
<include name="System.Web.Mobile.dll"></include>
<include name="System.Web.Services.dll"></include>
<include name="System.Xml.dll"></include>
<include name="System.Linq.dll"></include>
</assemblyfileset>
``` | How do you use GAC'd assemblies as references with csc.exe? | [
"",
"c#",
"reference",
"csc",
""
] |
As part of a project I'm working on, I'd like to clean up a file I generate of duplicate line entries. These duplicates often won't occur near each other, however. I came up with a method of doing so in Java (which basically made a copy of the file, then used a nested while-statement to compare each line in one file with the rest of the other). The problem, is that my generated file is pretty big and text heavy (about 225k lines of text, and around 40 megs). I estimate my current process to take 63 hours! This is definitely not acceptable.
I need an integrated solution for this, however. Preferably in Java. Any ideas? Thanks! | Hmm... 40 megs seems small enough that you could build a `Set` of the lines and then print them all back out. This would be way, way faster than doing O(n2) I/O work.
It would be something like this (ignoring exceptions):
```
public void stripDuplicatesFromFile(String filename) {
BufferedReader reader = new BufferedReader(new FileReader(filename));
Set<String> lines = new HashSet<String>(10000); // maybe should be bigger
String line;
while ((line = reader.readLine()) != null) {
lines.add(line);
}
reader.close();
BufferedWriter writer = new BufferedWriter(new FileWriter(filename));
for (String unique : lines) {
writer.write(unique);
writer.newLine();
}
writer.close();
}
```
If the order is important, you could use a `LinkedHashSet` instead of a `HashSet`. Since the elements are stored by reference, the overhead of an extra linked list should be insignificant compared to the actual amount of data.
**Edit:** As Workshop Alex pointed out, if you don't mind making a temporary file, you can simply print out the lines as you read them. This allows you to use a simple `HashSet` instead of `LinkedHashSet`. But I doubt you'd notice the difference on an I/O bound operation like this one. | Okay, most answers are a bit silly and slow since it involves adding lines to some hashset or whatever and then moving it back from that set again. Let me show the most optimal solution in pseudocode:
```
Create a hashset for just strings.
Open the input file.
Open the output file.
while not EOF(input)
Read Line.
If not(Line in hashSet)
Add Line to hashset.
Write Line to output.
End If.
End While.
Free hashset.
Close input.
Close output.
```
Please guys, don't make it more difficult than it needs to be. :-) Don't even bother about sorting, you don't need to. | Deleting duplicate lines in a file using Java | [
"",
"java",
"file",
"text",
"file-io",
"duplicates",
""
] |
i need to re-project a series of ariel images that have been referenced in a geographical coordinate system into a UTM projection. I had read that using getPixel and setPixel might be slow - should set up a series of 2 dimensional arrays for intermediate access and then flush the values to the destination image when I am done.
Is this normally this sort of image processing is done by the professionals? | Most image processing is feature detection, segmentation of a scene, fault finding, classification and tracking ....
You might want to take a peek at the book:
1. Image Processing in C (applicable for other languages too)
2. Image Processing - Principles and Applications
Which describes many fast and effective means of many image transformations. These two books helped me when I was processing images :)
If I understand your question ... If you are re-aligning or assembling many images, and you don't have orientation as well as position, you can use these algorithms for re-alignment of edges and common features. If you are stitching by position then these algorithms will help in re-sampling/resizing your images for more efficient assembly. There are also some open source libraries for these kinds of things. (OpenCV comes to mind)
**edit**: If I were re-projecting large images into new projections based on position conversion (and it were dynamic, not static) I would look into building an on-demand application that will refactor images given required resolution and desired position. The application can then pull the nearest resolution of the relative neighbourhood images and provide a result at the desired resolution.
Without more background, I hope this helps!
**edit 2**:
Comment from answer below:
Depends on the images. If they are fixed size then an array might be good. If they vary then it might be better to implement a system that provides get/setpixel using relative sampling/averaging to match up images of differing res?
I don't know the ins and outs of the images you are working with, and what you are doing, but often **abstracting what a 'pixel' is** rather than accessing values in an array is useful. This way you can implement conversion, sampling, rotating, correcting algorithms on the backend. Like GetVPixel() or SetVPixel(). This may be more useful when working with multiple, differing res/format images. Like
```
SetVPixel(img1, coord1, GetVPixel(img2, coord2))
```
Obviously in an OOP/C# manner. img1 and img2 can be different in size, res, geographics, alignment or anything else providing your backend understands both. | If you don't mind using unsafe code, you can wrap the Bitmap's BitmapData in an object that allows you to efficiently get and set pixels. The below code is mostly taken from [a gaussian blur filter](http://www.cnblogs.com/dah/archive/2007/03/30/694527.html), with a couple of modifications of my own. It's not the most flexible code if your bitmap formats differ but I hope it illustrates how you can manipulate bitmaps more efficiently.
```
public unsafe class RawBitmap : IDisposable
{
private BitmapData _bitmapData;
private byte* _begin;
public RawBitmap(Bitmap originBitmap)
{
OriginBitmap = originBitmap;
_bitmapData = OriginBitmap.LockBits(new Rectangle(0, 0, OriginBitmap.Width, OriginBitmap.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
_begin = (byte*)(void*)_bitmapData.Scan0;
}
#region IDisposable Members
public void Dispose()
{
OriginBitmap.UnlockBits(_bitmapData);
}
#endregion
public unsafe byte* Begin
{
get { return _begin; }
}
public unsafe byte* this[int x, int y]
{
get
{
return _begin + y * (_bitmapData.Stride) + x * 3;
}
}
public unsafe byte* this[int x, int y, int offset]
{
get
{
return _begin + y * (_bitmapData.Stride) + x * 3 + offset;
}
}
public unsafe void SetColor(int x, int y, Color color)
{
byte* p = this[x, y];
p[0] = color.B;
p[1] = color.G;
p[2] = color.R;
}
public unsafe Color GetColor(int x, int y)
{
byte* p = this[x, y];
return new Color
(
p[2],
p[1],
p[0]
);
}
public int Stride
{
get { return _bitmapData.Stride; }
}
public int Width
{
get { return _bitmapData.Width; }
}
public int Height
{
get { return _bitmapData.Height; }
}
public int GetOffset()
{
return _bitmapData.Stride - _bitmapData.Width * 3;
}
public Bitmap OriginBitmap { get; private set; }
}
``` | image processing techniques - direct manipulation of destination image or virtualized? | [
"",
"c#",
"image-processing",
"gdi+",
""
] |
Before I have the audacity to file a bug report, I thought I'd check my assumptions among wiser Pythonistas here. I encountered a baffling case today, so I whittled it down to a toy example, shown below:
```
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
A little script to demonstrate that a function won't re-initialize its
list parameters between calls, but instead allows them to retain state.
"""
def bleedscope(a=[], b=[]):
"""
On each call, unless explicitly passed, both `a` and `b` should be
initialized as empty lists.
"""
c = a
if b:
c.extend(b)
return len(c)
x = bleedscope(b=[1])
print x # Should be 1, as expected.
x = bleedscope(b=[2])
print x # Expect also to be 1, but it's 2. `a` is retained.
x = bleedscope(a=[1])
print x # Now 1 as expected.
x = bleedscope(b=[3])
print x # 1 as expected? No, it's 3! Insanity!
```
I thought function arguments were local in scope to the function, and were garbage-collected at the end of a function call, never to retain state between them. I have tested the above script on Python 2.5.2 and Python 2.6.1, though, and my understanding does not the results. Argument `a` certainly retains state between most of these calls; the most perplexing one being the final call to `bleedscope`, where it skips the state of the previous call and goes back to the state at the end of the second (i.e., `[1, 2]`). [I suggest running this in your favorite debugger to see for yourself. If you don't have one, I suggest [Winpdb](http://winpdb.org/) as a solid FOSS standalone Python debugger.]
What's going on here? | In Python default parameter values only get initialized when the def call is parsed. In the case of an object (such as your lists), it gets reused between calls. Take a look at this article about it, which also provides the necessary workaround:
<http://effbot.org/zone/default-values.htm> | This is your problem:
```
def bleedscope(a=[], b=[]):
```
it should be
```
def bleedscope(a=None, b=None):
if a is None: a = []
if b is None: b = []
```
The default parameters are only executed once when the function is parsed, thus using the same 2 lists every time. | Python function calls are bleeding scope, stateful, failing to initialize parameters? | [
"",
"python",
"scope",
""
] |
I'm building a PHP/MySQL app where users can log in and search for media assets. They can also save searches and create lightboxes (collections of assets). Finally, they can create user groups.
Does it make more sense to query all at once, at log in, for the id's for their saved searches, lightboxes, and groups and save those in session vars? Or to perform the queries when they first hit the appropriate pages? I'm looking for efficiency, and the sessions seem the way to go, but am I overlooking anything? | Biggest Rule: **Only put in the session what you need in the session**
I don't think it would be wise at all to put everything you need in the session all at once because you'll have a lot of occurrences where that isn't needed. The user might not stay long enough to make use of all the data in there, so you just wasted time and resources putting it there.
Put your information in there on demand (when they go to each page that requires that information).
Always keep your session object neat and slim and your performance will thank you. | Querying all at login is a bad idea. First it slows down login and 2nd it creates a static workload on your SQL server for every login.
If you query when applicable, you have a varied load. (even if you cache the results to be used later)
Also if you store results in sessions, then you are increasing the memory used for each request for that user.
There are many things that can be good for your particular site but we need more data to be able to answer that better. | Query all at once and save to session, or multiple times? | [
"",
"php",
"mysql",
"performance",
""
] |
I'm using TCPListener which according to [this](http://msdn.microsoft.com/en-us/library/system.net.sockets.tcplistener.aspx) page should be in System.Net.Sockets, I have
```
using System.Net;
using System.Net.Sockets;
...
TCPListener tcpListener = new TCPListener(10);
```
Visual Studio is producing the following error
> Error 1 The type or namespace name
> 'TCPListener' could not be found (are
> you missing a using directive or an
> assembly
> reference?) C:\path\WindowsService.cs 85 13 Windows
> Service Test1
Did I miss something? | You need to spell it correctly: it's `TcpListener`, not `TCPListener`. C# is case-sensitive. | It's case sensitive, i.e. TcpListener | TCPListener missing from System.Net.Sockets namespace | [
"",
"c#",
".net-3.5",
""
] |
I am trying to write to the registry from my application, but when I do I get access denied. Of course, it works if i run the app as Administrator. However, with my applcation, it is not initiated by the user. It start automatically.
So, the question is, how do i read/write to my own registry key from the C++ app?
Thanks for any help. | Write to `HKEY_CURRENT_USER`
And check out this posts
[Vista + VB.NET - Access Denied while writing to HKEY\_LOCAL\_MACHINE](https://stackoverflow.com/questions/698193/vista-vb-net-access-denied-while-writing-to-hkeylocalmachine)
[Writing string (REG\_SZ) values to the registry in C++](https://stackoverflow.com/questions/505024/writing-string-regsz-values-to-the-registry-in-c)
[How to read registry branch HKEY\_LOCAL\_MACHINE in Vista?](https://stackoverflow.com/questions/877851/how-to-read-registry-branch-hkeylocalmachine-in-vista) | If your application starts automatically, could it be rewritten as a service? It would have system-level access to registry. | Write to registry in Windows Vista | [
"",
"c++",
"windows-vista",
"registry",
"access-denied",
""
] |
How can I read an XML attribute using C#'s XmlDocument?
I have an XML file which looks somewhat like this:
```
<?xml version="1.0" encoding="utf-8" ?>
<MyConfiguration xmlns="http://tempuri.org/myOwnSchema.xsd" SuperNumber="1" SuperString="whipcream">
<Other stuff />
</MyConfiguration>
```
How would I read the XML attributes SuperNumber and SuperString?
Currently I'm using XmlDocument, and I get the values in between using XmlDocument's `GetElementsByTagName()` and that works really well. I just can't figure out how to get the attributes? | ```
XmlNodeList elemList = doc.GetElementsByTagName(...);
for (int i = 0; i < elemList.Count; i++)
{
string attrVal = elemList[i].Attributes["SuperString"].Value;
}
``` | You should look into [XPath](https://www.w3schools.com/xml/xpath_intro.asp). Once you start using it, you'll find its a lot more efficient and easier to code than iterating through lists. It also lets you directly get the things you want.
Then the code would be something similar to
```
string attrVal = doc.SelectSingleNode("/MyConfiguration/@SuperNumber").Value;
```
Note that XPath 3.0 became a W3C Recommendation on April 8, 2014. | Read XML Attribute using XmlDocument | [
"",
"c#",
".net",
"xml",
"xmldocument",
""
] |
I would like to know how many web pages on the web are using JavaScript, in percentage.
The metric I'm looking is the number of pages having a `<script type="text/javascript">` tag.
I'm pretty sure someone (like Google) did studies on that and publish the results !
The goal is to have an idea on how much JavaScript is widespread on the web landscape. | Google published [Web Authoring Statistics](http://code.google.com/webstats/index.html) a few years ago. They found then that [the script tag was found in roughly half the pages they surveyed](http://code.google.com/webstats/2005-12/scripting.html) in a sample of over a half-billion documents.
Since the web has grown a bit since they did the survey, it's probably safe to invoke the spirit of Carl Sagan, and answer "Billions and Billions!" | This is kind of meaningless: a lot of pages use javascript, but use it in such a way that they degrade gracefully if the scripting is not enabled.
Also, the penetration numbers you cite are both inaccurate and misleading. They don't take into account things like noscript users, smartphones (which often have very buggy javascript implementations) and they don't account for google, which doesn't process your javascript when indexing the site. Also, 95% javascript penetration sounds higher than it is. Taken the other way, at least one person in 20 who visits you site won't have javascript.
Finally, you should consider your audience. You might be developing for a corporate intranet site where you can enforce browser settings and guarantee that number is 100%, or you might be doing a site for the U.S. goverment and be legally required to support screen readers.
Here are some similar SO questions:
* <https://stackoverflow.com/questions/121108/how-many-people-disable-javascript/>
* [Do web sites really need to cater for browsers that don't have Javascript enabled?](https://stackoverflow.com/questions/822872/do-web-sites-really-need-to-cater-for-browsers-that-dont-have-javascript-enabled/) | How many webpage on the web make use of JavaScript? | [
"",
"javascript",
"html",
""
] |
I need to inherit from a base class, one method of which has a constructor with 8 arguments.
I won't ever need all 8 arguments, I only need one. However, I do need to implement that method.
```
public MyClass : BaseClass
{
public class MyClass(string myArg):base(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8)
{
// do stuff
}
}
```
results in an epic fail compiler message where args2-8 are hard-coded. Any hints?
Clarification: Arguments are all properties of the base class which are set via with this
initialization.
As the base class is a framework class, I'm not in a position to amend its properties or constructor.
Hopefully the final edit for those who want to know what the arguments are (and no, the opening brace is not an issue, thanks anyway) here's the VB.NET code I'm trying to port as part of a Custom Membership Provider.
Sadly, finding an en example of C# membership provider was not possible.
```
Public Sub New(ByVal userName As String)
MyBase.New("Shiningstar.SSSMembershipProvider", userName, _
userName.GetHashCode, userName, "", "", False, False, Today, _
Today, Today, Today, Today)
Me.m_UserName = userName ' UserName() is read only
End Sub
```
The base class in this case is System.Web.Security.MembershipUser | Without the exact error message, I cannot be sure, but I suspect that your arg1 .. arg8 are instance fields of the class, which cannot be used before the base constructor.
If you make them static fields, that problem would be solved. | I've never heard of method constructors, so I assume you mean a normal constructor. You should be able to hard code some of the parameters in. Here is a small code example that compiles without error:
```
public class MyBaseClass
{
public MyBaseClass ( int arg2, string arg1,string ar3)
{ }
}
public class MyClass : MyBaseClass
{
public MyClass (int argument) : base (argument, "not supplied", "hard-coded")
{ }
}
```
I hope this answers your question.
**Edit (some stumble-stones:)**
---
Are you sure you have the right access modifiers (protected, internal, private, public, protected internal) ? | Is it possible to use hard-coded values in a base constructor? | [
"",
"c#",
"inheritance",
""
] |
From Sun's [Java Tutorial](http://java.sun.com/docs/books/tutorial/collections/interfaces/collection.html), I would have thought this code would convert a set into an array.
```
import java.util.*;
public class Blagh {
public static void main(String[] args) {
Set<String> set = new HashSet<String>();
set.add("a");
set.add("b");
set.add("c");
String[] array = set.toArray(new String[0]);
System.out.println(set);
System.out.println(array);
}
}
```
However, this gives
```
[a, c, b]
[Ljava.lang.String;@9b49e6
```
What have I misunderstood? | The code works fine.
Replace:
```
System.out.println(array);
```
With:
```
System.out.println(Arrays.toString(array));
```
Output:
```
[b, c, a]
[b, c, a]
```
The `String` representation of an array displays the a "textual representation" of the array, obtained by [`Object.toString`](http://java.sun.com/javase/6/docs/api/java/lang/Object.html#toString()) -- which is the class name and the hash code of the array as a hexidecimal string. | for the sake of completeness check also [java.util.Arrays.toString](http://java.sun.com/j2se/1.5.0/docs/api/java/util/Arrays.html#toString(java.lang.Object[])) and [java.util.Arrays.deepToString](http://java.sun.com/j2se/1.5.0/docs/api/java/util/Arrays.html#deepToString(java.lang.Object[])).
The latter is particularly useful when dealing with
nested arrays (like Object[][]). | Java: Converting a set to an array for String representation | [
"",
"java",
"arrays",
"set",
""
] |
I want Eclipse to automatically generate Javadoc comments for my getter and setter methods based on the previously defined comments for the fields. How can I achieve this?
Background: A policy in our company is to comment every method and field (even if they have self-explanatory names). So I have to do redundant work by describing the fields and describing the getters / setters again.
Example:
```
/**
* name of the dynamic strategy
*/
private String dynName;
/**
* get the name of the dynamic strategy
* @return
*/
public String getDynName() {
return dynName;
}
```
Searching the web showed that I'm not the only one with the problem - but I couldn't find any solutions. I checked out <http://jautodoc.sourceforge.net/> but seems like it is not capable of doing this. | I finally found a solution (or at least a workaround) myself. I read about [Spoon](http://spoon.gforge.inria.fr/) on SO. It's an Java program processor which allows to read and modify java source files. It can even be used as Eclipse Plugin or Ant/Maven script.
Everything you have to do, is to extend the AbstractProcessor, which will process a method. If
the method name starts with get/set it looks for the corresponding field, extracts its comment and replaces or extends the accessors comment with it.
I have a little ant script, which takes all my sources and processes them.
Something integrated in eclipses code templates would be of course more convenient, but for now this way is ok! | JAutodoc since ver 1.6 (1 year after the question) has a new option "[G,S]etter from field comment", which does exactly what you want.
This is a quite handy feature. Field comments are usually not included in the final Javadoc HTML because they might/should be private members (generating Javadoc for every private member is not good either), so the comments would be completely lost without it!
I wonder if this Q/A thread might have motivated the author to implement this nice feature. | How to automatically generate comments for getter/setter based on field comments in Eclipse? | [
"",
"java",
"eclipse",
"javadoc",
""
] |
Are there any production-ready libraries for streaming XPath expressions evaluation against provided xml-document? My investigations show that most of existing solutions load entire DOM-tree into memory before evaluating xpath expression. | Would this be practical for a complete XPath implementation, given that XPath syntax allows for:
```
/AAA/XXX/following::*
```
and
```
/AAA/BBB/following-sibling::*
```
which implies look-ahead requirements ? i.e. from a particular node you're going to have to load the rest of the document anyway.
The doc for the [Nux](http://acs.lbl.gov/nux/) library (specifically [StreamingPathFilter](http://acs.lbl.gov/nux/api/nux/xom/xquery/StreamingPathFilter.html)) makes this point, and references some implementations that rely on a *subset* of XPath. Nux claims to perform some streaming query capability, but given the above there will be some limitations in terms of XPath implementation. | **XSLT 3.0 provides [streaming mode of processing](http://www.w3.org/TR/xslt-21/#streaming)** and this will become a standard with the XSLT 3.0 W3C specification becoming a W3C Recommendation.
At the time of writing this answer (May, 2011) Saxon provides some **[support for XSLT 3.0 streaming](http://www.saxonica.com/documentation/sourcedocs/streaming/streaming-templates.xml)** . | Streaming XPath evaluation | [
"",
"java",
"xml",
"dom",
"xpath",
"evaluation",
""
] |
Can anyone help, I am using the following for adding a bookmark to IE and Firefox but its not working in Chrome and I don't get my error msg saying "not supported" either..
Anybody know of a good script to support ALL browsers or at least to come back and tell me its not supported, I have access to jQuery - maybe there is some way to detect the browser
I am currently using this and it works for IE and Firefox but not chrome
```
if (window.sidebar) { // Mozilla Firefox
window.sidebar.addPanel(name, url, "");
}
else if (window.external) { // IE
window.external.AddFavorite(url, name);
}
else if (window.opera && window.print) {
window.external.AddFavorite(url, name);
}
else {
alert('not supported');
}
``` | Sorry, but there's no cross-browser way to do this. Your FF example is broken as well: It won't create a regular bookmark, but a bookmark set to be opened in the sidebar. You'd have to [use the bookmark-service](https://developer.mozilla.org/en/Code_snippets/Bookmarks) to create an actual bookmark, but this'll fail due to security restrictions. | After discovering - like Edison! - a bunch of ways this doesn't work, I eventually came across [this page](http://www.google.com/support/forum/p/Chrome/thread?tid=6abd47b3491f46ee&hl=en) that says adding bookmarks via JS is explicitly disabled in Chrome. Unfortunately it does not explain why.
*Update: I was asked to expand this answer by another SO user...*
My links and buttons for this function all have a `class="addbookmark"` associated with them. When the user agent is Chrome, I use some jQuery to disable the links and explain why:
```
<script type="text/javascript" src="/scripts/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="/scripts/bookmark.js"></script>
<script>
title='A Label for this Bookmark, ie title of this page'; // for example, not really generated this way...
$jQuery(document).ready(function(){
// chrome does not permit addToFavorites() function by design
if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {
$('.addbookmark').attr({
title: 'This function is not available in Google Chrome. Click the star symbol at the end of the address-bar or hit Ctrl-D to create a bookmark.',
href: 'javascript:return false'
})
.css({opacity: .25}); // dim the button/link
}
});
</script>
```
And then elsewhere on the page:
```
<td rowspan="2" class="noprint" style="width:24px;">
<a class="addbookmark" title="Save a Bookmark for this page"
href="javascript:addToFavorites(location.href,title)">
<img style="width:24px; height:24px; padding-top:2px;" src="/images/bookmark.gif"></a>
</td>
```
... which is by no means perfect, but it seems one's options are fairly limited.
The version of [jQuery](http://jquery.com/) isn't important, and it's up to you whether you want a local copy or hot-link to the [google version](http://code.google.com/apis/libraries/). `bookmark.js` is pretty much exactly as per the OP's code:
```
$ cat /scripts/bookmark.js
/* simple cross-browser script for adding a bookmark
source: http://stackoverflow.com/questions/992844/add-to-browser-favourites-bookmarks-from-javascript-but-for-all-browsers-mine-do
*/
function addToFavorites(url, name) {
if (window.sidebar) { // Mozilla Firefox
window.sidebar.addPanel(name, url, "");
} else if (window.external) { // IE
window.external.AddFavorite(url, name);
} else if (window.opera && window.print) {
window.external.AddFavorite(url, name);
} else {
alert("Sorry! Your browser doesn't appear to support this function.");
}
}
```
Hope that's useful. | Add to browser favorites/bookmarks from JavaScript but for all browsers (mine doesn't work in Chrome)? | [
"",
"javascript",
"firefox",
"google-chrome",
"cross-browser",
"bookmarks",
""
] |
I need to be able to tell if an image exists in a directory or not. Given the file name and the directory, how can I tell if it exists?
Thanks! | ```
file_exists($filename);
```
<http://www.php.net/file_exists> | ```
$dir = '/var/img/'; $name = 'img.jpg';
echo is_file($dir.$name);
``` | PHP: Tell if a file exists? | [
"",
"php",
"php4",
""
] |
I'd like to be able to create a simple PNG image, say of a red square using a c# web based service to generate the image, called from an `<img src="myws.ashx?x=100>` HTML element.
some example HTML:
```
<hmtl><body>
<img src="http://mysite.com/webservice/rectangle.ashx?size=100">
</body></html>
```
Is there is anyone who can cobble together a simple (working) C# class just to get me started? Once off and going I'm sure I can finish this off to actually do what I want it to do.
* End game is to create simple Red/Amber/Green (RAG) embedded status markers for a data driven web page that shows performance metrics etc\*
* I'd like it to use PNG's as I anticipate using transparency in the future\*
* ASP.NET 2.0 C# solution please... (I don't have a production 3.5 box yet)
tia
**SOLUTION**
rectangle.html
```
<html>
<head></head>
<body>
<img src="rectangle.ashx" height="100" width="200">
</body>
</html>
```
rectangle.ashx
```
<%@ WebHandler Language="C#" Class="ImageHandler" %>
```
rectangle.cs
```
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Web;
public class ImageHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
int width = 600; //int.Parse(context.Request.QueryString["width"]);
int height = 400; //int.Parse(context.Request.QueryString["height"]);
Bitmap bitmap = new Bitmap(width,height);
Graphics g = Graphics.FromImage( (Image) bitmap );
g.FillRectangle( Brushes.Red, 0f, 0f, bitmap.Width, bitmap.Height ); // fill the entire bitmap with a red rectangle
MemoryStream mem = new MemoryStream();
bitmap.Save(mem,ImageFormat.Png);
byte[] buffer = mem.ToArray();
context.Response.ContentType = "image/png";
context.Response.BinaryWrite(buffer);
context.Response.Flush();
}
public bool IsReusable {
get {return false;}
}
}
``` | Web services, especially SOAP expect things like an XML envelope with the details of the call in. You'd be better off using a `HttpHandler`.
Something like this:
```
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Web;
public class ImageHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
int width = int.Parse(context.Request.QueryString["width"]);
int height = int.Parse(context.Request.QueryString["height"]);
using (Bitmap bitmap = new Bitmap(width,height)) {
...
using (MemoryStream mem = new MemoryStream()) {
bitmap.Save(mem,ImageFormat.Png);
mem.Seek(0,SeekOrigin.Begin);
context.Response.ContentType = "image/png";
mem.CopyTo(context.Response.OutputStream,4096);
context.Response.Flush();
}
}
}
}
```
This is very rough of course. You'd call it then:
```
<img src="myhandler.ashx?width=10&height=10"/>
``` | A web service is not suitable for this. It returns a message in a specific format, typically SOAP, so it can't be an image.
Use a regular web form instead, where you remove all markup except the `@page` directive. Use the `BinaryWrite` method to write the image data to the response stream.
Example:
```
byte[] imageData;
using (Bitmap image = new Bitmap(10,10)) {
using (Graphics g = Graphics.FromImage(image)) {
g.Clear(Color.Red);
}
using (MemoryStream m = new MemoryStream()) {
image.Save(m, ImageFormat.Png);
imageData = m.ToArray();
}
}
Response.ContentType = "image/png";
Response.BinaryWrite(imageData);
``` | Create PNG image with C# HttpHandler webservice | [
"",
"c#",
"web-services",
"png",
"httphandler",
"image",
""
] |
I'm trying to call a RESTful web service from an Android application using the following method:
```
HttpHost target = new HttpHost("http://" + ServiceWrapper.SERVER_HOST,ServiceWrapper.SERVER_PORT);
HttpGet get = new HttpGet("/list");
String result = null;
HttpEntity entity = null;
HttpClient client = new DefaultHttpClient();
try {
HttpResponse response = client.execute(target, get);
entity = response.getEntity();
result = EntityUtils.toString(entity);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (entity!=null)
try {
entity.consumeContent();
} catch (IOException e) {}
}
return result;
```
I can browse to address and see the xml results using the Android Emulator browser and from my machine. I have given my app the INTERNET permission.
I'm developing with eclipse.
I've seen it mentioned that I might need to configure a proxy but since the web service I'm calling is on port 80 this shouldn't matter should it? I can call the method with the browser.
Any ideas? | I think the problem might be on the first line:
```
new HttpHost("http://" + ServiceWrapper.SERVER_HOST,ServiceWrapper.SERVER_PORT);
```
The `HttpHost` constructor expects a hostname as its first argument, not a hostname with a `"http://"` prefix.
Try removing `"http://"` and it should work:
```
new HttpHost(ServiceWrapper.SERVER_HOST,ServiceWrapper.SERVER_PORT);
``` | The error means the URL can't be resolved via DNS. The are a many problems which might cause this. If you sit behind a proxy you should configure it to be used.
```
HttpHost proxy = new HttpHost(”proxy”,port,”protocol”);
client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
```
Also check that your internetpermission looks like this
```
<uses-permission android:name=”android.permission.INTERNET”></uses-permission>
```
As sometimes it won't work as empty tag.
Also check out [Emulator Networking](http://developer.android.com/guide/developing/tools/emulator.html#emulatornetworking) and the limitations section there | Unresolved Host Exception Android | [
"",
"java",
"android",
"rest",
""
] |
If I want to create a URL using a variable I have two choices to encode the string. `urlencode()` and `rawurlencode()`.
What exactly are the differences and which is preferred? | It will depend on your purpose. If interoperability with other systems is important then it seems rawurlencode is the way to go. The one exception is legacy systems which expect the query string to follow form-encoding style of spaces encoded as + instead of %20 (in which case you need urlencode).
**rawurlencode** follows RFC 1738 prior to PHP 5.3.0 and RFC 3986 afterwards (see <https://www.php.net/manual/en/function.rawurlencode.php>)
> Returns a string in which all non-alphanumeric characters except -\_.~ have been replaced with a percent (%) sign followed by two hex digits. This is the encoding described in » RFC 3986 for protecting literal characters from being interpreted as special URL delimiters, and for protecting URLs from being mangled by transmission media with character conversions (like some email systems).
Note on RFC 3986 vs 1738. rawurlencode prior to php 5.3 encoded the tilde character (`~`) according to RFC 1738. As of PHP 5.3, however, rawurlencode follows RFC 3986 which does not require encoding tilde characters.
**urlencode** encodes spaces as plus signs (not as `%20` as done in rawurlencode)(see <https://www.php.net/manual/en/function.urlencode.php>)
> Returns a string in which all non-alphanumeric characters except -\_. have been replaced with a percent (%) sign followed by two hex digits and spaces encoded as plus (+) signs. It is encoded the same way that the posted data from a WWW form is encoded, that is the same way as in application/x-www-form-urlencoded media type. This differs from the » RFC 3986 encoding (see rawurlencode()) in that for historical reasons, spaces are encoded as plus (+) signs.
This corresponds to the definition for application/x-www-form-urlencoded in [RFC 1866](http://www.ietf.org/rfc/rfc1866.txt).
**Additional Reading:**
You may also want to see the discussion at <http://bytes.com/groups/php/5624-urlencode-vs-rawurlencode>.
Also, [RFC 2396](http://www.ietf.org/rfc/rfc2396.txt) is worth a look. RFC 2396 defines valid URI syntax. The main part we're interested in is from 3.4 Query Component:
> Within a query component, the characters `";", "/", "?", ":", "@", "&", "=", "+", ",", and "$"` are reserved.
As you can see, the `+` is a reserved character in the query string and thus would need to be encoded as per RFC 3986 (as in rawurlencode). | Proof is in the source code of PHP.
I'll take you through a quick process of how to find out this sort of thing on your own in the future any time you want. Bear with me, there'll be a lot of C source code you can skim over (I explain it). [If you want to brush up on some C, a good place to start is our SO wiki](https://stackoverflow.com/tags/c/info).
Download the source (or use <https://heap.space/> to browse it online), grep all the files for the function name, you'll find something such as this:
PHP 5.3.6 (most recent at time of writing) describes the two functions in their native C code in the file *url.c*.
**RawUrlEncode()**
```
PHP_FUNCTION(rawurlencode)
{
char *in_str, *out_str;
int in_str_len, out_str_len;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &in_str,
&in_str_len) == FAILURE) {
return;
}
out_str = php_raw_url_encode(in_str, in_str_len, &out_str_len);
RETURN_STRINGL(out_str, out_str_len, 0);
}
```
**UrlEncode()**
```
PHP_FUNCTION(urlencode)
{
char *in_str, *out_str;
int in_str_len, out_str_len;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &in_str,
&in_str_len) == FAILURE) {
return;
}
out_str = php_url_encode(in_str, in_str_len, &out_str_len);
RETURN_STRINGL(out_str, out_str_len, 0);
}
```
Okay, so what's different here?
They both are in essence calling two different internal functions respectively: **php\_raw\_url\_encode** and **php\_url\_encode**
So go look for those functions!
## Lets look at php\_raw\_url\_encode
```
PHPAPI char *php_raw_url_encode(char const *s, int len, int *new_length)
{
register int x, y;
unsigned char *str;
str = (unsigned char *) safe_emalloc(3, len, 1);
for (x = 0, y = 0; len--; x++, y++) {
str[y] = (unsigned char) s[x];
#ifndef CHARSET_EBCDIC
if ((str[y] < '0' && str[y] != '-' && str[y] != '.') ||
(str[y] < 'A' && str[y] > '9') ||
(str[y] > 'Z' && str[y] < 'a' && str[y] != '_') ||
(str[y] > 'z' && str[y] != '~')) {
str[y++] = '%';
str[y++] = hexchars[(unsigned char) s[x] >> 4];
str[y] = hexchars[(unsigned char) s[x] & 15];
#else /*CHARSET_EBCDIC*/
if (!isalnum(str[y]) && strchr("_-.~", str[y]) != NULL) {
str[y++] = '%';
str[y++] = hexchars[os_toascii[(unsigned char) s[x]] >> 4];
str[y] = hexchars[os_toascii[(unsigned char) s[x]] & 15];
#endif /*CHARSET_EBCDIC*/
}
}
str[y] = '\0';
if (new_length) {
*new_length = y;
}
return ((char *) str);
}
```
## And of course, php\_url\_encode:
```
PHPAPI char *php_url_encode(char const *s, int len, int *new_length)
{
register unsigned char c;
unsigned char *to, *start;
unsigned char const *from, *end;
from = (unsigned char *)s;
end = (unsigned char *)s + len;
start = to = (unsigned char *) safe_emalloc(3, len, 1);
while (from < end) {
c = *from++;
if (c == ' ') {
*to++ = '+';
#ifndef CHARSET_EBCDIC
} else if ((c < '0' && c != '-' && c != '.') ||
(c < 'A' && c > '9') ||
(c > 'Z' && c < 'a' && c != '_') ||
(c > 'z')) {
to[0] = '%';
to[1] = hexchars[c >> 4];
to[2] = hexchars[c & 15];
to += 3;
#else /*CHARSET_EBCDIC*/
} else if (!isalnum(c) && strchr("_-.", c) == NULL) {
/* Allow only alphanumeric chars and '_', '-', '.'; escape the rest */
to[0] = '%';
to[1] = hexchars[os_toascii[c] >> 4];
to[2] = hexchars[os_toascii[c] & 15];
to += 3;
#endif /*CHARSET_EBCDIC*/
} else {
*to++ = c;
}
}
*to = 0;
if (new_length) {
*new_length = to - start;
}
return (char *) start;
}
```
One quick bit of knowledge before I move forward, [EBCDIC is another character set](http://en.wikipedia.org/wiki/Extended_Binary_Coded_Decimal_Interchange_Code), similar to ASCII, but a total competitor. PHP attempts to deal with both. But basically, this means byte EBCDIC 0x4c byte isn't the `L` in ASCII, it's actually a `<`. I'm sure you see the confusion here.
Both of these functions manage EBCDIC if the web server has defined it.
Also, they both use an array of chars (think string type) `hexchars` look-up to get some values, the array is described as such:
```
/* rfc1738:
...The characters ";",
"/", "?", ":", "@", "=" and "&" are the characters which may be
reserved for special meaning within a scheme...
...Thus, only alphanumerics, the special characters "$-_.+!*'(),", and
reserved characters used for their reserved purposes may be used
unencoded within a URL...
For added safety, we only leave -_. unencoded.
*/
static unsigned char hexchars[] = "0123456789ABCDEF";
```
Beyond that, the functions are really different, and I'm going to explain them in ASCII and EBCDIC.
## Differences in ASCII:
**URLENCODE:**
* Calculates a start/end length of the input string, allocates memory
* Walks through a while-loop, increments until we reach the end of the string
* Grabs the present character
* If the character is equal to ASCII Char 0x20 (ie, a "space"), add a `+` sign to the output string.
* If it's not a space, and it's also not alphanumeric (`isalnum(c)`), and also isn't and `_`, `-`, or `.` character, then we , output a `%` sign to array position 0, do an array look up to the `hexchars` array for a lookup for `os_toascii` array (an array from [Apache that translates](http://svn.apache.org/repos/asf/apr/apr-util/branches/1.0.x/encoding/apr_base64.c) char to hex code) for the key of `c` (the present character), we then bitwise shift right by 4, assign that value to the character 1, and to position 2 we assign the same lookup, except we preform a logical and to see if the value is 15 (0xF), and return a 1 in that case, or a 0 otherwise. At the end, you'll end up with something encoded.
* If it ends up it's not a space, it's alphanumeric or one of the `_-.` chars, it outputs exactly what it is.
**RAWURLENCODE:**
* Allocates memory for the string
* Iterates over it based on length provided in function call (not calculated in function as with URLENCODE).
**Note:** Many programmers have probably never seen a for loop iterate this way, it's somewhat hackish and not the standard convention used with most for-loops, pay attention, it assigns `x` and `y`, checks for exit on `len` reaching 0, and increments both `x` and `y`. I know, it's not what you'd expect, but it's valid code.
* Assigns the present character to a matching character position in `str`.
* It checks if the present character is alphanumeric, or one of the `_-.` chars, and if it isn't, we do almost the same assignment as with URLENCODE where it preforms lookups, however, we increment differently, using `y++` rather than `to[1]`, this is because the strings are being built in different ways, but reach the same goal at the end anyway.
* When the loop's done and the length's gone, It actually terminates the string, assigning the `\0` byte.
* It returns the encoded string.
**Differences:**
* UrlEncode checks for space, assigns a + sign, RawURLEncode does not.
* UrlEncode does not assign a `\0` byte to the string, RawUrlEncode does (this may be a moot point)
* They iterate differntly, one may be prone to overflow with malformed strings, I'm **merely suggesting** this and I **haven't** actually investigated.
They basically iterate differently, one assigns a + sign in the event of ASCII 20.
## Differences in EBCDIC:
**URLENCODE:**
* Same iteration setup as with ASCII
* Still translating the "space" character to a + *sign. Note-- I think this needs to be compiled in EBCDIC or you'll end up with a bug? Can someone edit and confirm this?*
* It checks if the present char is a char before `0`, with the exception of being a `.` or `-`, **OR** less than `A` but greater than char `9`, **OR** greater than `Z` and less than `a` but not a `_`. **OR** greater than `z` (yeah, EBCDIC is kinda messed up to work with). If it matches any of those, do a similar lookup as found in the ASCII version (it just doesn't require a lookup in os\_toascii).
**RAWURLENCODE:**
* Same iteration setup as with ASCII
* Same check as described in the EBCDIC version of URL Encode, with the exception that if it's greater than `z`, it excludes `~` from the URL encode.
* Same assignment as the ASCII RawUrlEncode
* Still appending the `\0` byte to the string before return.
## Grand Summary
* Both use the same hexchars lookup table
* URIEncode doesn't terminate a string with \0, raw does.
* If you're working in EBCDIC I'd suggest using RawUrlEncode, as it manages the `~` that UrlEncode does not ([this is a reported issue](https://bugs.php.net/bug.php?id=53248)). It's worth noting that ASCII and EBCDIC 0x20 are both spaces.
* They iterate differently, one may be faster, one may be prone to memory or string based exploits.
* URIEncode makes a space into `+`, RawUrlEncode makes a space into `%20` via array lookups.
**Disclaimer:** I haven't touched C in years, and I haven't looked at EBCDIC in a really really long time. If I'm wrong somewhere, let me know.
## Suggested implementations
Based on all of this, rawurlencode is the way to go most of the time. As you see in Jonathan Fingland's answer, stick with it in most cases. It deals with the modern scheme for URI components, where as urlencode does things the old school way, where + meant "space."
If you're trying to convert between the old format and new formats, be sure that your code doesn't goof up and turn something that's a decoded + sign into a space by accidentally double-encoding, or similar "oops" scenarios around this space/20%/+ issue.
If you're working on an older system with older software that doesn't prefer the new format, stick with urlencode, however, I believe %20 will actually be backwards compatible, as under the old standard %20 worked, just wasn't preferred. Give it a shot if you're up for playing around, let us know how it worked out for you.
Basically, you should stick with raw, unless your EBCDIC system really hates you. Most programmers will never run into EBCDIC on any system made after the year 2000, maybe even 1990 (that's pushing, but still likely in my opinion). | urlencode vs rawurlencode? | [
"",
"php",
"urlencode",
"url-encoding",
""
] |
I'm developing a fair sized hospital simulation game in java.
Right now, my pain method is starting to look a little big, and I need a way to split it up into different sections...
I have an idea, but I'm not sure if this is the best way.
It starts by painting the grass, then the hospital building, then any buildings, then people, then any building previews when building. The grass and hospital building will not change, so I only need to paint this once. The buildings themselves won't change very often, only when new ones are built.
I was thinking, use boolean values to determine which sections need repainting?
Ideal, id like to be able to split up the paint method, and then call each one when needed, but I'm unsure how to physically split it up.
I am still quite new to java, and learning on the go.
Thanks in advance.
Rel | Another idea is to create a super class or interface for all items that must be drawn on the screen. Lets cvall this class ScreenObject. You can then have a draw(Graphics2d g) method specified in the ScreenObject class. Next, each object that must be drawn implements the draw() method and is only concerned about drawing itself. You can even consider creating a variable that determines whether this draw method should be run at all.
In the main class that paints the screen you can have a reference to all ScreenObjects in an ArrayList and your paint() method will simply iterate over this calling draw() on each object. | I'm assuming from your description that your scene is split up into tiles. Keeping an array of booleans is a good way to keep track of which tiles need redrawn on the next update. A LinkedList might perform a little better in some situations. (I'm thinking of a Game of Life simulation where there are tons of tiles to redraw and you need to check each neighbor, so you may not need to go this route.)
Without seeing your code I can't give very specific advice on splitting up your paint method. I can tell you that in sprite animations, each sprite object typically has its own draw method that takes the main Graphics object (or more likely a buffer) as a parameter. Since the sprite should know its own image and location, it can then draw itself into the main image. Your paint method can then just loop through your list of sprites that need to be redrawn and call their draw method.
You might look to [Killer Game Programming in Java](http://books.google.com/books?id=SVHVgbeMVvoC&pg=PA668&lpg=PA668&dq=java+tilin&source=bl&ots=0kUVW45J42&sig=Nfv0piFeuGQx8YOXzZfALEPQqFs&hl=en&ei=G_cXSsSJOIKMtge-5IT0DA&sa=X&oi=book_result&ct=result&resnum=10#PPP1,M1) for more detailed information. | How can I split up paint swing method in java? | [
"",
"java",
"swing",
"paint",
"repaint",
""
] |
I'm creating a binary file to transmit to a third party that contains images and information about each image. The file uses a record length format, so each record is a particular length. The beginning of each record is the Record Length Indicator, which is 4 characters long and represents the length of the record in Big Endian format.
I'm using a BinaryWriter to write to the file, and for the Record Length Indicator I'm using Encoding.Default.
The problem I'm having is that there is one character in one record that is displaying as a "?" because it is unrecognized. My algorithm to build the string for the record length indicator is this:
```
private string toBigEndian(int value)
{
string returnValue = "";
string binary = Convert.ToString(value, 2).PadLeft(32, '0');
List<int> binaryBlocks = new List<int>();
binaryBlocks.Add(Convert.ToInt32(binary.Substring(0, 8), 2));
binaryBlocks.Add(Convert.ToInt32(binary.Substring(8, 8), 2));
binaryBlocks.Add(Convert.ToInt32(binary.Substring(16, 8), 2));
binaryBlocks.Add(Convert.ToInt32(binary.Substring(24, 8), 2));
foreach (int block in binaryBlocks)
{
returnValue += (char)block;
}
Console.WriteLine(value);
return returnValue;
}
```
It takes the length of the record, converts it to 32-bit binary, converts that to chunks of 8-bit binary, and then converts each chunk to its appropriate character. The string that is returned here does contain the correct characters, but when it's written to the file, one character is unrecognized. This is how I'm writing it:
```
//fileWriter is BinaryWriter and record is Encoding.Default
fileWriter.Write(record.GetBytes(toBigEndian(length)));
```
Perhaps I'm using the wrong type of encoding? I've tried UTF-8, which should work, but it gives me extra characters sometimes.
Thanks in advance for your help. | The problem is that you should not return the value as a string at all.
When you cast the value to a char, and then encode it as 8 bit characters, there are several values that will be encoded into the wrong byte code, and several values that will fail to be encoded at all (resulting in the ? characters). The only way not to lose data in that step would be to encode it as UTF-16, but that would give you eight bytes instead of four.
You should return is as a byte array, so that you can write it to the file without converting it back and forth between character data and binary data.
```
private byte[] toBigEndian(int value) {
byte[] result = BitConverter.GetBytes(value);
if (BitConverter.IsLittleEndian) Array.Reverse(result);
return result;
}
fileWriter.Write(toBigEndian(length));
``` | If you really want a binary four bytes (i.e. not just four characters, but a big-endian 32-bit length value) then you want something like this:
```
byte[] bytes = new byte[4];
bytes[3] = (byte)((value >> 24) & 0xff);
bytes[2] = (byte)((value >> 16) & 0xff);
bytes[1] = (byte)((value >> 8) & 0xff);
bytes[0] = (byte)(value & 0xff);
fileWriter.Write(bytes);
``` | Using wrong encoding when writing to a file C# | [
"",
"c#",
"character-encoding",
""
] |
I am having some trouble provding a Win32 tooltips control with dynamic text in unicode format. I use the following code to set up the control:
```
INITCOMMONCONTROLSEX icc;
icc.dwSize = sizeof(INITCOMMONCONTROLSEX);
icc.dwICC = ICC_WIN95_CLASSES;
InitCommonControlsEx(&icc);
HWND hwnd_tip = CreateWindowExW(0, TOOLTIPS_CLASSW, NULL,
WS_POPUP | TTS_NOPREFIX | TTS_ALWAYSTIP,
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
NULL, NULL, hinst, NULL
);
SetWindowPos(hwnd_tip, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
TOOLINFOW ti;
memset(&ti, 0, sizeof(TOOLINFOW));
ti.cbSize = sizeof(TOOLINFOW);
ti.hwnd = hwnd_main;
ti.uId = (UINT) hwnd_control;
ti.uFlags = TTF_IDISHWND | TTF_SUBCLASS;
ti.lpszText = L"This tip is shown correctly, including unicode characters.";
SendMessageW(hwnd_tip, TTM_ADDTOOLW, 0, (LPARAM) &ti);
```
This works fine as long as I provide the tooltip text in `ti.lpszText`. However, I want the text to be dynamic, so instead I set `ti.lpszText` to `LPSTR_TEXTCALLBACKW` and handle the callback in my WindowProc(), like this:
```
...
case WM_NOTIFY:
{
NMHDR *nm = (NMHDR *) lParam;
switch (nm->code)
{
case TTN_GETDISPINFOW:
{
static std::wstring tip_string = L"Some random unicode string.";
NMTTDISPINFOW *nmtdi = (NMTTDISPINFOW *) lParam;
nmtdi->lpszText = (LPWSTR) tip_string.c_str();
}
break;
}
}
break;
...
```
Which does not work, as I never receive the `TTN_GETDISPINOW` message. (Note: It works if I handle `TTN_GETDISPINFO` instead and use `NMTTDISPINFO` to provide a char array, but then no unicode support...)
I'm guessing I'm doing something wrong in my setup or message handling here? Any suggestions on how to do it properly?
**Update**
Also note that my project is not compiled in unicoe mode (i.e. \_UNICODE is not defined and the project is set to use multi-byte character set). This is intentional and I would like to keep it like that as, I have no desire to rewrite the entire application to be unicode-aware (at least not yet). Since the \_UNICODE define is used to select \*W versions of various functions and data structures I was hoping I could achieve the same result by using these explicitly in my code, as shown above. | Thanks for the Robert Scott link. I found a way to solve it now.
**In short, the trick was to make sure the receiving window was a unicode window and register a unicode window procedure for it.**
The problem was that I did not have a unicode `WindowProc()` for my parent window handling the `TTN_GETDISPINFOW` notification message. Since this window (class) was created with `RegisterClassEx()/CreateWindowEx() and not RegisterClassExW()/CreateWindowExW(), it did not have registered window procedure for unicode messages.`
To get around the problem I changed `ti.hwnd` from `hwnd_main` to `hwnd_control` when sending TTM\_ADDTOOLW, resulting in the control's window procedure receving the notifications instead of its parent. In order to intercept the unicode events now sent to the control's window procedure, I subclassed it using SetWindowLongW(hwnd\_control, GWL\_WNDPROC, (LONG) NewControlWndProc).
Note that hwnd\_control is a standard "LISTBOX" window created with CreateWindowExW() and is therefore unicode-aware, since all buildt-in Windows classes are automatically registered in both unicode and ANSI version by the system. | The fact that you get the TTN\_GETDISPINFO notification code but not TTN\_GETDISPINFOW indicates that your project is setup to "Use Multi-Byte Character Set".
Check the projects property pages: "Configuration Properties" -> "General" -> "Character Set"
This property should be set to "Use Unicode Character Set". | How to set up Win32 tooltips control with dynamic unicode text? | [
"",
"c++",
"winapi",
"unicode",
"tooltip",
""
] |
> **Possible Duplicate:**
> [What REALLY happens when you don’t free after malloc?](https://stackoverflow.com/questions/654754/what-really-happens-when-you-dont-free-after-malloc)
When ending a program in C/C++, you have to clean up by freeing pointers. What happens if you doesn't free the memory, like if you have a pointer to an int and doesn't delete it when ending the program? Is the memory still used and can only be freed by restart, or is it automatically freed when the program ends? And in the last case, why free it, if the operating system does it for you? | When your program ends all of the memory will be freed by the operating system.
The reason you should free it yourself is that memory is a finite resource within your running program. Sure in very short running simple programs, failing to free memory won't have a noticable effect. However on long running programs, failing to free memory means you will be consuming a finite resource without replenishing it. Eventually it will run out and your program will rudely crash. This is why you must free memory. | When the program ends, all memory (freed or not) is reclaimed by the operating system. It is still good practice to free everything you allocate, though - mainly just to be in the habit of it, or in case you extend your program so that it doesn't end where it used to. | importance of freeing memory? | [
"",
"c++",
"c",
"memory",
""
] |
I have 2 tables:
1) table Masterdates which contains all dates since Jan 1, 1900
2) table Stockdata which contains stock data in the form
date, symbol, open, high, low, close, volume (primary key = date, symbol)
This is what I'm looking to retrieve (presented here in CSV format)
MDate,SDate,Symbol,Open,High,...
6/4/2001,6/4/2001,Foo,47,49,...
6/5/2001,null,null,null,null,...
6/6/2001,6/6/2001,Foo,54,56,...
where MDate is from Masterdates and SDate is from Stockdata. I need to have the output start with the first (earliest) extent date for the desired symbol (in this example, Foo, starting on 6/4/2001) in Stockdata, and then include all dates in Masterdates up to and including the last (latest) available date for the desired symbol in Stockdata, outputting nulls where there is no corresponding Stockdata record for a given Masterdate record in the range described.
Is there a way to do this in a single query, a series of queries, and/or by adding auxiliary tables, that will yield fast results? Or will I have to dump out supersets of what I want, and then construct the final output using my (non-SQL) programing language?
TIA | Tested in SQLITE3, your DB implementation may differ
```
SELECT m.date,
s.symbol,
s.open,
s.high,
s.low,
s.close,
s.volume
FROM masterdate AS m LEFT OUTER JOIN
stockdata AS s ON m.date = s.date
AND s.symbol = 'Foo'
WHERE m.date >= (SELECT MIN(date) FROM stockdata WHERE symbol = 'Foo')
AND m.date <= (SELECT MAX(date) FROM stockdata WHERE symbol = 'Foo')
```
If this does not execute quicky enough then you could pronably improve performance by setting variables for minimum and maximum value in one query and then using those in the main query. This would save you at least one index hit.
So (In SQL Server Syntax)
```
SET @symbol = 'Foo'
SELECT @mindate = MIN(date),
@maxdate = MAX(date)
FROM stockdata
WHERE stockdata.symbol = @symbol
SELECT m.date,
s.symbol,
s.open,
s.high,
s.low,
s.close,
s.volume
FROM masterdate AS m LEFT OUTER JOIN
stockdata AS s ON m.date = s.date
AND s.symbol = @symbol
WHERE m.date BETWEEN @mindate AND @maxdate
```
You will also need to be sure that you have an index on masterdate.date and a composite index on stockdata(date, symbol). | This is a classic left join:
```
SELECT * FROM masterdates
LEFT JOIN stockdata ON masterdates.date = stockdata.date;
```
Obviously this should be refined to only return the required columns. | Complex(?) SQL join query | [
"",
"sql",
""
] |
Is there a java compiler flag that allows me to use `goto` as a valid construct? If not, are there any third-party java compilers that supports `goto`? If not, are there any other languages that support `goto` while at the same time can easily call methods written in Java?
The reason is I'm making a language that is implemented in Java. Gotos are an important part of my language; I want to be able to compile it to native or JVM bytecode, although it has to be able to easily use Java libraries (ie. C supports `goto`, but to use it I'd have to rewrite the libraries in C).
I want to generate C or Java, etc source files, and not bytecode or machine code. I'm using a third-party compiler to do that. | JVM support goto at bytecode level.
If you are doing your own language, you should use libraries like [BCEL](http://jakarta.apache.org/bcel/) or [ASM](http://asm.ow2.org/), not generating .java file. | The JVM bytecode contains a goto instruction (e.g. see the [BCEL](http://jakarta.apache.org/bcel/manual.html) documentation).
Don't forget that Java itself supports the concept of jumping to labels, using:
```
break {labelname}
```
or
```
continue {labelname}
```
See this [JDC tech tip](http://java.sun.com/developer/TechTips/2000/tt0613.html) for more info. If your language is compiled to JVM bytecode, then you may be able to make use of this. | Java compilers or JVM languages that support goto? | [
"",
"java",
"programming-languages",
"language-design",
""
] |
I have to do that filter, I've found nice article about that (<http://www.codersource.net/csharp_image_processing_erosion.aspx>), but why the value 11 ([on this picture](http://www.codersource.net/images/ImageProcessing_Csharp_Errosion_erosion_gray_image.GIF)) isn't instead value 16 and 19 (in the second row). This value is the minimum yet. | Erosion in a gray-scale image takes the minimum of the values around the pixel according to the structuring element.
If you put the cross shaped structuring element on the element in the second row with initial value 19, you'll realize that its neighborhood is the cells with values 23(up), 42(left), 255(right), 11(down) and 19(the cell it self). Out of these, 11 is the minimum value so the value after erosion is 11. | You are using a mapping function to change the value of each pixel. For a particular pixel, say 56 in the article, you are wondering what the new eroded value should be. So you take that 3x3 binary mask and center it on the 56 pixel. Then you take they minimum value of the neighbor pixels wherever there is a one in the mask. So you take the minimum of 198 (top), 78 (bottom), 32 (left neighbor), 16 (right neighbor), and 56, the center itself. Obviously, the minimum value is 16. So 16 is the new, eroded value for what used to be 56. You just do this for every pixel and you get an eroded image. Cool!
Answer to your added question:
Pretend you have an old picture and a new one. You calculate new values from the old ones only. So the 11 is a new value. You don't use it. You just use old values. So you get 19 from the pixel to the left of 255, and the minimum is 16, the one above the 255 | Mathematical morphology - Erosion. Am I understanding it wrong? | [
"",
"c#",
""
] |
I have a config file that is in the following form:
```
protocol sample_thread {
{ AUTOSTART 0 }
{ BITMAP thread.gif }
{ COORDS {0 0} }
{ DATAFORMAT {
{ TYPE hl7 }
{ PREPROCS {
{ ARGS {{}} }
{ PROCS sample_proc }
} }
} }
}
```
The real file may not have these exact fields, and I'd rather not have to describe the the structure of the data is to the parser before it parses.
I've looked for other configuration file parsers, but none that I've found seem to be able to accept a file of this syntax.
I'm looking for a module that can parse a file like this, any suggestions?
If anyone is curious, the file in question was generated by Quovadx Cloverleaf. | [pyparsing](http://pyparsing.wikispaces.com/Introduction) is pretty handy for quick and simple parsing like this. A bare minimum would be something like:
```
import pyparsing
string = pyparsing.CharsNotIn("{} \t\r\n")
group = pyparsing.Forward()
group << pyparsing.Group(pyparsing.Literal("{").suppress() +
pyparsing.ZeroOrMore(group) +
pyparsing.Literal("}").suppress())
| string
toplevel = pyparsing.OneOrMore(group)
```
The use it as:
```
>>> toplevel.parseString(text)
['protocol', 'sample_thread', [['AUTOSTART', '0'], ['BITMAP', 'thread.gif'],
['COORDS', ['0', '0']], ['DATAFORMAT', [['TYPE', 'hl7'], ['PREPROCS',
[['ARGS', [[]]], ['PROCS', 'sample_proc']]]]]]]
```
From there you can get more sophisticated as you want (parse numbers seperately from strings, look for specific field names etc). The above is pretty general, just looking for strings (defined as any non-whitespace character except "{" and "}") and {} delimited lists of strings. | Taking Brian's pyparsing solution another step, you can create a quasi-deserializer for this format by using the Dict class:
```
import pyparsing
string = pyparsing.CharsNotIn("{} \t\r\n")
# use Word instead of CharsNotIn, to do whitespace skipping
stringchars = pyparsing.printables.replace("{","").replace("}","")
string = pyparsing.Word( stringchars )
# define a simple integer, plus auto-converting parse action
integer = pyparsing.Word("0123456789").setParseAction(lambda t : int(t[0]))
group = pyparsing.Forward()
group << ( pyparsing.Group(pyparsing.Literal("{").suppress() +
pyparsing.ZeroOrMore(group) +
pyparsing.Literal("}").suppress())
| integer | string )
toplevel = pyparsing.OneOrMore(group)
sample = """
protocol sample_thread {
{ AUTOSTART 0 }
{ BITMAP thread.gif }
{ COORDS {0 0} }
{ DATAFORMAT {
{ TYPE hl7 }
{ PREPROCS {
{ ARGS {{}} }
{ PROCS sample_proc }
} }
} }
}
"""
print toplevel.parseString(sample).asList()
# Now define something a little more meaningful for a protocol structure,
# and use Dict to auto-assign results names
LBRACE,RBRACE = map(pyparsing.Suppress,"{}")
protocol = ( pyparsing.Keyword("protocol") +
string("name") +
LBRACE +
pyparsing.Dict(pyparsing.OneOrMore(
pyparsing.Group(LBRACE + string + group + RBRACE)
) )("parameters") +
RBRACE )
results = protocol.parseString(sample)
print results.name
print results.parameters.BITMAP
print results.parameters.keys()
print results.dump()
```
Prints
```
['protocol', 'sample_thread', [['AUTOSTART', 0], ['BITMAP', 'thread.gif'], ['COORDS',
[0, 0]], ['DATAFORMAT', [['TYPE', 'hl7'], ['PREPROCS', [['ARGS', [[]]], ['PROCS', 'sample_proc']]]]]]]
sample_thread
thread.gif
['DATAFORMAT', 'COORDS', 'AUTOSTART', 'BITMAP']
['protocol', 'sample_thread', [['AUTOSTART', 0], ['BITMAP', 'thread.gif'], ['COORDS', [0, 0]], ['DATAFORMAT', [['TYPE', 'hl7'], ['PREPROCS', [['ARGS', [[]]], ['PROCS', 'sample_proc']]]]]]]
- name: sample_thread
- parameters: [['AUTOSTART', 0], ['BITMAP', 'thread.gif'], ['COORDS', [0, 0]], ['DATAFORMAT', [['TYPE', 'hl7'], ['PREPROCS', [['ARGS', [[]]], ['PROCS', 'sample_proc']]]]]]
- AUTOSTART: 0
- BITMAP: thread.gif
- COORDS: [0, 0]
- DATAFORMAT: [['TYPE', 'hl7'], ['PREPROCS', [['ARGS', [[]]], ['PROCS', 'sample_proc']]]]
```
I think you will get further faster with pyparsing.
-- Paul | Parsing an existing config file | [
"",
"python",
"parsing",
"config",
""
] |
I noticed that by default, all updates in the django admin site are done as transactions.
I need to either:
- turn off transactions (globally or for a particular admin view)
- inside of a save() method of an entity being saved via the admin interface, commit the transaction
The reason is that I overrode the save() method, and am notifying an external, non-django system about the change that just took place. However, the external system does not see the update since django has still not committed the transaction.
Does anyone have any suggestions on how to accomplish this? | You can use [commit\_manually](http://docs.djangoproject.com/en/dev/topics/db/transactions/#django-db-transaction-commit-manually) to get full control of a transaction in a particular view/function. | [How to globally deactivate transaction management](http://docs.djangoproject.com/en/dev/topics/db/transactions/#how-to-globally-deactivate-transaction-management) | Django admin: Turning off DB transactions | [
"",
"python",
"django",
"database",
"transactions",
"django-admin",
""
] |
Here is the definition of the stored procedure:
```
CREATE OR REPLACE PROCEDURE usp_dropTable(schema VARCHAR, tblToDrop VARCHAR) IS
BEGIN
DECLARE v_cnt NUMBER;
BEGIN
SELECT COUNT(*)
INTO v_cnt
FROM all_tables
WHERE owner = schema
AND table_name = tblToDrop;
IF v_cnt > 0 THEN
EXECUTE IMMEDIATE('DROP TABLE someschema.some_table PURGE');
END IF;
END;
END;
```
Here is the call:
```
CALL usp_dropTable('SOMESCHEMA', 'SOME_TABLE');
```
For some reason, I keep getting insufficient privileges error for the EXECUTE IMMEDIATE command. I looked online and found out that the insufficient privileges error usually means the oracle user account does not have privileges for the command used in the query that is passes, which in this case is DROP. However, I have drop privileges. I am really confused and I can't seem to find a solution that works for me.
Thanks to you in advance.
SOLUTION:
As Steve mentioned below, Oracle security model is weird in that it needs to know explicitly somewhere in the procedure what kind of privileges to use. The way to let Oracle know that is to use AUTHID keyword in the CREATE OR REPLACE statement. If you want the same level of privileges as the creator of the procedure, you use AUTHID DEFINER. If you want Oracle to use the privileges of the user currently running the stored procedure, you want to use AUTHID CURRENT\_USER. The procedure declaration looks as follows:
```
CREATE OR REPLACE PROCEDURE usp_dropTable(schema VARCHAR, tblToDrop VARCHAR)
AUTHID CURRENT_USER IS
BEGIN
DECLARE v_cnt NUMBER;
BEGIN
SELECT COUNT(*)
INTO v_cnt
FROM all_tables
WHERE owner = schema
AND table_name = tblToDrop;
IF v_cnt > 0 THEN
EXECUTE IMMEDIATE('DROP TABLE someschema.some_table PURGE');
END IF;
END;
END;
```
Thank you everyone for responding. This was definitely very annoying problem to get to the solution. | Oracle's security model is such that when executing dynamic SQL using Execute Immediate (inside the context of a PL/SQL block or procedure), the user does not have privileges to objects or commands that are granted via role membership. Your user likely has "DBA" role or something similar. You must explicitly grant "drop table" permissions to this user. The same would apply if you were trying to select from tables in another schema (such as sys or system) - you would need to grant explicit SELECT privileges on that table to this user. | You should use this example with **AUTHID CURRENT\_USER** :
```
CREATE OR REPLACE PROCEDURE Create_sequence_for_tab (VAR_TAB_NAME IN VARCHAR2)
AUTHID CURRENT_USER
IS
SEQ_NAME VARCHAR2 (100);
FINAL_QUERY VARCHAR2 (100);
COUNT_NUMBER NUMBER := 0;
cur_id NUMBER;
BEGIN
SEQ_NAME := 'SEQ_' || VAR_TAB_NAME;
SELECT COUNT (*)
INTO COUNT_NUMBER
FROM USER_SEQUENCES
WHERE SEQUENCE_NAME = SEQ_NAME;
DBMS_OUTPUT.PUT_LINE (SEQ_NAME || '>' || COUNT_NUMBER);
IF COUNT_NUMBER = 0
THEN
--DBMS_OUTPUT.PUT_LINE('DROP SEQUENCE ' || SEQ_NAME);
-- EXECUTE IMMEDIATE 'DROP SEQUENCE ' || SEQ_NAME;
-- ELSE
SELECT 'CREATE SEQUENCE COMPTABILITE.' || SEQ_NAME || ' START WITH ' || ROUND (DBMS_RANDOM.VALUE (100000000000, 999999999999), 0) || ' INCREMENT BY 1'
INTO FINAL_QUERY
FROM DUAL;
DBMS_OUTPUT.PUT_LINE (FINAL_QUERY);
cur_id := DBMS_SQL.OPEN_CURSOR;
DBMS_SQL.parse (cur_id, FINAL_QUERY, DBMS_SQL.v7);
DBMS_SQL.CLOSE_CURSOR (cur_id);
-- EXECUTE IMMEDIATE FINAL_QUERY;
END IF;
COMMIT;
END;
/
``` | Execute Immediate within a stored procedure keeps giving insufficient priviliges error | [
"",
"sql",
"stored-procedures",
"oracle10g",
"privileges",
""
] |
So I was writing some code, and I had something like this:
```
class Box
{
private:
float x, y, w, h;
public:
//...
Rectangle & GetRect( void ) const
{
return Rectangle( x, y, w, h );
}
};
```
Then later in some code:
```
Rectangle rect = theBox.GetRect();
```
Which worked in my debug build, but in release there were "issues" returning that Rectangle by reference -- I basically got an uninitialized rectangle. The Rectangle class has an = operator and a copy constructor. Without getting into why this broke, I'm actually more interested in the correct way to return a (new) object by reference **for the purpose of ~~assigning~~ copying to a variable.** Am I just being silly? Should it not be done? I know I can return a pointer and then dereference on assignment, but I'd rather not. Some part of me feels like returning by value would result in redundant copying of the object -- does the compiler figure that out and optimize it?
It seems like a trivial question. I feel almost embarrassed I don't know this after many years of C++ coding so hopefully someone can clear this up for me. :) | You can't return a reference to a temporary object on the stack. You have three options:
1. Return it by value
2. Return by reference via a pointer to something that you created on the heap with the new operator.
3. Return by reference what you received by reference as an argument. [EDIT: Thanks to @harshath.jr for pointing this out]
Note that when you return by value as in the code below, the compiler should optimize the assignment to avoid the copy - i.e. it will just create a single Rectangle (rect) by optimizing the create+assign+copy into a create. This only works when you create the new object when returning from the function.
```
Rectangle GetRect( void ) const
{
return Rectangle( x, y, w, h );
}
Rectangle rect = theBox.GetRect();
``` | No you cannot do this. Essentially what you're trying to do in this sample is return a reference to a temporary variable on the stack. By the time the reference is returned, the variable it's pointing to will be destroyed and hence the reference is invalid. | Is there a right way to return a new object instance by reference in C++? | [
"",
"c++",
"object",
"reference",
"return",
"variable-assignment",
""
] |
A few minutes ago, I asked whether it was better to perform many queries at once at log in and save the data in sessions, or to query as needed. I was surprised by the answer, (to query as needed). Are there other good rules of thumb to follow when building PHP/MySQL multi-user apps that speed up performance?
I'm looking for specific ways to create the most efficient application possible. | ## hashing
know your hashes (arrays/tables/ordered maps/whatever you call them). a hash lookup is very fast, and sometimes, if you have O(n^2) loops, you may reduce them to O(n) by organizing them into an array (keyed by primary key) first and then processing them.
an example:
```
foreach ($results as $result)
if (in_array($result->id, $other_results)
$found++;
```
is slow - `in_array` loops through the whole `$other_result`, resulting in O(n^2).
```
foreach ($other_results as $other_result)
$hash[$other_result->id] = true;
foreach ($results as $result)
if (isset($hash[$result->id]))
$found++;
```
the second one is a lot faster (depending on the result sets - the bigger, the faster), because isset() is (almost) constant time. actually, this is not a very good example - you could do this even faster using built in php functions, but you get the idea.
## optimizing (My)SQL
* **mysql.conf:** i don't have any idea how much performance you can gain by optimizing your mysql configuration instead of leaving the default. but i've read you can ignore every postgresql benchmark that used the default configuration. afaik with configuration matters less with mysql, but why ignore it? rule of thumb: try to fit the whole database into memory :)
* **explain [query]:** an obvious one, a lot of people get wrong. learn about indices. there are rules you can follow, you can benchmark it and you can make a huge difference. if you really want it all, learn about the different types of indices (btrees, hashes, ...) and when to use them.
## caching
caching is hard, but if done right it makes **the** difference (not *a* difference). in my opinion: if you can live without caching, don't do it. it often adds a lot of complexity and points of failures. google did a bit of proxy caching once (to make the intertubes faster), and some people saw private information of others.
in php, there are 4 different kinds of caching people regulary use:
* **query caching:** almost always translates to memcached (sometimes to APC shared memory). store the result set of a certain query to a fast key/value (=hashing) storage engine. queries (now lookups) become *very* cheap.
* **output caching:** store your generated html for later use (instead of regenerating it every time). this can result in the biggest speed-ups, but somewhat works against PHPs dynamic nature.
* **browser caching:** what about etags and http responses? if done right you may avoid most of the work *right at the beginning*! most php programmers ignore this option because they have no idea what HTTP is.
* **opcode caching:** APC, zend optimizer and so on. makes php code load faster. can help with big applications. got nothing to do with (slow) external datasources though, and the potential is somewhat limited.
sometimes it's not possible to live without caches, e.g. if it comes to thumbnails. image resizing is very expensive, but fortunatley easy to control (most of the time).
## profiler
[xdebug](http://www.xdebug.org/) shows you the bottlenecks of your application. if your app is too slow, it's helpful to know why.
## queries in loops
there are (php-)experts who *do not know what a join is* (and for every one you educate, two new ones without that knowledge will surface - and they will write frameworks, see schnalles law). sometimes, those queries-in-loops are not that obvious, e.g. if they come with libraries. count the queries - if they grow with the results shown, there is something wrong.
> inexperienced developers do have a primal, insatiable urge to write frameworks and content management systems
*schnalle's law* | Optimize your MySQL queries *first*, then the PHP that handles it, and then lastly cache the results of large queries and searches. MySQL is, by far, the most frequent bottleneck in an application. A poorly designed query can take two to three times longer than a well designed query that only selects needed information.
Therefore, if your queries are optimized *before* you cache them, you have saved a good deal of processing time.
However, on some shared hosts caching is file-system only thanks to a lack of Memcached. In this instance it may be better to run smaller queries than it is to cache them, as the seek time of the hard drive (and waiting for access due to other sites) can easily take longer than the query when your site is under load. | What are the rules of thumb to follow when building highly efficient PHP/MySQL programs? | [
"",
"php",
"mysql",
"performance",
""
] |
Please have a look on the following code -
```
var abc_text = "Hello";
var def_text = "world";
function testMe(elem) {
var xyz = elem+"_text";
alert(xyz);
}
testMe("abc");
testMe("def");
```
I am trying to pass prefix to a function and the try to print some pre-defined values by concatenating. But the above example just prints "abc\_text" and "def\_text" .. instead of "Hello" and "world". How can I get it working?
Thank you.
EDIT
I am using Jquery. | You can eval xyz, but it's better to store abc\_text and def\_text in associative array or in object;
```
var text = {"abc" : "Hello", "def" : "Word"};
``` | in this case use
```
var xyz = window[elem+"_text"];
``` | How to access javascript variable value by creating another variable via concatenation? | [
"",
"javascript",
""
] |
Is it possible to add elements to a collection while iterating over it?
More specifically, I would like to iterate over a collection, and if an element satisfies a certain condition I want to add some other elements to the collection, and make sure that these added elements are iterated over as well. (I realise that this *could* lead to an unterminating loop, but I'm pretty sure it won't in my case.)
The [Java Tutorial](http://java.sun.com/docs/books/tutorial/collections/interfaces/collection.html) from Sun suggests this is not possible: "Note that `Iterator.remove` is the *only* safe way to modify a collection during iteration; the behavior is unspecified if the underlying collection is modified in any other way while the iteration is in progress."
So if I can't do what I want to do using iterators, what do you suggest I do? | How about building a Queue with the elements you want to iterate over; when you want to add elements, enqueue them at the end of the queue, and keep removing elements until the queue is empty. This is how a breadth-first search usually works. | There are two issues here:
The first issue is, adding to an `Collection` after an `Iterator` is returned. As mentioned, there is no defined behavior when the underlying `Collection` is modified, as noted in the documentation for `Iterator.remove`:
> ... The behavior of an iterator is
> unspecified if the underlying
> collection is modified while the
> iteration is in progress in any way
> other than by calling this method.
The second issue is, even if an `Iterator` could be obtained, and then return to the same element the `Iterator` was at, there is no guarantee about the order of the iteratation, as noted in the [`Collection.iterator`](http://docs.oracle.com/javase/7/docs/api/java/util/Collection.html#iterator()) method documentation:
> ... There are no guarantees concerning the
> order in which the elements are
> returned (unless this collection is an
> instance of some class that provides a
> guarantee).
For example, let's say we have the list `[1, 2, 3, 4]`.
Let's say `5` was added when the `Iterator` was at `3`, and somehow, we get an `Iterator` that can resume the iteration from `4`. However, there is no guarentee that `5` will come after `4`. The iteration order may be `[5, 1, 2, 3, 4]` -- then the iterator will still miss the element `5`.
As there is no guarantee to the behavior, one cannot assume that things will happen in a certain way.
One alternative could be to have a separate `Collection` to which the newly created elements can be added to, and then iterating over those elements:
```
Collection<String> list = Arrays.asList(new String[]{"Hello", "World!"});
Collection<String> additionalList = new ArrayList<String>();
for (String s : list) {
// Found a need to add a new element to iterate over,
// so add it to another list that will be iterated later:
additionalList.add(s);
}
for (String s : additionalList) {
// Iterate over the elements that needs to be iterated over:
System.out.println(s);
}
```
**Edit**
Elaborating on [Avi's answer](https://stackoverflow.com/questions/993025/java-adding-elements-to-a-collection-during-iteration/993036#993036), it is possible to queue up the elements that we want to iterate over into a queue, and remove the elements while the queue has elements. This will allow the "iteration" over the new elements in addition to the original elements.
Let's look at how it would work.
Conceptually, if we have the following elements in the queue:
`[1, 2, 3, 4]`
And, when we remove `1`, we decide to add `42`, the queue will be as the following:
`[2, 3, 4, 42]`
As the queue is a [FIFO](http://en.wikipedia.org/wiki/FIFO) (first-in, first-out) data structure, this ordering is typical. (As noted in the documentation for the [`Queue`](http://docs.oracle.com/javase/7/docs/api/java/util/Queue.html) interface, this is not a necessity of a `Queue`. Take the case of [`PriorityQueue`](http://docs.oracle.com/javase/7/docs/api/java/util/PriorityQueue.html) which orders the elements by their natural ordering, so that's not FIFO.)
The following is an example using a [`LinkedList`](http://docs.oracle.com/javase/7/docs/api/java/util/LinkedList.html) (which is a [`Queue`](http://docs.oracle.com/javase/7/docs/api/java/util/Queue.html)) in order to go through all the elements along with additional elements added during the dequeing. Similar to the example above, the element `42` is added when the element `2` is removed:
```
Queue<Integer> queue = new LinkedList<Integer>();
queue.add(1);
queue.add(2);
queue.add(3);
queue.add(4);
while (!queue.isEmpty()) {
Integer i = queue.remove();
if (i == 2)
queue.add(42);
System.out.println(i);
}
```
The result is the following:
```
1
2
3
4
42
```
As hoped, the element `42` which was added when we hit `2` appeared. | Adding elements to a collection during iteration | [
"",
"java",
"iterator",
""
] |
I was playing around with SQL Queries and this one came to my mind - `select x,y from table T`.
Here x and y can be arithmetic expressions like 2.0/5.0 OR 1+2, the result has the number of rows of table T, with the first column having value 2.0/5.0 i.e. 0.444444 and the second column having value 3.
I am curious to know as to how this query is executed. I have learned that in the SQL query engine there is a mapping from SQL representation of a query to an internal representation (like relational algebra) which is then optimized in order to yield an optimal query execution plan.
Please correct my understanding if its wrong - For the query which I have stated, there would be an internal mapping from my query Q to an internal representation which is equivalent to that of `select * from table T`. Then for all the rows returned, n number of columns are projected out where n is the number of arithmetic expressions stated in the Q. And all rows for the n columns would have their respective evaluations of the arithmetic expressions.
cheers | It most likely depends on the database.
If the expressions you use for x and y were constant then a decent database ought to recognize that and perform the calculation only once and just putting the value in the result set.
If the expressions included some other function then it would have to execute the expression each time in case the function had side effects.
In general you are correct, calculate the virtual table described in the from clause, then I believe the filters from the where clause are applied followed by the select clause. | No, the expressions are only evaluated once (at least in MS SQL Server).
You can easily see this if you do:
```
select rand() from tableT
```
All rows will have the same random number. | How would this SQL query be evaluated by the query engine? | [
"",
"sql",
"sql-execution-plan",
""
] |
I have a common database joining situation involving three tables. One table, A, is the main table with a primary key named `id`. Tables B and C contain auxiliary data for entries and A, and each also has a column named `id` which is a foreign key pointing to A.`id`. Now, if I want all data from A, B and C in one query, I would write:
```
SELECT *
FROM A
INNER JOIN B
ON B.id = A.id
INNER JOIN C
ON C.id = A.id
```
which of course works perfectly.
Recently, our DBA told us that this is inefficient in Oracle, and you need to join conditions between C and B as well, as follows:
```
SELECT *
FROM A
INNER JOIN B
ON B.id = A.id
INNER JOIN C
ON C.id = A.id AND C.id = B.id
```
This looked redundant to me, so naturally I didn't believe here. Until I actually ran into a slow query that had a terrible execution plan, and managed to fix it by exactly adding the missing join condition. I ran explain plan on both versions: the one without the "redundant" query condition had a cost of 1 035 while the "improved" one had 389 (and there were huge differences in cardinality and bytes as well). Both queries produced the exact same result.
Can anyone explain why this extra condition makes a difference? To me C and B are not even related. Note also that if you take away the other join condition it is equally bad - they both need to be there. | What you've got is two issues.
Firstly, with the original SQL, the optimizer makes an estimate about the number of rows in A with rows matching the ID in B which also have a matching row in C. The estimate is inaccurate, and the wrong plan is chosen.
Now, you add the redundant condition. Oracle assumes no conditions are truly redundant (as, if they were, an intelligent developer wouldn't include them). It also assumes that each condition is independent of the others. For example, a select where hair = 'bald' may get 10% of a table, a select where gender = 'F' may get 50%. Oracle would assume that a select where hair = 'bald' and gender = 'F' would give 5% (whereas in reality baldness is mostly limited to men).
By adding the 'redundant' predicate, Oracle will over-estimate the numbers or rows to be excluded and will choose the plan accordingly.
If, with the redundant predicate, Oracle is choosing a better plan, it suggests that the estimates for the original query over-estimated the number of rows matching. The redundant predicate is countering that with an under-estimate. And in this case, two wrongs are making a right.
It's not a solution I'd recommend, but if it works.....
PS. I'm assuming data types of all the IDs are consistent. If B.ID and C.ID are date and A.ID was character, or vice versa, then it is possible to have some rows where A.ID = B.ID and A.ID = C.ID but B.ID != C.ID, because implicit conversion may lose timestamps. | Interesting.
It seems that Oracle can infer this transitive equality only under some circumstances : They call it [Transitive Closure](http://jonathanlewis.wordpress.com/2007/01/01/transitive-closure/) and you should be able to benefit from it when query rewriting is enabled.
But to be on the safe side, better spell out the redundant predicate yourself. | Adding redudant join conditions in Oracle results in a different plan | [
"",
"sql",
"oracle",
"join",
""
] |
I'm in the process of building a web application using cherrypy.
What template technology do you recommend I use? | Do you mean View in MVC? I recommend you very nice template engine [Jinja2](http://jinja.pocoo.org/2/documentation/). | If you mean a templating engine, I've had some success using [mako](http://www.makotemplates.org/) with cherrypy. They just seem to play nicely together.
Mako is extremely easy to get started with and customize, which is, I assume, also two of your major reasons for choosing cherrypy. The cherrypy official tutorial also uses mako, and you can see a [simple sample application](http://www.cherrypy.org/wiki/intro/1) there. | Which template technology should I use with CherryPy? | [
"",
"python",
"templates",
"template-engine",
"cherrypy",
""
] |
Such as in PHP:
```
<?php
$a = 'hello';
$$a = 'world';
echo $hello;
// Prints out "world"
?>
```
I need to create an unknown number of HashMaps on the fly (which are each placed into an arraylist). Please say if there's an easier or more Java-centric way. Thanks. | The best you can do is have a HashMap of HashMaps. For example:
```
Map<String,Map<String,String>> m = new HashMap<String,Map<String,String>>();
// not set up strings pointing to the maps.
m.put("foo", new HashMap<String,String>());
``` | Its not called variable variables in java.
Its called reflection.
Take a look at java.lang.reflect package docs for details.
You can do all such sorts of things using reflection.
Bestoes,
jrh. | Does Java support variable variables? | [
"",
"java",
""
] |
I have a program in which I need to run multiple insert statements (dynamically generated) against a MS SQL Table. Right now, I do (pseudo-code):
```
Loop
Generate Insert Statement String
SQLCommand.Text = Generated Insert Statement String
SQLCommand.Execute().
End Loop
Close Connection
```
Is it better performance-wise to simply construct one big string of inserts, separated by semi-colons. And run only one SQLCommand.Execute() statement? Or does it not make a difference?
Thanks! | You need to start a transaction before you begin your inserts. Then, when you have send all your inserts to the server and finished the loop, you should commit. This will save you a lot writes on the database!
See more here: <http://msdn.microsoft.com/en-us/library/5ha4240h.aspx> | you might find this [technique](http://blog.sqlauthority.com/2007/06/08/sql-server-insert-multiple-records-using-one-insert-statement-use-of-union-all/) useful. It significantly cuts down on the number of statements processed. | Executing Multiple Insert Statements, what's the Best Way? | [
"",
"sql",
"database",
"sql-server-2005",
"database-connection",
""
] |
I have a simple method which is called from multiple threads;
```
@Override
public Bitmap getFullBitmap(Filter f, ProgressCallback<String> pc) {
// Requires synchronisation?
Bitmap bitmap = fullMap.get(f.id);
if(bitmap == null){
f.setProgressCallback(pc);
bitmap = f.e.evaluate(currentBitmap);
fullMap.put(f.id, bitmap);
}
return bitmap;
}
```
As none of the objects used are fields of the class (Apart from fullMap) is it ok just to call this or might one thread change the value of **bitmap** for example, while the method is executing?
fullMap is a SoftHashMap which maintains SoftReferences of Bitmap objects indexed but the Filter's id that was used to create it. If that makes any sense.
I haven't had any problems but I thought I might need it.
Please ask for clarification if this is not clear, the question makes sense in my head ;)
**EDIT**
* currentBitmap is an object of type Bitmap, there is one bitmap in the system which is considered current and it's managed by this class.
* This code forms a very basic cache,
the bitmap returned will always be
the same for each id and is not
modified outside of this method.
* By using Soft References in a
SoftHashMap as descibed by [Dr
Heinx](http://www.javaspecialists.eu/archive/Issue098.html) and a FIFO queue of hard
references for the 10 most recently
added I hope to avoid expensive calls
to f.e.evaluate. That being said, the
call f.e.evaluate will return an
identical bitmap object if it is
given the same input. After some
thought it seems that synchronizing
the method is a good idea as nothing
positive comes of two threads
executing this code for the same
filter.
* In addition I made bitmap final as it
shouldn't be mutated after creation.
Many thanks!
Gav | 2 threads could access the map `fullMap` at the same time. Both could determine that the map doesn't contain a value for the same key, each create one, and then write it back, thus inserting a key twice.
This may well not be a problem beyond one of efficiency. However it can be a source of confusion, and may cause problems in the future as your solution evolves (how expensive will it be to create these objects in the future? What happens if someone copies/paste the code somewhere less appropriate!)
I would strongly recommend synchronising on the above (most probably on `fullMap` itself rather than the containing object, but more context would be useful before deciding exactly what's required) | SoftHashMap.put itself may just not be thread-safe. SoftHashMap isn't in the standard library, but [WeakHashMap](http://java.sun.com/j2se/1.4.2/docs/api/java/util/WeakHashMap.html) is, and it's not synchronized. Besides synchronizing the method on the map, you may want to use [Collections.synchronizedMap](http://java.sun.com/j2se/1.5.0/docs/api/java/util/Collections.html#synchronizedMap(java.util.Map)) to ensure other methods don't modify the map concurrently. | Java Synchronisation - Do I need it for this simple method? | [
"",
"java",
"synchronization",
"methods",
""
] |
As in, if I have an XML Document
```
<root a="value">
<item name="first">
x
<foo name = "firstgrandchild">There is nothing here</foo>
y
<foo name = "secondgrandchild">There is something here</foo>
</item>
<item name="second">
xy
<foo/>
ab
</item>
</root>
```
I want to first find the first occurrence of node "item" and then update the attribute, and then I want to update the first occurrence of node "foo" and then update the attribute etc.,
My Code is as below
```
myDoc.Load("Items2.xml");
myNode = myDoc.DocumentElement;
mySearchNode = myNode.SelectSingleNode("/root/item");
mySearchNode.Attributes["name"].Value = "Joel";
Console.WriteLine(mySearchNode.OuterXml);
mySearchChildNode = mySearchNode.SelectSingleNode("/item/foo");
Console.WriteLine(mySearchChildNode.OuterXml);
```
While, the first search and update of attribute works fine, the second one fails as mySearchNode.SelectSingleNode returns null.
Question - Is there something fundamentally that is wrong with this code?
Why does not the SelectSingleNode work as expected in the second instance, as far as it is concerned, I am executing it on a XmlNode of type Element.
Kindly assist.
Many Thanks, | Your second XPath query should be without the leading slash. / means "root of document". If you omit the slash, the query will be relative to your mySearchNode variable. You also should not include "item" again, your query is relative to the "item" node you selected. In code:
```
myDoc.Load("Items2.xml");
myNode = myDoc.DocumentElement;
mySearchNode = myNode.SelectSingleNode("/root/item");
mySearchNode.Attributes["name"].Value = "Joel";
Console.WriteLine(mySearchNode.OuterXml);
mySearchChildNode = mySearchNode.SelectSingleNode("foo");
Console.WriteLine(mySearchChildNode.OuterXml);
``` | mySearchNode is the `item` node, so if `foo` is a child of `item` your second xpath should simply be `"foo"` | C # SelectSingleNode - Can it be used recursively? | [
"",
"c#",
"xml",
"selectsinglenode",
""
] |
Although this question is similar to [this thread](https://stackoverflow.com/questions/175103/regex-to-match-url-end-of-line-or-character)
I think I might be doing something wrong at the time of constructing the code with the Regular Expression.
I want to match anything in a line up to a comment ("#") or the end of the line (if it doesn't have a comment).
The regex I am using is: `(.*)(#|$)`
`(.*)` = Everything
`(#|$)` = comment or end of line
The code:
```
OPTION = re.compile(r'(?P<value>.*)(#|$)')
file = open('file.txt')
lines = file.read()
for line in lines.split('\n'):
get_match = OPTION.match(line)
if get_match:
line_value = get_match.group('value')
print "Match= %s" % line_value
```
The above works but does not strip out the comment.
If the file has a line like:
```
this is a line # and this is a comment
```
I still get the whole line when running the code.
Am I missing additional values/information in the regular expression or do I need to have a change on the code? | The \* is greedy (consumes as much of the string as it can) and is thus consuming the entire line (past the # and to the end-of-line). Change ".\*" to ".\*?" and it will work.
See the [Regular Expression HOWTO](http://docs.python.org/howto/regex.html#repeating-things) for more information. | Here's the correct regex to do something like this:
```
([^#]*)(#.*)?
```
Also, why don't you just use
```
file = open('file.txt')
for line in file:
``` | Expression up to comment or end of line | [
"",
"python",
"regex",
""
] |
Suppose it is a long article (say 100,000 words), and I need to write a PHP file to display page 1, 2, or page 38 of the article, by
```
display.php?page=38
```
but the number of words for each page can change over time (for example, right now if it is 500 words per page, but next month, we can change it to 300 words per page easily). What is a good way to divide the long article and store into the database?
**P.S.** The design may be further complicated if we want to display 500 words but include whole paragraphs. That is, if we are showing word 480 already but the paragraph has 100 more words remaining, then show those 100 words anyway even though it exceeds the 500 words limit. (and then, the next page shouldn't show those 100 words again). | I would do it by splitting articles on chuks when saving them. The save script would split the article using whatever rules you design into it and save each chunk into a table like this:
```
CREATE TABLE article_chunks (
article_id int not null,
chunk_no int not null,
body text
}
```
Then, when you load a page of an article:
```
$sql = "select body from article_chunks where article_id = "
.$article_id." and chunk_no=".$page;
```
Whenever you want to change the logic of splitting articles into pages, you run a script thats pulls all the chunks together and re-splits them:
**UPDPATE:** Giving the advice I suppose your application is read-intensive more than write-intensive, meaning that articles are read more often than they are written | You could of course output exactly 500 words per page, but the better way would be to put some kind of breaks into your article (end of sentence, end of paragraph). Put these at places where a break would be good. This way your pages won't have exactly X words in it each, but about or up to X and it won't tear sentences or paragraphs apart.
Of course, when displaying the pages, don't display these break markers. | How to divide a long article and store in the database for easy retrieval and with paging? | [
"",
"php",
"database",
"database-design",
"schema",
""
] |
Maybe I am just blind, but I do not see how to use Guice (just starting with it) to replace the `new` call in this method:
```
public boolean myMethod(String anInputValue) {
Processor proc = new ProcessorImpl(anInputValue);
return proc.isEnabled();
}
```
For testing there might be a different implementation of the Processor, so I'd like to avoid the `new` call and in the course of that get rid of the dependency on the implementation.
If my class could just remember an instance of Processor I could inject it via the constructor, but as the Processors are designed to be immutable I need a new one every time.
How would I go about and achieve that with Guice (2.0) ? | There is some time since I used Guice now, but I remember something called "assisted injection". It allows you to define a factory method where some parameters are supplied and some are injected. Instead of injecting the Processor you inject a processor factory, that has a factory method that takes the `anInputValue` parameter.
I point you to the [javadoc of the FactoryProvider](http://google-guice.googlecode.com/svn/trunk/latest-javadoc/com/google/inject/assistedinject/FactoryProvider.html). I believe it should be usable for you. | You can get the effect you want by injecting a "Provider", which can by asked at runtime to give you a Processor. Providers provide a way to defer the construction of an object until requested.
They're covered in the Guice Docs [here](http://code.google.com/docreader/#p=google-guice&s=google-guice&t=ProviderBindings) and [here](http://code.google.com/docreader/#p=google-guice&s=google-guice&t=InjectingProviders).
The provider will look something like
```
public class ProcessorProvider implements Provider<Processor> {
public Processor get() {
// construct and return a Processor
}
}
```
Since Providers are constructed and injected by Guice, they can themselves have bits injected.
Your code will look something like
```
@Inject
public MyClass(ProcessorProvider processorProvider) {
this.processorProvider = processorProvider;
}
public boolean myMethod(String anInputValue) {
return processorProvider.get().isEnabled(anInputValue);
}
``` | How to use Google Guice to create objects that require parameters? | [
"",
"java",
"dependency-injection",
"guice",
""
] |
Is there a way to get the case-insensitive distinct rows from this SAS SQL query? ...
```
SELECT DISTINCT country FROM companies;
```
The ideal solution would consist of a single query.
Results now look like:
```
Australia
australia
AUSTRALIA
Hong Kong
HONG KONG
```
... where any of the 2 distinct rows is really required
One could upper-case the data, but this unnecessarily changes values in a manner that doesn't suit the purpose of this query. | If you have some primary int key (let's call it ID), you could use:
```
SELECT country FROM companies
WHERE id =
(
SELECT Min(id) FROM companies
GROUP BY Upper(country)
)
``` | Normalizing case does seem advisable -- if 'Australia', 'australia' and 'AUSTRALIA' all occur, which one of the three would you want as the "case-sensitively unique" answer to your query, after all? If you're keen on some specific heuristics (e.g. count how many times they occur and pick the most popular), this can surely be done but might be a huge amount of extra work -- so, how much is such persnicketiness worth to you? | Is it possible to do a case-insensitive DISTINCT with SAS (PROC SQL)? | [
"",
"sql",
"sas",
"proc-sql",
""
] |
Is there any event in C# that fires when the form STOPS being moved. Not while its moving.
If there is no event for it, is there a way of doing it with WndProc? | The ResizeEnd event fires after a move ends. Perhaps you could use that. | This is not a failsafe solution, but it's pure .NET and it's dead simple. Add a timer to your form, set it to a relatively short delay (100-150 ms seemed OK for me). Add the following code for the Form.LocationChanged and Timer.Tick events:
```
private void Form_LocationChanged(object sender, EventArgs e)
{
if (this.Text != "Moving")
{
this.Text = "Moving";
}
tmrStoppedMoving.Start();
}
private void Timer_Tick(object sender, EventArgs e)
{
tmrStoppedMoving.Start();
this.Text = "Stopped";
}
```
If you want more exact handling (knowing exactly when the mouse button is release in the title bar and such) you will probably need to dive into monitoring windows messages. | C# Form Move Stopped Event | [
"",
"c#",
"winforms",
"events",
"move",
"wndproc",
""
] |
I have a class library file that is not is not getting picked up when I add it to the reference and bin folder.
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
namespace SecuritySettings
{
public class Security
{
...
public Security()
{...}
}
}
```
Is there something that I am not doing behind the scene or something else? | Try checking your .csproj fie (open in notepad) for the reference and ensure the path is correct.
Also, instead of copying the file directly into the bin folder (which is genrally bad as this is the folder Visual Studio deploy built dll's into), create a new folder in your project (for example a folder called 'libs') and reference it from there. | Check the project setting, look at the Root namespace settings, that may be confusing you. | Why would my Class Library not get referenced? | [
"",
"c#",
".net",
"asp.net",
"class",
""
] |
I am a newbie in the area of AOP. The first time I coded something applying concepts of AOP, I was thrilled to understand how aspects eliminate cross cutting patterns in your application. I was overwhelmed by the thought of solving cross cutting patterns like security, logging, transactions, auditing and etc applying AOP.
However, when I first proposed usage of AOP to the client I am working for, I was told that they don't support it. I was told that AOP means more maintenance! Your pointcuts have to change if your code changes. Hence, you might have to analyze, change and test your aspects whenever you change the code to which they were applied?
What do you have to say regarding this? Why are mainstream companies not open yet to extensive usage of AOP? Where is the AOP world going? | AOP is a relatively new concept, and large companies are generally wary towards new concepts. They fear getting stuck with a lot of AOP code and unable to find people who can maintain it.
Regarding the specific criticism, it seems uninformed or misunderstood. The whole point of AOP is to reduce maintenance work by reducing code duplication in the area of cross-cutting concerns. However, it is true that it can make maintenance more difficult by making it harder to understand the the code - with AOP, when you look at a particular piece of code, there's always the chance that an aspect defined somewhere else completely changes its behaviour.
Personally, I'm not sure the benefits of AOP (are there really that many cross-cutting concerns?) outweigh this problem. The only way to I can see to solve it would be through support in IDEs; but making you even more dependant on an IDE isn't such a great thing either.
The trend seems to be towards app servers and frameworks that address specific, important cross-cutting concerns like transactions and security in a similar manner as AOP (i.e. central declarative definition) but without giving you its full power to confuse maintenance developers. | AOP is one of those things that's an interesting idea that just doesn't work all that well in practice. Java's had AOP available for a decade or more now, and it's not being used much because it seems to introduce more problems than it fixes. | Future of Aspect Oriented Programming | [
"",
"java",
"aop",
"aspects",
""
] |
I want to run the following sql command:
```
ALTER TABLE `my_table` ADD UNIQUE (
`ref_id` ,
`type`
);
```
The problem is that some of the data in the table would make this invalid, therefore altering the table fails.
Is there a clever way in MySQL to delete the duplicate rows? | if you don't care which row gets deleted, use IGNORE:
```
ALTER IGNORE TABLE `my_table` ADD UNIQUE (
`ref_id` ,
`type`
);
``` | SQL can, at best, handle this arbitrarily. To put it another way: this is your problem.
You have data that currently isn't unique. You want to make it unique. You need to decide how to handle the duplicates.
There are a variety of ways of handling this:
* Modifying or deleting duplicate rows by hand if the numbers are sufficiently small;
* Running statements to update or delete duplicate that meet certain criteria to get to a point where the exceptions can be dealt with on an individual basis;
* Copying the data to a temporary table, emptying the original and using queries to repopulate the table; and
* so on.
**Note:** these all require user intervention.
You could of course just copy the table to a temporary table, empty the original and copy in the rows just ignoring those that fail but I expect that won't give you the results that you really want. | Changing table field to UNIQUE | [
"",
"sql",
"mysql",
"unique",
""
] |
How to make a where in clause similar to one in SQL Server?
I made one by myself but can anyone please improve this?
```
public List<State> Wherein(string listofcountrycodes)
{
string[] countrycode = null;
countrycode = listofcountrycodes.Split(',');
List<State> statelist = new List<State>();
for (int i = 0; i < countrycode.Length; i++)
{
_states.AddRange(
from states in _objdatasources.StateList()
where states.CountryCode == countrycode[i].ToString()
select new State
{
StateName = states.StateName
});
}
return _states;
}
``` | This expression should do what you want to achieve.
```
dataSource.StateList.Where(s => countryCodes.Contains(s.CountryCode))
``` | This will translate to a where in clause in Linq to SQL...
```
var myInClause = new string[] {"One", "Two", "Three"};
var results = from x in MyTable
where myInClause.Contains(x.SomeColumn)
select x;
// OR
var results = MyTable.Where(x => myInClause.Contains(x.SomeColumn));
```
In the case of your query, you could do something like this...
```
var results = from states in _objectdatasource.StateList()
where listofcountrycodes.Contains(states.CountryCode)
select new State
{
StateName = states.StateName
};
// OR
var results = _objectdatasource.StateList()
.Where(s => listofcountrycodes.Contains(s.CountryCode))
.Select(s => new State { StateName = s.StateName});
``` | Where IN clause in LINQ | [
"",
"c#",
"linq",
""
] |
I tried using Formatter.format, but that seems to leave the mantissa on numbers with 0 mantissa, whereas the C version does not. Is there an equivalent of C's %g format specifier in Java, and if not, is there a way to fake it? My intention is to preserve the mantissa exactly like C's for compatibility reasons.
foo.c
```
#include <stdio.h>
int main (int argc, char const *argv[])
{
printf("%g\n", 1.0);
return 0;
}
```
Main.java
```
class Main {
public static void main(String[] args) {
System.out.printf("%g\n", 1.0);
}
}
```
Console:
```
$ javac Main.java && java Main
1.00000
$ gcc foo.c && ./a.out
1
```
Similarly, with 1.2 as input, the mantissa is longer in Java's version
```
$ javac Main.java && java Main
1.20000
$ gcc foo.c && ./a.out
1.2
``` | Have you tried the [java.text.DecimalFormat](http://java.sun.com/javase/6/docs/api/java/text/DecimalFormat.html) class?
```
System.out.println(new DecimalFormat().format(1.0));
```
outputs:
```
1
```
whereas:
```
System.out.println(new DecimalFormat().format(1.2));
```
outputs:
```
1.2
``` | **edit**:
This code causes the fractional part to go missing if the exponent is 17 digits, because of my misunderstanding of how String.format formatted those numbers. So don't please don't use this code :P
Thanks for the input, guys. I couldn't find a way to configure DecimalFormat or NumberFormat to exactly clone the functionality, but it seems this method works (followed by an example):
```
String.format("%.17g", x).replaceFirst("\\.?0+(e|$)", "$1");
```
main.c
```
#include <stdio.h>
int main (int argc, char const *argv[])
{
printf("%.*g\n", 17, -0.0);
printf("%.*g\n", 17, 0.0);
printf("%.*g\n", 17, 1.0);
printf("%.*g\n", 17, 1.2);
printf("%.*g\n", 17, 0.0000000123456789);
printf("%.*g\n", 17, 1234567890000000.0);
printf("%.*g\n", 17, 0.0000000123456789012345678);
printf("%.*g\n", 17, 1234567890123456780000000.0);
return 0;
}
```
Main.java
```
class Main {
public static String formatDouble(double x) {
return String.format("%.17g", x).replaceFirst("\\.?0+(e|$)", "$1");
}
public static void main(String[] args) {
System.out.println(formatDouble(-0.0));
System.out.println(formatDouble(0.0));
System.out.println(formatDouble(1.0));
System.out.println(formatDouble(1.2));
System.out.println(formatDouble(0.0000000123456789));
System.out.println(formatDouble(1234567890000000.0));
System.out.println(formatDouble(0.0000000123456789012345678));
System.out.println(formatDouble(1234567890123456780000000.0));
}
}
```
and their outputs:
```
$ gcc foo.c && ./a.out
-0
0
1
1.2
1.23456789e-08
1234567890000000
1.2345678901234567e-08
1.2345678901234568e+24
$ javac Main.java && java Main
-0
0
1
1.2
1.23456789e-08
1234567890000000
1.2345678901234567e-08
1.2345678901234568e+24
``` | What is the Java equivalent of C's printf %g format specifier? | [
"",
"java",
"c",
"printf",
"formatter",
""
] |
**Update: Problem solved, and staying solved.** *If you want to see the site in action, visit [Tweet08](http://www.tweet08.com)*
I've got several queries that act differently in SSMS versus when run inside my .Net application. The SSMS executes fine in under a second. The .Net call times out after 120 seconds (connection default timeout).
I did a SQL Trace (and collected *everything*) I've seen that the connection options are the same (and match the SQL Server's defaults). The SHOWPLAN All, however, show a huge difference in the row estimates and thus the working version does an aggressive Table Spool, where-as the failing call does not.
In the SSMS, the datatypes of the temp variables are based on the generated SQL Parameters in the .Net, so they are the same.
The failure executes under Cassini in a VS2008 debug session. The success is under SSMS 2008 . Both are running against the same destination server form the same network on the same machine.
Query in SSMS:
```
DECLARE @ContentTableID0 TINYINT
DECLARE @EntryTag1 INT
DECLARE @ContentTableID2 TINYINT
DECLARE @FieldCheckId3 INT
DECLARE @FieldCheckValue3 VARCHAR(128)
DECLARE @FieldCheckId5 INT
DECLARE @FieldCheckValue5 VARCHAR(128)
DECLARE @FieldCheckId7 INT
DECLARE @FieldCheckValue7 VARCHAR(128)
SET @ContentTableID0= 3
SET @EntryTag1= 8
SET @ContentTableID2= 2
SET @FieldCheckId3= 14
SET @FieldCheckValue3= 'igor'
SET @FieldCheckId5= 33
SET @FieldCheckValue5= 'a'
SET @FieldCheckId7= 34
SET @FieldCheckValue7= 'a'
SELECT COUNT_BIG(*)
FROM dbo.ContentEntry AS mainCE
WHERE GetUTCDate() BETWEEN mainCE.CreatedOn AND mainCE.ExpiredOn
AND (mainCE.ContentTableID=@ContentTableID0)
AND ( EXISTS (SELECT *
FROM dbo.ContentEntryLabel
WHERE ContentEntryID = mainCE.ID
AND GetUTCDate() BETWEEN CreatedOn AND ExpiredOn
AND LabelFacetID = @EntryTag1))
AND (mainCE.OwnerGUID IN (SELECT TOP 1 Name
FROM dbo.ContentEntry AS innerCE1
WHERE GetUTCDate() BETWEEN innerCE1.CreatedOn AND innerCE1.ExpiredOn
AND (innerCE1.ContentTableID=@ContentTableID2
AND EXISTS (SELECT *
FROM dbo.ContentEntryField
WHERE ContentEntryID = innerCE1.ID
AND (ContentTableFieldID = @FieldCheckId3
AND DictionaryValueID IN (SELECT dv.ID
FROM dbo.DictionaryValue AS dv
WHERE dv.Word LIKE '%' + @FieldCheckValue3 + '%'))
)
)
)
OR EXISTS (SELECT *
FROM dbo.ContentEntryField
WHERE ContentEntryID = mainCE.ID
AND ( (ContentTableFieldID = @FieldCheckId5
AND DictionaryValueID IN (SELECT dv.ID
FROM dbo.DictionaryValue AS dv
WHERE dv.Word LIKE '%' + @FieldCheckValue5 + '%')
)
OR (ContentTableFieldID = @FieldCheckId7
AND DictionaryValueID IN (SELECT dv.ID
FROM dbo.DictionaryValue AS dv
WHERE dv.Word LIKE '%' + @FieldCheckValue7 + '%')
)
)
)
)
```
Trace's version of .Net call (*some formatting added*):
```
exec sp_executesql N'SELECT COUNT_BIG(*) ...'
,N'@ContentTableID0 tinyint
,@EntryTag1 int
,@ContentTableID2 tinyint
,@FieldCheckId3 int
,@FieldCheckValue3 varchar(128)
,@FieldCheckId5 int
,@FieldCheckValue5 varchar(128)
,@FieldCheckId7 int
,@FieldCheckValue7 varchar(128)'
,@ContentTableID0=3
,@EntryTag1=8
,@ContentTableID2=2
,@FieldCheckId3=14
,@FieldCheckValue3='igor'
,@FieldCheckId5=33
,@FieldCheckValue5='a'
,@FieldCheckId7=34
,@FieldCheckValue7='a'
``` | Checked and this server, a development server, was not running SQL Server 2005 SP3. Tried to install that (with necessary reboot), but it didn't install. Oddly now both code and SSMS return in subsecond time.
Woot this is a HEISENBUG. | It is not your indexes.
This is parameter-sniffing, as it usually happens to parametrized stored procedures. It is not widely known, even among those who know about parameter-sniffing, but it can also happen when you use parameters through sp\_executesql.
You will note that the version that you are testing in SSMS and the version the the profiler is showing are not identical because the profiler version shows that your .Net application is executing it through sp\_executesql. If you extract and execute the full sql text that is actually being run for your application, then I believe that you will see the same performance problem with the same query plan.
FYI: the query plans being different is the key indicator of parameter-sniffing.
FIX: The easiest way to fix this one assuming it is executing on SQL Server 2005 or 2008 is to add the clause "OPTION (RECOMPILE)" as the last line of you SELECT statement. Be forewarned, you may have to execute it twice before it works and it does not always work on SQL Server 2005. If that happens, then there are other steps that you can take, but they are a little bit more involved.
One thing that you could try is to check and see if "Forced Parameterization" has been turned on for your database (it should be in the SSMS Database properties, under the Options page). To tunr Forced Parameterization off execute this command:
```
ALTER DATABASE [yourDB] SET PARAMETERIZATION SIMPLE
``` | Query times out in .Net SqlCommand.ExecuteNonQuery, works in SQL Server Management Studio | [
"",
"sql",
"sql-server",
"t-sql",
"timeout",
"ssms",
""
] |
I'm parsing an XML file with the `XmlReader` class in .NET and I thought it would be smart to write a generic parse function to read different attributes generically. I came up with the following function:
```
private static T ReadData<T>(XmlReader reader, string value)
{
reader.MoveToAttribute(value);
object readData = reader.ReadContentAsObject();
return (T)readData;
}
```
As I came to realise, this does not work entirely as I have planned; it throws an error with primitive types such as `int` or `double`, since a cast cannot convert from a `string` to a numeric type. Is there any way for my function to prevail in modified form? | First check to see if it can be cast.
```
if (readData is T) {
return (T)readData;
}
try {
return (T)Convert.ChangeType(readData, typeof(T));
}
catch (InvalidCastException) {
return default(T);
}
``` | Have you tried [Convert.ChangeType](http://msdn.microsoft.com/en-us/library/system.convert.changetype.aspx)?
If the method always returns a string, which I find odd, but that's besides the point, then perhaps this changed code would do what you want:
```
private static T ReadData<T>(XmlReader reader, string value)
{
reader.MoveToAttribute(value);
object readData = reader.ReadContentAsObject();
return (T)Convert.ChangeType(readData, typeof(T));
}
``` | Cast object to T | [
"",
"c#",
"generics",
"casting",
""
] |
On my website, users can set preferences for their current timezone. I have a bunch of datetimes in my database, but I want to show each time appropriately, given A) what timezone they are in, and B) whether or not Daylight Savings is in effect.
What is the best way to go about this? | This is a several-step process.
1. Allow the users to choose their timezone from the [Olson timezone database](http://www.twinsun.com/tz/tz-link.htm). It's probably already installed on your machine if you're on Linux or other Unices.
2. Store **all** dates and times as UTC. No exceptions.
3. When the user requests a page, load it up and whenever you need to format a time, use the user's timezone preferences and use timezone-aware formatting functions. Both PHP and Python have ways to store dates and times in a sensible manner.
[Haluk has a good example of how to use PHP's DateTimeZone.](https://stackoverflow.com/questions/927703/mysql-adjusting-for-timezones-and-dst/1481498#1481498) However, if you're working with legacy code where you will only use one timezone in a request, you can use something like this; it's what I used when I customized PunBB to display timezones properly (I've since moved on from there...)
```
/**
* Sets up the timezone system. $timezone is the timezone. In PunBB, this is
* called by setup_dates($pun_user['timezone']) in common.php.
*
* DON'T USE THIS unless you can't use PHP's DateTime module.
*/
function setup_dates($timezone) {
if(function_exists('date_default_timezone_set')) {
date_default_timezone_set($timezone) ;
} else {
putenv('TZ='.$timezone) ;
}
}
```
In Python, use the [pytz](http://pytz.sourceforge.net/) library, which should also already be installed on your server (again, assuming \*nix). If it's not, ask your sysadmin to install it (distributions usually customize it to work off of the builtin timezone database), or alternately just install it using `easy_install`. pytz provides great [usage examples](http://pytz.sourceforge.net/#example-usage). You'll want to use the `astimezone` method:
```
>>> utc_dt = datetime(2002, 10, 27, 6, 0, 0, tzinfo=utc)
>>> loc_dt = utc_dt.astimezone(eastern)
>>> loc_dt.strftime(fmt)
'2002-10-27 01:00:00 EST-0500'
```
Do this each time you format a time for users to read. | We use a date formatting method/function that adjusts for the user's timezone. Date/times are stored in our local timezone (PST) and converted appropriately.
I've seen other systems that store everything in GMT using unix timestamps. You will still need to convert it to the user's timezone. | Adjusting for timezones and DST | [
"",
"php",
"mysql",
"datetime",
""
] |
When executing a custom `RoutedUICommand` manually from code-behind, like this:
```
MyCommands.MyCommand.Execute(parameter, target)
```
do I need to call the `CanExecute` method first or is this already done inside the `Execute` method? | Do not assume that CanExecute will get called with Execute. The interface for ICommand does not imply that it calls CanExecute when Execute is called, so if it is important to you that it only execute when CanExecute is true, simply check it yourself.
Also, scanning the de-compiled code for RoutedUICommand, I don't see anywhere that checks CanExecute within Execute.
It is really more of the consumer's responsibility to determine when to call Execute/CanExecute. | You should call CanExecute manually if you need, Execute will not check it! | Executing WPF routed commands manually | [
"",
"c#",
"wpf",
"routed-commands",
""
] |
How can I use Cast() Extension method for above conversion?
e.g.
```
var aType = anonymousType;
IEnumreable<MyType> = aType.Cast();
```
Solved By
```
aType.Select(i => new MyType { } ).ToList();
``` | The only type that you can cast an anonymous type to is `Object`. If you want any other type, you have to create those objects from the data in the anonymously typed objects.
Example:
```
List<MyType> items = aType.Select(t => new MyType(t.Some, t.Other)).ToList();
```
You should consider to create the `MyType` objects already when you get the data, instead of creating anonymously typed objects. | Is `aType` is an `IEnumerable<anonymous type>` returned by e.g. a linq query?
You might want to use `Select` (which applies a transformation function to an element) insted of `Cast` which just performs a cast.
```
IEnumerable<MyType> = aCollection.Select(e => SomeExpressionWithE);
``` | How can I convert Anonymous type to Ttype? | [
"",
"c#",
""
] |
In Zend framework, using the MVC, if A user surf explicitly to <http://base/url/index.php> instead of just <http://base/url>, The system thinks the real base url is <http://base/url/index.php/> and according to that calculates all the URLs in the system.
So, if I have a controller XXX and action YYY The link will be
<http://base/url/index.php/XXX/YYY> which is of course wrong.
I am currently solving this by adding a line at index.php:
```
$_SERVER["REQUEST_URI"]=str_replace('index.php','',$_SERVER["REQUEST_URI"]);
```
I am wondering if there is a built-in way in ZF to solve this. | You can do it with ZF by using [`Zend_Controller_Router_Route_Static`](http://framework.zend.com/manual/en/zend.controller.router.html#zend.controller.router.routes.static) (phew!), example:
Read the manual page linked above, there are some pretty good examples to be found.
```
$route = new Zend_Controller_Router_Route_Static(
'index.php',
array('controller' => 'index', 'action' => 'index')
);
$router->addRoute('index', $route);
```
Can't say I totally disagree with your approach. That said, others may well point out 5000 or so disadvantages. Good luck with that. | Well it really depends on how you want to solve this. As you know the Zend Frameworks build on the front controller pattern, where each request that does not explicitly reference a file in the /public directory is redirected to *index.php*. So you could basically solve this in a number of ways:
1. Edit the .htaccess file (or server configuration directive) to rewrite the request to the desired request:
* RewriteRule (.\*index.php) /error/forbidden?req=$1 // Rewrite to the forbidden action of the error controller.
* RewriteRule index.php /index // Rewrite the request to the main controller and action
2. Add a static route in your bootstrapper as suggested by [karim79](https://stackoverflow.com/questions/901514/how-to-solve-the-case-when-users-surf-to-index-php/901554#901554). | How to solve the case when users surf to index.php | [
"",
"php",
"zend-framework",
"zend-framework-mvc",
""
] |
Consider following example:
```
#include <iostream>
#include <functional>
#include <algorithm>
#include <vector>
#include <boost/bind.hpp>
const int num = 3;
class foo {
private:
int x;
public:
foo(): x(0) {}
foo(int xx): x(xx) {}
~foo() {}
bool is_equal(int xx) const {
return (x == xx);
}
void print() {
std::cout << "x = " << x << std::endl;
}
};
typedef std::vector<foo> foo_vect;
int
main() {
foo_vect fvect;
for (int i = -num; i < num; i++) {
fvect.push_back(foo(i));
}
foo_vect::iterator found;
found = std::find_if(fvect.begin(), fvect.end(),
boost::bind(&foo::is_equal, _1, 0));
if (found != fvect.end()) {
found->print();
}
return 0;
}
```
Is there a way to use some sort of negator adaptor with `foo::is_equal()` to find first non zero element. I don't want to write `foo::is_not_equal(int)` method, I believe there is a better way. I tried to play with `std::not2`, but without success. | Since you're using Boost.Bind:
```
std::find_if(fvect.begin(), fvect.end(),
!boost::bind(&foo::is_equal, _1, 0)
);
```
(Note the "!") | The argument to `std::not2` needs to look like a 'normal' binary predicate, so you need to adapt `foo::is_equal` with something like `std::mem_fun_ref`. You should be able to do something like:
```
std::not2(std::mem_fun_ref(&foo::is_equal))
``` | Negator adaptors in STL | [
"",
"c++",
"boost",
""
] |
What is the general approach with Java swing to update a textarea with lines of text (say from a Thread) and then have the text caret flow to the bottom of the textarea as text is being added. Also update the scrollbar so that it is at the bottom.
I was thinking that I would have a stringbuffer and append text to that and then set the string in the textarea and position the scrollbar at the bottom. | Use [`append()`](http://java.sun.com/javase/6/docs/api/javax/swing/JTextArea.html#append(java.lang.String)) to add the text, then [`setCaretPosition()`](http://java.sun.com/javase/6/docs/api/javax/swing/text/JTextComponent.html#setCaretPosition(int)) to make sure you scroll with it.
```
myTextPane.append(textFromSomewhere);
myTextPane.setCaretPosition(myTextPane.getDocument().getLength());
``` | The append() method doesn't do what you want?
And although you didn't ask: when you're generating something in a background thread, be sure to use SwingUtilities.invokeLater() to update your components. | Java Swing: Approach for dynamically appending text in text area, have scrollbar update | [
"",
"java",
"swing",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.