Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I've a method that I want to be able to accept either a single string (a path, but not necessarily one that exists on the machine running the code) or a list/tuple of strings. Given that strings act as lists of characters, how can I tell which kind the method has received? I'd like to be able to accept either standard or unicode strings for a single entry, and either lists or tuples for multiple, so isinstance doesn't seem to be the answer unless I'm missing a clever trick with it (like taking advantage of common ancestor classes?). Python version is 2.5
You can check if a variable is a string or unicode string with * Python 3: ``` isinstance(some_object, str) ``` * Python 2: ``` isinstance(some_object, basestring) ``` This will return `True` for both strings and unicode strings As you are using python 2.5, you could do something like this: ``` if isinstance(some_object, basestring): ... elif all(isinstance(item, basestring) for item in some_object): # check iterable for stringness of all items. Will raise TypeError if some_object is not iterable ... else: raise TypeError # or something along that line ``` Stringness is probably not a word, but I hope you get the idea
`isinstance` **is** an option: ``` In [2]: isinstance("a", str) Out[2]: True In [3]: isinstance([], str) Out[3]: False In [4]: isinstance([], list) Out[4]: True In [5]: isinstance("", list) Out[5]: False ```
Check if input is a list/tuple of strings or a single string
[ "", "python", "typechecking", "python-2.5", "" ]
We have some applications that sometimes get into a bad state, but only in production (of course!). While taking a heap dump can help to gather state information, it's often easier to use a remote debugger. Setting this up is easy -- one need only add this to his command line: -Xdebug -Xrunjdwp:transport=dt\_socket,server=y,suspend=n,address=PORT There seems to be no available security mechanism, so turning on debugging in production would effectively allow arbitrary code execution (via hotswap). We have a mix of 1.4.2 and 1.5 Sun JVMs running on Solaris 9 and Linux (Redhat Enterprise 4). How can we enable secure debugging? Any other ways to achieve our goal of production server inspection? **Update:** For JDK 1.5+ JVMs, one can specify an interface and port to which the debugger should bind. So, KarlP's suggestion of binding to loopback and just using a SSH tunnel to a local developer box should work given SSH is set up properly on the servers. However, it seems that JDK1.4x does not allow an interface to be specified for the debug port. So, we can either block access to the debug port somewhere in the network or do some system-specific blocking in the OS itself (IPChains as Jared suggested, etc.)? Update #2: This is a hack that will let us limit our risk, even on 1.4.2 JVMs: Command line params: ``` -Xdebug -Xrunjdwp: transport=dt_socket, server=y, suspend=n, address=9001, onthrow=com.whatever.TurnOnDebuggerException, launch=nothing ``` Java Code to turn on debugger: ``` try { throw new TurnOnDebuggerException(); } catch (TurnOnDebugger td) { //Nothing } ``` TurnOnDebuggerException can be any exception guaranteed not to be thrown anywhere else. I tested this on a Windows box to prove that (1) the debugger port does not receive connections initially, and (2) throwing the TurnOnDebugger exception as shown above causes the debugger to come alive. The launch parameter was required (at least on JDK1.4.2), but a garbage value was handled gracefully by the JVM. We're planning on making a small servlet that, behind appropriate security, can allow us to turn on the debugger. Of course, one can't turn it off afterward, and the debugger still listens promiscuously once its on. But, these are limitations we're willing to accept as debugging of a production system will always result in a restart afterward. **Update #3:** I ended up writing three classes: (1) TurnOnDebuggerException, a plain 'ol Java exception, (2) DebuggerPoller, a background thread the checks for the existence of a specified file on the filesystem, and (3) DebuggerMainWrapper, a class that kicks off the polling thread and then reflectively calls the main method of another specified class. This is how its used: 1. Replace your "main" class with DebuggerMainWrapper in your start-up scripts 2. Add two system (-D) params, one specifying the real main class, and the other specifying a file on the filesystem. 3. Configure the debugger on the command line with the onthrow=com.whatever.TurnOnDebuggerException part added 4. Add a jar with the three classes mentioned above to the classpath. Now, when you start up your JVM everything is the same except that a background poller thread is started. Presuming that the file (ours is called TurnOnDebugger) doesn't initially exist, the poller checks for it every N seconds. When the poller first notices it, it throws and immediately catches the TurnOnDebuggerException. Then, the agent is kicked off. You can't turn it back off, and the machine is not terribly secure when its on. On the upside, I don't think the debugger allows for multiple simultaneous connections, so maintaining a debugging connection is your best defense. We chose the file notification method because it allowed us to piggyback off of our existing Unix authen/author by specifying the trigger file in a directory where only the proper uses have rights. You could easily build a little war file that achieved the same purpose via a socket connection. Of course, since we can't turn off the debugger, we'll only use it to gather data before killing off a sick application. If anyone wants this code, please let me know. However, it will only take you a few minutes to throw it together yourself.
If you use SSH you can allow tunneling and tunnel a port to your local host. No development required, all done using sshd, ssh and/or putty. The debug socket on your java server can be set up on the local interface 127.0.0.1.
You're absolutely right: the Java Debugging API is inherently insecure. You can, however, limit it to UNIX domain sockets, and write a proxy with SSL/SSH to let you have authenticated and encrypted external connections that are then proxied into the UNIX domain socket. That at least reduces your exposure to someone who can get a process into the server, or someone who can crack your SSL.
Secure Debugging for Production JVMs
[ "", "java", "security", "debugging", "" ]
I have a `List<object>` with different types of objects in it like integers, strings, and custom types. All custom types are protobuf-adjusted. What I wanna do now is to serialize / deserialize this list with protobuf.net. Up until now I suspect that I have to declare each and every type explicitly, which is unfortunately not possible with these mixed-list constructs. Because the binary formater has no problems to do these things I hope that I missed something and that you can help me out. So my question is how to deal with objects in protobuf.net.
(disclosure: I'm the author of protobuf-net) `BinaryFormatter` is a metadata-based serializer; i.e. it sends .NET type information about every object serialized. protobuf-net is a contract-based serializer (the binary equivalent of `XmlSerializer` / `DataContractSerializer`, which will also reject this). There is no current mechanism for transporting *arbitrary* objects, since the other end will have *no way* of knowing what you are sending; however, if you have a *known set* of *different* object types you want to send, there may be options. There is also work in the pipeline to allow runtime-extensible schemas (rather than just attributes, which are fixed at build) - but this is far from complete. --- This isn't ideal, but it works... it should be easier when I've completed the work to support runtime schemas: ``` using System; using System.Collections.Generic; using ProtoBuf; [ProtoContract] [ProtoInclude(10, typeof(DataItem<int>))] [ProtoInclude(11, typeof(DataItem<string>))] [ProtoInclude(12, typeof(DataItem<DateTime>))] [ProtoInclude(13, typeof(DataItem<Foo>))] abstract class DataItem { public static DataItem<T> Create<T>(T value) { return new DataItem<T>(value); } public object Value { get { return ValueImpl; } set { ValueImpl = value; } } protected abstract object ValueImpl {get;set;} protected DataItem() { } } [ProtoContract] sealed class DataItem<T> : DataItem { public DataItem() { } public DataItem(T value) { Value = value; } [ProtoMember(1)] public new T Value { get; set; } protected override object ValueImpl { get { return Value; } set { Value = (T)value; } } } [ProtoContract] public class Foo { [ProtoMember(1)] public string Bar { get; set; } public override string ToString() { return "Foo with Bar=" + Bar; } } static class Program { static void Main() { var items = new List<DataItem>(); items.Add(DataItem.Create(12345)); items.Add(DataItem.Create(DateTime.Today)); items.Add(DataItem.Create("abcde")); items.Add(DataItem.Create(new Foo { Bar = "Marc" })); items.Add(DataItem.Create(67890)); // serialize and deserialize var clone = Serializer.DeepClone(items); foreach (DataItem item in clone) { Console.WriteLine(item.Value); } } } ```
There is a way of doing this, albeit not a very clean way, by using a wrapper object that utilises another serialisation mechanism that supports arbitrary objects. I am presenting an example below using JSON but, like I said, resorting to a different serialisation tool seems like defeating the purpose of using protobuf: ``` [DataContract] public class ObjectWrapper { [DataMember(Order = 1)] private readonly string _serialisedContent; [DataMember(Order = 2)] private readonly string _serialisedType; public object Content { get; private set; } [UsedImplicitly] private ObjectWrapper() { } public ObjectWrapper(object content) { _serialisedContent = JsonConvert.SerializeObject(content); _serialisedType = content.GetType().FullName; Content = content; } [ProtoAfterDeserialization] private void Initialise() { var type = Type.GetType(_serialisedType); Content = type != null ? JsonConvert.DeserializeObject(_serialisedContent, type) : JsonConvert.DeserializeObject(_serialisedContent); } } ``` EDIT: This can also be done using C#'s built-in binary serialisation ``` [DataContract] public class ObjectWrapper { [DataMember(Order = 1)] private readonly string _serialisedContent; public object Content { get; private set; } [UsedImplicitly] private ObjectWrapper() { } public ObjectWrapper(object content) { using (var stream = new MemoryStream()) { var formatter = new BinaryFormatter(); formatter.Serialize(stream, content); stream.Flush(); stream.Position = 0; _serialisedContent = Convert.ToBase64String(stream.ToArray()); } } [ProtoAfterDeserialization] private void Initialise() { var data = Convert.FromBase64String(source); using (var stream = new MemoryStream(data)) { var formatter = new BinaryFormatter(); stream.Seek(0, SeekOrigin.Begin); return formatter.Deserialize(stream); } } } ```
protobuf and List<object> - how to serialize / deserialize?
[ "", "c#", ".net-3.5", "protobuf-net", "" ]
I'm building a generic ASP.NET server control that has an attribute used to specify a type name. I'm using a control builder to generate the generic version of my control by passing the attribute value to `Type.GetType(string)`. This works great. However, if the type that I want to specify is generic, I have to use syntax like this: ``` <gwb:GenericControl runat="server" TypeName="System.Collections.Generic.List`1[System.String]" /> ``` I'd like to be able to type it like this: ``` <gwb:GenericControl runat="server" TypeName="System.Collections.Generic.List<System.String>" /> ``` I know I could manually parse the value for angle brackets and convert them to square brackets, and add in the appropriate backtick-numeric prefix, but **I was wondering if there was any built-in way to do this conversion?** I assume the `Generic<T>` syntax is specific to C# (or at least different in VB.NET) so I'm guessing I'd also have to parse any other language-specific syntax. I've noticed that ASP.NET MVC does this in the `Inherits` attribute of the `Page` directive, but I'm not sure how. ``` <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MyModel>" %> ```
No, there is no built-in way of doing this. The reason why is that type names like `Generic<T>` are indeed specific to C#. They are actually written out differently in metadata. The short version is that it will be the type name, followed by a ` and then a number corresponding with the count of generic parameters. `Generic<T>` for instance will be written out as Generic`1 and `Generic<T1,T2>` will be written out as Generic`2. Arrays add a bit of complication to the syntax but it's the general rule. When you use Type.GetType you are actually doing a MetaData query vs. a C# query. So the type name must be provided as it appears in MetaData.
There's no built-in way of doing this. You need to parse it out. This is probably what the MVC framework is doing internally.
Type.GetType(string) using "Generic<T>" syntax?
[ "", "c#", "asp.net", "generics", "reflection", "" ]
I am confused as to why the following code snippet would not exit when called in the thread, but would exit when called in the main thread. ``` import sys, time from threading import Thread def testexit(): time.sleep(5) sys.exit() print "post thread exit" t = Thread(target = testexit) t.start() t.join() print "pre main exit, post thread exit" sys.exit() print "post main exit" ``` The docs for `sys.exit()` state that the call should exit from Python. I can see from the output of this program that "post thread exit" is never printed, but the main thread just keeps on going even after the thread calls exit. Is a separate instance of the interpreter being created for each thread, and the call to `exit()` is just exiting that separate instance? If so, how does the threading implementation manage access to shared resources? What if I did want to exit the program from the thread (not that I actually want to, but just so I understand)?
`sys.exit()` raises the `SystemExit` exception, as does `thread.exit()`. So, when `sys.exit()` raises that exception inside that thread, it has the same effect as calling `thread.exit()`, which is why only the thread exits.
> What if I did want to exit the program from the thread? ### For Linux: ``` os.kill(os.getpid(), signal.SIGINT) ``` This sends a `SIGINT` to the main thread which raises a `KeyboardInterrupt`. While more complicated, this has the benefit that the main thread follows the standard shutdown with cleanup (e.g. threads, sockets, files, finally code). Also a handler can be setup, to react in a different. ### For Windows: The above does not work on Windows, as you can only send a `SIGTERM` signal, which is not handled by Python and has the same effect as `os._exit()`. The only option is to use: ``` os._exit() ``` This will exit the entire process without any cleanup. If a cleanup is needed, the thread needs to communicate with the main thread in another way (e.g. through a queue or sending an event to its event-loop).
Why does sys.exit() not exit when called inside a thread in Python?
[ "", "python", "python-2.6", "" ]
I have two columns. ColA and ColB contains char(10) with data "20090520" and "20090521". I want to select and get the date difference in days. I have tried using Format() and CDate() but MS Access always display as #ERROR.
Access prefers its dates in this format: ``` #2009-12-01# ``` You can convert your date to something Access understands with: ``` CDate(Format([ColA], "0000-00-00")) ``` Or alternatively: ``` DateSerial(Left([ColA],4),Mid([ColA],5,2),Right([ColA],2)) ``` And to display the result in your preferred format: ``` Format(<date here>, "dd-mm-yyyy") ```
Try using DateSerial() to convert the dates: ``` DateSerial(Left([FieldName],4),Mid([FieldName],5,2),Right([FieldName],2)) ```
MS Access - Select Char as Date and doing a date diff
[ "", "sql", "ms-access", "" ]
I would like to know how can i read a value of input text from the managed bean. I know it is possible to read this way and it is very stright forward. ``` <h:inputText id="username" value="#{mylogin.username}" required="true" /> ``` But what if lets say i have a value like ``` <h:inputText id="username" value="some_value" required="true" /> ``` And i want to read this "some\_value" in my managed bean. Is it possible ? Another question is it possible to access to the session variables in managed bean or should i somehow pass them to there ?
In the latter case that `some_value` is not bean managed, IMHO. Nonetheless, you can read that. Do something like this, ``` FacesContext ctx = FacesContext.getCurrentInstance(); HttpServletRequest request = (HttpServletRequest)ctx.getExternalContext().getRequest(); request.getParameter("username"); ``` Similarly, regarding accessing session variable, ``` FacesContext ctx = FacesContext.getCurrentInstance(); HttpServletRequest request = (HttpServletRequest)ctx.getExternalContext().getSession(false); ```
``` <h:inputText id="username" value="#{mylogin.username}" required="true" /> ``` This would be the best way, in my opinion. Is there a reason you would like to avoid this? You can, as [harto suggests](https://stackoverflow.com/questions/905194/basic-question-about-jsf-inputtext-and-about-sessions-in-jsf-managed-bean/905380#905380), use component binding, but (as Vinegar points out) you gain nothing from this approach. ``` <h:inputText id="username" value="some_value" required="true" /> ``` If you want to read the above value, it is possible to read it directly from the request parameters. The [ExternalContext](http://java.sun.com/javaee/5/docs/api/javax/faces/context/ExternalContext.html) encapsulates the underlying container API and can be accessed in a managed bean like so: ``` FacesContext facesContext = FacesContext .getCurrentInstance(); ExternalContext extContext = facesContext .getExternalContext(); Map<String, String> params = extContext .getRequestParameterMap(); ``` But, aside from violating the model-view-presenter contract, you can run into some practical problems. The parameter key may not be "username", but might be something like "j\_id\_jsp\_115874224\_691:username", depending on whether you make the component a child of any [NamingContainer](http://java.sun.com/javaee/5/docs/api/javax/faces/component/NamingContainer.html)s (like [UIForm](http://java.sun.com/javaee/5/docs/api/javax/faces/component/UIForm.html) - see the [prependId attribute](http://java.sun.com/javaee/javaserverfaces/1.2_MR1/docs/tlddocs/h/form.html)) or if the view is namespaced. Hard-coding this value anywhere is probably a bad idea. You can read about the relationship between JSF component IDs and rendered HTML IDs [here](http://illegalargumentexception.blogspot.com/2009/02/jsf-working-with-component-ids.html). If you want to use [UIComponent.getClientId](http://java.sun.com/javaee/5/docs/api/javax/faces/component/UIComponent.html#getClientId(javax.faces.context.FacesContext)) to generate the the key, you are back to component binding because you need to get a reference to the component. > Another question is it possible to access to the session variables in managed bean..? See [ExternalContext.getSessionMap](http://java.sun.com/javaee/5/docs/api/javax/faces/context/ExternalContext.html#getSessionMap()).
JSF inputText and Sessions in jsf managed bean
[ "", "java", "jsp", "jsf", "" ]
For Gecko there's Mozilla Developer Network For IE there's MSDN. For webkit there's...Apple Developer Connection? There are a [couple](https://developer.apple.com/library/safari/#documentation/AppleApplications/Conceptual/SafariJSProgTopics/WebKitJavaScript.html) of JavaScript related documents on ADC, but nothing as comprehensive as MDN or MSDN. There's no reference. There's no way to look up methods of arrays or strings for webkit, or anything is there? So what, do we just assume it's the same as Gecko? IE?
How about the WebKit DOM Reference? <http://developer.apple.com/safari/library/documentation/AppleApplications/Reference/WebKitDOMRef/index.html> **Update** Thanks for the comments - yes this now redirects. Perhaps as others have said, one of the other browsers' references would be a good place to start - then for Safari's own DOM extensions/additions, there's the 'Safari DOM Additions Reference': <https://developer.apple.com/documentation/webkitjs> Otherwise it looks like it would be a case of finding your way through the confusing set of documents there in the Safari Developer Library: <http://developer.apple.com/library/safari/navigation/>
I use [quirksmode.org](http://quirksmode.org/) for all my JavaScript needs. MDC is my resource for references and basic how-tos and quirksmode to show me that I, in fact, cannot even use it in IE. WebKit and Gecko seem to behave similarly enough when it comes to JavaScript anyway. But other than what you listed, I have never come across anything specific to WebKit.
Webkit JavaScript Reference
[ "", "javascript", "webkit", "" ]
If I create an object inside of the main scope: INDEX.PHP: ``` $db = new database(); ``` Then how can I use this same object inside of a completely different class? ANYTHING.PHP: ``` class anything { function __construct(){ $db->execute($something); # I want to use the same object from INDEX.PHP } } ``` Would I need to make $db a global or is there a 'better' more obvious way?
You could just use `global` to find it: ``` class anything { function __construct(){ global $db; $db->execute($something); } } ``` Or, you could pass it in when creating a new anything: ``` class anything { function __construct($db) { $db->execute($something); } } ``` It really depends on what makes the most sense for you.
For the DB you may want to use [Singleton pattern](http://www.php.net/manual/en/language.oop5.patterns.php) ``` class anything { public function load($id) { $db = DB::getInstance(); $res = $db->query('SELECT ... FROM tablename WHERE id = '.(int)$id); // etc... } } ``` You may want to extend it if you need different DB connections at the same time (i.e main db and forum's db). Then you'll use it like `DB::getInstance('forum');` and store instances in associative array.
How can I use a different object inside of a class?
[ "", "php", "oop", "class", "object", "" ]
What is the best way to solve this problem in code? The problem is that I have 2 dollar amounts (known as a pot), that need to be allocated to 3 people. Each person gets a specific amount that comes from both pots and the rates must be approximately the same. I keep coming across rounding issues where my allocations either add up to too much or too little. Here is a specific example: Pot #1 987,654.32 Pot #2 123,456.78 Person #1 gets Allocation Amount: 345,678.89 Person #2 gets Allocation Amount: 460,599.73 Person #3 gets Allocation Amount: 304,832.48 My logic is as follows (Code is in c#): ``` foreach (Person person in People) { decimal percentage = person.AllocationAmount / totalOfAllPots; decimal personAmountRunningTotal = person.AllocationAmount; foreach (Pot pot in pots) { decimal potAllocationAmount = Math.Round(percentage * pot.Amount, 2); personAmountRunningTotal -= potAllocationAmount; PersonPotAssignment ppa = new PersonPotAssignment(); ppa.Amount = potAllocationAmount; person.PendingPotAssignments.Add(ppa); } foreach (PersonPotAssignment ppa in person.PendingPotAssignments) { if (personAmountRunningTotal > 0) //Under Allocated { ppa.Amount += .01M; personAmountRunningTotal += .01M; } else if (personAmountRunningTotal < 0) //Over Allocated { ppa.Amount -= .01M; personAmountRunningTotal -= .01M; } } } ``` The results I get are as follows: Pot #1, Person #1 = 307,270.13 Pot #1, Person #2 = 409,421.99 Pot #1, Person #3 = 270,962.21 Pot #1 Total = 987,654.33 (1 penny off) Pot #2, Person #1 = 38,408.76 Pot #2, Person #2 = 51,177.74 Pot #2, Person #3 = 33,870.27 Pot #2 Total = 123,456.77 (1 penny off) The Pot Totals should match the original totals. I think I may be missing something or there may be an extra step that I need to take. I think I am on the right track. Any help would be greatly appreciated.
This happens in financial calculations a lot when rounding to the nearest penny. No amount of tweaking the individual operations rounding algorithm will work for every case. You have to have an accumulator that tracks the amount allocated after the rounding and distribution operation. At the end of the allocations, you check the accumulator against the actual results (summed together) and distribute the leftover penny. In the math example below, if you take 0.133 and round it to 0.13 and add 3 times you get a penny less than if you add 0.133 3 times first and then round. ``` 0.13 0.133 0.13 0.133 +0.13 +0.133 _____ ______ 0.39 0.399 -> 0.40 ```
+1 for Matt Spradley's solution. As an additional comment to Matt's solution, you of course also need to account for the case where you end up allocating penny (or more) *less* than the target amount -- in that case, you need to subtract money from one or more of the allocated amounts. You also need to ensure that you don't end up subtracting a penny from an allocated amount of $0.00 (in the event that you are allocating a very small amount among a large number of recipients).
Rounding issues with allocating dollar amounts across multiple people
[ "", "c#", ".net", "puzzle", "rounding", "" ]
I would like seek some guidance in writing a "process profiler" which runs in kernel mode. I am asking for a kernel mode profiler is because I run loads of applications and I do not want my profiler to be swapped out. When I said "process profiler" I mean to something that would monitor resource usage by the process. including usage of threads and their statistics. And I wish to write this in python. Point me to some modules or helpful resource. Please provide me guidance/suggestion for doing it. ## Thanks, Edit::: Would like to add that currently my interest isto write only for linux. however after i built it i will have to support windows.
It's going to be very difficult to do the process monitoring part in Python, since the python interpreter doesn't run in the kernel. I suspect there are two easy approaches to this: 1. use the /proc filesystem if you have one (you don't mention your OS) 2. Use dtrace if you have dtrace (again, without the OS, who knows.) --- Okay, following up after the edit. First, there's no way you're going to be able to write code that runs in the kernel, in python, and is portable between Linux and Windows. Or at least if you were to, it would be a hack that would live in glory forever. That said, though, if your purpose is to process Python, there are a lot of Python tools available to get information from the Python interpreter at run time. If instead your desire is to get process information from *other* processes in general, you're going to need to examine the options available to you in the various OS APIs. Linux has a /proc filesystem; that's a useful start. I suspect Windows has similar APIs, but I don't know them. If you have to write kernel code, you'll almost certainly need to write it in C or C++.
**don't** try and get python running in kernel space! You would be much better using an existing tool and getting it to spit out XML that can be sucked into Python. I wouldn't want to port the Python interpreter to kernel-mode (it sounds grim writing it). The /proc option does sound good. **some code** code that reads proc information to determine memory usage and such. Should get you going: <http://www.pixelbeat.org/scripts/ps_mem.py> **reads memory information of processes using Python through /proc/smaps** like charlie suggested.
Writing a kernel mode profiler for processes in python
[ "", "python", "kernel", "" ]
As the author of a C# application, I found that troubleshooting issues reported by users would be much easier if I had access to the exception or debug logs. I have included a home-grown logging mechanism that the user can turn on or off. I want the user to be able to submit the logs via the internet so I can review the logs for the error. I have thought of using either **SMTPClient** or a **web service** to send the information. SMTPClient might not work because firewalls may block outgoing SMTP access. Would a web service has issue with sending a large amount of data (potentially 1+ MB)? What would you recommend as the best way to have an application transmit error reports directly to developers for review? **EDIT:** Clarification: This is a Windows application and when an error occurs I want to bring up a dialog asking to submit the error. My question is about the mechanism to transmit the error log from the application to me (developer) via the internet.
We use 3 methods where I work * SMTP to a dedicated mailbox. This requires a **lot** of configuration and dancing around with "big corporate" IT departments to work out what their mail server is and how to authenticate against it and send through it. Then there's programs like Norton Internet Security that can block outbound SMTP traffic on the client machine which throw extra spanners in the works. * Submission to an asmx on our server. This is our preferred method, but lots of things can get in the way. It's mainly proxies, but Norton can also step in and swat you down. If there's a proxy involved, run away run away :-) * HTTP POST using HttpWebRequest and mime typ of multipart/form-encoded. It also has proxy and firewall issues, but can sometimes work where asmx submission fails. Good luck. You're right in that it's **much** easier to debug if you've got the stack trace and perhaps even a screenie of what the poor old user was doing.
Some way that let's the user know you mean to do it. Ask them for a proxy, ask them for an email server, something like that. The security minded will get real nervous if they discover that you're opening a socket or something like it and sending data out without notification. And rightly so.
What is the best way to send application errors and logs by internet to the developers?
[ "", "c#", "web-services", "error-reporting", "error-logging", "" ]
I'm attempting to implement a simple Single Sign On scenario where some of the participating servers will be windows (IIS) boxes. It looks like SPNEGO is a reasonable path for this. Here's the scenario: * User logs in to my SSO service using his username and password. I authenticate him using some mechanism. * At some later time the user wants to access App A. + The user's request for App A is intercepted by the SSO service. The SSO service uses SPNEGO to log the user in to App A: - The SSO service hits the App A web page, gets a "WWW-Authenticate: Negotiate" response - The SSO service generates a "Authorization: Negotiate xxx" response on behalf of the user, responds to App A. The user is now logged in to App A. + The SSO service intercepts subsequent user requests for App A, inserting the Authorization header into them before passing them on to App A. Does that sound right? I need two things (at least that I can think of now): * the ability to generate the "Authorization: Negotiate xxx" token on behalf of the user, preferably using Python * the ability to validate "Authorization: Negotiate xxx" headers in Python (for a later part of the project)
This is exactly what Apple does with its [Calendar Server](http://trac.calendarserver.org/). They have a [python gssapi](http://trac.calendarserver.org/browser/PyKerberos) library for the kerberos part of the process, in order to implement [SPNEGO](http://www.ietf.org/rfc/rfc4559.txt). Look in CalendarServer/twistedcaldav/authkerb.py for the server auth portion. The kerberos module (which is a c module), doesn't have any useful docstrings, but PyKerberos/pysrc/kerberos.py has all the function definitions. Here's the urls for the svn trunks: <http://svn.calendarserver.org/repository/calendarserver/CalendarServer/trunk> <http://svn.calendarserver.org/repository/calendarserver/PyKerberos/trunk>
Take a look at the <http://spnego.sourceforge.net/credential_delegation.html> tutorial. It seems to be doing what you are trying to do.
SPNEGO (kerberos token generation/validation) for SSO using Python
[ "", "python", "active-directory", "single-sign-on", "kerberos", "spnego", "" ]
I'm trying to come up with an answer to two questions that didn't seem hard at first. Q1 : How do I obtain the number of elapsed seconds between UTC.Now() and a given date? A1 : Just like in the code below! Q2 : How do I determine how many fractional seconds have elapsed since the last "full" second ? I'd like to print the "total\_elapsed\_seconds.fractional\_seconds" -> "1234124.45". How do I do that? A2 : ??? ``` #include <iostream> #include <boost/date_time/gregorian/gregorian.hpp> #include <boost/date_time/posix_time/posix_time.hpp> using namespace std; using namespace boost::gregorian; using namespace boost::posix_time; void main() { ptime Jan1st1970(date(1970, 1, 1)); for(int i = 0; i < 10; i++) { ptime Now = second_clock::universal_time(); time_duration diff = Now - Jan1st1970; cout << Now << " : " << diff.total_seconds() << "." << diff.fractional_seconds() << endl; } } ```
You are using the `second_clock` to get the current time. As the name implies, it is accurate only to the nearest second. Since your reference time has no fractional seconds the duration fractional seconds always ends up being 0. Use the `microsec_clock` instead: ``` ptime Now = microsec_clock::universal_time(); ``` Also, in such a tight loop, I wouldn't expect the clock to update on every iteration, so you may also want to add a sleep from boost::thread: ``` boost::this_thread::sleep(boost::posix_time::milliseconds(25)); ```
You don't mention what operating system you use, but I know for a fact that window's clock won't give you resolution better than about 15 milliseconds (unless you really play some games). However, windows has what's called a performance timer that can give you nanosecond level resolution. It is really just a counter of how many times the CPU cycles (you can divide by the CPU's frequency to get time), so to use it as a clock you have to add that time to a known time: ``` ptime Start = microsec_clock::universal_time(); initMyClockToZero(); // You have to write this to use the performance timer .... do something .... int64 microseconds = getMyClockMicrosec(); // this too ptime Now = Start + posix_time::microseconds(microseconds); ``` I've also got a stopwatch style timer that I wrote myself using the windows calls. ``` #ifndef STOPWATCH_HPP #define STOPWATCH_HPP #include <iostream> #include <windows.h> //! \brief Stopwatch for timing performance values //! //! This stopwatch class is designed for timing performance of various //! software operations. If the values you get back a greater than a //! few seconds, you should be using a different tool. //! On a Core 2 Duo E6850 @ 3.00GHz, the start/stop sequence takes //! approximately 230 nano seconds in the debug configuration and 180 //! nano seconds in the release configuration. If you are timing on the //! sub-microsecond scale, please take this into account and test it on //! your machine. class Stopwatch{ public: //! \param start if set to true will initialize and then start the //! timer. Stopwatch(bool start=false){ _start.QuadPart = 0; _stop.QuadPart = 0; if(start) Start(); } //! Starts the stopwatch running void Start(){ QueryPerformanceCounter(&_start); } //! Run this when the event being timed is complete void Stop(){ QueryPerformanceCounter(&_stop); } //! Stops the timer and returns the result double StopResult(){ Stop(); return ResultNanoseconds(); } //! You can get the result of the stopwatch start-stop sequence at //! your leisure. double ResultNanoseconds(){ LARGE_INTEGER frequency; QueryPerformanceFrequency(&frequency); double cyclesPerNanosecond = static_cast<double>(frequency.QuadPart) / 1000000000.0; LARGE_INTEGER elapsed; elapsed.QuadPart = _stop.QuadPart - _start.QuadPart; return elapsed.QuadPart / cyclesPerNanosecond; } void PrintResultNanoseconds(){ std::cout << ResultNanoseconds() << "nanosec" << std::endl; } void PrintResultMicroseconds(){ std::cout << ResultNanoseconds()/100 << "microsec" << std::endl; } void PrintResultMilliseconds(){ std::cout << ResultNanoseconds()/100000 << "millisec" << std::endl; } void PrintResultSeconds(){ std::cout << ResultNanoseconds()/1000000000 << "sec" << std::endl; } private: LARGE_INTEGER _start; LARGE_INTEGER _stop; }; #endif STOPWATCH_HPP ```
C++ :: Boost :: posix_time (elapsed seconds. elapsed fractional seconds)
[ "", "c++", "" ]
Here's the thing: ``` object[] arrayText = new object[1]; if (arrayText[1] == null) { MessageBox.Show("Is null"); } ``` We know that is going to be null, but it throws an exception, but I don't want to handle it in a try/catch block because that is nested in a loop and try/catch will slow it down, also it doesn't look really good: ``` object[] arrayText = new object[1]; try { if (arrayText[1] == null) { } } catch (Exception ex) { MessageBox.Show("Is null"); } ``` Thanks for you suggestions!
`null` is not the problem here, but the index is invalid. Arrays in C# are 0-based, so if you create an array with 1 element, only index `0` is valid: ``` array[0] == null ``` You can avoid that by checking the bounds manually before accessing the index: ``` if (index < array.Length) { // access array[index] here } else { // no exception, this is the "invalid" case } ```
``` object[] arrayText = new object[1]; if (arrayText[0] == null) { MessageBox.Show("Is null"); } ``` Try that? Arrays are 0 based, so trying to access arrayText[1] will give you an OutOfBoundsException. And the try/catch won't really impact your performance that much there, there isn't much in the stack at that point.
Testing null array index
[ "", "c#", "arrays", "" ]
I am trying to create a function which will give me alphabet position when an index is passed. It will be same like how excel shows it's columns. A...Z, AA,AB.... I wrote the below function to get the results upto Z. It looks like ``` static string GetColumnName(int index) { const int alphabetsCount = 26; if (index <= alphabetsCount) { int code = (index - 1) + (int)'A'; return char.ConvertFromUtf32(code); } return string.Empty; } ``` This works fine until 'Z'. It return 'A' if I pass 1 and return 'B' if I pass 2 and so on. But, I am not able to figure out how will I get AA when I pass 27 to this function. I guess I need a recursive method to find it. Any inputs to this problem will be great! **Edit** This is suggested by Tordek. But his code will fail in numbers like 52, 78 etc. Added workaround for that and here is the final working code. ``` static string GetColumnName(int index) { const int alphabetsCount = 26; if (index > alphabetsCount) { int mod = index % alphabetsCount; int columnIndex = index / alphabetsCount; // if mod is 0 (clearly divisible) we reached end of one combination. Something like AZ if (mod == 0) { // reducing column index as index / alphabetsCount will give the next value and we will miss one column. columnIndex -= 1; // passing 0 to the function will return character '@' which is invalid // mod should be the alphabets count. So it takes the last char in the alphabet. mod = alphabetsCount; } return GetColumnName(columnIndex) + GetColumnName(mod); } else { int code = (index - 1) + (int)'A'; return char.ConvertFromUtf32(code); } } ```
Any recursive function can be converted into an equivalent iterative one. I find it always easy to think recursively first: ``` static string GetColumnName(int index) { const int alphabetsCount = 26; if (index > alphabetsCount) { return GetColumnName(index / alphabetsCount) + GetColumnName(index % alphabetsCount); } else { int code = (index - 1) + (int)'A'; return char.ConvertFromUtf32(code); } } ``` Which can be simple converted into: ``` static string GetColumnName(int index) { const int alphabetsCount = 26; string result = string.Empty; while (index > 0) { result = char.ConvertFromUtf32(64 + (index % alphabetsCount)) + result; index /= alphabetsCount; } return result; } ``` Even so, listen to Joel.
See this question: [Translate a column index into an Excel Column Name](https://stackoverflow.com/questions/297213/translate-an-index-into-an-excel-column-name) or this one: [How to convert a column number (eg. 127) into an excel column (eg. AA)](https://stackoverflow.com/questions/181596/how-to-convert-a-column-number-eg-127-into-an-excel-column-eg-aa#182924) Though the first link has a correct answer right at the top and the 2nd has several that are not correct.
Incrementing alphabets
[ "", "c#", "alphabet", "" ]
I'm trying to use python to parse a log file and match 4 pieces of information in one regex. (epoch time, SERVICE NOTIFICATION, hostname and CRITICAL) I can't seem to get this to work. So Far I've been able to only match two of the four. Is it possible to do this? Below is an example of a string from the log file and the code I've gotten to work thus far. Any help would make me a happy noob. [1242248375] SERVICE ALERT: myhostname.com;DNS: Recursive;CRITICAL;SOFT;1;CRITICAL - Plugin timed out while executing system call ``` hostname = options.hostname n = open('/var/tmp/nagios.log', 'r') n.readline() l = [str(x) for x in n] for line in l: match = re.match (r'^\[(\d+)\] SERVICE NOTIFICATION: ', line) if match: timestamp = int(match.groups()[0]) print timestamp ```
The question is a bit confusing. But you don't need to do *everything* with regular expressions, there are some good plain old string functions you might want to try, like 'split'. This version will also refrain from loading the entire file in memory at once, and it will close the file even when an exception is thrown. ``` regexp = re.compile(r'\[(\d+)\] SERVICE NOTIFICATION: (.+)') with open('var/tmp/nagios.log', 'r') as file: for line in file: fields = line.split(';') match = regexp.match(fields[0]) if match: timestamp = int(match.group(1)) hostname = match.group(2) ```
You can use `|` to match any one of various possible things, and `re.findall` to get all non-overlapping matches to some RE.
Python RegEx - Getting multiple pieces of information out of a string
[ "", "python", "regex", "" ]
I have the following: ``` <select id="price_select"></select> ``` I have an event handler that invokes the following: ``` var selected_option = "one"; var option_one = "<option>Option Contents</option>"; document.getElementById('price_select').innerHTML = eval('option_' + selected_option); ``` Works just fine in Firefox but not in IE6.
Can't you do something like this instead? ``` var selected_option = "one"; var options = { "one": "<option>Option Contents</option>" }; document.getElementById('price_select').innerHTML = options[selected_option]; ```
Working off of what [marknt15](https://stackoverflow.com/questions/924135/how-can-i-get-eval-to-function-properly-in-ie/924153#924153) and [MartinodF](https://stackoverflow.com/questions/924135/how-can-i-get-eval-to-function-properly-in-ie/924142#924142) said, you should be able to use native DOM manipulation to do what you're trying to do without using `eval()`. ``` var selected_option = "one"; var options = { "one": {"value": "0", "text":"OptionContents"} }; var e = document.createElement("option"); if(e.innerText) {// IE sets innerText like this e.innerText = options[selected_option].text; } else { // W3C sets inner text like this e.childNodes[0].nodeValue = options[selected_option].text; } e.value = options[selected_option].value; document.getElementById('price_select').appendChild(e); ``` You might want to consider using a full-featured JavaScript framework such as jQuery or Prototype to make things like this easier to handle though.
How can i get eval to function properly in IE?
[ "", "javascript", "" ]
My application has a button to execute a python script dynamically using *execfile*. If I define a function inside the script (eg. *spam()*) and try to use that function inside another function (eg. *eggs()*), I get this error: ``` NameError: global name 'spam' is not defined ``` What is the correct way to call the *spam()* function from within *eggs()*? ``` #mainprogram.py class mainprogram(): def runme(self): execfile("myscript.py") >>> this = mainprogram() >>> this.runme() # myscript.py def spam(): print "spam" def eggs(): spam() eggs() ``` Also, I can't seem to be able to execute a method from my main application in the script. i.e. ``` #mainprogram.py class mainprogram(): def on_cmdRunScript_mouseClick( self, event ): execfile("my2ndscript.py") def bleh(): print "bleh" #my2ndscript.py bleh() ``` The error is: ``` NameError: name 'bleh' is not defined ``` What is the correct way to call *bleh()* from *my2ndscript.py*? **EDIT**: Updated first issue
In the second case you will need `import` (not sure whether "mainprogram.py" is on your `$PYTHONPATH`) ``` #mainprogram.py class mainprogram: def runme(self): execfile("my2ndscript.py") def bleh(self): print "bleh" if __name__ == '__main__': mainprogram().runme() #my2ndscript.py import mainprogram x = mainprogram.mainprogram() x.bleh() ``` but this will create a second instance of `mainprogram`. Or, better yet: ``` #mainprogram.py class mainprogram: def runme(self): execfile("my2ndscript.py", globals={'this': self}) def bleh(self): print "bleh" if __name__ == '__main__': mainprogram().runme() #my2ndscript.py this.bleh() ``` I guess that `execfile` is not the right solution for your problem anyway. Why don't you use `import` or `__import__` (and `reload()` in case the script changes between those clicks)? ``` #mainprogram.py import my2ndscript class mainprogram: def runme(self): reload(my2ndscript) my2ndscript.main(self) def bleh(self): print "bleh" if __name__ == '__main__': mainprogram().runme() #my2ndscript.py def main(program): program.bleh() ```
You're 3 years 8 months wiser since you posted so I'm assuming you'd have figured the first issue out, but given that a solution has not yet been posted (primarily because no one seemed to have a problem with the first issue), the following is my solution. ## [UPDATED] The last solution I provided was incorrect. Below I am providing the correct solution and explaining it in detail using code that I executed. **The problem is inherent in Python's `execfile()` builtin. Its one of the reasons that function has been deprecated in Python 3.x.** When you executed `execfile()` inside `runme()`, the objects `spam()` and `eggs()` were loaded into method `runme()`'s namespace, and not into the global namespace *(as they should ideally be)*. Consider the following code: # myscript.py ``` def spam(): print 'spam' def eggs(): if 'spam' not in globals(): print 'method spam() is not present in global namespace' spam() try: eggs() except Exception as e: print e ``` # mainprogram.py ``` class mainprogram(): def runme(self): execfile("myscript.py") print 'Objects lying in local namespace of runme() are -' print locals() this = mainprogram() this.runme() ``` # Interpreter Output ``` >>>import mainprogram method spam() is not present in global namespace name 'spam' is not defined Objects lying in local namespace of runme() are - {'e': NameError("name 'spam' is not defined",), 'spam': <function spam at 0x000000000000002B>, 'eggs': <function eggs at 0x000000000000002C>, 'self': <mainprogram.mainprogram instance at 0x000000000000002D>} ``` From the output you can see that `spam()` is not in the global namespace, but in method `runme()`'s namespace. So hypothetically, the correct way to call `spam()` would have been ``` def eggs(): global this this.runme.spam() ``` However, there is no way to access `spam()` while it is lying inside `runme()`'s namespace. The solution, therefore, is to insert `spam()` in the global namespace as follows: # myscript.py ``` global spam def spam(): print "spam" def eggs(): spam() eggs() ``` This will ensure that a reference to object `spam()` is created inside the `globals()` dictionary (i.e., the global namespace), making it callable from `eggs()`.
NameError using execfile in python
[ "", "python", "class", "scope", "namespaces", "" ]
I'm updating an old ASP/MySql webapp to ASP.NET/MS SQL. We would like to keep the logins from the old website working in the new app. Unfortunately the passwords were stored in the MySql DB using MySql's password() function. **Is it possible to simulate MySql's password() function in either .NET or MS SQL?** Any help/links are appreciated.
According to MySQL documentation, the algorithm is a double SHA1 hash. When examining the MySQL source code, you find a function called make\_scrambled\_password() in libmysql/password.c. The function is defined as follows: ``` /* MySQL 4.1.1 password hashing: SHA conversion (see RFC 2289, 3174) twice applied to the password string, and then produced octet sequence is converted to hex string. The result of this function is used as return value from PASSWORD() and is stored in the database. SYNOPSIS make_scrambled_password() buf OUT buffer of size 2*SHA1_HASH_SIZE + 2 to store hex string password IN NULL-terminated password string */ void make_scrambled_password(char *to, const char *password) { SHA1_CONTEXT sha1_context; uint8 hash_stage2[SHA1_HASH_SIZE]; mysql_sha1_reset(&sha1_context); /* stage 1: hash password */ mysql_sha1_input(&sha1_context, (uint8 *) password, (uint) strlen(password)); mysql_sha1_result(&sha1_context, (uint8 *) to); /* stage 2: hash stage1 output */ mysql_sha1_reset(&sha1_context); mysql_sha1_input(&sha1_context, (uint8 *) to, SHA1_HASH_SIZE); /* separate buffer is used to pass 'to' in octet2hex */ mysql_sha1_result(&sha1_context, hash_stage2); /* convert hash_stage2 to hex string */ *to++= PVERSION41_CHAR; octet2hex(to, (const char*) hash_stage2, SHA1_HASH_SIZE); } ``` Given this method, you can create a .NET counterpart that basically does the same thing. Here's what I've come up with. When I run SELECT PASSWORD('test'); against my local copy of MySQL, the value returned is: `*94BDCEBE19083CE2A1F959FD02F964C7AF4CFC29` According to the source code (again in password.c), the beginning asterisk indicates that this is the post-MySQL 4.1 method of encrypting the password. When I emulate the functionality in VB.Net for example, this is what I come up with: ``` Public Function GenerateMySQLHash(ByVal strKey As String) As String Dim keyArray As Byte() = Encoding.UTF8.GetBytes(strKey) Dim enc = New SHA1Managed() Dim encodedKey = enc.ComputeHash(enc.ComputeHash(keyArray)) Dim myBuilder As New StringBuilder(encodedKey.Length) For Each b As Byte In encodedKey myBuilder.Append(b.ToString("X2")) Next Return "*" & myBuilder.ToString() End Function ``` Keep in mind that SHA1Managed() is in the System.Security.Cryptography namespace. This method returns the same output as the PASSWORD() call in MySQL. I hope this helps for you. Edit: Here's the same code in C# ``` public string GenerateMySQLHash(string key) { byte[] keyArray = Encoding.UTF8.GetBytes(key); SHA1Managed enc = new SHA1Managed(); byte[] encodedKey = enc.ComputeHash(enc.ComputeHash(keyArray)); StringBuilder myBuilder = new StringBuilder(encodedKey.Length); foreach (byte b in encodedKey) myBuilder.Append(b.ToString("X2")); return "*" + myBuilder.ToString(); } ```
You can encrypt strings using MD5 or SHA1 in .Net, but the actual algorithm used by MySQL is probably different to these two methods. I suspect it is based on some kind of 'salt' based on the instance of the server, but I don't know. In theory, since I believe MySQL is open source you could investigate the source and determine how this is done. <http://dev.mysql.com/doc/refman/5.1/en/encryption-functions.html#function_password> Edit 1: I believe the algorithm used is a double SHA1 with other 'tweaks' (according to [this](http://www.radialsoftware.co.uk/index.php?option=com_content&view=article&id=20:mysql-passwords&catid=11:understanding-mysql&Itemid=18) blog post).
Simulating MySql's password() encryption using .NET or MS SQL
[ "", ".net", "sql", "mysql", "sql-server", "encryption", "" ]
I want to get all values of a set interface in one go as a comma separated string. For Example(Java Language): ``` Set<String> fruits= new HashSet<String>(); fruits.add("Apple"); fruits.add("Banana"); fruits.add("Orange"); ``` If I print the set as `fruits.toString` then the output would be: ``` [Apple, Banana, Orange] ``` But my requirement is `Apple, Banana, Orange` without the square brackets.
I'm assuming this is Java. MartinodF's quick and dirty `toString().substring` approach will work, but what you're really looking for is a `join` method. If you do a lot of string manipulation, I'd suggest you take a look at the [Apache Commons](http://commons.apache.org/) [Lang](http://commons.apache.org/lang/) library. It provides a lot of useful features that are missing from the Java standard library, including a StringUtils class that would let you do this: ``` Set fruits = new HashSet(); fruits.add("Apple"); fruits.add("Banana"); fruits.add("Orange"); String allFruits = StringUtils.join(fruits, ", "); // allFruits is now "Apple, Banana, Orange" ```
Quick and dirty: ``` value.toString().substring(1, value.toString().length - 1); ```
How to get data from Set in one go
[ "", "java", "collections", "printing", "" ]
I'm reading a text file with the following format: ``` Room1*Exposition*Work 1 | Work 2 | Work 3 | Work n Room2*Exposition*Obra 1 | Work 2 | Work 3 | Work n ``` Using the following: ``` try { String path="contenidoDelMuseo.txt"; File myFile = new File (path); FileReader fileReader = new FileReader(myFile); BufferedReader reader = new BufferedReader(fileReader); String line = null; while ((line=reader.readLine())!=null){ String [] fields = line.split("\\*"); } ``` An IndexOutOfBoundsException is thrown each time I try to access `fields[1]`. Why? Edit: the whole code for the class is ``` /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * Buscar.java * * Created on 23/04/2009, 06:22:54 PM */ package interfaces; import java.io.File; import java.io.FileReader; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; /** * * @author Alirio */ public class Buscar extends javax.swing.JFrame { static ArrayList<String>obras = new ArrayList<String>(); static ArrayList<String>salas = new ArrayList<String>(); static ArrayList <String> exposiciones = new ArrayList <String>(); /** Creates new form Buscar */ public Buscar() { initComponents(); try { String ruta="contenidoDelMuseo.txt"; File myFile = new File (ruta); FileReader fileReader = new FileReader(myFile); BufferedReader reader = new BufferedReader(fileReader); String line = null; while ((line=reader.readLine())!=null){ System.out.println(line); String []camposABuscar = line.split("\\*"); salas.add(camposABuscar[0]); System.out.println(camposABuscar[0]); System.out.println(camposABuscar[1]); //System.out.println(camposABuscar[1]); // exposiciones.add(camposABuscar[1]); //String []obrasABuscar = camposABuscar[2].split("\\|"); /* for (int contador =0; contador <obrasABuscar.length; contador++) { obras.add(obrasABuscar[contador]); }*/ //System.out.print(obras.get(0)); } reader.close(); } catch (IOException ex){ ex.printStackTrace(); } } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { jPanel1 = new javax.swing.JPanel(); jPanel2 = new javax.swing.JPanel(); Buscatext = new javax.swing.JTextField(); Criterios = new javax.swing.JComboBox(); Buscar = new javax.swing.JButton(); labelBusqueda = new javax.swing.JLabel(); labelCriterios = new javax.swing.JLabel(); BotonSalir = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jPanel1.setLayout(null); jPanel2.setBackground(new java.awt.Color(255, 153, 0)); jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Buscador", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 11), new java.awt.Color(255, 255, 255))); // NOI18N jPanel2.setToolTipText("Hola"); Criterios.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "-Seleccione-", "Autor", "Sala", "Piso", " " })); Buscar.setText("Buscar"); Buscar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BuscarActionPerformed(evt); } }); labelBusqueda.setText("Busqueda:"); labelCriterios.setText("Criterios:"); BotonSalir.setText("Salir"); BotonSalir.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BotonSalirActionPerformed(evt); } }); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(labelBusqueda, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(Buscatext, javax.swing.GroupLayout.DEFAULT_SIZE, 204, Short.MAX_VALUE)) .addGap(63, 63, 63) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(labelCriterios) .addContainerGap()) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addComponent(Criterios, 0, 179, Short.MAX_VALUE) .addGap(56, 56, 56) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(BotonSalir, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(Buscar, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 136, Short.MAX_VALUE)) .addGap(60, 60, 60)))) ); jPanel2Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {Buscar, Criterios}); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(20, 20, 20) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(labelBusqueda) .addComponent(labelCriterios)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(Buscatext, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(Criterios, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(Buscar)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(BotonSalir) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel2Layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {Buscar, Criterios}); jPanel1.add(jPanel2); jPanel2.setBounds(20, 180, 720, 130); jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/LOGOTIPO.jpg"))); // NOI18N jPanel1.add(jLabel1); jLabel1.setBounds(10, 10, 250, 150); jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/fondos/iconoconejo.gif"))); // NOI18N jLabel3.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jLabel3MouseClicked(evt); } }); jPanel1.add(jLabel3); jLabel3.setBounds(710, 0, 50, 50); jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/fondos/background_1.jpg"))); // NOI18N jLabel2.setText("jLabel2"); jPanel1.add(jLabel2); jLabel2.setBounds(0, 0, 980, 980); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 763, javax.swing.GroupLayout.PREFERRED_SIZE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 619, javax.swing.GroupLayout.PREFERRED_SIZE) ); pack(); }// </editor-fold> private void jLabel3MouseClicked(java.awt.event.MouseEvent evt) { // TODO add your handling code here: ClaveAdministrador CA= new ClaveAdministrador(); CA.setVisible(true); } private void BotonSalirActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: InterfazSeleccion A= new InterfazSeleccion(); A.setVisible(true); this.setVisible(false); } private void BuscarActionPerformed(java.awt.event.ActionEvent evt) { String s = Buscatext.getText (); } /** * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Buscar().setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.JButton BotonSalir; private javax.swing.JButton Buscar; private javax.swing.JTextField Buscatext; private javax.swing.JComboBox Criterios; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JLabel labelBusqueda; private javax.swing.JLabel labelCriterios; // End of variables declaration } ```
I bet the first "line" of your file is actually blank, so your first time through the loop the split does nothing and hence the array is empty. You could just check the size of the **fields[]** array before attemtping to use it, if its null (or length = 0) move on to the next line.
I ran the code with your data. It worked...
split() method fail
[ "", "java", "split", "" ]
What is the best way to create databases on C# application, I mean by a click of a button, it will create a database with a different name but the same model? Currently, I script TSQL onto a C# application, so when I click a button, a new database will be created with the name I defined, it works well, however, it is extremely difficult to maintain, is there a better way to create database on C#? Regards
One way is to just have a copy of your database file (mdf) available for pushing onto a new server. This similiar to what microsoft does with it's Model database. Whenever you create a new database it starts by making a copy of that one. Your button click could copy the database file to the desired location, rename it as appropriate, then attach it to the running sql server instance. Whenever you need to update the database with a new schema, just copy the mdf to your deployment directory.
You can use SMO to create databases. See [MSDN sample](http://msdn.microsoft.com/en-us/library/ms162577.aspx).
Create Databases in a C# application
[ "", "c#", "database", "t-sql", "" ]
I have a pair of X.509 cert and a key file. How do I import those two in a single keystore? All examples I could Google always generate the key themselves, but I already have a key. I have tried: ``` keytool -import -keystore ./broker.ks -file mycert.crt ``` However, this only imports the certificate and not the key file. I have tried concatenating the cert and the key but got the same result. How do I import the key?
Believe or not, keytool does not provide such basic functionality like importing private key to keystore. You can try this [workaround](http://web.archive.org/web/20190426215445/http://cunning.sharp.fm/2008/06/importing_private_keys_into_a.html) with merging PKSC12 file with private key to a keystore: ``` keytool -importkeystore \ -deststorepass storepassword \ -destkeypass keypassword \ -destkeystore my-keystore.jks \ -srckeystore cert-and-key.p12 \ -srcstoretype PKCS12 \ -srcstorepass p12password \ -alias 1 ``` Or just use more user-friendly [KeyMan](https://www.ibm.com/developerworks/mydeveloperworks/groups/service/html/communityview?communityUuid=6fb00498-f6ea-4f65-bf0c-adc5bd0c5fcc) from IBM for keystore handling instead of keytool.
I used the following two steps which I found in the comments/posts linked in the other answers: **Step one: Convert the x.509 cert and key to a pkcs12 file** ``` openssl pkcs12 -export -in server.crt -inkey server.key \ -out server.p12 -name [some-alias] \ -CAfile ca.crt -caname root ``` **Note:** Make sure you put a password on the pkcs12 file - otherwise you'll get a null pointer exception when you try to import it. (In case anyone else had this headache). (**Thanks jocull!**) **Note 2:** You might want to add the `-chain` option to preserve the full certificate chain. (**Thanks Mafuba**) **Step two: Convert the pkcs12 file to a Java keystore** ``` keytool -importkeystore \ -deststorepass [changeit] -destkeypass [changeit] -destkeystore server.keystore \ -srckeystore server.p12 -srcstoretype PKCS12 -srcstorepass some-password \ -alias [some-alias] ``` **Finished** **OPTIONAL Step zero: Create self-signed certificate** ``` openssl genrsa -out server.key 2048 openssl req -new -out server.csr -key server.key openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt ``` **FAQ: I get error `IOException: keystore password was incorrect`** If you are using OpenSSL 3.0 and a JDK newer than Java8u302 and get the following error: ``` keytool error: java.io.IOException: keystore password was incorrect ``` You might caught in a change pf default cypher within openssl. [This Stack Overflow Answer](https://stackoverflow.com/a/72501767/102200) provides an answer. Maybe thank Thomas with an upvote.
How to import an existing X.509 certificate and private key in Java keystore to use in SSL?
[ "", "java", "ssl", "jks", "" ]
Any smart way of doing a "root" based path referencing in JavaScript, just the way we have `~/` in ASP.NET?
Have your page generate a tag with something like: ``` <link rel="home" id="ApplicationRoot" href="http://www.example.com/appRoot/" /> ``` Then, have a function in JavaScript that extracts the value such as: ``` function getHome(){ return document.getElementById("ApplicationRoot").href; } ```
Use [base](http://www.w3schools.com/TAGS/tag_base.asp) tag: ``` <head> <base href="http://www.example.com/myapp/" /> </head> ``` ... from now any link use on this page, no matter in javascript or html, will be relative to the base tag, which is "<http://www.example.com/myapp/>".
~/ equivalent in javascript
[ "", "javascript", "asp.net", "web-applications", "relative-path", "" ]
I have a 5yr old G4 PowerBook that I use while travelling, and I had intended to get some work done whilst I am away for the next few weeks. Eclipse just seems to be horrendously slow on it. I've tried tweaking the memory allocated to the VM, but it doesn't seem to do very much :) Any thoughts as to why it's so slow? I don't get this problem on my desktop - and that has less RAM, although it's running Linux. If I'm flogging a dead horse, what would you recommend as a Java development environment? Ideally, I would want good code completion, as my mental capacity is somewhat limited :) --- *Thank you all kindly for your responses. I've just set-up netbeans on the laptop, removed some of the cruft, and imported my project. After taking about half an hour scanning the project (there are a ton of external libraries) I am pleased to say that it is very responsive. Code completion is working nicely (although not quite as intuitive as eclipse). Unfortunately, I seem to be able to only select one of your answers - although i'll be using many of them. A new laptop is on the cards for when I get back from my trip.*
I've been using Eclipse for years, and I found that it never ran acceptably fast on my Mac until I got Ganymede (Eclipse 3.4) and ran it on my Core 2 Duo Macbook w/ 2GB of RAM. Before I had both of those things, it was only ever bearable on Linux or Windows. I'd recommend upgrading your computer. :-) Eclipse is, after all, a beast of a program no matter how you spin it.
I've found two primary limiters to Eclipse performance: 1. Available RAM (2GB is a minimum on a Windows PC) 2. Hard drive speed (I've had lots of issues with slow and/or highly fragmented drives.) Laptops have notoriously slow drives - and it's often compounded by the drive going into "power save" mode (thus spinning more slowly.) We also used to run Eclipse on top of ClearCase dynamic views....talk about a performance beast.... It may also be worth your time to trim down Eclipse (disabling unneeded plugins and the like.) Click "Help"->"Manage Configuration" to get to the interface where you can do this. The Eclipse distributions come with lots and lots of powerful tools - many of which most of us never use.
Eclipse performance on my G4 is horrific - any thoughts on a replacement?
[ "", "java", "performance", "eclipse", "" ]
I'm working on a website for my county's fair. I want to allow my visitors to be able to ask me questions by inputing their name, email, and comment in a form like this one: <http://lincolnfair.net/images/feedback.JPG> So I guess my real question is how can I send an email (using JavaScript/JQuery) to myself with all these fields as the main body of the email.
You should use a server-side script (e.g. PHP, Python, Perl, etc.). With pure HTML and JavaScript, you can use a [mailto form](https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-5250440.html), but this will be very unreliable.
I will suggest uservoice.com , it can integrate with your site nicely, a much more powerful user feedback system, without spending time to code the feedback system yourself
What is a good way to get feedback from a user on a website?
[ "", "javascript", "jquery", "html", "" ]
I know the questions seems ambiguous, but I couldn't think of any other way to put it, but, Is it possible to do something like this: ``` #include<iostream> class wsx; class wsx { public: wsx(); } wsx::wsx() { std::cout<<"WSX"; } ``` ?
Yes, that is possible. The following just declares `wsx` ``` class wsx; ``` That kind of declaration is called a forward declaration, because it's needed when two classes refer to each other: ``` class A; class B { A * a; }; class A { B * b; }; ``` One of them needs to be forward declared then.
In your example, ``` class wsx; // this is a class declaration class wsx // this is a class definition { public: wsx(); } ``` So yes, by using `class wsx;` it is possible to declare a class without defining it. A class declaration lets you declare pointers and references to that class, but not instances of the class. The compiler needs the class definition so it knows how much memory to allocate for an instance of the class.
Is it possible to declare a class without implementing it? (C++)
[ "", "c++", "class", "declaration", "definition", "forward-declaration", "" ]
(Came up with this question in the course of trying to answer [this other one](https://stackoverflow.com/questions/850017/how-to-manage-groups-in-the-database/850049#850049)) Consider the following MS-SQL table, called GroupTable: ``` GroupID ------- 1 2 3 ``` where GroupID is the primary key and is an Identity column. How do you insert a new row into the table (and hence generate a new ID) **without** using IDENTITY\_INSERT ON? Note that this: ``` INSERT INTO GroupTable() Values () ``` ... won't work. edit: we're talking SQL 2005 or SQL 2008 here.
This should work: ``` INSERT INTO GroupTable DEFAULT VALUES ```
Here you go: ``` INSERT INTO GroupTable DEFAULT VALUES ```
How to insert into a table with just one IDENTITY column?
[ "", "sql", "sql-server", "identity", "" ]
Does anyone know how to read a x.properties file in Maven. I know there are ways to use resource filtering to read a properties file and set values from that, but I want a way in my pom.xml like: ``` <properties file="x.properties"> </properties> ``` There was some discussion about this: [Maven External Properties](http://www.mail-archive.com/users@maven.apache.org/msg70112.html)
Try the [Properties Maven Plugin](http://www.mojohaus.org/properties-maven-plugin/)
Using the suggested Maven properties plugin I was able to read in a buildNumber.properties file that I use to version my builds. ``` <build> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>properties-maven-plugin</artifactId> <version>1.2.1</version> <executions> <execution> <phase>initialize</phase> <goals> <goal>read-project-properties</goal> </goals> <configuration> <files> <file>${basedir}/../project-parent/buildNumber.properties</file> </files> </configuration> </execution> </executions> </plugin> </plugins> ```
How to read an external properties file in Maven
[ "", "java", "build", "maven-2", "properties-file", "" ]
I've got the following code which I think ought to be binding a DataTable to a DataGridView, but the DataGridView shows up empty. The DataTable definately has rows, so I assume that I am binding the DataSource incorrectly some how. Does anyone see what is wrong with this: ``` DataBase db = new DataBase(re.OutputDir+"\\Matches.db"); MatchDBReader reader = new MatchDBReader(db.NewConnection()); BindingSource bindingSource = new BindingSource(); bindingSource.DataSource = reader.GetDataTable(); this.dataGridView1.DataSource = bindingSource.DataSource; ``` * The first line simply gets a handle to the DB that I'm pulling data from. * The next line is a provides a class for reading from that same db - in particular it exposes the GetDataTable method with returns the data table that I intend to put into the DataGridView. * The next line is uninteresting... * The 4th line attempts to grab the DataTable - QuickWatch indicates that this is working... * The final line is where I assume i've screwed up...my understanding is that this binds the DataTable to the DataGridView GUI, but nothing shows up. Any thoughts?
None of this worked for me, though it all seemed like good advice. What I ended up doing was the biggest, worst hack on earth. What I was hoping to accomplish was simply to load a DB table from a SQLite db and present it (read only, with sortable columns) in the DataGridView. The actual DB would be programmatically specified at runtime. I defined the DataSet by adding a DataGridView to the form and used the Wizards to statically define the DB connection string. Then I went into the Settings.Designer.cs file and added a `set` accessor to the DB Connection string property: ``` namespace FormatDetector.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "9.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } [global::System.Configuration.ApplicationScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.SpecialSettingAttribute(global::System.Configuration.SpecialSetting.ConnectionString)] [global::System.Configuration.DefaultSettingValueAttribute("data source=E:\\workspace\\Test\\Matches.db;useutf16encoding=True")] public string MatchesConnectionString { get { return ((string)(this["MatchesConnectionString"])); } set { (this["MatchesConnectionString"]) = value; } } } } ``` This is a klugey hack, but it works. Suggestions about how to clean this mess up are more than welcome. brian
Try binding the DataGridView directly to the BindingSource, and not the BindingSource's DataSource: ``` this.dataGridView1.DataSource = bindingSource; ```
DataGridView does not display DataTable
[ "", "c#", "sqlite", "datagridview", "datatable", "system.data.sqlite", "" ]
Try executing the following in JavaScript: ``` parseInt('01'); //equals 1 parseInt('02'); //equals 2 parseInt('03'); //equals 3 parseInt('04'); //equals 4 parseInt('05'); //equals 5 parseInt('06'); //equals 6 parseInt('07'); //equals 7 parseInt('08'); //equals 0 !! parseInt('09'); //equals 0 !! ``` I just learned the hard way that JavaScript thinks the leading zero indicates an [octal integer](http://en.wikipedia.org/wiki/Octal), and since there is no `"8"` or `"9"` in base-8, the function returns zero. Like it or not, [this is by design](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Functions/parseInt). What are the workarounds? *Note: For sake of completeness, I'm about to post a solution, but it's a solution that I hate, so please post other/better answers.* --- **Update:** The 5th Edition of the JavaScript standard ([ECMA-262](http://www.ecma-international.org/publications/standards/Ecma-262.htm)) introduces a breaking change that eliminates this behavior. Mozilla has a good [write-up](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/parseInt#ECMAScript_5_Removes_Octal_Interpretation).
This is a common Javascript gotcha with a simple solution: Just [specify the base](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt), or 'radix', like so: ``` parseInt('08',10); // 8 ``` You could also use [Number](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number): ``` Number('08'); // 8 ```
If you **know** your value will be in the signed 32 bit integer range, then `~~x` will do the correct thing in all scenarios. ``` ~~"08" === 8 ~~"foobar" === 0 ~~(1.99) === 1 ~~(-1.99) === -1 ``` If you look up binary not (`~`), the spec requires a "ToInt32" conversion for the argument which does the obvious conversion to an Int32 and is specified to coerce `NaN` values to zero. Yes, this is incredibly hackish but is so convenient...
How do I work around JavaScript's parseInt octal behavior?
[ "", "javascript", "integer", "octal", "" ]
How to convert a value from nanoseconds to seconds? Here's the code segment: ``` import java.io.*; import java.util.concurrent.*; .. class Stamper { public static void main (String[] args) { long start = System.nanoTime(); //some try with nested loops long end = System.nanoTime(); long elapsedTime = end - start; System.out.println("elapsed: " + elapsedTime + "nano seconds\n"); //convert to seconds TimeUnit seconds = new TimeUnit(); System.out.println("which is " + seconds.toSeconds(elapsedTime) + " seconds"); }} ``` The error is ``` Stamper.java:16: enum types may not be instantiated. ``` What does this mean?
Well, you could just divide by 1,000,000,000: ``` long elapsedTime = end - start; double seconds = (double)elapsedTime / 1_000_000_000.0; ``` If you use `TimeUnit` to convert, you'll get your result as a long, so you'll lose decimal precision but maintain whole number precision.
# `TimeUnit` Enum The following expression uses the [`TimeUnit`](http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/TimeUnit.html) enum (Java 5 and later) to convert from nanoseconds to seconds: ``` TimeUnit.SECONDS.convert(elapsedTime, TimeUnit.NANOSECONDS) ```
How to convert nanoseconds to seconds using the TimeUnit enum?
[ "", "java", "timeunit", "" ]
I have a windows service and use nlog for logging. Everything works fine when I run from the visual studio ide. The log file updates with no issues. When I install the service, the service runs fine but the log file never updates. I am running under LOCAL SERVICE if that helps. Yes, I have created the logs directory under my application folder. ``` <?xml version="1.0" encoding="utf-8" ?> <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" > <targets> <target name="file" xsi:type="File" fileName="${basedir}/logs/${shortdate}_info.txt" layout="${date} ${logger} ${message}" /> </targets> <rules> <logger name="*" minlevel="Info" maxlevel="Info" writeTo="file" /> </rules> </nlog> ```
Your local service account doesn't have access to write to the file location specified. You set it to use a system account in the "Log On" tab of the service properties dialog, or you can set up the user account as part of the setup process.
I've had this issue too. As mentioned by genki you are probably logging into the \Windows\System32 directory. Maybe check for the log file you are expecting there first. When writing services I've often put a line like this in the beginning to get the current directory to behave like a normal application ``` Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory); ```
Why won't my windows service write to my log file?
[ "", "c#", "logging", "windows-services", "service", "nlog", "" ]
I am using `/bin/tcsh` as my default shell. However, the tcsh style command `os.system('setenv VAR val')` doesn't work for me. But `os.system('export VAR=val')` works. So my question is how can I know the `os.system()` run command under which shell?
`os.system()` just calls the `system()` system call ("`man 3 system`"). On most \*nixes this means you get `/bin/sh`. Note that `export VAR=val` is technically not standard syntax (though `bash` understands it, and I think `ksh` does too). It will not work on systems where `/bin/sh` is actually the Bourne shell. On those systems you need to export and set as separate commands. (This will work with `bash` too.)
Was just reading [Executing BASH from Python](http://www.rubyops.net/executing-bash-from-python), then [17.1. subprocess — Subprocess management — Python v2.7.3 documentation](http://docs.python.org/2/library/subprocess.html#popen-constructor), and I saw the `executable` argument; and it seems to work: ``` $ python Python 2.7.1+ (r271:86832, Sep 27 2012, 21:16:52) [GCC 4.5.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> print os.popen("echo $0").read() sh >>> import subprocess >>> print subprocess.call("echo $0", shell=True).read() /bin/sh >>> print subprocess.Popen("echo $0", stdout=subprocess.PIPE, shell=True).stdout.read() /bin/sh >>> print subprocess.Popen("echo $0", stdout=subprocess.PIPE, shell=True, executable="/bin/bash").stdout.read() /bin/bash >>> print subprocess.Popen("cat <(echo TEST)", stdout=subprocess.PIPE, shell=True).stdout.read() /bin/sh: Syntax error: "(" unexpected >>> print subprocess.Popen("cat <(echo TEST)", stdout=subprocess.PIPE, shell=True, executable="/bin/bash").stdout.read() TEST ``` Hope this helps someone, Cheers!
os.system() execute command under which linux shell?
[ "", "python", "linux", "shell", "" ]
I'm building a thesaurus using a `HashMap <String,ArrayList<String>>` to hold words and their synonyms (this data structure is required). For the purpose of the assignment, the synonymity relation is considered transitive. (We can imagine the thesaurus as a graph). What I'm trying to accomplish is to print this graph in a text file, with a connected component on each line. In other words, all the words that can be pooled together as synonyms should go on a single line. ``` public void save() { try { FileWriter fw = new FileWriter(defaultDefinitionFile); BufferedWriter out = new BufferedWriter(fw); Set<String> keys = thesaurus.keySet(); Iterator<String> ite = keys.iterator(); while (ite.hasNext()) { String key = ite.next(); out.write(key); ArrayList<String> synonyms = thesaurus.get(key); Iterator<String> i = synonyms.iterator(); while (i.hasNext()) { String syn = i.next(); out.write(","+syn); keys.remove(syn); } out.write("\r\n"); } out.close(); fw.close(); } catch (Exception e) { System.out.println("Error writing to file"); e.printStackTrace(); } } ``` This is how I pictured it to happen: Print a word along with each of its synonyms, then remove those synonyms from the data structure so we don't have duplicate lines. Problem is of course that I can't delete anything while i'm iterating over the content of the hashmap. Any alternative approaches I'm missing? P.S. I'm keeping the 'graph' metaphor throughout only because i needed the title to be eloquent and succint. I understand that this metaphor is limited in usefulness.
You can store the words that were printed in a [Set](http://java.sun.com/javase/6/docs/api/java/util/Set.html), and then only handle words that are not yet in the set. *Side remark*: though it's true that one can think about this as a graph problem, your code doesn't treat this as such. If we were to treat this as a graph problem, then we wouldn't make the assumption that each word has all its synonyms listed in the corresponding `ArrayList`, thus calling for the calculation of the symmetric and transitive closure. Only then would we extract the equivalence classes. (In reality the synonym relation is not transitive, I know.)
I don't this this (your general idea) will work as "synonimity" is not a transitive property. There are plenty of words that have synonyms that are not themselves synonyms.
Find 'connected components' in graph
[ "", "java", "hashmap", "graph-traversal", "" ]
I'm about to start a new job where the coding practices are heavily centered around TDD and refactoring, and whose primary development language is Python. I come from the Java world, and have been a confident user of Eclipse for a good, long time. When not working in Java, I use emacs. I'm looking for an IDE for Python that will give me a lot of the capabilities I've grown used to with Eclipse, not only for refactoring but in terms of code completion, project management, SCM integration (currently CVS, but likely to switch to git one of these days) et al. What IDE should I use?
Have tried many different (Kate, Eclipse, Scite, Vim, Komodo): each one have some glitches, either limited functions, or slow and unresponsive. Final choice after many years: Emacs + ropemacs + flymake. Rope project file open dialog is extremely quick. Rope refactoring and code assist functions are super helpful. Flymake shows syntax mistakes. Emacs is the most configurable editor. I am very happy with this config. Python related part of config is here: public.halogen-dg.com browser/alex-emacs-settings/configs/cfg\_python.el
My 2 pennies, check out PyCharm <http://www.jetbrains.com/pycharm/> (also multi-platform)
What's a good IDE for Python on Mac OS X?
[ "", "python", "macos", "ide", "" ]
I am looking for some kind of example of a Javascript Time Picker that is similar to the one used in Windows to pick the time...well except with out the seconds being in their. I have a mockup in place at the moment but trying to figure out how some of the user functionality should be be as it is two inputs and a dropdown. I guess I just am not happy with it at this point. Thanks ahead of time for any help
The Windows time picker (if you're referring to the one to change the system clock) is basically just a masked edit text box. If you're looking for something similar, you just need some JavaScript to do masked edits, like this one: <http://digitalbush.com/projects/masked-input-plugin/> To make it specifically for time, you should be able to easily add logic to ensure the hours don't go over 12 (or 24), and the minutes don't go over 59. Personally, I prefer the way Google Calendar does time selections. There is a jQuery plugin for this which can be found here: <http://labs.perifer.se/timedatepicker/>
There are a number of jQuery plugins that you can use for the perfect looking time picker control. Here is a good one: <http://plugins.jquery.com/project/timepicker>
Javascript Time Picker like Windows
[ "", "javascript", "datetimepicker", "" ]
What is the best way to develop on SQL Server 2005 machine locally while you get your database design and application design smoothed out and then deploy to a shared host? In the MySQL / phpMyAdmin world you have an option to export the table as the DDL Statement with the data represented as a bunch of inserts following the DDL. Using this you can drop a table, recreate it, and load it with data all from a query window. Is there anything close to this in the Microsoft world? Is there any free/open source tools to help with this migration of data?
[SQL Server Management Studio Express](http://www.microsoft.com/downloads/details.aspx?FamilyId=C243A5AE-4BD1-4E3D-94B8-5A0F62BF7796&displaylang=en) (which is free) includes the "Generate Scripts" option that TheTXI referred to. The [Database Publication Wizard](http://www.microsoft.com/downloads/details.aspx?familyid=56E5B1C5-BF17-42E0-A410-371A838E570A&displaylang=en) is a more lightweight product (also free) that is specifically for generating export scripts for both schema and data. **Caveat** — neither is 100% reliable. I've sometimes had to tinker with the scripts to get them to run, particularly regarding the order of dependent objects. It's a pain, but still better than starting from scratch. As RedBeard mentioned, you should be keeping track of your DDL scripts, in particular the "diff" scripts that will upgrade you from one revision of the database to the next. In that case, these tools would not be useful during the normal development cycle. However, if you haven't been managing your scripts this way, these tools can help you get started, and are also good for creating new instances, migrating instances, comparing snapshots, and a host of other things.
Generate Scripts of all your database schema (tables, stored procedures, views, etc.) and also do exports of your data (if necessary) and then run those scripts and import the data into your shared host. Depending on that host, you could get access through Management Studio and it would be an even easier process.
Develop Locally on SQL Server 2005 then Deploying to Shared Hosting
[ "", ".net", "sql", "sql-server", "hosting", "data-migration", "" ]
I'm trying to create a new object of type T via its constructor when adding to the list. I'm getting a compile error: The error message is: > 'T': cannot provide arguments when creating an instance of a variable But my classes do have a constructor argument! How can I make this work? ``` public static string GetAllItems<T>(...) where T : new() { ... List<T> tabListItems = new List<T>(); foreach (ListItem listItem in listCollection) { tabListItems.Add(new T(listItem)); // error here. } ... } ```
In order to create an instance of a generic type in a function you must constrain it with the "new" flag. ``` public static string GetAllItems<T>(...) where T : new() ``` However that will only work when you want to call the constructor which has no parameters. Not the case here. Instead you'll have to provide another parameter which allows for the creation of object based on parameters. The easiest is a function. ``` public static string GetAllItems<T>(..., Func<ListItem,T> del) { ... List<T> tabListItems = new List<T>(); foreach (ListItem listItem in listCollection) { tabListItems.Add(del(listItem)); } ... } ``` You can then call it like so ``` GetAllItems<Foo>(..., l => new Foo(l)); ```
in .Net 3.5 and after you could use the activator class: ``` (T)Activator.CreateInstance(typeof(T), args) ```
Passing arguments to C# generic new() of templated type
[ "", "c#", ".net", "generics", "new-operator", "" ]
Has anybody used a good Java implementation of BBCode? I am looking at 1. [javabbcode](https://javabbcode.dev.java.net/) : nothing to see 2. [kefir-bb](http://sourceforge.net/projects/kefir-bb/) : Listed as alpha 3. BBcode parser in JBoss source code. Are there any better options?
**The current version of KefirBB 0.6 is not listed as beta anymore. I find the KefirBB parser very easy to configure and extend with my own tags:** [kefir-bb.sourceforge.net](http://kefir-bb.sourceforge.net/) *(This is the best [BBCode](http://en.wikipedia.org/wiki/BBCode) parser I've found so far)* I also found this code at [fyhao.com](http://fyhao.com/2010/06/computer-and-it/java/simple-java-bbcode-implementation/), but it does protect you against incorrectly nested tags (thus not suitable for parsing user entered input): ``` public static String bbcode(String text) { String html = text; Map<String,String> bbMap = new HashMap<String , String>(); bbMap.put("(\r\n|\r|\n|\n\r)", "<br/>"); bbMap.put("\\[b\\](.+?)\\[/b\\]", "<strong>$1</strong>"); bbMap.put("\\[i\\](.+?)\\[/i\\]", "<span style='font-style:italic;'>$1</span>"); bbMap.put("\\[u\\](.+?)\\[/u\\]", "<span style='text-decoration:underline;'>$1</span>"); bbMap.put("\\[h1\\](.+?)\\[/h1\\]", "<h1>$1</h1>"); bbMap.put("\\[h2\\](.+?)\\[/h2\\]", "<h2>$1</h2>"); bbMap.put("\\[h3\\](.+?)\\[/h3\\]", "<h3>$1</h3>"); bbMap.put("\\[h4\\](.+?)\\[/h4\\]", "<h4>$1</h4>"); bbMap.put("\\[h5\\](.+?)\\[/h5\\]", "<h5>$1</h5>"); bbMap.put("\\[h6\\](.+?)\\[/h6\\]", "<h6>$1</h6>"); bbMap.put("\\[quote\\](.+?)\\[/quote\\]", "<blockquote>$1</blockquote>"); bbMap.put("\\[p\\](.+?)\\[/p\\]", "<p>$1</p>"); bbMap.put("\\[p=(.+?),(.+?)\\](.+?)\\[/p\\]", "<p style='text-indent:$1px;line-height:$2%;'>$3</p>"); bbMap.put("\\[center\\](.+?)\\[/center\\]", "<div align='center'>$1"); bbMap.put("\\[align=(.+?)\\](.+?)\\[/align\\]", "<div align='$1'>$2"); bbMap.put("\\[color=(.+?)\\](.+?)\\[/color\\]", "<span style='color:$1;'>$2</span>"); bbMap.put("\\[size=(.+?)\\](.+?)\\[/size\\]", "<span style='font-size:$1;'>$2</span>"); bbMap.put("\\[img\\](.+?)\\[/img\\]", "<img src='$1' />"); bbMap.put("\\[img=(.+?),(.+?)\\](.+?)\\[/img\\]", "<img width='$1' height='$2' src='$3' />"); bbMap.put("\\[email\\](.+?)\\[/email\\]", "<a href='mailto:$1'>$1</a>"); bbMap.put("\\[email=(.+?)\\](.+?)\\[/email\\]", "<a href='mailto:$1'>$2</a>"); bbMap.put("\\[url\\](.+?)\\[/url\\]", "<a href='$1'>$1</a>"); bbMap.put("\\[url=(.+?)\\](.+?)\\[/url\\]", "<a href='$1'>$2</a>"); bbMap.put("\\[youtube\\](.+?)\\[/youtube\\]", "<object width='640' height='380'><param name='movie' value='http://www.youtube.com/v/$1'></param><embed src='http://www.youtube.com/v/$1' type='application/x-shockwave-flash' width='640' height='380'></embed></object>"); bbMap.put("\\[video\\](.+?)\\[/video\\]", "<video src='$1' />"); for (Map.Entry entry: bbMap.entrySet()) { html = html.replaceAll(entry.getKey().toString(), entry.getValue().toString()); } return html; } ``` BTW javaBBcode is part of opensource project: [JavaBB](http://www.javabb.org/).
I believe a better option is to use wiki markup. You can try the Mylyn Wikitext package which I currently use with great success for our Documentation system. However, this is not an answer to your problem, if what you try is to parse some forum text you already have automatically :-I
Java BBCode library
[ "", "java", "parsing", "bbcode", "" ]
I'm firing off tasks using an ExecutorService, dispatching tasks that need to be grouped by task-specific criteria: ``` Task[type=a] Task[type=b] Task[type=a] ... ``` Periodically I want to output the average length of time that each task took (grouped by `type`) along with statistical information such as mean/median and standard deviation. This needs to be pretty fast, of course, and ideally should not cause the various threads to synchronize when they report statistics. What's a good architecture for doing this?
[ThreadPoolExecutor](http://java.sun.com/javase/6/docs/api/java/util/concurrent/ThreadPoolExecutor.html) provides [beforeExecute](http://java.sun.com/javase/6/docs/api/java/util/concurrent/ThreadPoolExecutor.html#beforeExecute(java.lang.Thread,%20java.lang.Runnable)) and [afterExecute](http://java.sun.com/javase/6/docs/api/java/util/concurrent/ThreadPoolExecutor.html#afterExecute(java.lang.Runnable,%20java.lang.Throwable)) methods that you can override. You could use those to record your statistics in a single (member variable of your ExecutorService) [ConcurrentHashMap](http://java.sun.com/javase/6/docs/api/java/util/concurrent/ConcurrentHashMap.html) keyed on some unique identifier for your tasks, and storing the type, start time, and end time. Calculate the statistics from the `ConcurrentHashMap` when you are ready to look at them.
Subclass [Thread Pool Executor](http://java.sun.com/javase/6/docs/api/java/util/concurrent/ThreadPoolExecutor.html) and track the execution events: * start on [beforeExecute](http://java.sun.com/javase/6/docs/api/java/util/concurrent/ThreadPoolExecutor.html#beforeExecute%28java.lang.Thread,%20java.lang.Runnable%29) * end on [afterExecute](http://java.sun.com/javase/6/docs/api/java/util/concurrent/ThreadPoolExecutor.html#afterExecute%28java.lang.Runnable,%20java.lang.Throwable%29) It's worth noting that the methods are invoked by the worker thread which executes the task, so you need to insure thread safety for the execution tracking code. Also, the Runnables you will receive will most likely not be your Runnables, but wrapped in FutureTasks.
How to track task execution statistics using an ExecutorService?
[ "", "java", "concurrency", "statistics", "monitoring", "" ]
I would like to know if the following scenario is real?! 1. select() (RD) on non-blocking TCP socket says that the socket is ready 2. following recv() would return EWOULDBLOCK despite the call to select()
I am aware of an error in a popular desktop operating where `O_NONBLOCK` TCP sockets, particularly those running over the loopback interface, can sometimes return `EAGAIN` from `recv()` after `select()` reports the socket is ready for reading. In my case, this happens after the other side half-closes the sending stream. For more details, see the source code for `t_nx.ml` in the NX library of my OCaml Network Application Environment distribution. ([link](http://sourceforge.net/project/showfiles.php?group_id=118173&package_id=278919))
For `recv()` you would get `EAGAIN` rather than `EWOULDBLOCK`, and yes it is possible. Since you have just checked with `select()` then one of two things happened: * Something else (another thread) has drained the input buffer between `select()` and `recv()`. * A receive timeout was set on the socket and it expired without data being received.
select(), recv() and EWOULDBLOCK on non-blocking sockets
[ "", "c++", "c", "sockets", "" ]
using Javascript, it is easy to programatically select the text inside a textarea or input text element. How about for ``` <span>The quick brown fox jumps over the lazy dog</span> ``` is it possible to use JavaScript to select the words "quick brown fox"? Or select the whole sentence?
Courtesy of <http://www.sitepoint.com/forums/showthread.php?t=459934> ``` <script type="text/javascript"> function fnSelect(objId) { fnDeSelect(); if (document.selection) { var range = document.body.createTextRange(); range.moveToElementText(document.getElementById(objId)); range.select(); } else if (window.getSelection) { var range = document.createRange(); range.selectNode(document.getElementById(objId)); window.getSelection().addRange(range); } } function fnDeSelect() { if (document.selection) document.selection.empty(); else if (window.getSelection) window.getSelection().removeAllRanges(); } </script> <body> <div id="test1"> <p>jhsdgfhlsdlfkjsdklgjs</p> <p>jhsdgfhlsdlfkjsdklgjs</p> <p>jhsdgfhlsdlfkjsdklgjs</p> </div> <div id="test2"> <p>jhsdgfhlsdlfkjsdklgjs</p> <p>jhsdgfhlsdlfkjsdklgjs</p> <p>jhsdgfhlsdlfkjsdklgjs</p> </div> <a href="javascript:fnSelect('test1');">Select 1</a> <a href="javascript:fnSelect('test2');">Select 2</a> <a href="javascript:fnDeSelect();">DeSelect</a> </body> ```
You will need some way to manipulate the `span` tag. Such as an `id`, but then in javascript I would edit some of the `style` properties. You could have a property for everything you want to highlight like what is shown below. ``` .HL { background: #ffff99; color: #000000; } ``` If you do that then you will need to get a reference to the specific tag. ``` DocumentgetElementsByTagName("title") ``` Otherwise `Document.getElementByID("ID")` is good for unique ids. Then using `setAttribute(name, value)` To change the class to the one given. This is just a simple example but there are many ways to do this. ``` <span id="abc" class=""> Sample </span> var temp = Document.getelementByID("abc"); temp.setAttribute('class', 'HL'); ```
can i highlight any text using Javascript other than the textarea and input text element?
[ "", "javascript", "" ]
> **Possible Duplicate:** > [C# member variable initialization; best practice?](https://stackoverflow.com/questions/298183/c-member-variable-initialization-best-practice) Is there any benefit to this: ``` public class RemotingEngine { uint m_currentValueId; object m_lock; public RemotingEngine() { m_currentValueId = 0; m_lock = new object(); } ``` vs. this: ``` public class RemotingEngine { uint m_currentValueId = 0; object m_lock = new object(); ``` I have been avoiding the second one just because it feels 'dirty'. It is obviously less typing so that is appealing to me.
It can make a difference in an inheritance situation. See this link on the object initialization order: <http://www.csharp411.com/c-object-initialization/> 1. Derived static fields 2. Derived static constructor 3. Derived instance fields 4. Base static fields 5. Base static constructor 6. Base instance fields 7. Base instance constructor 8. Derived instance constructor So if this is a derived class, the entire base object is initialized between when your derived field is initialized and when your constructor runs.
There's not a whole lot of difference, I'd keep with the first one because it's more readable. Usually variables are defined at the top of the class, and I can go there and check out their default values instead of hunting down a constructor and seeing if it sets it. As far as the compiler is concerned, there is no difference, unless you have multiple constructors.
What are the best practices for Private Member Instantiation/Initialization?
[ "", "c#", ".net", "" ]
I'm trying to write a calendar function like this ``` function get_date($month, $year, $week, $day, $direction) { .... } ``` `$week` is a an integer (1, 2, 3...), $day is a day (Sun, Mon, ...) or number, whichever is easier. The direction is a little confusing, because it does a different calculation. For an example, let's call `get_date(5, 2009, 1, 'Sun', 'forward');` It uses the default, and gets the first Sunday in May ie 2009-05-03. If we call `get_date(5, 2009, 2, 'Sun', 'backward');` , it returns the second last Sunday in May ie 2009-05-24.
Perhaps it can be made quicker... This was VERY interesting to code. Please note that `$direction` is 1 for forward and -1 for backward to ease things up :) Also, `$day` begins with a value of 1 for Monday and ends at 7 for Sunday. ``` function get_date($month, $year, $week, $day, $direction) { if($direction > 0) $startday = 1; else $startday = date('t', mktime(0, 0, 0, $month, 1, $year)); $start = mktime(0, 0, 0, $month, $startday, $year); $weekday = date('N', $start); if($direction * $day >= $direction * $weekday) $offset = -$direction * 7; else $offset = 0; $offset += $direction * ($week * 7) + ($day - $weekday); return mktime(0, 0, 0, $month, $startday + $offset, $year); } ``` I've tested it with a few examples and seems to work always, be sure to double-check it though ;)
The language-agnostic version: To get the first particular day of the month, start with the first day of the month: yyyy-mm-01. Use whatever function is available to give a number corresponding to the day of the week. Subtract that number from the day you are looking for; for example, if the first day of the month is Wednesday (2) and you're looking for Friday (4), subtract 2 from 4, leaving 2. If the answer is negative, add 7. Finally add that to the first of the month; for my example, the first Friday would be the 3rd. To get the last Friday of the month, find the first Friday of the next month and subtract 7 days.
Get the First or Last Friday in a Month
[ "", "php", "datetime", "" ]
i have an ASP.NET web service that returning a custom entity object (Staff): ``` [WebMethod] public Staff GetStaffByLoginID(string loginID){} ``` how would i consume this in Java? thanks!
ASP.NET automatically generates a WSDL that contains the interface definitions for your web methods and the types they consume/return. Apache Axis provides a tool called [WSDL2Java](http://ws.apache.org/axis/java/user-guide.html#WSDL2JavaBuildingStubsSkeletonsAndDataTypesFromWSDL) that will generated the all of the code you need to consume the webservice. Simply point it to: <http://yoursite.com/YourWebService.asmx?WSDL> If you browse directly to the .ASMX file, you'll get a nice test harness that you can use to explore the various methods you can call. Once Axis reads your WSDL, it will generate some proxy classes, one of them will be based on the interface of Staff. However, I would not use this class as your actual business object, and instead would wrap access to the web service through a service layer. This service layer would use the proxy Staff class to populate your real business object. This protects your consuming code from any interface changes that may happen to the web service in the future, keeping the actual area of code that would be modified as small as possible. I do this for a living, interopping between Java and .NET on many platforms using SOAP. EDIT: Why the is this downvoted? It's the only correct answer here.
Just use Standard WSDL as mentioned by flyswat if you are using traditional asmx web services. other solutions if not using standard ASP.NET Web Services: Use REST <http://www.infoq.com/articles/REST-INTEROP> <http://www.codeproject.com/KB/XML/WSfromJava.aspx> Make sure the objects are serializable and as long as the you can cast it to a similar class on the Java side, you are good. Else, you might have to write some custom class mappers in Java.
can java consume .NET object returned by ASP.NET web service?
[ "", "java", "asp.net", "web-services", "" ]
I'm using a list of lists to store a matrix in python. I tried to initialise a 2x3 Zero matrix as follows. ``` mat=[[0]*2]*3 ``` However, when I change the value of one of the items in the matrix, it changes the value of that entry in *every* row, since the id of each row in `mat` is the same. For example, after assigning ``` mat[0][0]=1 ``` `mat` is `[[1, 0], [1, 0], [1, 0]]`. I know I can create the Zero matrix using a loop as follows, ``` mat=[[0]*2] for i in range(1,3): mat.append([0]*2) ``` but can anyone show me a more pythonic way?
Use a [list comprehension](http://docs.python.org/tutorial/datastructures.html?highlight=list%20comprehension#list-comprehensions): ``` >>> mat = [[0]*2 for x in xrange(3)] >>> mat[0][0] = 1 >>> mat [[1, 0], [0, 0], [0, 0]] ``` Or, as a function: ``` def matrix(rows, cols): return [[0]*cols for x in xrange(rows)] ```
Try this: ``` >>> cols = 6 >>> rows = 3 >>> a = [[0]*cols for _ in [0]*rows] >>> a [[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]] >>> a[0][3] = 2 >>> a [[0, 0, 0, 2, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]] ``` This is also discussed [in this answer](https://stackoverflow.com/questions/691946/short-and-useful-python-snippets/692458#692458): ``` >>> lst_2d = [[0] * 3 for i in xrange(3)] >>> lst_2d [[0, 0, 0], [0, 0, 0], [0, 0, 0]] >>> lst_2d[0][0] = 5 >>> lst_2d [[5, 0, 0], [0, 0, 0], [0, 0, 0]] ```
Creating lists of lists in a pythonic way
[ "", "list", "matrix", "python", "" ]
I would like to have a timer for an ASP.net application that will kick off every Sunday night and perform something (update a table in the database). However, I really don't want to write up a service that has to be deployed on the server in addition to the web application. Is there a way to accomplish this easily? Perhaps using a Global.asax file?
It seems that the best solution was to use [this technique](https://blog.stackoverflow.com/2008/07/easy-background-tasks-in-aspnet/). If I had more control over the server I would probably write up a console app to take advantage of scheduled tasks.
I'm not 100% sure *where* you would put it, but using a System.Threading.Timer would rock this. ``` // In some constructor or method that runs when the app starts. // 1st parameter is the callback to be run every iteration. // 2nd parameter is optional parameters for the callback. // 3rd parameter is telling the timer when to start. // 4th parameter is telling the timer how often to run. System.Threading.Timer timer = new System.Threading.Timer(new TimerCallback(TimerElapsed), null, new Timespan(0), new Timespan(24, 0, 0)); // The callback, no inside the method used above. // This will run every 24 hours. private void TimerElapsed(object o) { // Do stuff. } ``` Initially, you'll have to determine when to start the timer the first time, or you can turn the site on at the time you want this timer running on Sunday night. But as others said, use something other than the site to do this. It's way easy to make a Windows service to deal with this.
Global Timer in Asp.net
[ "", "c#", "asp.net", "" ]
In [Hidden Features of Java](https://stackoverflow.com/questions/15496/hidden-features-of-java) the top answer mentions [Double Brace Initialization](http://www.c2.com/cgi/wiki?DoubleBraceInitialization), with a *very* enticing syntax: ``` Set<String> flavors = new HashSet<String>() {{ add("vanilla"); add("strawberry"); add("chocolate"); add("butter pecan"); }}; ``` This idiom creates an anonymous inner class with just an instance initializer in it, which "can use any [...] methods in the containing scope". Main question: Is this as **inefficient** as it sounds? Should its use be limited to one-off initializations? (And of course showing off!) Second question: The new HashSet must be the "this" used in the instance initializer ... can anyone shed light on the mechanism? Third question: Is this idiom too **obscure** to use in production code? **Summary:** Very, very nice answers, thanks everyone. On question (3), people felt the syntax should be clear (though I'd recommend an occasional comment, especially if your code will pass on to developers who may not be familiar with it). On question (1), the generated code should run quickly. The extra .class files do cause jar file clutter, and slow program startup slightly (thanks to @coobird for measuring that). @Thilo pointed out that garbage collection can be affected, and the memory cost for the extra loaded classes may be a factor in some cases. Question (2) turned out to be most interesting to me. If I understand the answers, what's happening in DBI is that the anonymous inner class extends the class of the object being constructed by the new operator, and hence has a "this" value referencing the instance being constructed. Very neat. Overall, DBI strikes me as something of an intellectual curiousity. Coobird and others point out you can achieve the same effect with Arrays.asList, varargs methods, Google Collections, and the proposed Java 7 Collection literals. Newer JVM languages like Scala, JRuby, and Groovy also offer concise notations for list construction, and interoperate well with Java. Given that DBI clutters up the classpath, slows down class loading a bit, and makes the code a tad more obscure, I'd probably shy away from it. However, I plan to spring this on a friend who's just gotten his SCJP and loves good natured jousts about Java semantics! ;-) Thanks everyone! 7/2017: Baeldung [has a good summary](http://www.baeldung.com/java-double-brace-initialization) of double brace initialization and considers it an anti-pattern. 12/2017: @Basil Bourque notes that in the new Java 9 you can say: ``` Set<String> flavors = Set.of("vanilla", "strawberry", "chocolate", "butter pecan"); ``` That's for sure the way to go. If you're stuck with an earlier version, take a look at [Google Collections' ImmutableSet](https://google.github.io/guava/releases/19.0/api/docs/com/google/common/collect/ImmutableSet.html).
Here's the problem when I get too carried away with anonymous inner classes: ``` 2009/05/27 16:35 1,602 DemoApp2$1.class 2009/05/27 16:35 1,976 DemoApp2$10.class 2009/05/27 16:35 1,919 DemoApp2$11.class 2009/05/27 16:35 2,404 DemoApp2$12.class 2009/05/27 16:35 1,197 DemoApp2$13.class /* snip */ 2009/05/27 16:35 1,953 DemoApp2$30.class 2009/05/27 16:35 1,910 DemoApp2$31.class 2009/05/27 16:35 2,007 DemoApp2$32.class 2009/05/27 16:35 926 DemoApp2$33$1$1.class 2009/05/27 16:35 4,104 DemoApp2$33$1.class 2009/05/27 16:35 2,849 DemoApp2$33.class 2009/05/27 16:35 926 DemoApp2$34$1$1.class 2009/05/27 16:35 4,234 DemoApp2$34$1.class 2009/05/27 16:35 2,849 DemoApp2$34.class /* snip */ 2009/05/27 16:35 614 DemoApp2$40.class 2009/05/27 16:35 2,344 DemoApp2$5.class 2009/05/27 16:35 1,551 DemoApp2$6.class 2009/05/27 16:35 1,604 DemoApp2$7.class 2009/05/27 16:35 1,809 DemoApp2$8.class 2009/05/27 16:35 2,022 DemoApp2$9.class ``` These are all classes which were generated when I was making a simple application, and used copious amounts of anonymous inner classes -- each class will be compiled into a separate `class` file. The "double brace initialization", as already mentioned, is an anonymous inner class with an instance initialization block, which means that a new class is created for each "initialization", all for the purpose of usually making a single object. Considering that the Java Virtual Machine will need to read all those classes when using them, that can lead to some time in the [bytecode verfication](http://java.sun.com/docs/books/jvms/second_edition/html/ClassFile.doc.html#88597) process and such. Not to mention the increase in the needed disk space in order to store all those `class` files. It seems as if there is a bit of overhead when utilizing double-brace initialization, so it's probably not such a good idea to go too overboard with it. But as Eddie has noted in the comments, it's not possible to be absolutely sure of the impact. --- Just for reference, double brace initialization is the following: ``` List<String> list = new ArrayList<String>() {{ add("Hello"); add("World!"); }}; ``` It looks like a "hidden" feature of Java, but it is just a rewrite of: ``` List<String> list = new ArrayList<String>() { // Instance initialization block { add("Hello"); add("World!"); } }; ``` So it's basically a [instance initialization block](http://java.sun.com/docs/books/tutorial/java/javaOO/initial.html) that is part of an [anonymous inner class](http://java.sun.com/docs/books/tutorial/java/javaOO/innerclasses.html). --- Joshua Bloch's [Collection Literals proposal](http://mail.openjdk.java.net/pipermail/coin-dev/2009-March/001193.html) for [Project Coin](http://openjdk.java.net/projects/coin/) was along the lines of: ``` List<Integer> intList = [1, 2, 3, 4]; Set<String> strSet = {"Apple", "Banana", "Cactus"}; Map<String, Integer> truthMap = { "answer" : 42 }; ``` Sadly, it [didn't make its way](http://mail.openjdk.java.net/pipermail/lambda-dev/2014-March/011938.html) into neither Java 7 nor 8 and was shelved indefinitely. --- **Experiment** Here's the simple experiment I've tested -- make 1000 `ArrayList`s with the elements `"Hello"` and `"World!"` added to them via the `add` method, using the two methods: *Method 1: Double Brace Initialization* ``` List<String> l = new ArrayList<String>() {{ add("Hello"); add("World!"); }}; ``` *Method 2: Instantiate an `ArrayList` and `add`* ``` List<String> l = new ArrayList<String>(); l.add("Hello"); l.add("World!"); ``` I created a simple program to write out a Java source file to perform 1000 initializations using the two methods: *Test 1:* ``` class Test1 { public static void main(String[] s) { long st = System.currentTimeMillis(); List<String> l0 = new ArrayList<String>() {{ add("Hello"); add("World!"); }}; List<String> l1 = new ArrayList<String>() {{ add("Hello"); add("World!"); }}; /* snip */ List<String> l999 = new ArrayList<String>() {{ add("Hello"); add("World!"); }}; System.out.println(System.currentTimeMillis() - st); } } ``` *Test 2:* ``` class Test2 { public static void main(String[] s) { long st = System.currentTimeMillis(); List<String> l0 = new ArrayList<String>(); l0.add("Hello"); l0.add("World!"); List<String> l1 = new ArrayList<String>(); l1.add("Hello"); l1.add("World!"); /* snip */ List<String> l999 = new ArrayList<String>(); l999.add("Hello"); l999.add("World!"); System.out.println(System.currentTimeMillis() - st); } } ``` Please note, that the elapsed time to initialize the 1000 `ArrayList`s and the 1000 anonymous inner classes extending `ArrayList` is checked using the `System.currentTimeMillis`, so the timer does not have a very high resolution. On my Windows system, the resolution is around 15-16 milliseconds. The results for 10 runs of the two tests were the following: ``` Test1 Times (ms) Test2 Times (ms) ---------------- ---------------- 187 0 203 0 203 0 188 0 188 0 187 0 203 0 188 0 188 0 203 0 ``` As can be seen, the double brace initialization has a noticeable execution time of around 190 ms. Meanwhile, the `ArrayList` initialization execution time came out to be 0 ms. Of course, the timer resolution should be taken into account, but it is likely to be under 15 ms. So, there seems to be a noticeable difference in the execution time of the two methods. It does appear that there is indeed some overhead in the two initialization methods. And yes, there were 1000 `.class` files generated by compiling the `Test1` double brace initialization test program.
One property of this approach that has not been pointed out so far is that because you create inner classes, the whole containing class is captured in its scope. This means that as long as your Set is alive, it will retain a pointer to the containing instance (`this$0`) and keep that from being garbage-collected, which could be an issue. This, and the fact that a new class gets created in the first place even though a regular HashSet would work just fine (or even better), makes me not want to use this construct (even though I really long for the syntactic sugar). > Second question: The new HashSet must be the "this" used in the instance initializer ... can anyone shed light on the mechanism? I'd have naively expected "this" to refer to the object initializing "flavors". This is just how inner classes work. They get their own `this`, but they also have pointers to the parent instance, so that you can call methods on the containing object as well. In case of a naming conflict, the inner class (in your case HashSet) takes precedence, but you can prefix "this" with a classname to get the outer method as well. ``` public class Test { public void add(Object o) { } public Set<String> makeSet() { return new HashSet<String>() { { add("hello"); // HashSet Test.this.add("hello"); // outer instance } }; } } ``` To be clear on the anonymous subclass being created, you could define methods in there as well. For example override `HashSet.add()` ``` public Set<String> makeSet() { return new HashSet<String>() { { add("hello"); // not HashSet anymore ... } @Override boolean add(String s){ } }; } ```
Efficiency of Java "Double Brace Initialization"?
[ "", "java", "performance", "collections", "initialization", "" ]
What is the regular exp for a text that can't contain any special characters except space?
Because [Prajeesh](https://stackoverflow.com/users/112352/prajeesh) only wants to match spaces, \s will not suffice as it matches all whitespace characters including line breaks and tabs. A character set that should universally work across all RegEx parsers is: ``` [a-zA-Z0-9 ] ``` Further control depends on your needs. Word boundaries, multi-line support, etc... I would recommend visiting [Regex Library](http://regexlib.com/) which also has some links to various tutorials on how Regular Expression Parsing works.
`[\w\s]*` `\w` will match `[A-Za-z0-9_]` and the `\s` will match whitespaces. `[\w ]*` should match what you want.
Regular Expression for alphanumeric and space
[ "", "c#", ".net", "regex", "" ]
Writing a test app to emulate PIO lines, I have a very simple Python/Tk GUI app. Using the numeric Keys 1 to 8 to simulate PIO pins 1 to 8. Press the key down = PIO High, release the Key = PIO goes low. What I need it for is not the problem. I kind of went down a rabbit hole trying to use a factory to create the key press call back functions. Here is some stripped down code: ``` #!usr/bin/env python """ Python + Tk GUI interface to simulate a 8 Pio lines. """ from Tkinter import * def cb_factory(numberic_key): """ Return a call back function for a specific keyboard numeric key (0-9) """ def cb( self, event, key=numberic_key ): bit_val = 1<<numberic_key-1 if int(event.type) == 2 and not (bit_val & self.bitfield): self.bitfield |= bit_val self.message("Key %d Down" % key) elif int(event.type) == 3 and (bit_val & self.bitfield): self.bitfield &= (~bit_val & 0xFF) self.message("Key %d Up" % key) else: # Key repeat return print hex(self.bitfield) self.display_bitfield() return cb class App( Frame ): """ Main TK App class """ cb1 = cb_factory(1) cb2 = cb_factory(2) cb3 = cb_factory(3) cb4 = cb_factory(4) cb5 = cb_factory(5) cb6 = cb_factory(6) cb7 = cb_factory(7) cb8 = cb_factory(8) def __init__(self, parent): "Init" self.parent = parent self.bitfield = 0x00 Frame.__init__(self, parent) self.messages = StringVar() self.messages.set("Initialised") Label( parent, bd=1, relief=SUNKEN, anchor=W, textvariable=self.messages, text="Testing" ).pack(fill=X) self.bf_label = StringVar() self.bf_label.set("0 0 0 0 0 0 0 0") Label( parent, bd=1, relief=SUNKEN, anchor=W, textvariable=self.bf_label, text="Testing" ).pack(fill=X) # This Doesn't work! Get a traceback saying 'cb' expected 2 arguements # but only got 1? # # for x in xrange(1,9): # cb = self.cb_factory(x) # self.parent.bind("<KeyPress-%d>" % x, cb) # self.parent.bind("<KeyRelease-%d>" % x, cb) self.parent.bind("<KeyPress-1>", self.cb1) self.parent.bind("<KeyRelease-1>", self.cb1) self.parent.bind("<KeyPress-2>", self.cb2) self.parent.bind("<KeyRelease-2>", self.cb2) self.parent.bind("<KeyPress-3>", self.cb3) self.parent.bind("<KeyRelease-3>", self.cb3) self.parent.bind("<KeyPress-4>", self.cb4) self.parent.bind("<KeyRelease-4>", self.cb4) self.parent.bind("<KeyPress-5>", self.cb5) self.parent.bind("<KeyRelease-5>", self.cb5) self.parent.bind("<KeyPress-6>", self.cb6) self.parent.bind("<KeyRelease-6>", self.cb6) self.parent.bind("<KeyPress-7>", self.cb7) self.parent.bind("<KeyRelease-7>", self.cb7) self.parent.bind("<KeyPress-8>", self.cb8) self.parent.bind("<KeyRelease-8>", self.cb8) def display_bitfield(self): """ Display the PIO lines (1 for on, 0 for off) """ bin_lst = [] for x in xrange(8): bit = 1 << x if bit & self.bitfield: bin_lst.append("1") else: bin_lst.append("0") bin_lst.reverse() bin_str = " ".join( bin_lst ) self.bf_label.set( bin_str ) def message( self, msg_txt ): "set" self.messages.set( msg_txt ) def cb_factory(self, numberic_key ): """ Return a call back function for a specific keyboard numeric key (0-9) """ def cb( self, event, key=numberic_key ): bit_val = 1<<numberic_key-1 if int(event.type) == 2: self.bitfield |= bit_val self.message("Key %d Down" % key) else: self.bitfield &= (~bit_val & 0xFF) self.message("Key %d Up" % key) print hex(self.bitfield) self.display_bitfield() return cb ########################################################################## if __name__ == "__main__": root = Tk() root.title("PIO Test") theApp = App( root ) root.mainloop() ``` I finally got some sort of method factory working for the callback but I don't find it very satisfactory. So my question is, can you have a class method factory, that will produce class methods the way I tried (see commented out code and App class method cb\_factory())? NOTES: Yes, I know that this app only lets you hold down 4 keys at a time, but that is good enough for my purposes.
cb expects 'self' and 'event'. Maybe it only gets event from the bind?
In answer to your followup question. I'm not sure which part you don't understand but I'm guessing you don't quite have a handle on how event callbacks work? If so it's pretty easy. Tk runs in a loop looking for events (keypresses, mouseclicks, etc..). When you bind a callback/function to a event you're just telling it to call your function and pass an event object as it's argument. You can then query the event object for more details of what actually occurred. You are currently building seperate callback functions and binding each to 18 key events (down and release on keys 1-9). I think you can rewrite this to simply have cb as a method of your class because the event object will almost certainly contain the keycode as well. ``` class: def __init__(self): for x in xrange(8): self.parent.bind("<KeyPress-%d>" % x, self.keyaction) self.parent.bind("<KeyRelease-%d>" % x, self.keyaction) def keyaction(self, event): key = event.keycode # attribute may have another name, I haven't checked tk docs ... do stuff ... ``` Since we're now using **self**.keyaction as the callback it should get self as its first argument. It gets its keycode from the event object. Now neither value needs to be 'built' into the function when the function is created so the need to actually create different callbacks for each key is removed and the code easier to understand.
Factory for Callback methods - Python TKinter
[ "", "python", "methods", "factory", "" ]
In `AssemblyInfo` there are two assembly versions: 1. `AssemblyVersion`: Specify the version of the assembly being attributed. 2. `AssemblyFileVersion`: Instructs a compiler to use a specific version number for the Win32 file version resource. The Win32 file version is not required to be the same as the assembly's version number. I can get the `AssemblyVersion` with the following line of code: ``` Version version = Assembly.GetEntryAssembly().GetName().Version; ``` But how can I get the `AssemblyFileVersion`?
See my comment above asking for clarification on what you really want. Hopefully this is it: ``` System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly(); System.Diagnostics.FileVersionInfo fvi = System.Diagnostics.FileVersionInfo.GetVersionInfo(assembly.Location); string version = fvi.FileVersion; ```
There are [three versions](http://all-things-pure.blogspot.com/2009/09/assembly-version-file-version-product.html): **assembly**, **file**, and **product** (aka **Assembly Informational Version**). They are used by different features and take on different default values if you don't explicit specify them. ``` string assemblyVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString(); assemblyVersion = Assembly.LoadFile("your assembly file").GetName().Version.ToString(); string fileVersion = FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).FileVersion; string productVersion = FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).ProductVersion; ```
How can I get the assembly file version
[ "", "c#", ".net", "assemblies", "version", "" ]
The email field in user profiles in Drupal is as far as i understand not ment to be shown (for good and obvoius reasons). But I still need to know how to show user e-mail in Drupal 5.x profile (nodeprofile)?
Change the theme\_user\_profile hook (add the function to your template.php located at your current theme folder), like this: ``` function <your_theme_name>_user_profile($account, $fields) { // adding the email field to profile $email = array(); $email["value"] = check_plain($account->mail); $fields["email"][0] = $email; // end of adding the email field // the rest of the default profile hook taken from http://api.drupal.org/api/function/theme_user_profile/5 $output = '<div class="profile">'; $output .= theme('user_picture', $account); foreach ($fields as $category => $items) { if (strlen($category) > 0) { $output .= '<h2 class="title">'. check_plain($category) .'</h2>'; } $output .= '<dl>'; foreach ($items as $item) { if (isset($item['title'])) { $output .= '<dt class="'. $item['class'] .'">'. $item['title'] .'</dt>'; } $output .= '<dd class="'. $item['class'] .'">'. $item['value'] .'</dd>'; } $output .= '</dl>'; } $output .= '</div>'; return $output; } ``` **Update.** Sorry, didn't notice that you're using nodeprofile module. I've never used it, but am pretty sure the email can be shown the similar way
Add an email CCK field to your node profile CCK type. For more details, refer to the [Email Field](https://www.drupal.org/project/email) module. Here is an excerpt from its project page: > Features: > > * validation of emails > * turns addresses into mailto links > * encryption of email addresses > * contact form (see Display settings) > * provides Tokens (for D 7.x: use Entity tokens from the Entity API) > * exposes fields to Views > * can be used with Rules > * Panels Integration
How to show user e-mail in Drupal 5.x profile (nodeprofile)?
[ "", "php", "drupal", "drupal-5", "" ]
Or should I just stick with Python2.5 for a bit longer?
From [python.org](http://python.org/download/): > The current production versions are > Python 2.6.2 and Python 3.0.1. So, yes. Python 3.x contains some backwards incompatible changes, so [python.org](http://python.org/download/) also says: > start with Python 2.6 since more > existing third party software is > compatible with Python 2 than Python 3 > right now
Ubuntu has switched to 2.6 in it's latest release, and has not had any significant problems. So I would say "yes, it's stable".
Is Python2.6 stable enough for production use?
[ "", "python", "" ]
I've always done this back asswards in PHP or ASAP, so I figure it's time to actually learn the proper way to do it in SQL. I have the following 4 tables in a database: Category (Fields: CategoryNumber, Desc) (small table with 15 rows) Media (Fields: MediaID, Desc, CategoryNumber, etc) (huge table with 15,000 rows) Sales (Fields: Date, MediaID, EmployeeID etc) (huge table with 100,000 rows) Employees (Fields: EmployeeID, Name, etc) (small table with only 20 rows) Category only links to Media Media has links to both Category and Sales. Sales links to both the Media and Employee Employee only links to Sales What I would like to do is to write a query which tells me what categories a given employee has never sold any media in. I can write a simple query that looks for unmatched data between 2 tables, but I have no clue how to do it when I'm dealing with 4 tables. Thanks for your time and help!
``` SELECT c.CategoryNumber, c.Desc FROM Category c WHERE NOT EXISTS ( SELECT * FROM Employees e INNER JOIN Sales s on s.EmployeeID = e.EmployeeID INNER JOIN Media m on m.MediaID = s.MediaID WHERE e.Name = "Ryan" AND m.CategoryNumber = c.CategoryNumber ) ``` MS Access evidently needs a lot of parentheses (thanks, Ryan!): ``` select * from Category c where not exists ( select * from ( Employee e inner join Sales s on (s.EmployeeId = e.EmployeeId)) inner join Media m on (m.MediaID = s.MediaID) where (e.Name = 'Ryan' and m.CategoryNumber = c.CategoryNumber) ) ```
Here's my suggestion: ``` select * from Category c where not exists ( select * from Employee e inner join Sales s on s.EmployeeId = e.EmployeeId inner join Media m on m.MediaID = s.MediaID where e.Name = 'Ryan' and m.CategoryNumber = c.CategoryNumber ) ``` To query all employes with the categories in which they didn't sell anything: ``` select e.EmployeeName, c.CategoryNumber from Category c cross join Employee e where not exists ( select * from Sales s inner join Media m on m.MediaID = s.MediaID where c.categoryNumber = m.CategoryNumber and s.EmployeeId = e.EmployeeId ) ```
SQL: Have 4 Tables, Looking to find unmatched data
[ "", "sql", "ms-access", "" ]
I'm sorry about the naive question. I have the following: ``` public Array Values { get; set; } public List<object> CategoriesToList() { List<object> vals = new List<object>(); vals.AddRange(this.Values); return vals; } ``` But this won't work because I can't type the array. Is there any way to easily fix the code above or, in general, convert System.Collections.Array to System.Collections.Generic.List?
Make sure you're `using System.Linq;` and then change your line to: `vals.AddRange(this.Values.Cast<object>());` Edit: You could also iterate over the array and add each item individually. Edit Again: Yet another option to simply cast your array as `object[]` and either use the `ToList()` function or pass it into the `List<object>` constructor: `((object[])this.Values).ToList();` or `new List<object>((object[])this.Values)`
Can you just change your property declaration to this? : ``` public object[] Values { get; set; } ```
Array to List -- Cannot make AddRange(IEnumerable) work
[ "", "c#", "arrays", ".net-3.5", "list", "" ]
I have a `form` with two text boxes, one **select** drop down and one **radio button**. When the `enter` key is pressed, I want to call my JavaScript function, but when I press it, the `form` is submitted. How do I prevent the `form` from being submitted when the `enter` key is pressed?
``` if(characterCode == 13) { // returning false will prevent the event from bubbling up. return false; } else{ return true; } ``` Ok, so imagine you have the following textbox in a form: ``` <input id="scriptBox" type="text" onkeypress="return runScript(event)" /> ``` In order to run some "user defined" script from this text box when the enter key is pressed, and not have it submit the form, here is some *sample* code. Please note that this function doesn't do any error checking and most likely will only work in IE. To do this right you need a more robust solution, but you will get the general idea. ``` function runScript(e) { //See notes about 'which' and 'key' if (e.keyCode == 13) { var tb = document.getElementById("scriptBox"); eval(tb.value); return false; } } ``` returning the value of the function will alert the event handler not to bubble the event any further, and will prevent the keypress event from being handled further. ## NOTE: It's been pointed out that `keyCode` is [now deprecated](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keycode). The next best alternative `which` has [also been deprecated](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/which). Unfortunately the favored standard `key`, which is widely supported by modern browsers, has some [dodgy behavior in IE and Edge](https://caniuse.com/#feat=keyboardevent-key). Anything older than IE11 would still need a [polyfill](https://github.com/cvan/keyboardevent-key-polyfill). Furthermore, while the deprecated warning is quite ominous about `keyCode` and `which`, removing those would represent a massive breaking change to untold numbers of legacy websites. For that reason, **it is unlikely they are going anywhere anytime soon.**
Use both `event.which` and `event.keyCode`: ``` function (event) { if (event.which == 13 || event.keyCode == 13) { //code to execute here return false; } return true; }; ```
Prevent form submission on Enter key press
[ "", "javascript", "forms", "keypress", "dom-events", "enter", "" ]
I am trying to use 'py2app' to generate a standalone application from some Python scripts. The Python uses the 'lxml' package, and I've found that I have to specify this explicitly in the setup.py file that 'py2app' uses. However, the resulting application program still won't run on machines that haven't had 'lxml' installed. My Setup.py looks like this: ``` from setuptools import setup OPTIONS = {'argv_emulation': True, 'packages' : ['lxml']} setup(app=[MyApp.py], data_files=[], options={'py2app' : OPTIONS}, setup_requires=['py2app']) ``` Running the application produces the following output: ``` MyApp Error An unexpected error has occurred during execution of the main script ImportError: dlopen(/Users/ake/XXXX/XXXX/MyApp.app/Contents/Resources/lib/python2.5/lxml/etree.so, 2): Symbol not found: _xmlSchematronParse Referenced from: /Users/ake/XXXX/XXXX/MyApp.app/Contents/Resources/lib/python2.5/lxml/etree.so Expected in: dynamic lookup ``` The symbol '\_xmlSchematronParse' is from a library called 'libxml2' that 'lxml' depends on. The version that comes preinstalled with Mac OS X isn't up to date enough for 'lxml', so I had to install version 2.7.2 (in /usr/local). py2app, for some reason, is linking in the version in /Developer/SDKs/MacOSX10.3.9.sdk/usr/lib. When I run my application as a Python script though, the correct version is found. (I checked this just now by hiding the 2.7.2 version.) So my question now is, how can I tell py2app where to look for libraries?
Found it. py2app has a 'frameworks' option to let you specify frameworks, and also dylibs. My setup.py file now looks like this: ``` from setuptools import setup DATA_FILES = [] OPTIONS = {'argv_emulation': True, 'packages' : ['lxml'], 'frameworks' : ['/usr/local/libxml2-2.7.2/lib/libxml2.2.7.2.dylib'] } setup(app=MyApp.py, data_files=DATA_FILES, options={'py2app' : OPTIONS}, setup_requires=['py2app']) ``` and that's fixed it. Thanks for the suggestions that led me here.
I have no experience with the combination of lxml and py2app specifically, but I've had issues with py2app not picking up modules that were not explicitly imported. For example, I had to explicitly include modules that are imported via `__import__()`, like this: ``` OPTIONS['includes'] = [filename[:-3].replace('/', '.') for filename \ in glob.glob('path/to/*.py')] ``` Maybe it also helps in your case to insert an explicit `from lxml import etree` somewhere in your code?
Problem using py2app with the lxml package
[ "", "python", "lxml", "py2app", "" ]
Hey I'm trying to return a message when there are no results for the users current query! i know i need to tap into the keyup event, but it looks like the plugin is using it
You could try supplying a parse option (function to handle data parsing) and do what you need when no results are returned to parse. This example assumes you're getting back an array of JSON objects that contain FullName and Address attributes. ``` $('#search').autocomplete( { dataType: "json", parse: function(data) { var array = new Array(); if (!data || data.length == 0) { // handle no data case specially } else { for (var i = 0; i < data.length; ++i) { var datum = data[i]; array[array.length] = { data: datum, value: data.FullName + ' ' + data.Address, result: data.DisplayName }; } } return array; } }); ```
This question is really out of date, anyways I'm working with the new jQuery UI 1.8.16, autocomplete is now pretty different:<http://jqueryui.com/demos/autocomplete/#default> Anyways if you're trying to the do the same thing as the question asks, there is no more parse function, as far as I know there is no function that is called with the search results. The way I managed to pull this off is by overriding the autocomplete's filter function - Note: this will affect all your autocompletes ``` $.ui.autocomplete.filter = function(array, term) { var matcher = new RegExp( $.ui.autocomplete.escapeRegex(term), "i" ); var aryMatches = $.grep( array, function(value) { return matcher.test(value.label || value.value || value); }); if (aryMatches.length == 0){ aryMatches.push({ label: '<span class="info" style="font-style: italic;">no match found</span>', value: null }); } return aryMatches; }; ``` The function is slightly modified from the source, the grep call is the same, but if there are no results I add an object with a value of null, then I override the select calls to check for a null value. This gives you an effect where if you keep typing and no matches are found you get the 'no matches found' item in the dropdown, which is pretty cool. To override the select calls see [jQuery UI Autocomplete disable Select & Close events](https://stackoverflow.com/questions/6043506/jquery-ui-autocomplete-disable-select-close-events) ``` $(this).data('autocomplete').menu.options.selected = function(oEvent, ui){ if ($(ui.item).data('item.autocomplete').value != null){ //your code here - remember to call close on your autocomplete after } }; ``` Since I use this on all my autocompletes on a page, make sure you check if value is null first! Before you try to reference keys that aren't there.
Handling no results in jquery autocomplete
[ "", "javascript", "jquery", "jquery-ui", "autocomplete", "" ]
``` errorString="AxisFault\n faultCode: {http://schemas.xmlsoap.org/soap/envelope/}Server.generalException\n faultSubcode: \n faultString: My Error\n faultActor: \n faultNode: \n faultDetail: \n {}string: this is the fault detail" Pattern pattern = Pattern.compile(".*faultString(.*)", Pattern.DOTALL); Matcher matcher = pattern.matcher(errorString); if (matcher.matches()) { String match = matcher.group(1); return match; } ``` I want to get "My Error", but it returns to the end of the whole string instead of matching to the \n at the end of the faultString line. I've tried many techniques to get it to stop at the end of the line, without success. thanks
You shouldn't be passing [`Pattern.DOTALL`](http://java.sun.com/javase/6/docs/api/java/util/regex/Pattern.html#DOTALL); that causes newlines to be matched by `.*`, which is exactly what you *don't* want here. A better regex would be: ``` Pattern pattern = Pattern.compile("faultString: (.*)"); ``` and then, instead of `matcher.matches()`, use [`find()`](http://java.sun.com/javase/6/docs/api/java/util/regex/Matcher.html#find()) to see if it appears anywhere in the string. Note also that I've modified the regex to only group the "My Error" part, instead of ": My Error" like your original one would have. Just to be clear, here is the code I tested: ``` Pattern pattern = Pattern.compile("faultString: (.*)"); Matcher matcher = pattern.matcher(errorString); if (matcher.find()) { System.out.println(matcher.group(1)); } ``` where `errorString` is the same as yours. The output is: ``` My Error ```
I'd probably clean up Chris's regex to the following: `".*faultString:\\s*([^\\n]*).*"`
How do I extract this string using a regular expression in Java?
[ "", "java", "regex", "" ]
So say I have a collection of Bloops ``` Class Bloop Public FirstName Public LastName Public Address Public Number Public OtherStuff End Class ``` Then I have a class of Razzies ``` Class Razzie Public FirstName Public LastName End Class ``` Is it possible using Linq to select the FirstName and LastName out of all the Bloops in the collection of Bloops and return a collection of Razzies? Or am i limited to a For-Loop to do my work? To clear up any confusion, either VB or C# will do. Also this will probably lead to me asking the question of (What about using a "Where" clause).
This should do the job: ``` Dim results = From item In bloops _ Select New Razzie() With _ { _ .FirstName = item.FirstName, _ .LastName = item.LastName _ } ``` And if you want to convert the result from `IEnumerable<Bloop>` (what the LINQ query returns) to an array or `List<Bloop>`, just append a call to the `ToArray()` or `ToList()` extension methods respectively. Edit: Corrected the code so that it now has valid VB.NET 9 syntax.
``` List<Bloop> myBloops = new List<Bloops>; //populate myRazzies List<Razzie> myRazzies = myBloops.Select(x => new Razzie() { FirstName = x.FirstName, LastName = x.LastName}).ToList(); ```
Linq Select Certain Properties Into Another Object?
[ "", "c#", ".net", "vb.net", "linq", ".net-3.5", "" ]
I have a dal layer with lots of methods, all of them call stored procedures, some return lists (so with a use of `SqlDataReader`), others only a specific value. I have a helper method that creates the `SqlCommand`: ``` protected SqlCommand CreateSprocCommand(string name, bool includeReturn, SqlDbType returnType) { SqlConnection con = new SqlConnection(this.ConnectionString); SqlCommand com = new SqlCommand(name, con); com.CommandType = System.Data.CommandType.StoredProcedure; if (includeReturn) com.Parameters.Add("ReturnValue", returnType).Direction = ParameterDirection.ReturnValue; return com; } ``` Now my average (overly simplified) method body look like: ``` SqlCommand cmd = CreateSprocCommand("SomeSprocName"); //an override of the above mentioned method try { cmd.Connection.Open(); using (var reader = cmd.ExecuteReader()) { //some code looping over the recors } //some more code to return whatever needs to be returned } finally { cmd.Connection.Dispose(); } ``` Is there a way to refactor this, so that I won't lose my helper function (it does quite a bit of otherwise repetitive work), and yet be able to use `using`?
One way is to change it from *returning* a command to *taking* a delegate which uses the command: ``` protected void ExecuteSproc(string name, SqlDbType? returnType, Action<SqlCommand> action) { using (SqlConnection con = new SqlConnection(this.ConnectionString)) using (SqlCommand com = new SqlCommand(name, con)) { con.Open(); com.CommandType = System.Data.CommandType.StoredProcedure; if (returnType != null) { com.Parameters.Add("ReturnValue", returnType.Value).Direction = ParameterDirection.ReturnValue; } action(com); } } ``` (Note that I've also removed the `includeReturn` parameter and made `returnType` nullable instead. Just pass `null` for "no return value".) You'd use this with a lambda expression (or anonymous method): ``` ExecuteSproc("SomeName", SqlDbType.DateTime, cmd => { // Do what you want with the command (cmd) here }); ``` That way the disposal is in the same place as the creation, and the caller just doesn't need to worry about it. I'm becoming quite a fan of this pattern - it's a lot cleaner now that we've got lambda expressions.
You can do this: ``` protected static SqlCommand CreateSprocCommand(SqlConnection con, string name, bool includeReturn, SqlDbType returnType) { SqlCommand com = new SqlCommand(name, con); com.CommandType = System.Data.CommandType.StoredProcedure; if (includeReturn) com.Parameters.Add("ReturnValue", returnType).Direction = ParameterDirection.ReturnValue; return com; } ``` and call it like this: ``` using (SqlConnection con = new SqlConnection(this.ConnectionString)) using (SqlCommand cmd = CreateSprocCommand(con, "SomeSprocName", true, SqlDbType.Int) { cmd.Connection.Open(); using (var reader = cmd.ExecuteReader()) { //some code looping over the recors } //some more code to return whatever needs to be returned } ```
Refactor code into using statement
[ "", "c#", "using", "sqlconnection", "sqlcommand", "" ]
I am curious about COM+, DCOM. I know that MSFT does not encourage you to use this tools natively (meaning with C/C++, in fact there is not a lot of documentation available) but I want to learn to use these technologies, like embedding Internet Explorer into a C program. I thought that maybe I could find people that worked with this or that knows about this technology. Where to start? Any ideas? Any example (like Hello World DCOM)?
If you are serious about learning COM, Don Box's "Essential COM" is definitely an absolute "must read". COM can be confusing and in my humble opinion Don Box is one of the few people who actually "got it". The example code in "Essential COM" is in C++. You won't find many books that support COM in C. You can write COM in C, but it will be very, *very* painful. COM is optimized for C++ development. This book is not perfect nor "complete". There are some (granted, a bit esoteric) areas that the book skims over. For example, the book has like 1 1/2 pages on "monikers" (I have never seen a treatment of monikers that satisfies me). I consider this book to be THE fundamental book. Second, in real life you are likely to want to use a supporting library such as ATL, rather than writing all the COM glue directly. There are too many ways to make subtle mistakes in COM even in the basic set up. ATL will give you good patterns and implement the boring code for you. In learning, you are better off using plain C++. There are many books about ATL and several are quite good. I understand that ATL has changed quite a bit since the old days of VC++6, but I don't have first hand knowledge there: sadly, most of the COM code I work with is forever locked to the flavor of C++ in VC6. Make sure whatever book you get is written for the version of Visual Studio and/or ATL you are planing on using. Some background on COM books: Note that there are a lot of books out there that misunderstand COM, or focus on the wrong things. The older books are worse in this respect. Some of the first few books treated COM as little more than a plumbing detail needed to make OLE work ("Object Linking and Embedding", that's what allows you to drag-and-drop a spreadsheet range into a Word document). Because of that, a lot of the material out there is very confusing. It took a while before people realized that OLE wasn't that important and that COM really was. By the time Don Box published "Essential COM", the cracks on the foundation of COM had started to become evident. There isn't anything terribly flawed with COM, but the needs of the development community had evolved and outgrown what COM could do without serious revamping. .NET was born out of that effort to address the limitations in COM, especially in the area of "type information". Just a few years after "Effective COM" was published, the attention of the community shifted away to .NET. Because of that, good COM training material is now and will likely remain forever limited. So, COM is not broken, and it works great for the things it's used for (that's why Explorer still uses it). It's just not the best solution anymore for many of the problems that need solving today. In summary: I recommend "Essential COM" for the basics. Then, any of many good ATL books available (no strong preferences there), and then use other resources like MSDN or -- of course -- Stack Overflow, to cover areas that are of particular interest to you. If you'd rather avoid relying on resources of the dead-tree variety, go ahead and learn ATL from the web. But some books are worth reading the old fashioned way -- and "Essential COM" is one of them. Good luck.
[COM](http://www.microsoft.com/com/default.mspx), [COM+](http://msdn.microsoft.com/en-us/library/ms685978(VS.85).aspx) and [DCOM](http://msdn.microsoft.com/en-us/library/ms809340.aspx) are three completely different things. At this point, there is very little reason to learn COM and almost no reason to learn DCOM. The only reason I can think of is if you have to maintain or integrate legacy components. COM+ is still used because it allows for out of process hosting of components and nice things like distributed transaction management. The best way to start writing up some COM is using [ATL](http://msdn.microsoft.com/en-us/library/t9adwcde(VS.80).aspx). In .NET COM+ is called [Enterprise Services](http://msdn.microsoft.com/en-us/library/aa286569.aspx). The best book I know on COM is Don Box's [Essential COM](https://rads.stackoverflow.com/amzn/click/com/0201634465) and Tim Ewald's [COM+ book](https://rads.stackoverflow.com/amzn/click/com/0201615940) is excellent too.
COM, COM+, DCOM, where to start?
[ "", "c++", "c", "com", "com+", "dcom", "" ]
What's the best way to truncate a datetime value (as to remove hours minutes and seconds) in SQL Server? For example: ``` declare @SomeDate datetime = '2009-05-28 16:30:22' select trunc_date(@SomeDate) ----------------------- 2009-05-28 00:00:00.000 ```
This continues to frequently gather additional votes, even several years later, and so I need to update it for modern versions of Sql Server. For Sql Server 2008 and later, it's simple: ``` cast(getdate() as Date) ``` Note that the last three paragraphs near the bottom still apply, and you often need to take a step back and find a way to avoid the cast in the first place. But there are other ways to accomplish this, too. Here are the most common. ### The correct way (new since Sql Server 2008) ``` cast(getdate() as Date) ``` ### The correct way (old) ``` dateadd(dd, datediff(dd, 0, getdate()), 0) ``` This is older now, but it's still worth knowing because it can also easily adapt for other time points, like the first moment of the month, minute, hour, or year. This correct way uses documented functions that are part of the ANSI standard and are guaranteed to work, but it can be somewhat slower. It works by finding how many days there are from day 0 to the current day, and adding that many days back to day 0. It will work no matter how your `datetime` is stored and no matter what your locale is. ### The fast way ``` cast(floor(cast(getdate() as float)) as datetime) ``` This works because `datetime` columns are stored as 8-byte binary values. Cast them to `float`, `floor` them to remove the fraction, and the time portion of the values are gone when you cast them back to `datetime`. It's all just bit shifting with no complicated logic and it's *very* fast. Be aware this relies on an implementation detail that Microsoft is free to change at any time, even in an automatic service update. It's also not very portable. In practice, it's very unlikely this implementation will change any time soon, but it's still important to be aware of the danger if you choose to use it. And now that we have the option to cast as a date, it's rarely necessary. ### The wrong way ``` cast(convert(char(11), getdate(), 113) as datetime) ``` The wrong way works by converting to a string, truncating the string, and converting back to a datetime. It's *wrong,* for two reasons: 1. It might not work across all locales and 2. It's about the slowest possible way to do this... and not just a little; it's like an order of magnitude or two slower than the other options. --- **Update** This has been getting some votes lately, and so I want to add to it that since I posted this I've seen some pretty solid evidence that Sql Server will optimize away the performance difference between "correct" way and the "fast" way, meaning you should now favor the former. In either case, you want to **write your queries to avoid the need to do this in the first place.** It's very rare that you should do this work on the database. In most places, the database is already your bottleneck. It's generally the server that's the most expensive to add hardware to for performance improvements and the hardest one to get those additions right (you have to balance disks with memory, for example). It's also the hardest to scale outward, both technically and from a business standpoint; it's much easier technically to add a web or application server than a database server and even if that were false you don't pay $20,000+ per server license for IIS or Apache. The point I'm trying to make is that whenever possible you should do this work at the application level. The *only* time you should ever find yourself truncating a `datetime` on Sql Server is when you need to group by the day, and even then you should probably have an extra column set up as a computed column, maintained at insert/update time, or maintained in application logic. Get this index-breaking, CPU-heavy work off your database.
For SQL Server 2008 only ``` CAST(@SomeDateTime AS Date) ``` Then cast it back to datetime if you want ``` CAST(CAST(@SomeDateTime AS Date) As datetime) ```
How can I truncate a datetime in SQL Server?
[ "", "sql", "sql-server", "t-sql", "datetime", "truncate", "" ]
I need to write a python script that makes multiple HTTP requests to the same site. Unless I'm wrong (and I may very well be) urllib reauthenticates for every request. For reasons I won't go into I need to be able to authenticate once and then use that session for the rest of my requests. I'm using python 2.3.4
If you want to keep the authentication you need to reuse the cookie. I'm not sure if urllib2 is available in python 2.3.4 but here is an example on how to do it: ``` req1 = urllib2.Request(url1) response = urllib2.urlopen(req1) cookie = response.headers.get('Set-Cookie') # Use the cookie is subsequent requests req2 = urllib2.Request(url2) req2.add_header('cookie', cookie) response = urllib2.urlopen(req2) ```
Use [Requests](https://github.com/kennethreitz/requests) library. From <http://docs.python-requests.org/en/latest/user/advanced/#session-objects> : > The Session object allows you to persist certain parameters across > requests. It also persists cookies across all requests made from the > Session instance. > > ``` > s = requests.session() > > s.get('http://httpbin.org/cookies/set/sessioncookie/123456789') > r = s.get("http://httpbin.org/cookies") > > print r.text > # '{"cookies": {"sessioncookie": "123456789"}}' > ```
Keeping a session in python while making HTTP requests
[ "", "python", "http", "authentication", "" ]
What is JavaScript garbage collection? What's important for a web programmer to understand about JavaScript garbage collection, in order to write better code?
Eric Lippert wrote a [**detailed blog post**](https://blogs.msdn.microsoft.com/ericlippert/2003/09/17/how-do-the-script-garbage-collectors-work/) about this subject a while back (additionally comparing it to *VBScript*). More accurately, he wrote about [*JScript*](https://en.wikipedia.org/wiki/Jscript), which is Microsoft's own implementation of ECMAScript, although very similar to JavaScript. I would imagine that you can assume the vast majority of behaviour would be the same for the JavaScript engine of Internet Explorer. Of course, the implementation will vary from browser to browser, though I suspect you could take a number of the common principles and apply them to other browsers. Quoted from that page: > JScript uses a nongenerational > mark-and-sweep garbage collector. It > works like this: > > * Every variable which is "in scope" > is called a "scavenger". A scavenger > may refer to a number, an object, a > string, whatever. We maintain a list > of scavengers -- variables are moved > on to the scav list when they come > into scope and off the scav list when > they go out of scope. > * Every now and then the garbage > collector runs. First it puts a > "mark" on every object, variable, > string, etc – all the memory tracked > by the GC. (JScript uses the VARIANT > data structure internally and there > are plenty of extra unused bits in > that structure, so we just set one of > them.) > * Second, it clears the mark on the > scavengers and the transitive closure > of scavenger references. So if a > scavenger object references a > nonscavenger object then we clear the > bits on the nonscavenger, and on > everything that it refers to. (I am > using the word "closure" in a > different sense than in my earlier > post.) > * At this point we know that all the > memory still marked is allocated > memory which cannot be reached by any > path from any in-scope variable. All > of those objects are instructed to > tear themselves down, which destroys > any circular references. The main purpose of garbage collection is to allow the programmer *not* to worry about memory management of the objects they create and use, though of course there's no avoiding it sometimes - it is always beneficial to have at least a rough idea of how garbage collection works. **Historical note:** an earlier revision of the answer had an incorrect reference to the `delete` operator. In JavaScript [the `delete` operator removes a property from an object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete), and is wholly different to `delete` in C/C++.
Beware of circular references when DOM objects are involved: [Memory leak patterns in JavaScript](http://www.ibm.com/developerworks/web/library/wa-memleak/) Keep in mind that memory can only be reclaimed when there are no active references to the object. This is a common pitfall with closures and event handlers, as some JS engines will not check which variables actually are referenced in inner functions and just keep all local variables of the enclosing functions. Here's a simple example: ``` function init() { var bigString = new Array(1000).join('xxx'); var foo = document.getElementById('foo'); foo.onclick = function() { // this might create a closure over `bigString`, // even if `bigString` isn't referenced anywhere! }; } ``` A naive JS implementation can't collect `bigString` as long as the event handler is around. There are several ways to solve this problem, eg setting `bigString = null` at the end of `init()` (`delete` won't work for local variables and function arguments: `delete` removes properties from objects, and the variable object is inaccessible - ES5 in strict mode will even throw a `ReferenceError` if you try to delete a local variable!). I recommend to avoid unnecessary closures as much as possible if you care for memory consumption.
What is JavaScript garbage collection?
[ "", "javascript", "garbage-collection", "" ]
I am working hard to standardize one single way of Layered/n-Tiered design of my all applications. I am trying to make all my applications 5 tiered. Code: --- ## | UI | ## | ## | Business Object | ## | ## | OR-Mapper | ## | ## | Data Access | ## | ## | RDBMS | Suppose I am developing an application with a log-in/log-out capability for users. I am creating 4 projects under a VS2005 solution. Each project is for one of the upper 4 layers. I am designing my Business Object class as follows:- ``` public class User { private string _username; public string Username { get { return _username; } set { _username = value; } } private string _password; public string Password { get { return _password; } set { _password = value; } } public User() { } public bool LogIn(String username, String password) { bool success = false; if (UserMapper.UsernameExists(username)) { success = UserMapper.UsernamePasswordExists(username, password); } else { //do nothing } return success; } public bool LogOut() { bool success; //----some logic return success; } public static User GetUserByUsername(string username) { return UserMapper.GetUserByUsername(username); } public static UserCollection GetByUserTypeCode(string code) { return UserMapper.GetByUserTypeCode(code); } } ``` This is how I am giving my objects some functionality that matches the real-world scenario. Here GetByUsername() and GetByUserTypeCode() are getter functions. These functions does't match a real-world logic. Coz, in real-world, a User never "Gets by Username" or "Gets by UserTypeCode". So these functions are kept static. My class for O-R Mapper layer is as follows:- ``` public static class UserMapper { public static bool UsernameExists(String username) { bool exists = false; if (UserDA.CountUsername(username) == 1) { exists = true; } return exists; } public static bool UsernamePasswordExists(String username, String password) { bool exists = false; if (UserDA.CountUsernameAndPassword(username, password) == 1) { exists = true; } return exists; } } ``` And finally, the DA class is as follows:- ``` public static class UserDA { public static int CountUsername(string username) { int count = -1; SqlConnection conn = DBConn.Connection; if (conn != null) { try { SqlCommand command = new SqlCommand(); command.Connection = conn; command.CommandText = @"SELECT COUNT(*) FROM User WHERE User_name = @User_name"; command.Parameters.AddWithValue("@User_name", username); command.Connection.Open(); object idRaw = command.ExecuteScalar(); command.Connection.Close(); if (idRaw == DBNull.Value) { count = 0; } else { count = (int)idRaw; } } catch (Exception ex) { count = -1; } } return count; } public static int CountUsernameAndPassword(string username, string password) { int count = 0; SqlConnection conn = DBConn.Connection; if (conn != null) { try { SqlCommand command = new SqlCommand(); command.Connection = conn; command.CommandText = @"SELECT COUNT(*) FROM User WHERE User_name = @User_name AND Pass_word = @Pass_word"; command.Parameters.AddWithValue("@User_name", username); command.Parameters.AddWithValue("@Pass_word", password); command.Connection.Open(); object idRaw = command.ExecuteScalar(); command.Connection.Close(); if (idRaw == DBNull.Value) { count = 0; } else { count = (int)idRaw; } } catch (Exception ex) { count = 0; } } return count; } public static int InsertUser(params object[] objects) { int count = -1; SqlConnection conn = DBConn.Connection; if (conn != null) { try { SqlCommand command = new SqlCommand(); command.Connection = conn; command.CommandText = @"INSERT INTO User(ID, User_name, Pass_word, RegDate, UserTypeCode, ActualCodeOrRoll) VALUES(@ID, @User_name, @Pass_word, @RegDate, @UserTypeCode, @ActualCodeOrRoll)"; command.Parameters.AddWithValue("@ID", objects[0]); command.Parameters.AddWithValue("@User_name", objects[1]); command.Parameters.AddWithValue("@Pass_word", objects[2]); command.Parameters.AddWithValue("@RegDate", objects[3]); command.Parameters.AddWithValue("@UserTypeCode", objects[4]); command.Parameters.AddWithValue("@ActualCodeOrRoll", objects[5]); command.Connection.Open(); count = command.ExecuteNonQuery(); command.Connection.Close(); } catch (Exception ex) { count = -1; } } return count; } public static SqlDataReader GetUserByUsername(string username) { SqlDataReader dataReader = null; SqlConnection conn = DBConn.Connection; if (conn != null) { try { SqlCommand command = new SqlCommand(); command.Connection = conn; command.CommandText = @"SELECT * FROM User WHERE User_name = @User_name"; command.Parameters.AddWithValue("@User_name", username); command.Connection.Open(); dataReader = command.ExecuteReader(CommandBehavior.CloseConnection); } catch (Exception ex) { dataReader.Close(); dataReader.Dispose(); } } return dataReader; } public static SqlDataReader GetUserByUserTypeCode(string userTypeCode) { SqlDataReader dataReader = null; SqlConnection conn = DBConn.Connection; if (conn != null) { try { SqlCommand command = new SqlCommand(); command.Connection = conn; command.CommandText = @"SELECT * FROM User WHERE UserTypeCode = @UserTypeCode"; command.Parameters.AddWithValue("@UserTypeCode", userTypeCode); command.Connection.Open(); dataReader = command.ExecuteReader(CommandBehavior.CloseConnection); } catch (Exception ex) { dataReader.Close(); dataReader.Dispose(); } } return dataReader; } } ``` If anyone closely examine the these classes he can understand that, O-R Mapper layer needs the reference of BusinessObject-layer. BusinessObject- layer also needs a reference of O-R Mapper-layer. This should create a circular dependency. How can I avoid this problem? Someone suggested using plain Data Transfer Objects (DTO). But, as far as I know, according to OOP, attributes and functionality of a real-world object should be grouped together as a class. If I use DTO then how can I encapsulate functionality into a class? Moreover I am creating another class without any attribute (BO). To me that is breach of OOP in both ways. If I do so, then what is OOP for in this world? The same answer can be applied for "UserManager" classes. I found a [blog](http://imar.spaanjaars.com/QuickDocId.aspx?quickdoc=476). It discusses about implementing interfaces. Define a separate interface, implement it in your data class in the BusinessObject and program against your interface in the BusinessObject and in the OR-Mapper layer. But I could not do this. Can anyone show me that with a practical example?
I think there are a few things you can do that together could help with your design. I also think that you might want to read up on [Dependency Injection](http://en.wikipedia.org/wiki/Dependency_injection) as perhaps providing a better design pattern for what you want to do. Assuming you just want to make what you have work though: * First, remove the `static` methods from your `User` class, since they 'create' users, and therefore are best just left on the `UserMapper`. * After that, there will still be a number of methods potentially that use `UserMapper` functionality from the `User` class. Create an interface `IUserLookup` (or something) that supports the `UserNameExists` and `UserNamePasswordExists` methods; put this interface in the same project as the `User` class. * Implement the `IUserLookup` on the `UserMapper` class, and then 'inject' it into the `User` class instances it creates with the static methods through a constructor, so basically, as the `UserMapper` creates `User` objects, it gives them a reference to the `IUserLookup` interface that it implements itself. In this way, `User` only uses methods on `IUserLookup`, which is in the same solution, so no reference needed. And `UserMapper` references this solution, so it can create `User` objects and implement the `IUserLookup` interface.
If the OR Mapper is actually doing OR, then it probably *doesn't* need a reference to the BL - it just needs to know the `Type`(s) that is (are) involved. But that is a side issue... The main answer to this type of issue is "Inversion of Control" / "Dependency Injection", presumably snipping everything under the BL - so the BL depends only on an interface (defined in a base assembly), but doesn't know about the concrete OR/DA/RDBMS (they are supplied by the IoC/DI). This is a big topic, so I'm being intentionally vague. Personally I like StructureMap, but there are *lots* of IoC/DI tools available. Note that *technically* it *is* possible to create circular assembly references; it is a **really** bad idea, though - and the tools will (intentionally) fight you at every step.
Circular reference between Assemblies in C# and Visual Studio 2005
[ "", "c#", "visual-studio-2005", "n-tier-architecture", "" ]
How do I retrieve the starting time of a process using c# code? I'd also like to know how to do it with the functionality built into Widows, if possible.
``` public DateTime GetProcessStartTime(string processName) { Process[] p = Process.GetProcessesByName(processName); if (p.Length <= 0) throw new Exception("Process not found!"); return p[0].StartTime; } ``` If you know the ID of the process, you can use Process.GetProcessById(int processId). Additionaly if the process is on a different machine on the network, for both GetProcessesByName() and GetProcessById() you can specify the machine name as the second paramter. To get the process name, make sure the app is running. Then go to task manager on the Applications tab, right click on your app and select Go to process. In the processes tab you'll see your process name highlighted. Use the name before .exe in the c# code. For e.g. a windows forms app will be listed as "myform.vshost.exe". In the code you should say ``` Process.GetProcessesByName("myform.vshost"); ```
Process has a property "StartTime": <http://msdn.microsoft.com/en-us/library/system.diagnostics.process.starttime.aspx> Do you want the start time of the "current" process? Process.GetCurrentProcess will give you that: <http://msdn.microsoft.com/en-us/library/system.diagnostics.process.getcurrentprocess.aspx>
Starting time of a process
[ "", "c#", ".net", "" ]
Can anyone tell me how to get the filename without the extension? Example: ``` fileNameWithExt = "test.xml"; fileNameWithOutExt = "test"; ```
If you, like me, would rather use some library code where they probably have thought of all special cases, such as what happens if you pass in **null** or dots in the path but not in the filename, you can use the following: ``` import org.apache.commons.io.FilenameUtils; String fileNameWithOutExt = FilenameUtils.removeExtension(fileNameWithExt); ```
The easiest way is to use a regular expression. ``` fileNameWithOutExt = "test.xml".replaceFirst("[.][^.]+$", ""); ``` The above expression will remove the last dot followed by one or more characters. Here's a basic unit test. ``` public void testRegex() { assertEquals("test", "test.xml".replaceFirst("[.][^.]+$", "")); assertEquals("test.2", "test.2.xml".replaceFirst("[.][^.]+$", "")); } ```
How to get the filename without the extension in Java?
[ "", "java", "file", "" ]
I'm trying to debug an extJS based JavaScript form in Firefox 3.0.8, with Firebug, but none of my debugging statements are working. `console.log` produces the error `console is not defined` in the console. The `debugger` statement just doesn't work.
It might be that you have another Firefox extension installed which messes up for Firebug's console. I installed "HttpWatch Basic" for instance and it broke console.log() .. Disabled HttpWatch and everything was fine again.
Are you using Firefox 2.x ? Call loadFirebugConsole() to load the logger explicitly before you try to log to it.
Debugging not working in Firefox - Firebug
[ "", "javascript", "firefox", "extjs", "firebug", "" ]
I don't understand this error in C# > error CS0236: A field initializer cannot reference the non-static field, method, or property 'Prv.DB.getUserName(long)' For the following code ``` public class MyDictionary<K, V> { public delegate V NonExistentKey(K k); NonExistentKey nonExistentKey; public MyDictionary(NonExistentKey nonExistentKey_) { } } class DB { SQLiteConnection connection; SQLiteCommand command; MyDictionary<long, string> usernameDict = new MyDictionary<long, string>(getUserName); string getUserName(long userId) { } } ```
Any object initializer used outside a constructor has to refer to static members, as the instance hasn't been constructed until the constructor is run, and direct variable initialization conceptually happens before any constructor is run. getUserName is an instance method, but the containing instance isn't available. To fix it, try putting the usernameDict initializer inside a constructor.
The links below may shed some light on why doing what you are trying to do may not be such a good thing, in particular the second link: [Why Do Initializers Run In The Opposite Order As Constructors? Part One](https://learn.microsoft.com/en-us/archive/blogs/ericlippert/why-do-initializers-run-in-the-opposite-order-as-constructors-part-one) [Why Do Initializers Run In The Opposite Order As Constructors? Part Two](https://learn.microsoft.com/en-us/archive/blogs/ericlippert/why-do-initializers-run-in-the-opposite-order-as-constructors-part-two)
What does "a field initializer cannot reference non static fields" mean in C#?
[ "", "c#", "delegates", "" ]
I have a set of nightly reports. Sometimes I get the exception: > The process cannot access the file because it is being used by another process How do I tell what process is holding on to the file? I am thinking that it is McAfee but I need to prove it.
The problem was the MailMessage in .NET was holding on to the file attachments. I had to do a dispose on the attachment and then it worked.
Use a tool like [Process Explorer](http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx) or [Process Monitor](http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx).
The process cannot access the file because it is being used by another process
[ "", "c#", "" ]
I need help on regex or [`preg_match`](http://php.net/preg_match) because I am not that experienced yet with regards to those so here is my problem. I need to get the value "get me" but I think my function has an error. The number of html tags are dynamic. It can contain many nested html tag like a bold tag. Also, the "get me" value is dynamic. ``` <?php function getTextBetweenTags($string, $tagname) { $pattern = "/<$tagname>(.*?)<\/$tagname>/"; preg_match($pattern, $string, $matches); return $matches[1]; } $str = '<textformat leading="2"><p align="left"><font size="10">get me</font></p></textformat>'; $txt = getTextBetweenTags($str, "font"); echo $txt; ?> ```
``` <?php function getTextBetweenTags($string, $tagname) { $pattern = "/<$tagname ?.*>(.*)<\/$tagname>/"; preg_match($pattern, $string, $matches); return $matches[1]; } $str = '<textformat leading="2"><p align="left"><font size="10">get me</font></p></textformat>'; $txt = getTextBetweenTags($str, "font"); echo $txt; ?> ``` That should do the trick
Try this ``` $str = '<option value="123">abc</option> <option value="123">aabbcc</option>'; preg_match_all("#<option.*?>([^<]+)</option>#", $str, $foo); print_r($foo[1]); ```
PHP/regex: How to get the string value of HTML tag?
[ "", "php", "html", "regex", "" ]
> **Possible Duplicate:** > [Post your extension goodies for C# .Net (codeplex.com/extensionoverflow)](https://stackoverflow.com/questions/271398/post-your-extension-goodies-for-c-net-codeplex-com-extensionoverflow) I'm fond of C# 3.0. One of my favorite parts is extension methods. I like to think of extension methods as utility functions that can apply to a broad base of classes. I am being warned that this question is subjective and likely to be closed, but I think it's a good question, because we all have "boilerplate" code to do something relatively static like "escape string for XML" - but I have yet to find a place to collect these. I'm especially interested in common functions that perform logging/debugging/profiling, string manipulation, and database access. Is there some library of these types of extension methods out there somewhere? Edit: moved my code examples to an answer. (Thanks Joel for cleaning up the code!)
You might like [MiscUtil](http://www.yoda.arachsys.com/csharp/miscutil/). Also, a lot of people like this one: ``` public static bool IsNullOrEmpty(this string s) { return s == null || s.Length == 0; } ``` but since 9 times out of 10 or more I'm checking that it's *not* null or empty, I personally use this: ``` public static bool HasValue(this string s) { return s != null && s.Length > 0; } ``` Finally, one I picked up just recently: ``` public static bool IsDefault<T>(this T val) { return EqualityComparer<T>.Default.Equals(val, default(T)); } ``` Works to check both value types like DateTime, bool, or integer for their default values, or reference types like string for null. It even works on object, which is kind of eerie.
Here's a couple of mine: ``` // returns the number of milliseconds since Jan 1, 1970 (useful for converting C# dates to JS dates) public static double UnixTicks(this DateTime dt) { DateTime d1 = new DateTime(1970, 1, 1); DateTime d2 = dt.ToUniversalTime(); TimeSpan ts = new TimeSpan(d2.Ticks - d1.Ticks); return ts.TotalMilliseconds; } ``` and a ToDelimitedString function: ``` // apply this extension to any generic IEnumerable object. public static string ToDelimitedString<T>(this IEnumerable<T> source, string delimiter, Func<T, string> action) { if (source == null) { throw new ArgumentException("Source can not be null."); } if (delimiter == null) { throw new ArgumentException("Delimiter can not be null."); } string strAction = string.Empty; string delim = string.Empty; var sb = new StringBuilder(); foreach (var item in source) { strAction = action.Invoke(item); sb.Append(delim); sb.Append(strAction); delim = delimiter; } return sb.ToString(); } ```
Is there an existing library of extension methods for C#? or share your own
[ "", "c#", "extension-methods", "boilerplate", "" ]
I am new to C# and .Net and am coming from a Java background. I am trying to get my head around the .NET way of doing web applications and am not having much luck. I want to build an application to handle requests urls and write responses that return images. Having only used Java servlets in the web application field I am after some good resources and/or explanations on handling the request side of the application. How are requests handled? and with what Objects? What is the cycle? how do pages function around this? These are basic broad questions so if anyone knows of resources that covers them all thoroughly please let me know. What I have found so far has bits of information not the overall picture.
The overall page cycle is complex - but for serving images, you may want to look primarily at the `IHttpHandler` interface - or (more simply) create a "generic handler" (.ashx file). The `IHttpHandler` is the simplest "request/response" setup, without the burden of .aspx pages; you simply read from the context.Request, and write to the context.Response.
FOr serving up just image have a look HttpHandlers. As for Page life cycles: I love this image: [![EggHeadCafe](https://i.stack.imgur.com/JFBGj.jpg)](https://i.stack.imgur.com/JFBGj.jpg) (source: [eggheadcafe.com](http://www.eggheadcafe.com/articles/o_aspNet_Page_LifeCycle.jpg))
ASP.NET request lifecycle confusion
[ "", "c#", "asp.net", "request", "page-lifecycle", "" ]
One of the libraries we are using for our product uses a singleton for access to it. I'm pretty sure it's implemented as a static instance (it isn't open source). This works well for a single document application, but our app may have more than one document loaded. I'm assuming access to the instance is written something like this: ``` Instance* getInstance() { static Instance* inst = new Instance(); return inst; } ``` In situations like this, is there some way to robustly create more than one instance? The only thing I can think of is to have more than process and use some type of IPC to tie it all together. I can't think of anything less hacky. I have asked the vendor to implement some type of session token so I can have multiple concurrent instances, but they are big and we are small. Cory **Edit:** * the machine is a Windows machine * the global static is basically a big factory. I want a session token of some type so I can easily say "release all the resources from this session" (there's no way to re-initialize the global statics that I know of) Rather than try some dodgy shenanigans to get what I want, I'm going to wrap the whole thing with my own class and add a session key to every getter. Internally I'll keep track of what has been allocated add my own release method to return resources. This is suboptimal for lots of reasons, but I can't think of a better idea. Thanks to everybody for the great feedback.
The only thing that I can think of is to sub-class it if you are lucky enough to have the singleton class defined like: ``` class Document { public: static Document* getInstance() { static Document inst; return &inst; } virtual ~Document(); protected: Document(); private: struct Impl; Impl *pImpl; }; ``` If you can subclass it and the subclass will have access to the constructor, then you can create an *instanceable* subclass like: ``` class MyDocument: public Document { public: MyDocument(): Document() { } }; ``` This might not be completely safe since the implementer may have made some nasty assumptions. But it is an idea or some approach that might have some chance of working. With any luck the vendor might be amenable to this option if you mention it... good luck.
Even if you were able to solve this particular issue while having everything happen in-proc, I would be worried that this singleton issue is just the tip of the iceberg. The library obviously wasn't designed for your scenario. Isolating each load of the DLL into its own process sounds right and non-hacky to me, though of course it could be expensive for you.
Creating multiple instances of global statics in C++?
[ "", "c++", "static", "singleton", "global", "" ]
I am trying to store/retrieve a value that is stored in the Application Settings. From within my console application I can not seem to access the Properties.Setting namespace. My web surfing has revealed that a little more work might be needed to do this from within a Console application. How does one do this? ``` string test = Properties.Settings.Default.MyString; ``` Thanks!
By default there is no Settings file in a Console application. However, you can add one simply by right-clicking your project in the solution explorer, choosing "Properties" and then in the resulting window, click the "Settings" tab. There should be a link saying "Click here to create a default settings file". Once that's created, you're off to the races.
1. Ensure the namespace of the class you're using is the default namespace of your project. 2.then you cna use ``` string s = Properties.Settings.Default.THENAMEINSETTINGS; ``` . [![enter image description here](https://i.stack.imgur.com/3Wiy1.png)](https://i.stack.imgur.com/3Wiy1.png)
How do I access the Properties namespace from within a console app?
[ "", "c#", ".net", "properties", "global-variables", "application-settings", "" ]
How do you change the JavaScript that will execute when a form button is clicked? I've tried changing its onClicked and its onclicked child attributes like so: ``` $('mybutton').onClick = 'doSomething'; ``` and ``` $('mybutton').attributes["onclick"] = 'doSomething()'; ``` Neither seem to work. My other options are: 1. To have two buttons and hide one and show the other. 2. To have it directed to a function that evals a string and change the string to the function I want to execute. Neither seem very elegant. I'm using Prototype as a js library so it that has any useful tools I can use them.
For Prototype, I believe that it would be something like this: ``` $("mybutton").observe('click', function() { // do something here }); ``` EDIT: Or, as it says in [the documentation](http://www.prototypejs.org/api/event), you could simply specify the function you want to call on click: ``` $('mybutton').observe('click', respondToClick); function respondToClick(event) { // do something here } ``` But this is all, again, Prototype-specific.
If the original onclick event was set through HTML attributes, you can use the following to overwrite it: ``` $("#myButtonId").setAttribute("onclick", "myFunction();"); ```
Changing the onclick event delegate of an HTML button?
[ "", "javascript", "prototypejs", "" ]
I have a SQL table where in each row I store the country and the city of a things location. For example: ``` record1, New York, USA record2, Rome, Italy record3, Milano, Italy record3, Birghiman, UK record4, London, UK record5, London, UK record6, London, UK record7, Birmingham, UK ``` I would like to generate a list that is ordered by country and city, and each city show up only once in the result. I would like to know how to solve this in SQL and Linq To SQL in an elegant way.
``` select distinct country, city from <Table> order by country, city; ```
``` SELECT MIN(record) AS record, City, Country FROM [MyTable] GROUP BY City, Country ORDER BY Country, City ```
Getting list of cities and countries from a SQL Table
[ "", "sql", "linq", "linq-to-sql", "" ]
I am trying to bind a DataGridView to a List, where MyObject looks like ``` class MyObject { public string Property1 { get; set; } public string Property2 { get; set; } } //List<MyObject> objects; grid.Columns[0].DataPropertyName = "Property1"; grid.DataSource = objects; ``` I want only one property to be displayed, but instead I get another column added to my DataGridView where the Property2 is also displayed. How can I prevent it from being added?
If you *never* want that property displayed: ``` class MyObject { public string Property1 { get; set; } [Browsable(false)] public string Property2 { get; set; } } ``` Otherwise, as already stated - set `AutoGenerateColumns` to false and add them manually.
It sounds like you have the AutoGenerateColumns property of your DataGridView control set to True. You can either set it to False, or use the .Columns.Remove method to remove the column you don't want to see.
Binding DataGridView to a List<>, some properties Should not be shown
[ "", "c#", "data-binding", "datagridview", "" ]
The possible answers are either **"never"** or **"it depends"**. Personally, I would say, **it depends**. Following usage would make a collection appear (to me) to be a flyweight: ``` public final static List<Integer> SOME_LIST = Collections.unmodifiableList( new LinkedList<Integer>(){ // scope begins { add(1); add(2); add(3); } } // scope ends ); ``` Right? You can't **ever** change it, because the only place where the "original" collection object is known (which **could** be changed), is the scope inside **unmodifiableList**'s parameter list, which ends immediately. Second thing is: when you retrieve an element from the list, it's an **Integer** which **itself** is a flyweight. *Other obvious cases where **final static** and **unmodifiableList** are not used, would **not** be considered as flyweights.* Did I miss something? Do I have to consider some internal aspects of **LinkedList** which could compromise the flyweight?
i think you are referring to the [flyweight pattern.](http://en.wikipedia.org/wiki/Flyweight_pattern) the fundamental idea of this pattern is that you are dealing with complex objects whose instances can be reused, and put out different representations with its methods. to make such a object work correctly it should be immutable. immutability is clearly given when creating a List the way you described. but since there is no external object/parameters on which the SOME\_LISt operates on i would not call this an example of a flyweight pattern. another typical property of the flyweight pattern is the "interning" of such objects. when creating just a single instance of an object this does not make sense. if you are dealing a lot with lists that are passed around from one object to another and you want to ensure the Immutability, a better option might be to use [Google-Collections](http://code.google.com/p/google-collections/). ``` final static ImmutableList<Integer> someList = ImmutableList.of(1, 2, 3); ``` of course it is also possible to construct more complex Immutable Objects with Builders. this creates an instance of an immutable list. it will still implement the List interface, but will refuse to execute any add(),addAll() set(), remove() operation. so you can still pass it to methods when a List interface is required, yet be sure that its content is not altered.
I think your example are for immutable objects, a [flyweight](http://en.wikipedia.org/wiki/Flyweight_pattern) is something quite different. Immutable objects are candidates for flyweight, but a flyweight doesn't have to be immutable, it just has to be designed to save memory.
Java: Does Collections.unmodifiableXYZ(...) in special cases make a collection object a flyweight?
[ "", "java", "collections", "design-patterns", "" ]
I have a program that receives real time data on 1000 topics. It receives -- on average -- 5000 messages per second. Each message consists of a two strings, a topic, and a message value. I'd like to save these strings along with a timestamp indicating the message arrival time. I'm using 32 bit Windows XP on 'Core 2' hardware and programming in C#. I'd like to save this data into 1000 files -- one for each topic. I know many people will want to tell me to save the data into a database, but I don't want to go down that road. I've considered a few approaches: 1) Open up 1000 files and write into each one as the data arrives. I have two concerns about this. I don't know if it is possible to open up 1000 files simultaneously, and I don't know what effect this will have on disk fragmentation. 2) Write into one file and -- somehow -- process it later to produce 1000 files. 3) Keep it all in RAM until the end of the day and then write one file at a time. I think this would work well if I have enough ram although I might need to move to 64 bit to get over the 2 GB limit. How would you approach this problem?
I agree with Oliver, but I'd suggest a modification: have 1000 queues, one for each topic/file. One thread receives the messages, timestamps them, then sticks them in the appropriate queue. The other simply rotates through the queues, seeing if they have data. If so, it reads the messages, then opens the corresponding file and writes the messages to it. After it closes the file, it moves to the next queue. One advantage of this is that you can add additional file-writing threads if one can't keep up with the traffic. I'd probably first try setting a write threshold, though (defer processing a queue until it's got N messages) to batch your writes. That way you don't get bogged down opening and closing a file to only write one or two messages.
I can't imagine why you wouldn't want to use a database for this. This is what they were built for. They're pretty good at it. If you're not willing to go that route, storing them in RAM and rotating them out to disk every hour might be an option but remember that if you trip over the power cable, you've lost a lot of data. Seriously. Database it. **Edit:** I should add that getting a robust, replicated and complete database-backed solution would take you less than a day if you had the hardware ready to go. Doing this level of transaction protection in any other environment is going to take you weeks longer to set up and test.
Storing Real Time data into 1000 files
[ "", "c#", "real-time", "" ]
I have inherited couple of .Net (C#) application which does not have any tracing or logging added to it. This application does everything from Creating , Reading , Updating and deleting records. It sends email and calls web services. Of course it is a nightmare to maintain it because there is no logging and no try catch mechanism (I know I could not believe it either). So what would be the best way of implementing logging in this system. I can not go to every function call and add logging lines. Is there some way where I can have dynamic logging which can log based on the method names I provide. I.E. When UpdateOrder() is called , my logger should log (updated order method was called ) Thank you
You could use an AOP framework like [Postsharp](http://www.postsharp.org/) to create a specific attribute to log method calls : ``` public class TraceAttribute : OnMethodBoundaryAspect { public override void OnEntry( MethodExecutionEventArgs eventArgs) { Trace.TraceInformation("Entering {0}.", eventArgs.Method); } public override void OnExit( MethodExecutionEventArgs eventArgs) { Trace.TraceInformation("Leaving {0}.", eventArgs.Method); } } ``` (this code is the example from the home page) You can then apply this attribute to the methods you want to log : ``` [Trace] public void UpdateOrder() { ... } ```
Use log4net, it is the .NET version of the Apache log4j. The library is well tested, used by programmers everywhere, and is very customizable. Since you've inherited this code, it would not be a bad thing to go through it and start adding logging support. The customization settings are handled through a global file within the project with can specify where the logging information goes (Emailed, text files, console) and what level of verbosity is needed per output source of the logging information.
Best way to add logging in existing application (windows or web) .Net
[ "", "c#", ".net", "logging", "" ]
I have a windows mobile 5.0 application (smartphone) that contains a flat data file (CSV), which contains a header row (two doubles), and a list of entries (two doubles, DateTime, and a string). Occasionally, I need to "sync" the mobile application with a desktop application. The desktop application should read the CSV from the mobile device, and replace it with a new CSV file, based on the contents of the old one. This seems pretty easy via RAPI (I'm guessing), but I need to ensure that the mobile application is not running. Is there a way to do this? Mutex? Remote Process Viewer like stuff? File locking? Thanks for any help you have Mike
Just use a simple file locking mechanism for the file being read/updated. Either rename the file before use or create a second 'lock' file which you can check for the existence of.
For whatever reason, the [built-in RAPI Functions](http://msdn.microsoft.com/en-us/library/aa457105.aspx) don't have anything for checking running processes like the [ToolHelp API's](http://msdn.microsoft.com/en-us/library/aa915058.aspx). With C you could create a set of custom functions in a device library that call the ToolHelp APIs and in turn are called through [CeRapiInvoke](http://msdn.microsoft.com/en-us/library/ms834931.aspx) (which is a generic catch-all entry point for custom RAPI functions). Unfortunately there's no simple mechanism to do this in managed code.
Ensuring Windows Mobile application is not running - From a desktop app
[ "", "c#", "windows-mobile", "compact-framework", "" ]
I am trying to get my Mac setup as a php server, however, as successful as I have been so far, I seem to have run into a bit of bother. My PHP opening statments are not working... but only the shorthand ones. This works: ``` <?php phpinfo(); ?> ``` This doesn't: ``` <? phpinfo(); ?> ``` It's Mac 10.5. Hope that someone can help. Thanks
In your php.ini, set [short\_open\_tag](http://ie.php.net/manual/en/ini.core.php#ini.short-open-tag) to On. ``` short_open_tag = On ``` From the docs: > short\_open\_tag boolean > > Tells whether the short form (`<? ?>` ) > of PHP's open tag should be > allowed. If you want to use PHP in > combination with XML, you can disable > this option in order to use `<?xml ?>` > inline. Otherwise, you can print it > with PHP, for example: `<?php echo > '<?xml version="1.0"'; ?>` . Also if > disabled, you must use the long form > of the PHP open tag (`<?php ?>` ). Edit: `short_open_tag` is [PHP\_INI\_ALL as of 5.3.0](http://www.php.net/manual/en/ini.list.php), which means that it can be changed anywhere (php.ini, .htaccess, in script). And it was PHP\_INI\_PERDIR before 5.3.0, which means that it can be set in php.ini and .htaccess. Therefore, you can change its value in most cases even if you don't control the server. However, this setting is off by default. If you are going to distribute your script, it won't work on most installations out of the box. In this case, a search/replace to switch to `<?php` is a good idea.
Check if your php.ini file contains the [`short_open_tag=1`](http://php.net/manual/es/ini.core.php) line.
why would shorthand PHP opening statements not be working?
[ "", "php", "php-shorttags", "" ]
Fedora Core 9 includes Python 2.5.1. I can use YUM to get latest and greatest releases. To get ready for 2.6 official testing, I wanted to start with 2.5.4. It appears that there's no Fedora 9 YUM package, because 2.5.4 isn't an official part of FC9. I downloaded 2.5.4, did `./configure; make; make install` and wound up with two Pythons. The official 2.5.1 (in `/usr/bin`) and the new 2.5.4. (in `/usr/local/bin`). None of my technology stack is installed in `/usr/local/lib/python2.5`. It appears that I have several choices for going forward. Anyone have any preferences? * Copy /usr/lib/python2.5/\* to /usr/local/lib/python2.5 to replicate my environment. This should work, unless some part of the Python libraries have /usr/bin/python wired in during installation. This is sure simple, but is there a down side? * Reinstall everything by running `easy_install`. Except, `easy_install` is (currently) hard-wired to `/usr/bin/python`. So, I'd have to fix `easy_install` first, then reinstall everything. This takes some time, but it gives me a clean, new latest-and-greatest environment. But is there a down-side? [And why does easy\_install hard-wire itself?] * Relink `/usr/bin/python` to be `/usr/local/bin/python`. I'd still have to copy or reinstall the library, so I don't think this does me any good. [It would make `easy_install` work; but so would editing `/usr/bin/easy_install`.] Has anyone copied their library? Is it that simple? Or should I fix `easy_install` and simply step through the installation guide and build a new, clean, latest-and-greatest? --- **Edit** Or, should I * Skip trying to resolve the 2.5.1 and 2.5.4 issues and just jump straight to 2.6?
Normally, you would only have one version of a python release installed. Since 2.5.1 and 2.5.4 are from the same release, copying your libraries should work fine. What you would need to watch out for, is that you now have /usr/bin/python, and /usr/local/bin/python in your path, and some utilities may get confused. If you need to have both micro-releases installed at once, I would keep 2.5.4 out of your path altogether, or allow it to completely clobber the other (do so at your own risk though ;) If you go with the former, you can also point 2.5.4 to your site-packages by using the PYTHONPATH environment variable. Ubuntu takes a different route, and this is how you can handle different major releases. The python binary is given with the version appended: ``` /usr/bin/python -> python2.6 /usr/bin/python2.5 /usr/bin/python2.6 ``` Each has their own /usr/lib/python2.X directory with versions of all the modules. And lastly, you can further customize your setup by [modifying your site.py](http://www.python.org/doc/2.5.4/inst/search-path.html)
I suggest you create a virtualenv (or several) for installing packages into.
Fedora Python Upgrade broke easy_install
[ "", "python", "fedora", "easy-install", "" ]
What happens is whenever i upload media onto my site; everyone will get a notification. Each person can click a box to remove and it will be gone from their msg queue forever. If i had 10,000 people on my site how would i add it to every person msg queue? I can imagine it takes a lot of time so would i opt for something like a filesystem journal? mark that i need to notify people, the data then my current position. Then update my position every 100 inserts or so? I would need a PK on my watcher list so if anyone registers in the middle of it my order will not be broken since i'll be sorting via PK? Is this the best solution for a mass notification system? -edit- This site is a user created content site. Admins can send out global messages and popular people may have thousands of subscribers.
If 10000 inserts into a narrow many to many table linking the recipients to the messages `(recipientid, messageid, status)` is slow, I expect you've get bigger problems with your design. This is the kind of operation I wouldn't typically even worry about batching or people subscribing in the middle of the post operation - basically: Assuming `@publisherid` known, `@msg` known on SQL Server: ``` BEGIN TRANSACTION INSERT INTO msgs (publisherid, msg) VALUES(@publisherid, @msg) SET @messageid = SCOPE_IDENTITY() INSERT INTO msqqueue (recipientid, messageid, status) SELECT subscriberid, @messageid, 0 -- unread FROM subscribers WHERE subscribers.publisherid = @publisherid COMMIT TRANSACTION ```
Maybe just record for each user which notifications they have seen- so the set of notifications to show to a user are ones created before their "earliest\_notification" horizon (when they registered, or a week ago...) minus the ones they have acknowledged. That way you delay inserting anything until it's a single user at once- plus if you only show users messages less than a week old, you can purge the read-this-notification flags that are a week or more old. (Peformance optimisation hint from my DBA at my old job: "business processes are the easiest things to change, look at them first")
Best way to do 10,000 inserts in a SQL db?
[ "", "sql", "notifications", "" ]
In the following example i can create an object dynamically via a string; however, i have no way to get at the public methods of BASE class. i can't cast obj to a BASE because i don't know what generic will be used at design time. any suggestings on doing so at runtime would be nice. Project A contains Class A{T,J> : BASE{T,J> Project B contains Class B{T,J> : BASE{T,J> Project C contains Class BASE{T,J> public virtual control{T,J> item Project Windows Form cmdGo\_Click event string dll = textbox1.text //ex "ProjectA.dll" string class = textbox2.text //ex "A`2[enuT,enuJ]" object obj = activator.createinstancefrom(dll,class)
At *runtime* the generics part of the equation does not matter, because the compiler has already filled in the gaps for the generic implementation. I believe you can use reflection to get at the base class methods, like in this example below, I hope this helps. ``` MethodInfo[] baseMethods = obj.GetType().BaseType.GetMethods(); object retObj = baseMethods[0].Invoke(obj, new object[] {"paramVal1", 3, "paramVal3"}); ```
This code creates an instance of BASE<int, string> : ``` Type type = typeof(BASE<,>).MakeGenericType(typeof(int), typeof(string)); object instance = Activator.CreateInstance(type); ```
C# Create objects with Generics at runtime
[ "", "c#", "generics", "runtime", "activator", "" ]
I am building a site that will (obvisouly) have a front end public portion that I want to drive with Concrete5, but then it will also have a members section that I would like to build with Code Igniter. Does anyone have any idea how I could do that? I guess I could just throw the Code Igniter code into a sub directory, but would I run into any issues with that?
i can't see why not. As you suggested a separate folder on the site would be one solution. (you might have to tweak the .htaccess file (if you are using one) to ignore the other cms/framework Another solution would be to have separate subdomains, eg example.com and members.example.com
The answer, since the OP hasn't posted it, is to change the .htaccess rule: ``` RewriteBase / ``` to: ``` RewriteBase /foo/ ``` where `foo` is your subdirectory that the index.php and CI reside. This .htaccess should also be in the same folder as the CI index.php. Works like a charm. Also don't forget to add the subdirectory to the base\_url config setting.
Can I use Code Igniter with Concrete5?
[ "", "php", "codeigniter", "frameworks", "content-management-system", "concrete5", "" ]
I have the following snippet in my Ant script. It executes just fine: ``` <exec executable="C:\test\foo\programName.exe" /> ``` But then when I try to execute it by setting the directory, like so: ``` <exec executable="programName.exe" dir="C:\test\foo\" /> ``` I get: > Execute failed: java.io.IOException: > Cannot run program "programName.exe" > (in directory "C:\test\foo"): > CreateProcess error=2, The system > cannot find the file specified Please help! Why is it not working when the directory is specified separately?
I ended up sticking with this: ``` <exec executable="${basedir}\myexefile.exe}" /> ```
Add the **resolveexecutable** attribute: ``` <exec executable="programName.exe" resolveexecutable="true" dir="C:\test\foo\" /> ``` > **resolveexecutable** When this > attribute is true, the name of the > executable is resolved firstly against > the project basedir and if that does > not exist, against the execution > directory if specified. On Unix > systems, if you only want to allow > execution of commands in the user's > path, set this to false. since Ant 1.6 > **No, default is false**
Execute with Ant works with absolute path but not relative path
[ "", "java", "ant", "relative-path", "absolute-path", "" ]
When learning new languages such as C++ from PHP, does reading other language snippets help you understand better by giving one a different prospective, or does doing so confuse a noob like me? Also, any advice on learning C++ would be great.
I find that reading short snippets helps a lot. A good book is really handy too. Once you understand most of the language itself, reading large, full-size programs helps a lot with learning how common problems are solved in that language. Most languages don't have a term for this, but it is like the "Pythonic" way in Python. As for learning C++, first get a good understanding of C. C is quite simple, so it shouldn't take that long. Once you know C, start learning about the C++ specific features one at a time. This way, you can still write useful programs (C is mostly a subset of C++), before you learn the real "C++ic" way.
I find it helps to 1. Get a good grasp of the syntax and semantics of the language, by looking at SIMPLE examples and relating it to something **you already know** 2. Look at what libraries and design patterns are common. Find out **why** they are common. Was the language designed to encourage them? Is it convention? Efficient? 3. **have an idea** that you want to implement in the language. It will give you a goal, and some perspective. 4. Look at other's code, once you are comfortable picking apart and reading it, and comfortable with source-layout, conventions, common-naming and so on I find it best to dive-in heads first. Get feedback from people if possible. Most importantly: **don't be afraid of making mistakes** they are a big part of the learning process. And try and **relate things** to concepts you are already comfortable with.
When learning new languages related readings, Distractions or Aids?
[ "", "c++", "programming-languages", "" ]
The exact warning I get is ``` warning C4715: 'hand::show' : not all control paths return a value ``` and hand::show is ``` std::ostream& hand::show(std::ostream& os) const { if(side == left) { return os<<display[0]<<display[1]<<display[2]<<display[3]<<display[4]; } if(side == right) { return os<<display[4]<<display[3]<<display[2]<<display[1]<<display[0]; } } ``` where side is a variable of type orientation ``` orientation{ left = -1, right = 1 }; ``` What does the warning mean, and what would be the best solution to get rid of it?
Your compiler isn't smart enough to take into account that the only two options for `side` are `left` and `right`, so it thinks it's possible for neither return statement to be executed. When `side` is neither `left` nor `right`, your function doesn't say which value to return.
The error means that if side is neither left nor right, your function will not return a value - either side is declared improperly or your enum is. An enum should be defined like ``` enum orientation {left, right}; ``` So try changing your orientation structure to that.
What does "warning: not all control paths return a value" mean? (C++)
[ "", "c++", "controls", "warnings", "" ]
When you code a distributed algorithm, do you use any library to model abstract things like processor, register, message, link, etc.? Is there any library that does that? I'm thinking about e.g. self-stabilizing algorithms, like self-stabilizing minimum spanning-tree algorithms.
There's a [DVM system](http://www.keldysh.ru/dvm/) that can be used for implementing different distributed algorithms. It works on top of [MPI](http://www.mpi-forum.org/). However it is more for matrix-oriented scientific algorithms where distribution is done in terms of data blocks. I had a brief experience using it - it's much more convenient than direct usage of MPI and allows for much more readable and maintainable code.
You may want to check out [OpenMP](http://en.wikipedia.org/wiki/OpenMP).
Helper library for distributed algorithms programming?
[ "", "c++", "algorithm", "distributed-computing", "distributed-algorithm", "" ]
I am working through trying to learn to program in Python and am focused on getting a better handle on how to use Standard and other modules. The dir function seems really powerful in the interpreter but I wonder if I am missing something because of my lack of OOP background. Using S.Lotts book I decided to use his Die class to learn more about syntax and use of classes and instances. Here is the original code: ``` class Die(object): ''' simulate a six-sided die ''' def roll(self): self.value=random.randrange(1,7) return self.value def getValue(self): return self.value ``` I was looking at that and after creating some instances I wondered if the word value was a keyword somehow and what the use of the word object in the class statement did and so I decided to find out by changing the class definition to the following: ``` class Die(): ''' simulate a six-sided die ''' def roll(self): self.ban=random.randrange(1,7) return self.ban def getValue(self): return self.ban ``` That change showed me that I got the same behavior from my instances but the following methods/attributes were missing from the instances when I did dir: ``` '__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', _repr__', '__setattr__', '__str__', '__weakref__' ``` I also figured out that when I did a dir on an instance I had an additional keyword-**ban** which I finally figured out was an attribute of my instance. This helped me understand that I could use **d1.ban** to access the value of my instance. The only reason I could figure out that this was an attribute was I typed **d1.happy** and got an **AttributeError** I figured out that **d1.GetValue** was a method attached to Die because that is what the interpreter told me. So when I am trying to use some complicated but helpful module like BeautifulSoup how can I know which of the things that are listed are attributes of my instance or methods of my instance after typing **dir(instance)**. I would need to know this because this poking around has taught me that with attributes I am calling the result of a method and with methods I am invoking a function on my instance. This question is probably too wordy but it sure did help me better understand the difference between attributes and methods. Specifically, when I look at the result of calling dir on an instance of my Die class I see this ``` ['__doc__', '__module__', 'ban', 'getValue', 'roll'] ``` So it would seem useful to know by looking at that list which are attributes and which are methods without having to resort to trial and error or result to typing in **hasattr(myInstance,suspectedAttributeName)**. After posting the question I tried ``` for each in dir(d1): print hasattr(d1,each) ``` which tells me strictly speaking that all methods are attributes. but I can't call a method without the **()** so it seems to me that the hasattr() is misleading.
Instead of: "`print hasattr(d1,each)`", try: "`print each, type(getattr(d1,each))`". You should find the results informative. Also, in place of `dir()` try `help()`, which I think you're really looking for.
Consider using the standard library's `inspect` module -- it's often the handiest approach to introspection, packaging up substantial chunks of functionality (you could implement that from scratch, but reusing well-tested, well-designed code is a good thing). See <http://docs.python.org/library/inspect.html> for all the details, but for example `inspect.getmembers(foo, inspect.ismethod)` is an excellent way to get all methods of foo (you'll get `(name, value)` pairs sorted by name).
How do you know when looking at the list of attributes and methods listed in a dir which are attributes and which are methods?
[ "", "python", "attributes", "methods", "python-datamodel", "" ]
I am looking to build some reports for Quickbooks data, without using Quickbooks built-in reporting, or through a third party library (like QODBC). Quickbooks 2008 and newer are built on a SQL backend.. In looking around there seems to be several products and angles to do this from. Ideally I would like to be able to do direct SQL hits on the database myself, or use something like Crystal Reports. I wanted to ask here to gather any things to look at closer, and what to potentially avoid to save myself grief. Thanks in Advance! **Update**: It seems Quickbooks encrypts it's sql database so you can't read it directly with a reporting tool.. There are a few products on the market that can help.. more to come.
Your best bet is the QuickBooks SDK, it provides facilities to fetch data and also fetch reporting data directly from QuickBooks, formatted as XML for easy parsing and display however you want to display it. You can see the data that's available using the qbXML/QBFC [QuickBooks On-Screen reference](https://developer.intuit.com/qbsdk-current/Common/newOSR/index.html) (the requests you can send to QuickBooks are found in the 'Select Message' drop-down box at the top of the screen). The QuickBooks SDK is a free download (registration required) from the [Intuit Developer Network](http://developer.intuit.com/technical_resources/?id=1488) If you're writing a desktop application, you can look into using QBFC, which is an API that talks to QuickBooks using COM/DCOM. If you're using PHP, there's a popular [QuickBooks PHP framework](https://idnforums.intuit.com/messageview.aspx?catid=56&threadid=9164) on the IDN forums. If you're using ASP.NET, here's a [QuickBooks ASP .NET framework](https://idnforums.intuit.com/messageview.aspx?catid=56&threadid=11040&enterthread=y) too. If you want direct SQL access, you should look at QODBC (which is an SQL wrapper which translates SQL queries to qbXML SDK requests) or AccessBooks (which uses the SDK to mirror QuickBooks data to an SQL database).
If its hosted on SQL 2005 or 2008 you can make use of Reporting Services (free) and the Report Builder that is bundled with it. If you use 2008 then I recommend downloading Report Builder 2.0 <http://www.microsoft.com/downloads/details.aspx?familyid=9f783224-9871-4eea-b1d5-f3140a253db6> Here's some links to learn RS: <http://www.google.com/search?q=reporting+services+tutorial+video&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a>
Approaches to building reports with Quickbooks 2008+ Data
[ "", "sql", "report", "quickbooks", "building", "" ]
Could somebody point me in the right direction of how I could read a binary file that is defined by a C struct? It has a few #define inside of the struct, which makes me thing that it will complicate things. The structure looks something like this: (although its larger and more complicated than this) ``` struct Format { unsigned long str_totalstrings; unsigned long str_name; #define STR_ORDERED 0x2 #define STR_ROT13 0x4 unsigned char stuff[4]; #define str_delimiter stuff[0] } ``` I would really appreciate it if somebody could point me in the right direction on how to do this. Or if theres any tutorial out there that covers this topic? Thanks a lot in advance for your help.
Reading a binary defined by a struct is easy. ``` Format myFormat; fread(&myFormat, sizeof(Format), 1, fp); ``` the #defines don't affect the structure at all. (Inside is an odd place to put them, though). However, this is not cross-platform safe. It is the simplest thing that will possibly work, in situations where you are assured the reader and writer are using the same platform. The better way would be to re-define your structure as such: ``` struct Format { Uint32 str_totalstrings; //assuming unsigned long was 32 bits on the writer. Uint32 str_name; unsigned char stuff[4]; }; ``` and then have a 'platform\_types.h" which typedefs Uint32 correctly for your compiler. Now you can read directly into the structure, but for endianness issues you still need to do something like this: ``` myFormat.str_totalstrings = FileToNative32(myFormat.str_totalstrings); myFormat.str_name = FileToNative32(str_name); ``` where FileToNative is either a no-op or a byte reverser depending on platform.
There are some bad ideas and good ideas: ## That's a bad idea to: * Typecast a raw buffer into struct + There are [endianness](https://en.wikipedia.org/wiki/Endianness) issues (little-endian vs big-endian) when parsing integers >1 byte long or floats + There are [byte alignment issues](http://www.catb.org/esr/structure-packing/) in structures, which are very compiler-dependent. One can try to disable alignment (or enforce some manual alignment), but it's generally a bad idea too. At the very least, you'll ruin performance by making CPU access unaligned integers. Internal RISC core would have to do 3-4 ops instead of 1 (i.e. "do part 1 in first word", "do part 2 in second word", "merge the result") to access it every time. Or worse, compiler pragmas to control alignment will be ignored and your code will break. + There are no exact size guarantees for regular `int`, `long`, `short`, etc, type in C/C++. You can use stuff like `int16_t`, but these are available only on modern compilers. + Of course, this approach breaks completely when using structures that reference other structures: one has to unroll them all manually. * Write parsers manually: it's much harder than it seems on the first glance. + A good parser needs to do lots of sanity checking on every stage. It's easy to miss something. It is even easier to miss something if you don't use exceptions. + Using exceptions makes you prone to fail if your parsing code is not exception-safe (i.e. written in a way that it can be interrupted at some points and it won't leak memory / forget to finalize some objects) + There could be performance issues (i.e. doing lots of unbuffered IO instead of doing one OS `read` syscall and parsing a buffer then — or vice versa, reading whole thing at once instead of more granular, lazy reads where it's applicable). ## It's a good idea to * Go cross-platform. Pretty much self-explanatory, with all the mobile devices, routers and IoT stuff booming around in the recent years. * Go declarative. Consider using any of declarative specs to describe your structure and then use a parser generator to generate a parser. There are several tools available to do that: * [Kaitai Struct](http://kaitai.io) — my favorite so far, cross-platform, cross-language — i.e. you describe your structure once and then you can compile it into a parser in C++, C#, Java, Python, Ruby, PHP, etc. * [binpac](https://www.bro.org/sphinx/components/binpac/README.html) — pretty dated, but still usable, C++-only — similar to Kaitai in ideology, but unsupported since 2013 * [Spicy](http://www.icir.org/hilti/manual.html) — said to be "modern rewrite" of binpac, AKA "binpac++", but still in early stages of development; can be used for smaller tasks, C++ only too.
Reading binary file defined by a struct
[ "", "c++", "data-structures", "binary", "" ]
I have some code where I use a thread static object in C#. ``` [ThreadStatic] private DataContext connection ``` I was wondering, in this case, what if any change would I get if I put the static modifier on the thread static context? ``` [ThreadStatic] private static DataContext connection ``` With the first would there be one copy of the context per instance per thread, with the other only one copy per thread?
The `ThreadStaticAttribute` is only designed to be used on static variables, as [the documentation points out](https://learn.microsoft.com/en-us/dotnet/api/system.threadstaticattribute). If you use it on an instance variable, I suspect it will do precisely nothing.
In the first case it would probably be ignored, whereas in the second case you are correct, one instance per thread.
ThreadStatic Modified with Static C#
[ "", "c#", "static", "thread-static", "" ]
To what extent are modern C++ features like: 1. polymorphism, 2. STL, 3. exception safety/handling, 4. templates with policy-based class design, 5. smart pointers 6. new/delete, placement new/delete used in game studios? I would be interested to know the names of libraries and the C++ features they use. For example, Orge3D uses all modern C++ features including exceptions and smart pointers. In other words, if I would be looking for an example for a game library using modern C++, I would go to Orge3D. But I don't know if these features deter game studios from using Orge3D. Further I don't know if there are other examples. For example, I used Box2D some time before briefly, but it uses only placement new, and class keyword as the C++ features. Even encapsulation is broken in these classes as all members are public. Ideally, if C++ features would be the best match for all situations, these would be used most often. But it seems not. What are the impedances? The obvious one is having to read stacks of books, but that's half a reason only. This question is a follow up on "[C++ for Game Programming - Love or Distrust?](https://stackoverflow.com/questions/829656/c-for-game-programming-love-or-distrust)" (From the responses there I got an impression that many C++ features are still not used in games; which is not necessarily the way it *should* be).
I've worked in 2 game companies, seen a number of codebases, and observed a number of debates on matters such as these among game developers, so I might be able to offer some observations. The short answer for each point is that it varies highly from studio to studio or even from team to team within the same studio. Long answers enumerated below: * polymorphism, Used by some studios but not others. Many teams still prefer to avoid it. Virtual function calls do come at a cost and that cost is noticeable at times even on modern consoles. Of those that do use polymorphism, my cynical assumption is that only a small percentage use it well. * STL, Split down the middle, for many of the same reasons as polymorphism. STL is easy to use incorrectly, so many studios choose to avoid it on these grounds. Of those that use it heavily, many people pair it with custom allocators. EA has created [EASTL](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2271.html), which addresses many of the issue STL causes in game development. * exception safety/handling, Very few studios use exception handling. One of the first recommendations for modern consoles is to turn off both RTTI and exceptions. PC games probably use exceptions to much greater effect, but among console studios exceptions are very frequently shunned. They increase code size, which can be at a premium, and literally are not supported on some relevant platforms. * templates with policy-based class design, Policy based design... I haven't come across any of it. Templates are used pretty frequently for things like introspection/reflection and code reuse. Policy based design, when I read Alexandrescu's book, seemed like a flawed promise to me. I doubt it's used very heavily in the game industry, but it will vary highly from studio to studio. * smart pointers Smart pointers are embraced by many of the studios that also use polymorphism and STL. Memory management in console games is extremely important, so a lot of people dislike reference counting smart pointers because they're not explicit about when they free... but these are certainly not the only kind of smart pointer. The smart pointer idea in general is still gaining traction. I think it will be much more commonplace in 2-3 years. * new/delete, placement new/delete These are used frequently. They are often overridden to use custom allocators underneath, so that memory can be tracked and leaks can be found with ease. I think I agree with your conclusion. C++ isn't used in game studios to as much of an extent as it could be. There are good and bad reasons for this. The good ones are because of performance implications or memory concerns, the bad ones are because people are stuck in a rut. In a lot of ways it makes sense to do things the way they've always been done, and if that means C with limited C++ then it means C with limited C++. But there are a number of anti-C++ biases floating around... some justified and some not.
1. Pretty extensively, although people are mindful of the overhead of virtual function calls 2. It depends. Some developers swear off it completely, others make limited use of containers like vectors that will have good cache coherency and runtime performance and won't allocate constantly. I think a general observation would be that the more console-oriented the studio the less STL they use. PC developers can get away with it because they can fall back on the virtual memory system and there's plenty of CPU. Console guys care about every allocation and if you are doing a multiplatform title you get into the wonderful world of different platform's STL implementations behaving differently and having different bugs, although this situation has certainly improved in recent years. Game developers also like to manage their own heaps and allocations and this can be difficult to deal with with STL. 3. Expect it to be disabled in the compiler settings 4. Haha, good one. 5. I'm not sure. I haven't really seen smart pointer use in game code, although aside from a general aversion to dynamic memory I don't think there's anything particularly objectionable about smart pointers from a game development standpoint. 6. This one again depends. PC guys may allocate and deallocate like they just don't care. Console guys care about every allocation. That doesn't mean no new and delete but it can mean that dynamic allocations are only done once when the game or current level is set up and then left until the game or current level is torn down. Per frame allocating and deallocating is best avoided, not just to keep total memory use down but to avoid fragmentation. You'll see a lot of fixed sized arrays and statically allocated structures in a console game engine.
Modern C++ Game Programming Examples
[ "", "c++", "" ]
I have a very simple table with two columns, but has 4.5M rows. ``` CREATE TABLE `content_link` ( `category_id` mediumint(8) unsigned NOT NULL, `content_id` int(10) unsigned NOT NULL, PRIMARY KEY (`content_id`,`category_id`), KEY `content_id` (`content_id`,`category_id`) ) ENGINE=MyISAM; ``` When I run a simple query like: ``` SELECT * FROM content_link WHERE category_id = '11'; ``` mysql spikes the CPU and takes 2-5 seconds before returning about 10 rows. The data is spread very evenly across the table and I'm accessing indexed fields (I've also analyzed/optimized the table and I never change the content of the table), so what reason is there for the query to take so long? Edit: It seems navicat was lying to me and my primary key was not actually keyed in the right order as it was displaying the table to me.
`category_id` is not the first column in any index. Recreate your secondary key as follows: ``` UNIQUE KEY `ix_category_id` (`category_id`, `content_id`) ``` Note the column order, it matters.
The UNIQUE KEY ordering is a good solution and you should add a partition strategy to your table too. By partitioning the table in fragments, MySQL will query the specific partition with the right data set. I've applied and I had excellent results. ``` CREATE TABLE ti (id INT, amount DECIMAL(7,2), tr_date DATE) ENGINE=INNODB PARTITION BY HASH( MONTH(tr_date) ) PARTITIONS 6; ``` You need MySQL 5.1. Try <http://dev.mysql.com/doc/refman/5.1/en/partitioning.html>
Simple MySQL Table Running Slow Queries
[ "", "sql", "mysql", "performance", "myisam", "" ]