Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I've got two list boxes, one a master, the other a child. When the index changes on the master, the child listbox gets filled appropriately with records relating to the master. My problem is coming up when one master takes a long time to get all the records and before it has completed getting the records, a user clicks a different master that takes less time to fill. What happens is that eventually, the master that was taking longer fills in the child list box even though the user isn't on that master anymore. I've been using BackgroundWorker threads to do the filling. ``` bw_LoadAll.DoWork += new DoWorkEventHandler(bg_LoadAllWork); bw_LoadAll.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bg_LoadAllWorkCompleted); bw_LoadAll.WorkerSupportsCancellation = true; ``` I subscribed to the SelectedIndexChanged event for the master and I set the canceled equal to true: ``` bw_LoadAll.CancelAsync(); ``` Here is the code in the DoWork method: ``` List<object> s = Repository.Instance().LoadAll(); if (!bw_LoadAll.CancellationPending) { e.Result = s; } else { e.Cancel = true; } ``` But for some reason, the code for the worker completed keeps getting called. Here is the worker completed code: ``` if (!e.Cancelled) { ddl.DataSource = e.Result; ddl.DisplayMember = "QuickName"; ddl.ValueMember = "ID"; } ``` Is there something else I have to do to cancel this thread from returning?
Your method, bg\_LoadAllWork, should be defined as: ``` void bg_LoadAllWork(object sender, DoWorkEventArgs e) { // Do your work here... } ``` Inside of bg\_LoadAllWork, you need to check for `e.CancellationPending`, and if it's true, set `e.Cancel = true;` This last part is important - if you never set e.Cancel, then your "e.Cancelled" will never equal true. The call to CancelAsync doesn't actually cancel anything - it's more like "Request that the background work cancel itself" - you have to put the logic in place to cause the cancellation.
From [CodeProject](http://www.codeproject.com/KB/cpp/BackgroundWorker_Threads.aspx) in your do\_work function you need to check for CancellationPending on the worker thread then set the DoWorkEventArgs.Cancel variable to true.
Canceling Worker threads in winforms
[ "", "c#", "winforms", "multithreading", "backgroundworker", "" ]
If I am creating a java class to be generic, such as: ``` public class Foo<T> ``` How can one determine internally to that class, what 'T' ended up being? ``` public ???? Bar() { //if its type 1 // do this //if its type 2 // do this //if its type 3 // do this //if its type 4 // do this } ``` I've poked around the Java API and played with the Reflection stuff, instanceof, getClass, .class, etc, but I can't seem to make heads or tails of them. I feel like I'm close and just need to combine a number of calls, but keep coming up short. To be more specific, I am attempting to determine whether the class was instantiated with one of 3 possible types.
I've used a similar solution to what he explains here for a few projects and found it pretty useful. <http://blog.xebia.com/2009/02/07/acessing-generic-types-at-runtime-in-java/> The jist of it is using the following: ``` public Class returnedClass() { ParameterizedType parameterizedType = (ParameterizedType)getClass() .getGenericSuperclass(); return (Class) parameterizedType.getActualTypeArguments()[0]; } ```
In contrast to .NET Java generics are implemented by a technique called "type erasure". What this means is that the compiler will use the type information when generating the class files, but not transfer this information to the byte code. If you look at the compiled classes with javap or similar tools, you will find that a `List<String>` is a simple `List` (of `Object`) in the class file, just as it was in pre-Java-5 code. Code accessing the generic List will be "rewritten" by the compiler to include the casts you would have to write yourself in earlier versions. In effect the following two code fragments are identical from a byte code perspective once the compiler is done with them: Java 5: ``` List<String> stringList = new ArrayList<String>(); stringList.add("Hello World"); String hw = stringList.get(0); ``` Java 1.4 and before: ``` List stringList = new ArrayList(); stringList.add("Hello World"); String hw = (String)stringList.get(0); ``` When reading values from a generic class in Java 5 the necessary cast to the declared type parameter is automatically inserted. When inserting, the compiler will check the value you try to put in and abort with an error if it is not a String. The whole thing was done to keep old libraries and new generified code interoperable without any need to recompile the existing libs. This is a major advantage over the .NET way where generic classes and non-generic ones live side-by-side but cannot be interchanged freely. Both approaches have their pros and cons, but that's the way it is in Java. To get back to your original question: You will not be able to get at the type information at runtime, because it simply is not there anymore, once the compiler has done its job. This is surely limiting in some ways and there are some cranky ways around it which are usually based on storing a class-instance somewhere, but this is not a standard feature.
Java Generic Class - Determine Type
[ "", "java", "generics", "" ]
Hi I am generating a DropDownList in my code behind file ``` protected DropDownList CountryList() { DropDownList ddl = new DropDownList(); XDocument xmlDoc = XDocument.Load(Server.MapPath("Countries.xml")); var countries = from country in xmlDoc.Descendants("Country") select new { Name = country.Element("name").Value, }; foreach (var c in countries) { ddl.Items.Add(c.Name); } return ddl; } ``` I had dreams on then having <%= CountryList() %> on my aspx page. But when I do this it prints the string - "System.Web.UI.WebControls.DropDownList". Can I make this way of doing it work or do I have to setup a ContentPlaceHolder and then add the DropDownList to the content? Cheers
The `<%= %>` is only a shorthand to the Response.Write method, you should [add the controls programatically](http://msdn.microsoft.com/en-us/library/kyt0fzt1.aspx) Or just add an asp:DropDownList tag there you want it, and then in the code behind, you can bind the data directly from your Linq to XML query, using the DataSource property, and the DataBind() method. For example: On your .aspx file: ``` <asp:DropDownList ID="CountryListDropDown" runat="server"> </asp:DropDownList> ``` On your code-behind Page\_Load: ``` CountryListDropDown.DataSource = countries; // your query CountryListDropDown.DataBind(); ``` Since your query has only one selected field, you don't have to specify the DataValueField and DataTextField values.
``` DropDownList ddl = new DropDownList(); ddl.ID = "test"; form1.Controls.Add(ddl); //your formID ```
Generate DropDownList from code behind
[ "", "c#", "asp.net", "" ]
I have following table (SQL Server) Table name is LandParcels ``` Blockid ParcelNo Stateorprivate ======================== 11001901 30 Deemana 11001901 35 Deemana 11001901 41 State 11001901 45 State 11001901 110 Private 11001901 111 Private 11001902 1 Deemana 11001902 11 State 11001902 16 Private 11002001 15 Deemana 11002001 16 State 11003001 20 Private 11002003 2 Deemana 11002003 3 State 11003003 4 Private ``` Blockid (Numeric) = first 6 digits used for Cadastral Map No and last 2 digits for the Block No eg: 110019 is Cadastal map no and 01 is Block No. I used the following query ``` select substring(ltrim(str(blockid)),1,6) as blockid,stateorprivate, count(*) as noofLP from LandParcels group by blockid, stateorprivate order by blockid asc ``` Result is ``` Blockid Stateorprivate noofLP ======================== 110019 Deemana 2 110019 State 2 110019 Private 2 110019 Deemana 1 110019 State 1 110019 Private 1 110020 Deemana 1 110020 State 1 110020 Private 1 110020 Deemana 1 110020 State 1 110020 Private 1 ``` I want to get the following result for a report ``` blockid noofBlocks Deemana State Private Amt_of_Deemana_State_Private 110019 2 3 3 3 9 110020 2 2 2 2 6 ``` How to query this. Pl help me.
You could do something like this: ``` SELECT SUBSTRING(LTRIM(STR(Blockid)), 1, 6) AS blockid, COUNT(DISTINCT SUBSTRING(LTRIM(STR(Blockid)), 7, 2)) AS noofBlocks, SUM(CASE Stateorprivate WHEN 'Deemana' THEN 1 ELSE 0 END) AS Deemana, SUM(CASE Stateorprivate WHEN 'State' THEN 1 ELSE 0 END) AS [State], SUM(CASE Stateorprivate WHEN 'Private' THEN 1 ELSE 0 END) AS [Private], SUM(CASE Stateorprivate WHEN 'Deemana' THEN 1 WHEN 'State' THEN 1 WHEN 'Private' THEN 1 ELSE 0 END) AS Amt_of_Deemana_State_Private FROM LandParcels GROUP BY SUBSTRING(LTRIM(STR(Blockid)), 1, 6) ``` However, if the database schema is under your control, you should consider normalization.
You start your query: ``` select substring(ltrim(str(blockid)),1,6) as blockid ``` which immediately gives the DB an ambiguity -- in the rest of the query, does `blockid` stand for the original column of that name, or does it stand for this homonymous one? **don't do that** -- it's absurd to overload a DB engine with even more ambiguity than it already had to deal with; use `as myblockid` or whatever here, and `myblockid` in the rest of the query when **that** is what you mean. This may not solve every problem, but it will make your life, the DB engine's, AND that of anybody trying to help you out, much less of a nightmare.
T-SQL Problem
[ "", "sql", "t-sql", "dd", "" ]
I can't find any idea of the way to use this attribute?
[MSDN](http://msdn.microsoft.com/en-us/library/system.activities.design.base.propertyediting.editorreuseattribute(VS.100).aspx) indicates it is indeed to indicate that a property editor can be reused without needing to recreate each time. This is a performance win, especially if your editor needs to do significant work on start up which can be avoided. Unless you *are* actually having performance issues then I wouldn't worry about it.
imagine you have scenario like this: ``` class Complex { public OtherComplex1 Property1 { get; set; } public OtherComplex2 Property2 { get; set; } public OtherComplex2 Property3 { get; set; } ..... public OtherComplexN PropertyN { get; set; } } ``` each of your properties has its own type designer, which displays some properties, etc. say, you have two different instances of the Complex class + instance of some other arbitrary class. now, when you toggle between your objects like this - complex instance 1 -> other -> complex instance 2 - everything will work fine, but if you do something like this: complex instance 1 -> complex instance 2, you'd notice that properties are not beeing refreshed. that is default behavior of property grid, which tries to optimize number of data refresh operations. unless you want to bake a lot of logic in order to keep your designers updated, i'd suggest marking your complexTypes with editor reuse attribute set to false - in this case, whenever selection changes to a different instance, property grid would still refresh your designers.
What is EditorReuseAttribute really for?
[ "", "c#", "attributes", "componentmodel", "" ]
Im storing imdb.com links for each movie thats listed in the DB, and check for duplicates before a new movie is inserted. The problem is, some links are <http://imdb.com/whatever> while others are http://**www**.imdb.com/whatever What would be the best way to force www. into every link thats submitted? I realize I should be storing the url without http:// or <http://www>. which would alleviate this problem all together.... but its too late to make that decision now.
Why don't you just store IMDB's movie id rather than the entire URL? If you just store the ID then you can build the URL programmatically. For Instance for this url <http://www.imdb.com/title/tt1049413/> you could just store tt1049413. This is a better design in my opinion because if IMDB ever changes their URL format you can just change the part of your app that builds the url rather than changing every row with a bad url.
Use MySQL to fix the existing ones: ``` UPDATE table SET URL=REPLACE(URL,'http://imdb.com','http://www.imdb.com') WHERE URL LIKE 'http://imdb.com/%'; ``` Then use PHP to fix inbound URLs beforehand: ``` $url = str_replace('http://imdb.com','http://www.imdb.com',$url); ``` But the best method is to store imdb.com's movie ID in your database instead: ``` http://www.imdb.com/title/tt0088846/ ``` Store "tt0088846" instead, or even better, 88846 as your Primary Key, and use a constant: ``` $imdb_url = "http://www.imdb.com/title/tt{ID}/"; $url = str_replace("{ID}", $movie_id, $imdb_url); ``` That way it's much faster and easier to detect duplicates. Note that IMDB has different media types (actors, etc.) which use a different prefix (nm for actors, etc.) so be aware when designing your database.
How do you make non-www. links contain www. in php?
[ "", "php", "" ]
My google searches on how to split a string on a delimiter have resulted in some useful functions for splitting strings when the string is known (i.e. see below): ``` SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER FUNCTION [dbo].[Split] (@String varchar(8000), @Delimiter char(1)) returns @temptable TABLE (items varchar(8000)) as begin declare @idx int declare @slice varchar(8000) select @idx = 1 if len(@String)<1 or @String is null return while @idx!= 0 begin set @idx = charindex(@Delimiter,@String) if @idx!=0 set @slice = left(@String,@idx - 1) else set @slice = @String if(len(@slice)>0) insert into @temptable(Items) values(@slice) set @String = right(@String,len(@String) - @idx) if len(@String) = 0 break end return end ``` This works well for a known string like: ``` SELECT TOP 10 * FROM dbo.Split('This,Is,My,List',',') ``` However, I would like to pass a column to a function, and have it unioned together with my other data in it's own row... for example given the data: ``` CommaColumn ValueColumn1 ValueColumn2 ----------- ------------ ------------- ABC,123 1 2 XYZ, 789 2 3 ``` I would like to write something like: ``` SELECT Split(CommaColumn,',') As SplitValue, ValueColumn1, ValueColumn2 FROM MyTable ``` And get back ``` SplitValue ValueColumn1 ValueColumn2 ---------- ------------ ------------ ABC 1 2 123 1 2 XYZ 2 3 789 2 3 ``` Is this possible, or has anyone done this before?
Yes, it's possible with CROSS APPLY (SQL 2005+): ``` with testdata (CommaColumn, ValueColumn1, ValueColumn2) as ( select 'ABC,123', 1, 2 union all select 'XYZ, 789', 2, 3 ) select b.items as SplitValue , a.ValueColumn1 , a.ValueColumn2 from testdata a cross apply dbo.Split(a.CommaColumn,',') b ``` Notes: 1. You should add an index to the result set of your split column, so that it returns two columns, IndexNumber and Value. 2. In-line implementations with a numbers table are generally faster than your procedural version here. eg: ``` create function [dbo].[Split] (@list nvarchar(max), @delimiter nchar(1) = N',') returns table as return ( select Number = row_number() over (order by Number) , [Value] = ltrim(rtrim(convert(nvarchar(4000), substring(@list, Number , charindex(@delimiter, @list+@delimiter, Number)-Number ) ))) from dbo.Numbers where Number <= convert(int, len(@list)) and substring(@delimiter + @list, Number, 1) = @delimiter ) ``` Erland Sommarskog has the definitive page on this, I think: <http://www.sommarskog.se/arrays-in-sql-2005.html>
Fix it the right way--make that column a related table. No good ever comes of comma-separated scalar columns.
SQL 2005 Split Comma Separated Column on Delimiter
[ "", "sql", "sql-server-2005", "" ]
Here's the situation: I'm using jquery.validate.js to validate my forms, but I need to add a server-side validation layer. jQuery Validate uses class names within form-elements to determine what it should do -- I want to fetch those class names into PHP so that I can perform the same validations on the server-side. I'm hoping to do something like this: ``` foreach($_POST as $key=>$value) { $class=array(...// get this #key element class name list with jQuery $error=...// based on the class names, perform specific PHP validations if($error=="") return true; else return false; } ``` Question is, can I do this? Can I fetch element class names w/ jQuery and pass them to PHP?
You could get jQuery to send the class names along with the form - HOWEVER this leads to serious security issues. Seeing as everything posted to your server is really done by your users browsers, your users will have the ability to then change your validation rules and as such bypass them, and that would make your entire purpose here useless. I would instead suggest the following. Make a function in php to take in the name of a form element and return appropriate class names. When generating each form element for the form, call this function to get the class names (and then applying the jQuery validation). When you read your form in your PHP code - use the same function to get the class names and then you know which validation rules to apply in your server side php code. Hope it made sense.
Never trust the client(browser)! You should never allow anything on the client to dictate to the server how to test the validity of posted information. This is a very bad idea.
Passing values from jQuery to PHP
[ "", "php", "jquery", "" ]
I am doing a series of searches in a string, and somewhere along the line one of the strings will be missed, and my set of searches should fail. I had expected that once the position reached std::string::npos it would stay there, but it does not. Passing std::string::npos to std::string.find seems to start the search at the beginning again ``` std::string str("frederick"); std::string::size_type pos = str.find("der",std::string::npos); TS_ASSERT_EQUALS(pos, std::string::npos); // FAIL, 3 is returned ``` Why is it not being taken to indicate the end of the string? Update: The intention is search for a series of strings in order, and check the result at the end ``` pos = str.find(string1, pos) pos = str.find(string2, pos) pos = str.find(string3, pos) if (pos != std:string::npos) { // All strings found ```
Looking at the spec, I think that there may be a bug in your implementation. `basic_string::find` should return the lowest position `xpos` such that `pos <= xpos` and `xpos + str.size() <= size()` and `at(xpos + I) == str.at(I)` for all elements `I` controlled by `str`. `basic_string::npos` is -1 converted to an unsigned type so must be the largest number representable by that unsigned type. Given that no other position `xpos` can satisfy even the first part of `npos` <= `xpos` and `find` must return `npos` on failure, as far as I can see `npos` is the only valid return value for `basic_string::find` when passed `npos` as the second parameter.
Compare string::find() and string::copy(). (In N2798, that's 21.3.7.2 and 21.3.6.7, pages 686/687) Both take a position argument. Yet only string::copy has a "Requires: pos <= size()" clause. Hence, string::find does *not* require pos <= size(). From that point on, Charles Bailey has the correct logic. Look at the range of valid return values, and it becomes clear that only the only return value which matches the rqeuirements is string::npos. Any other value returned is smaller than string::npos, failing 21.3.7.2/1. --- From N2798=08-0308, copyright ISO/IEC: 21.3.7.2 `basic_string::find [string::find]` `size_type find(const basic_string<charT,traits,Allocator>& str,` `size_type pos = 0) const;` 1 Effects: Determines the lowest position `xpos`, if possible, such that both of the following conditions obtain: — `pos <= xpos` and `xpos + str.size() <= size();` — `traits::eq(at(xpos+I), str.at(I))` for all elements `I` of the string controlled by `str`. 2 Returns: `xpos` if the function can determine such a value for `xpos`. Otherwise, returns `npos`. 3 Remarks: Uses `traits::eq()`.
Why does std::string.find(text,std::string:npos) not return npos?
[ "", "c++", "std", "" ]
I have a collection of items that contain an Enum (TypeCode) and a User object, and I need to flatten it out to show in a grid. It's hard to explain, so let me show a quick example. Collection has items like so: ``` TypeCode | User --------------- 1 | Don Smith 1 | Mike Jones 1 | James Ray 2 | Tom Rizzo 2 | Alex Homes 3 | Andy Bates ``` I need the output to be: ``` 1 | 2 | 3 Don Smith | Tom Rizzo | Andy Bates Mike Jones | Alex Homes | James Ray | | ``` I've tried doing this using foreach, but I can't do it that way because I'd be inserting new items to the collection in the foreach, causing an error. Can this be done in Linq in a cleaner fashion?
I'm not saying it is a *great* way to pivot - but it is a pivot... ``` // sample data var data = new[] { new { Foo = 1, Bar = "Don Smith"}, new { Foo = 1, Bar = "Mike Jones"}, new { Foo = 1, Bar = "James Ray"}, new { Foo = 2, Bar = "Tom Rizzo"}, new { Foo = 2, Bar = "Alex Homes"}, new { Foo = 3, Bar = "Andy Bates"}, }; // group into columns, and select the rows per column var grps = from d in data group d by d.Foo into grp select new { Foo = grp.Key, Bars = grp.Select(d2 => d2.Bar).ToArray() }; // find the total number of (data) rows int rows = grps.Max(grp => grp.Bars.Length); // output columns foreach (var grp in grps) { Console.Write(grp.Foo + "\t"); } Console.WriteLine(); // output data for (int i = 0; i < rows; i++) { foreach (var grp in grps) { Console.Write((i < grp.Bars.Length ? grp.Bars[i] : null) + "\t"); } Console.WriteLine(); } ```
Marc's answer gives sparse matrix that can't be pumped into Grid directly. I tried to expand the code from the [link provided by Vasu](http://www.extensionmethod.net/Details.aspx?ID=147) as below: ``` public static Dictionary<TKey1, Dictionary<TKey2, TValue>> Pivot3<TSource, TKey1, TKey2, TValue>( this IEnumerable<TSource> source , Func<TSource, TKey1> key1Selector , Func<TSource, TKey2> key2Selector , Func<IEnumerable<TSource>, TValue> aggregate) { return source.GroupBy(key1Selector).Select( x => new { X = x.Key, Y = source.GroupBy(key2Selector).Select( z => new { Z = z.Key, V = aggregate(from item in source where key1Selector(item).Equals(x.Key) && key2Selector(item).Equals(z.Key) select item ) } ).ToDictionary(e => e.Z, o => o.V) } ).ToDictionary(e => e.X, o => o.Y); } internal class Employee { public string Name { get; set; } public string Department { get; set; } public string Function { get; set; } public decimal Salary { get; set; } } public void TestLinqExtenions() { var l = new List<Employee>() { new Employee() { Name = "Fons", Department = "R&D", Function = "Trainer", Salary = 2000 }, new Employee() { Name = "Jim", Department = "R&D", Function = "Trainer", Salary = 3000 }, new Employee() { Name = "Ellen", Department = "Dev", Function = "Developer", Salary = 4000 }, new Employee() { Name = "Mike", Department = "Dev", Function = "Consultant", Salary = 5000 }, new Employee() { Name = "Jack", Department = "R&D", Function = "Developer", Salary = 6000 }, new Employee() { Name = "Demy", Department = "Dev", Function = "Consultant", Salary = 2000 }}; var result5 = l.Pivot3(emp => emp.Department, emp2 => emp2.Function, lst => lst.Sum(emp => emp.Salary)); var result6 = l.Pivot3(emp => emp.Function, emp2 => emp2.Department, lst => lst.Count()); } ``` \* can't say anything about the performance though.
Pivot data using LINQ
[ "", "c#", "linq", "pivot-table", "" ]
I am using ***Log4J*** in my application for logging. Previously I was using debug call like: **Option 1:** ``` logger.debug("some debug text"); ``` but some links suggest that it is better to check `isDebugEnabled()` first, like: **Option 2:** ``` boolean debugEnabled = logger.isDebugEnabled(); if (debugEnabled) { logger.debug("some debug text"); } ``` So my question is "**Does option 2 improve performance any way?**". Because in any case Log4J framework have same check for debugEnabled. For option 2 it might be beneficial if we are using multiple debug statement in single method or class, where the framework does not need to call `isDebugEnabled()` method multiple times (on each call); in this case it calls `isDebugEnabled()` method only once, and if Log4J is configured to debug level then actually it calls `isDebugEnabled()` method twice: 1. In case of assigning value to debugEnabled variable, and 2. Actually called by logger.debug() method. I don't think that if we write multiple `logger.debug()` statement in method or class and calling `debug()` method according to option 1 then it is overhead for Log4J framework in comparison with option 2. Since `isDebugEnabled()` is a very small method (in terms of code), it might be good candidate for inlining.
In this particular case, Option 1 is better. The guard statement (checking `isDebugEnabled()`) is there to prevent potentially expensive computation of the log message when it involves invocation of the `toString()` methods of various objects and concatenating the results. In the given example, the log message is a constant string, so letting the logger discard it is just as efficient as checking whether the logger is enabled, and it lowers the complexity of the code because there are fewer branches. Better yet is to use a more up-to-date logging framework where the log statements take a format specification and a list of arguments to be substituted by the logger—but "lazily," only if the logger is enabled. This is the approach taken by [slf4j](http://www.slf4j.org/apidocs/org/slf4j/Logger.html#debug(java.lang.String,%20java.lang.Object[])). See [my answer to a related question](https://stackoverflow.com/questions/105852/conditional-logging-with-minimal-cyclomatic-complexity/105908#105908) for more information, and an example of doing something like this with log4j.
Since in option 1 the message string is a constant, there is absolutely no gain in wrapping the logging statement with a condition, on the contrary, if the log statement is debug enabled, you will be evaluating twice, once in the `isDebugEnabled()` method and once in `debug()` method. The cost of invoking `isDebugEnabled()` is in the order of 5 to 30 nanoseconds which should be negligible for most practical purposes. Thus, option 2 is not desirable because it pollutes your code and provides no other gain.
In log4j, does checking isDebugEnabled before logging improve performance?
[ "", "java", "logging", "log4j", "" ]
In the C++ standard libraries I found only a floating point log method. Now I use log to find the level of an index in a binary tree ( `floor(2log(index))` ). Code (C++): ``` int targetlevel = int(log(index)/log(2)); ``` I am afraid that for some of the edge elements (the elements with value 2^n) log will return n-1.999999999999 instead of n.0. Is this fear correct? How can I modify my statement so that it always will return a correct answer?
You can use this method instead: ``` int targetlevel = 0; while (index >>= 1) ++targetlevel; ``` Note: this will modify index. If you need it unchanged, create another temporary int. The corner case is when index is 0. You probably should check it separately and throw an exception or return an error if index == 0.
If you are on a recent-ish x86 or x86-64 platform (and you probably are), use the `bsr` instruction which will return the position of the highest set bit in an unsigned integer. It turns out that this is exactly the same as log2(). Here is a short C or C++ function that invokes `bsr` using inline ASM: ``` #include <stdint.h> static inline uint32_t log2(const uint32_t x) { uint32_t y; asm ( "\tbsr %1, %0\n" : "=r"(y) : "r" (x) ); return y; } ```
How to do an integer log2() in C++?
[ "", "c++", "floating-accuracy", "logarithm", "" ]
Is there any Win32 API to put the machine into hibernate or suspend mode? I read MSDN and found that `WM_POWERBROADCAST` message gets broadcasted when power-management events occur. I thought of simulating the same with `PostMessage(WM_POWERBROADCAST)`. Is this the correct way of doing or any Win32 API exists to achieve this?
Check out [`SetSuspendState`](http://msdn.microsoft.com/en-us/library/aa373201(VS.85).aspx). Note that you need SE\_SHUTDOWN\_NAME privilege, as mentioned on the referenced msdn page.
As posted by Ben Schwehn, SetSuspendState is the way to go. On win95, you should call SetSystemPowerState. You can also call IsPwrSuspendAllowed and IsPwrHibernateAllowed or GetPwrCapabilities to tell if the machine supports suspend/hibernate.
Is there any Win32 API to trigger the hibernate or suspend mode in Windows?
[ "", "c++", "windows", "winapi", "sdk", "suspend", "" ]
I have a WPF Window that contains a TextBox. I have implemented a Command that executes on Crtl-S that saves the contents of the window. My problem is that if the textbox is the active control, and I have newly edited text in the textbox, the latest changes in the textbox are not commited. I need to tab out of the textbox to get the changes. In WinForms, I would typically call EndEdit on the form, and all pending changes would get commited. Another alternative is using onPropertyChange binding rather than onValidation, but I would rather not do this. What is the WPF equivalent to EndEdit, or what is the pattern to use in this type of scenario? Thanks,
To avoid the issue of needing to tab away, you could simply change the UpdateSourceTrigger property of your controls' binding. Try the following: ``` <TextBox.Text> <Binding Path="MyProperty" UpdateSourceTrigger="PropertyChanged"/> </TextBox.Text> ``` This tells WPF to update the backing object whenever the Text property is changed. This way, you don't need to worry about tabbing away. Hope this helps! **EDIT:** The accepted answer for the following SO question provides a way to automatically run validation rules for a page. You could modify it to call UpdateSource() on all BindingExpression objects instead. **[Link](https://stackoverflow.com/questions/127477/detecting-wpf-validation-errors)**
Based on Pwninstein answer, I have now implemented an `EndEdit` in my common class for WPF Views / Windows that will look for bindings and force an update on them, code below; Code below; ``` private void EndEdit(DependencyObject parent) { LocalValueEnumerator localValues = parent.GetLocalValueEnumerator(); while (localValues.MoveNext()) { LocalValueEntry entry = localValues.Current; if (BindingOperations.IsDataBound(parent, entry.Property)) { BindingExpression binding = BindingOperations.GetBindingExpression(parent, entry.Property); if (binding != null) { binding.UpdateSource(); } } } for(int i=0; i < VisualTreeHelper.GetChildrenCount(parent); i++) { DependencyObject child = VisualTreeHelper.GetChild(parent, i); this.EndEdit(child); } } protected void EndEdit() { this.EndEdit(this); } ``` In my Save command, I now just call the `EndEdit` method, and I don't have to worry about other programmers selection of binding method.
EndEdit equivalent in WPF
[ "", "c#", ".net", "wpf", "data-binding", "textbox", "" ]
I am trying to control stuff with PHP from keyboard input. The way I am currently detecting keystrokes is with: ``` function read() { $fp1=fopen("/dev/stdin", "r"); $input=fgets($fp1, 255); fclose($fp1); return $input; } print("What is your first name? "); $first_name = read(); ``` The problem is that it is not reading the keystrokes 'live'. I don't know if this is possible using this method, and I would imagine that this isn't the most effective way to do it either. My question is 1) if this is a good way to do it, then how can I get it to work so that as you type on the page, it will capture the keystrokes, and 2) if this is a bad way of doing it, how can I implement it better (maybe using ajax or something)? edit: I am using PHP as a webpage, not command line.
I'm assuming that you're using PHP as a web-scripting language (not from the command line)... From what I've seen, you'll want to use Javascript on the client side to read key inputs. Once the server delivers the page to the client, there's no PHP interaction. So using AJAX to read client key inputs and make calls back to the server is the way to go. There's some more info on Javascript and detecting key presses [here](http://www.javascriptkit.com/javatutors/javascriptkey.shtml) and some info on how to use AJAX [here](http://docs.jquery.com/Ajax/load#urldatacallback). A neat option for jQuery is to use something like [delayedObserver](http://code.google.com/p/jquery-utils/wiki/DelayedObserver)
If you are writing a CLI application (as opposed to a web application), you can use [ncurses' getch()](http://www.php.net/manual/en/function.ncurses-getch.php) function to get a single key stroke. Good luck! If you're not writing a CLI application, I would suggest following Andrew's answer.
Keyboard input in PHP
[ "", "php", "keyboard-events", "" ]
I wonder if Perl, Python, or Ruby can be used to write a program so that it will look for 0x12345678 in the memory of another process (probably the heap, for both data and code data) and then if it is found, change it to 0x00000000? It is something similar to [Cheat Engine](http://www.cheatengine.org/), which can do something like that on Windows.
I initially thought this was not possible but after seeing Brian's comment, I searched CPAN and lo and behold, there is [Win32::Process::Memory](http://search.cpan.org/perldoc/Win32::Process::Memory): ``` C:\> ppm install Win32::Process::Info C:\> ppm install Win32::Process::Memory ``` The module apparently uses the [`ReadProcessMemory`](http://msdn.microsoft.com/en-us/library/ms680553.aspx) function: Here is one of my attempts: ``` #!/usr/bin/perl use strict; use warnings; use Win32; use Win32::Process; use Win32::Process::Memory; my $process; Win32::Process::Create( $process, 'C:/opt/vim/vim72/gvim.exe', q{}, 0, NORMAL_PRIORITY_CLASS, q{.} ) or die ErrorReport(); my $mem = Win32::Process::Memory->new({ pid => $process->GetProcessID(), access => 'read/query', }); $mem->search_sub( 'VIM', sub { print $mem->hexdump($_[0], 0x20), "\n"; }); sub ErrorReport{ Win32::FormatMessage( Win32::GetLastError() ); } END { $process->Kill(0) if $process } ``` Output: ``` C:\Temp> proc 0052A580 : 56 49 4D 20 2D 20 56 69 20 49 4D 70 72 6F 76 65 : VIM - Vi IMprove 0052A590 : 64 20 37 2E 32 20 28 32 30 30 38 20 41 75 67 20 : d 7.2 (2008 Aug 0052A5F0 : 56 49 4D 52 55 4E 54 49 4D 45 3A 20 22 00 : VIMRUNTIME: ". 0052A600 : 20 20 66 61 6C 6C 2D 62 61 63 6B 20 66 6F 72 20 : fall-back for 0052A610 : 24 56 : $V ```
It is possible to do so if you have attached your program as a debugger to the process, which should be possible in those languages if wrappers around the appropriate APIs exist, or by directly accessing the windows functions through something like ctypes (for python). However, it may be easier to do in a more low-level language, since in higher level ones you'll have to be concerned with how to translate highlevel datatypes to lower ones etc. Start by calling [OpenProcess](http://msdn.microsoft.com/en-us/library/ms684320(VS.85).aspx) on the process to debug, with the appropriate access requested (you'll need to be an Admin on the machine / have fairly high privileges to gain access). You should then be able to call functions like [ReadProcessMemory](http://msdn.microsoft.com/en-us/library/ms680553(VS.85).aspx) and [WriteProcessMemory](http://msdn.microsoft.com/en-us/library/ms681674(VS.85).aspx) to read from and write to that process's memory. **[Edit]** Here's a quick python proof of concept of a function that successfully reads memory from another process's address space: ``` import ctypes import ctypes.wintypes kernel32 = ctypes.wintypes.windll.kernel32 # Various access flag definitions: class Access: DELETE = 0x00010000 READ_CONTROL= 0x00020000 SYNCHRONIZE = 0x00100000 WRITE_DAC = 0x00040000 WRITE_OWNER = 0x00080000 PROCESS_VM_WRITE = 0x0020 PROCESS_VM_READ = 0x0010 PROCESS_VM_OPERATION = 0x0008 PROCESS_TERMINATE = 0x0001 PROCESS_SUSPEND_RESUME = 0x0800 PROCESS_SET_QUOTA = 0x0100 PROCESS_SET_INFORMATION = 0x0200 PROCESS_QUERY_LIMITED_INFORMATION = 0x1000 PROCESS_QUERY_INFORMATION = 0x0400 PROCESS_DUP_HANDLE = 0x0040 PROCESS_CREATE_THREAD = 0x0002 PROCESS_CREATE_PROCESS = 0x0080 def read_process_mem(pid, address, size): """Read memory of the specified process ID.""" buf = ctypes.create_string_buffer(size) gotBytes = ctypes.c_ulong(0) h = kernel32.OpenProcess(Access.PROCESS_VM_READ, False, pid) try: if kernel32.ReadProcessMemory(h, address, buf, size, ctypes.byref(gotBytes)): return buf else: # TODO: report appropriate error GetLastError raise Exception("Failed to access process memory.") finally: kernel32.CloseHandle(h) ``` Note that you'll need to determine where in memory to look for things - most of that address space is going to be unmapped, thought there are some standard offsets to look for things like the program code, dlls etc.
How to write a Perl, Python, or Ruby program to change the memory of another process on Windows?
[ "", "python", "ruby", "perl", "winapi", "readprocessmemory", "" ]
I came across some Java code that had the following structure: ``` public MyParameterizedFunction(String param1, int param2) { this(param1, param2, false); } public MyParameterizedFunction(String param1, int param2, boolean param3) { //use all three parameters here } ``` I know that in C++ I can assign a parameter a default value. For example: ``` void MyParameterizedFunction(String param1, int param2, bool param3=false); ``` Does Java support this kind of syntax? Are there any reasons why this two step syntax is preferable?
No, the structure you found is how Java handles it, (that is, with overloading instead of default parameters). For constructors, *[**See Effective Java: Programming Language Guide's**](https://en.wikipedia.org/wiki/Joshua_Bloch#Bibliography)* Item 1 tip (Consider static factory methods instead of constructors) if the overloading is getting complicated. For other methods, renaming some cases or using a parameter object can help. This is when you have enough complexity that differentiating is difficult. A definite case is where you have to differentiate using the order of parameters, not just number and type.
No, but you can use the [Builder Pattern](http://en.wikipedia.org/wiki/Builder_pattern), as described in [this Stack Overflow answer](https://stackoverflow.com/questions/222214/managing-constructors-with-many-parameters-in-java-1-4/222295#222295). As described in the linked answer, the Builder Pattern lets you write code like ``` Student s1 = new StudentBuilder().name("Eli").buildStudent(); Student s2 = new StudentBuilder() .name("Spicoli") .age(16) .motto("Aloha, Mr Hand") .buildStudent(); ``` in which some fields can have default values or otherwise be optional.
Does Java support default parameter values?
[ "", "java", "methods", "parameters", "overloading", "default-parameters", "" ]
We have a postgres DB with postgres enums. We are starting to build JPA into our application. We also have Java enums which mirror the postgres enums. Now the big question is how to get JPA to understand Java enums on one side and postgres enums on the other? The Java side should be fairly easy but I'm not sure how to do the postgres side.
This involves making multiple mappings. First, a Postgres enum is returned by the JDBC driver as an instance of type PGObject. The type property of this has the name of your postgres enum, and the value property its value. (The ordinal is not stored however, so technically it's not an enum anymore and possibly completely useless because of this) Anyway, if you have a definition like this in Postgres: ``` CREATE TYPE mood AS ENUM ('sad', 'ok', 'happy'); ``` Then the resultset will contain a PGObject with type "mood" and value "happy" for a column having this enum type and a row with the value 'happy'. Next thing to do is writing some interceptor code that sits between the spot where JPA reads from the raw resultset and sets the value on your entity. E.g. suppose you had the following entity in Java: ``` public @Entity class Person { public static enum Mood {sad, ok, happy} @Id Long ID; Mood mood; } ``` Unfortunately, JPA does not offer an easy interception point where you can do the conversion from PGObject to the Java enum Mood. Most JPA vendors however have some proprietary support for this. Hibernate for instance has the TypeDef and Type annotations for this (from Hibernate-annotations.jar). ``` @TypeDef(name="myEnumConverter", typeClass=MyEnumConverter.class) public @Entity class Person { public static enum Mood {sad, ok, happy} @Id Long ID; @Type(type="myEnumConverter") Mood mood; ``` These allow you to supply an instance of UserType (from Hibernate-core.jar) that does the actual conversion: ``` public class MyEnumConverter implements UserType { private static final int[] SQL_TYPES = new int[]{Types.OTHER}; public Object nullSafeGet(ResultSet arg0, String[] arg1, Object arg2) throws HibernateException, SQLException { Object pgObject = arg0.getObject(X); // X is the column containing the enum try { Method valueMethod = pgObject.getClass().getMethod("getValue"); String value = (String)valueMethod.invoke(pgObject); return Mood.valueOf(value); } catch (Exception e) { e.printStackTrace(); } return null; } public int[] sqlTypes() { return SQL_TYPES; } // Rest of methods omitted } ``` This is not a complete working solution, but just a quick pointer in hopefully the right direction.
I've actually been using a simpler way than the one with PGObject and Converters. Since in Postgres enums are converted quite naturally to-from text you just need to let it do what it does best. I'll borrow Arjan's example of moods, if he doesn't mind: The enum type in Postgres: ``` CREATE TYPE mood AS ENUM ('sad', 'ok', 'happy'); ``` The class and enum in Java: ``` public @Entity class Person { public static enum Mood {sad, ok, happy}; @Enumerated(EnumType.STRING) Mood mood; ``` } That @Enumerated tag says that serialization/deserialization of the enum should be done in text. Without it, it uses int, which is more troublesome than anything. At this point you have two options. You either: 1. Add *stringtype=unspecified* to the connection string, as explained in [JDBC connection parameters](https://jdbc.postgresql.org/documentation/94/connect.html).This lets Postgres guess the right-side type and convert everything adequately, since it receives something like 'enum = unknown', which is an expression it already knows what to do with (feed the ? value to the left-hand type deserialiser). **This is the preferred option,** as it should work for all simple UDTs such as enums in one go. ``` jdbc:postgresql://localhost:5432/dbname?stringtype=unspecified ``` Or: 2. Create an implicit conversion from varchar to the enum in the database. So in this second case the database receives some assignment or comparison like 'enum = varchar' and it finds a rule in its internal catalog saying that it can pass the right-hand value through the serialization function of varchar followed by the deserialization function of the enum. That's more steps than should be needed; and having too many implicit casts in the catalog can cause arbitrary queries to have ambiguous interpretations, so use it sparingly. The cast creation is: CREATE CAST (CHARACTER VARYING as mood) WITH INOUT AS IMPLICIT; Should work with just that.
Java Enums, JPA and Postgres enums - How do I make them work together?
[ "", "java", "postgresql", "jpa", "" ]
With PHP5 using "copy on write" and passing by reference causing more of a performance penalty than a gain, why should I use pass-by-reference? Other than call-back functions that would return more than one value or classes who's attributes you want to be alterable without calling a set function later(bad practice, I know), is there a use for it that I am missing?
You use pass-by-reference when you want to modify the result and that's all there is to it. Remember as well that in PHP objects are **always** pass-by-reference. Personally I find PHP's system of copying values implicitly (I guess to defend against accidental modification) cumbersome and unintuitive but then again I started in strongly typed languages, which probably explains that. But I find it interesting that objects differ from PHP's normal operation and I take it as evidence that PHP"s implicit copying mechanism really isn't a good system.
A recursive function that fills an array? Remember writing something like that, once. There's no point in having hundreds of copies of a partially filled array and copying, splicing and joining parts at every turn.
Is there a need to pass variable by reference in php5?
[ "", "php", "pass-by-reference", "" ]
so let's say i'm building this contact management system. There is a USER table and a CONTACT\_INFO table. For every USER, I can have zero or more CONTACT\_INFO records. The way I've defined it, I've setup a foreign key in my CONTACT\_INFO table to point to the relevant USER record. I would like do a search for all the USER records that do not have CONTACT\_INFO records. I expect that this could be done: ``` SELECT * FROM user u WHERE u.user_id NOT IN (SELECT DISTINCT c.user_id FROM CONTACT_INFO); ``` My concern is that as the tables grow, this query's performance can degrade significantly. One idea I'm playing with is to add a column in the USER table that says if it has any CONTACT\_INFO records or not. Also, I was wondering, if upon inserting any record into CONTACT\_INFO, the DBMS has to verify that the record exists, it would already be accessing that record for the sake of verification and so updating it, when I update a CONTACT\_INFO record should not be that costly, performance-wise. As always, feedback is appreciated.
From my tests, the following is faster than BradC's method: ``` select (...) from user u where not exists (select null from CONTACT_INFO c where u.user_id = c.user_id) ``` This may be because the compiler does have to do the conversion itself, I don't know. Le Dorfier is correct in principle, though: if you have set up your indexes right on the database (i.e. both user\_id columns should be indexed), both your answer and most of these responses here will be extremely fast, regardless of how many records you have in your database. Incidentally, if you're looking for a way to get a query that lists users along with a "HasContactInfo" boolean value, you could do something like this: ``` select u.(...), (case when exists (select null from CONTACT_INFO c where c.user_id = u.user_id) then 1 else null end) has_contact_info from user u ``` This second solution may not be useful in your case, but I found it to be much faster than some simpler queries that I had assumed would get optimized automatically.
Easiest way is: ``` SELECT (...) FROM user u LEFT OUTER JOIN CONTACT_INFO c ON u.user_id = c.user_id WHERE c.user_id IS NULL ``` It looks more unwieldy, but should scale better.
Create optimum query to find records that are in only one table
[ "", "sql", "query-optimization", "" ]
How to get last 30 / 60 / 90 days records from given date in java? I have some records with receivedDate. I want to fetch the records for last 30 or 60 or 90 days from received Date. How to resolve it?
Use [java.util.Calendar](http://java.sun.com/j2se/1.5.0/docs/api/java/util/Calendar.html). ``` Date today = new Date(); Calendar cal = new GregorianCalendar(); cal.setTime(today); cal.add(Calendar.DAY_OF_MONTH, -30); Date today30 = cal.getTime(); cal.add(Calendar.DAY_OF_MONTH, -60); Date today60 = cal.getTime(); cal.add(Calendar.DAY_OF_MONTH, -90); Date today90 = cal.getTime(); ```
# tl;dr ``` LocalDate // Represent a date-only value, without time-of-day and without time zone. .now( // Capture today's date as seen in the wall-clock time used by the people of a particular region (a time zone). ZoneId.of( "Asia/Tokyo" ) // Specify the desired/expected zone. ) // Returns a `LocalDate` object. .minus( // Subtract a span-of-time. Period.ofDays( 30 ) // Represent a span-of-time unattached to the timeline in terms of years-months-days. ) // Returns another `LocalDate` object. ``` # Avoid legacy date-time classes The bundled java.util.Date & .Calendar group of classes are notoriously troublesome. Avoid them. # *java.time* The modern approach uses the *java.time* classes built into Java 8 and later, and back-ported to Java 6 & 7. ## `LocalDate` The [`LocalDate`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/time/LocalDate.html) class represents a date-only value without time-of-day and without [time zone](https://en.wikipedia.org/wiki/Time_zone) or [offset-from-UTC](https://en.wikipedia.org/wiki/UTC_offset). A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in [Paris France](https://en.wikipedia.org/wiki/Europe/Paris) is a new day while still “yesterday” in [Montréal Québec](https://en.wikipedia.org/wiki/America/Montreal). If no time zone is specified, the JVM implicitly applies its current default time zone. That default may [change at any moment](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/TimeZone.html#setDefault(java.util.TimeZone)) during runtime(!), so your results may vary. Better to specify your desired/expected time zone explicitly as an argument. If critical, confirm the zone with your user. Specify a [proper time zone name](https://en.wikipedia.org/wiki/List_of_tz_zones_by_name) in the format of `Continent/Region`, such as `America/Montreal`, `Africa/Casablanca`, or `Pacific/Auckland`. Never use the 2-4 letter abbreviation such as `EST` or `IST` as they are *not* true time zones, not standardized, and not even unique(!). ``` ZoneId z = ZoneId.of( "America/Montreal" ) ; LocalDate today = LocalDate.now( z ) ; ``` If you want to use the JVM’s current default time zone, ask for it and pass as an argument. If omitted, the code becomes ambiguous to read in that we do not know for certain if you intended to use the default or if you, like so many programmers, were unaware of the issue. ``` ZoneId z = ZoneId.systemDefault() ; // Get JVM’s current default time zone. ``` Or specify a date. You may set the month by a number, with sane numbering 1-12 for January-December. ``` LocalDate ld = LocalDate.of( 1986 , 2 , 23 ) ; // Years use sane direct numbering (1986 means year 1986). Months use sane numbering, 1-12 for January-December. ``` Or, better, use the [`Month`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/time/Month.html) enum objects pre-defined, one for each month of the year. Tip: Use these `Month` objects throughout your codebase rather than a mere integer number to make your code more self-documenting, ensure valid values, and provide [type-safety](https://en.wikipedia.org/wiki/Type_safety). Ditto for [`Year`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/time/Year.html) & [`YearMonth`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/time/YearMonth.html). ``` LocalDate ld = LocalDate.of( 1986 , Month.FEBRUARY , 23 ) ; ``` ## Date math You can define a span-of-time in terms of years-months-days with the `Period` class. ``` Period days_30 = Period.ofDays( 30 ) ; Period days_60 = Period.ofDays( 60 ) ; Period days_90 = Period.ofDays( 90 ) ; ``` You can add and subtract a `Period` to/from a `LocalDate`, resulting in another `LocalDate` object. Call the [`LocalDate::plus`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/time/LocalDate.html#plus(java.time.temporal.TemporalAmount)) or [`LocalDate::minus`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/time/LocalDate.html#minus(java.time.temporal.TemporalAmount)) methods. ``` ZoneId z = ZoneId.of( "Africa/Tunis" ) ; LocalDate today = LocalDate.now( z ) ; LocalDate ago_30 = today.minus( days_30 ) ; LocalDate ago_60 = today.minus( days_60 ) ; LocalDate ago_90 = today.minus( days_90 ) ; ``` You more directly call `LocalDate.minusDays`, but I suspect the named `Period` objects will make your code more readable and self-documenting. ``` LocalDate ago = today.minusDays( 30 ) ; ``` ## JDBC Sounds like you are querying a database. As of JDBC 4.2 and later, you can exchange *java.time* objects with your database. For a database column of a data type akin to the SQL-standard standard `DATE` (a date-only value, without time-of-day and without time zone), use `LocalDate` class in Java. ``` myPreparedStatement.setObject( … , ago_30 ) ; ``` Retrieval: ``` LocalDate ld = myResultSet.getObject( … , LocalDate.class ) ; ``` --- # About *java.time* The [*java.time*](http://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) framework is built into Java 8 and later. These classes supplant the troublesome old [legacy](https://en.wikipedia.org/wiki/Legacy_system) date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/10/docs/api/java/util/Date.html), [`Calendar`](https://docs.oracle.com/javase/10/docs/api/java/util/Calendar.html), & [`SimpleDateFormat`](http://docs.oracle.com/javase/10/docs/api/java/text/SimpleDateFormat.html). To learn more, see the [*Oracle Tutorial*](http://docs.oracle.com/javase/tutorial/datetime/TOC.html). And search Stack Overflow for many examples and explanations. Specification is [JSR 310](https://jcp.org/en/jsr/detail?id=310). The [*Joda-Time*](http://www.joda.org/joda-time/) project, now in [maintenance mode](https://en.wikipedia.org/wiki/Maintenance_mode), advises migration to the [java.time](http://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes. You may exchange *java.time* objects directly with your database. Use a [JDBC driver](https://en.wikipedia.org/wiki/JDBC_driver) compliant with [JDBC 4.2](http://openjdk.java.net/jeps/170) or later. No need for strings, no need for `java.sql.*` classes. Where to obtain the java.time classes? * [**Java SE 8**](https://en.wikipedia.org/wiki/Java_version_history#Java_SE_8), [**Java SE 9**](https://en.wikipedia.org/wiki/Java_version_history#Java_SE_9), [**Java SE 10**](https://en.wikipedia.org/wiki/Java_version_history#Java_SE_10), [**Java SE 11**](https://en.wikipedia.org/wiki/Java_version_history#Java_SE_11), and later - Part of the standard Java API with a bundled implementation. + Java 9 adds some minor features and fixes. * [**Java SE 6**](https://en.wikipedia.org/wiki/Java_version_history#Java_SE_6) and [**Java SE 7**](https://en.wikipedia.org/wiki/Java_version_history#Java_SE_7) + Most of the *java.time* functionality is back-ported to Java 6 & 7 in [***ThreeTen-Backport***](http://www.threeten.org/threetenbp/). * [**Android**](https://en.wikipedia.org/wiki/Android_(operating_system)) + Later versions of Android bundle implementations of the *java.time* classes. + For earlier Android (<26), the [***ThreeTenABP***](https://github.com/JakeWharton/ThreeTenABP) project adapts [***ThreeTen-Backport***](http://www.threeten.org/threetenbp/) (mentioned above). See [*How to use ThreeTenABP…*](http://stackoverflow.com/q/38922754/642706). The [**ThreeTen-Extra**](http://www.threeten.org/threeten-extra/) project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as [`Interval`](http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/Interval.html), [`YearWeek`](http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/YearWeek.html), [`YearQuarter`](http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/YearQuarter.html), and [more](http://www.threeten.org/threeten-extra/apidocs/index.html). --- # *Joda-Time* **UPDATE:** The Joda-Time library is now in maintenance-mode. Its creator, Stephen Colebourne, went on to lead the JSR 310 and *java.time* implementation based on lessons learned with Joda-Time. I leave this section intact as history, but advise using *java.time* instead. Here is some example code using the [Joda-Time](http://www.joda.org/joda-time/) 2.3 library’s [LocalDate](http://www.joda.org/joda-time/apidocs/org/joda/time/LocalDate.html) class. ``` LocalDate now = LocalDate.now(); LocalDate thirty = now.minusDays( 30 ); LocalDate sixty = now.minusDays( 60 ); LocalDate ninety = now.minusDays( 90 ); ``` Dump to console… ``` System.out.println( "now: " + now ); System.out.println( "thirty: " + thirty ); System.out.println( "sixty: " + sixty ); System.out.println( "ninety: " + ninety ); ``` When run… ``` now: 2014-03-26 thirty: 2014-02-24 sixty: 2014-01-25 ninety: 2013-12-26 ``` ## Time Zone The beginning and ending of a day depends on your time zone. A new day dawns in Paris earlier than in Montréal. By default, the LocalDate class uses your JVM's default time zone to determine the current date. Alternatively, you may pass a DateTimeZone object. ``` LocalDate localDate = new LocalDate( DateTimeZone.forID( "Europe/Paris" ) ); ```
Find out Last 30 Days, 60 Days and 90 Days in java
[ "", "java", "date", "" ]
I have written earlier in C/C++ but currently, I need it to convert into C#. Can anyone tell me the code/way How to write drivers in C#? Actually currently I have some problems with my old application written in C++ and we have to write the drivers of our LPT1,COM Printers and other USB drivers in C#.
Simply you can't. C# produces intermediate language that is interpreted by a virtual machine (.NET). All these stuff runs in user mode and WDM drivers run in kernel mode. There is a DDK but it is not supported in VStudio either (but you can make a makefile project for compilation though). Driver development is complex, prone to blue screen and requires a good understanding of C , kernel structures and mem manipulation. None of those skills are required for C# and .NET therefore there is a long and painful training path.
Actually, you can write some drivers in C# if you use UMDF because it runs in usermode (see [Getting Started with UMDF](http://msdn.microsoft.com/en-us/library/windows/hardware/dn384105(v=vs.85).aspx)). But my recommendation is to use C/C++.
Writing drivers in C#
[ "", "c#", "driver", "drivers", "" ]
When declaring primitives does it matter if I use the assignment operator or copy constructor? Which one gives the optimal performance, or do most compilers today compile these two statements to the same machine code? ``` int i = 1; int j( 1 ); ```
Same for: ``` int i = 1; int j( 1 ); ``` Not for: ``` Cat d; Cat c1; c1 = d; Cat c2(d);//<-- more efficient ```
I'm fairly certain that they are the same, however if you do a static initialization, there is no initialization during runtime, the value is built into the binary. ``` static int i = 1; ``` Though, this isn't always appropriate, given the meaning of the keyword static.
Which is more efficient when initializing a primitive type?
[ "", "c++", "performance", "" ]
Is it possible to create a C# EXE or Windows Service that can process Web Service requests? Obviously, some sort of embedded, probably limited, web server would have to be part of the EXE/service. The EXE/service would not have to rely on IIS being installed. Preferably, the embedded web service could handle HTTPS/SSL type connections. The scenario is this: customer wants to install a small agent (a windows service) on their corporate machines. The agent would have two primary tasks: 1) monitor the system over time and gather certain pieces of data and 2) respond to web service requests (SOAP -v- REST is still be haggled about) for data gathering or system change purposes. The customer likes the idea of web service APIs so that any number of clients (in any language) can be written to tap into the various agents running on the corporate machines. They want the installation to be relatively painless (install .NET, some assemblies, a service, modify the Windows firewall, start the service) without requiring IIS to be installed and configured. I know that I can do this with Delphi. But the customer would prefer to have this done in C# if possible. Any suggestions?
Yes, it's possible, you may want to have a look at [WCF](http://msdn.microsoft.com/en-us/netframework/aa663324.aspx) and [Self Hosting](http://msdn.microsoft.com/en-us/library/bb332338.aspx).
Yes, it is possible (and fairly easy). Here is a [CodeProject article](http://www.codeproject.com/KB/IP/CSHTTPServer.aspx) showing how to make a basic HTTP server in C#. This could easily be put in a standalone EXE or service, and used as a web service.
Is it possible to create a standalone, C# web service deployed as an EXE or Windows service?
[ "", "c#", "web-services", "windows-services", "embeddedwebserver", "" ]
Thanks for the input on [this question](https://stackoverflow.com/questions/975545/if-create-cant-instantiate-should-it-return-empty-object-null-or-throw-an), I've decided to go with making my Create() method **throw exceptions** so as Jon Skeet said, you don't have to handle them everywhere and can just let them bubble up, seems the best approach for larger applications. So now I create instances of my classes with this code: ``` try { SmartForms smartForms = SmartForms.Create("ball"); smartForms.Show(); } catch (CannotInstantiateException ex) { Console.WriteLine("Item could not be instantiated: {0}", ex.Message); } ``` custom exception: ``` using System; namespace TestFactory234.Exceptions { class CannotInstantiateException : Exception { } } ``` **How do I know which Exception class to use?** In the above instance, I created my own Exception since I don't know where to get a list of "all system exceptions" or if there is one for "not being able to instantiate an object" yet or if it has some other meaning to use it, etc. Choosing an exception type to me has always seems such an **arbitrary** process, so creating my own seems to be the best idea in general. **Or am I missing something about exceptions? What other implications involved in deciding which Exception type to use?**
If the reason you can't create the object is because the argument to Create was invalid, you should probably throw an `ArgumentException`. However, you could always create our own class derived from `ArgumentException` if you really want to be able to handle that kind of exception separately to others. (Are you sure you want to?)
[Why Create Custom Exceptions?](https://stackoverflow.com/questions/417428/why-create-custom-exceptions) explains in pretty good detail why and when to use the custom exceptions.
How to know when to use an existing Exception or write a custom Exception?
[ "", "c#", "exception", "custom-exceptions", "" ]
I have several classes (A, B, C, ...) that all use a `List<AnotherClass>` to store references to 'other' objects. But 'other' is different for each of the classes A, B, C. So Class A contains `List<Class_X>` Class B contains `List<Class_Y>` Class C contains `List<Class_Z>` Instead of implementing Add / Delete / Search (etc) functions in A, B, C it seems logical to me to create a class `ListRef<T>` from `List<T>` ``` public class ListRef<T>: List<T> { protected ListRef<T> ListOfObjects = null; protected string name = null; public ListRef<T> { ListOfObjects = new ListRef<T>(); } } ``` Using the code above (is this the right code for what I want?) I don't know how I can supply the right class (Class\_X, Class\_Y, Class\_Z) replacing/specifying `<T>` in the constructor of each class (A, B, C) that will use ListRef. In the constructor of class A I would like to write something like: ``` public A() : base<Class_X> { } ``` How can I specify from WITHIN class A what kind of objects need to be stored in ListOfObjects? I prefer NOT to write ``` public A() { ListOfObjects = new ListRef<Class_X(); } ``` as I would like to have ListOfObjects declared **private** instead of **protected** --- Inside Listref I JUST want to be able to Add, Delete, Search objects. So I'm not actually using those classes (Class\_X, Class\_Y, Class\_Z). currently I have ``` public class A { private List<Class_X> ListOfObjects = null; A() { ListOfObjects = new List<Class_X>(); } public void Add(string Name) { Class_X Object = new Class_X(Name); ListOfObjects.Add(Object); } public void Delete(Class_X Object) { ListOfObjects.Remove(Object); } } ``` and the same kind of code for class B (using Class\_Y) and for class C (using class\_Z). To me it seems logical to use ONE class ListRef to perform the Add and Delete operations and maintain the list for all classes I use. (of course the real code is more complicated)
If I understand you question correctly, it sounds like what you want to do is create a group of classes A, B, C, etc.. that each manage a collection of some other type (X, Y, Z) - but you don't want to duplicate some of the list management logic across A, B, and C. There are two different ways to achieve this. **First, the inheritance approach:** you could give A, B, and C a common generic base class that is parameterized on the type of the item each will manage. Here's a code example: ``` public abstract class ABCBase<T> { protected IList<T> m_List = new List<T>(); // methods that manage the collection // I chose to make the virtual so that derived // classes could alter then behavior - may not be needed public virtual void Add( T item ) { ... } public virtual void Remove( T item ) { ... } public virtual int Find( T item ) { ... } } public class A : ABCBase<X> { ... } public class B : ABCBase<Y> { ... } public class C : ABCBase<Z> { ... } ``` **Second, is the composition approach:** create a manager class for your colleciton that implements the operations on the child list, and aggregate that in each of A, B, and C: ``` public class ListManager<T> { private IList<T> m_List = new List<T>(); public void Add( T item ) { ... } public void Remove( T item ) { ... } public int Find( T item ) { ... } } public class A { public ListManager<X> ListOfX { get; protected set; } public A() { ListOfX = new ListManager<X>(); } } public class B { public ListManager<Y> ListOfX { get; protected set; } public B() { ListOfY = new ListManager<Y>(); } } public class C { public ListManager<Z> ListOfX { get; protected set; } public C() { ListOfX = new ListManager<Z>(); } } ``` **You could also choose to mix both of these approaches -** creating a list management class but also creating base class (or interface) for A, B, C - so that each exposes a consistent property ChildList (or some such) that consumers could use without always having to know the type actual types A, B, C.
Here is how I would recommend doing it... ``` public class ABC_Base<TChild> { public IEnumberable<TChild> Children { get; set; } public void AddChild(TChild item) { } public void RemoveChild(TChild item) { } //etc } public class A : ABC_Base<X> // X is the type for your child { } //Used like so... A myA = new A(); myA.AddChild(new X()); // or if you are wanting to specify when created then this... public class A<TChild> : ABC_Base<TChild> { } //Used like so... A myA = new A<X>(); A myOtherA = new A<Y>(); myA.Addchild(new X()); myOtherA.AddChild(new Y()); ```
Handling objects of different classes in a derived List<T> class
[ "", "c#", "" ]
What are the different ways of implementing multilingual support in Swing applications? Are you using ResourceBundle with property file and implementing it in every frame? Does it work good for you? What if you use some kind of GUI editor? Is there any other way around? At work we are using Matisse4MyEclipse and the code gets regenerated every time we save the screen, so simply using Externalize Strings won't work here. One way is to define it as custom property for each component, which is very annoying. Another way is to go over the multilanguage components and their properties again after matisse's generated code, which is a pain, too.
Well, you had to use `ResourceBundle`s. But if you are setting the componet text property use instead of human readable text the text for `RB.getString()`. Then if the Matisse regenerates form the bundle key will stay and localization will work. Example: I will use this image from Matisse pages: [![Illustration](https://i.stack.imgur.com/cA94I.gif)](https://i.stack.imgur.com/cA94I.gif) (source: [myeclipseide.com](http://www.myeclipseide.com/documentation/quickstarts/m4m_overview/images/properties_view1.gif)) . there you can see the the property **text**. There is value "My New Label". Instead of this you can use `rb.getString("myNewLabel.my.message")` where `rb` is `ResourceBundle`. The only problem should be too intelligent properties editor going against you. I never work with any wysiwyg editor (personal preference, I do always UI design by hand).
This is how I implemented the internationalization : * give a name to every component which has an internationalized text * at runtime, take the container(frame, dialog, applet) ,iterate all the components and build an i18n key for every component using its name and all parent names. * for every component type(JTextField, JLable, etc) define some keys for every internationalize field(text, label, hint, etc). * take this i18n key and query your ResourceBundle, take the results and populate the component fields. It works with generated code or with manual created code. Edit: Here it is : ``` public void buildIds() { buildId(true); int count = getComponentCount(); if (count == 0) { return; } for (int i = 0; i < count; i++) { Component component = getComponent(i); if (component instanceof AbstractComponent) { ((AbstractComponent) component).buildIds(); } } } protected void buildId(boolean fireChange) { String prevId = this.id; String computedId; if (getName() == null) { computedId = ClassUtilities.shortClassName(getClass()).toLowerCase() + "_" + Long.toHexString(ID_GENERATOR.getAndIncrement()); } else { java.util.List<Component> parents = null; Component parent = getParent(); if (parent != null) { StringBuilder buider = new StringBuilder(80); parents = new ArrayList<Component>(); while (parent != null) { if (parent.getName() != null) { parents.add(parent); } parent = parent.getParent(); } Collections.reverse(parents); if (parents.size() > 0) { for (Component component : parents) { if (buider.length() > 0) { buider.append('.'); } buider.append(component.getName()); } buider.append('.'); } buider.append(name); computedId = buider.toString().toLowerCase(); } else { computedId = name; } } this.id = computedId; if (fireChange && prevId != null && !prevId.equals(computedId)) { componentIdChanged(this, prevId); } } ```
How to implement multilanguage in Java/Swing applications?
[ "", "java", "swing", "internationalization", "multilingual", "" ]
Ok first of all I like to mention what im doing is completely ethical and yes I am port scanning. The program runs fine when the port is open but when I get to a closed socket the program halts for a very long time because there is no time-out clause. Below is the following code ``` int main(){ int err, net; struct hostent *host; struct sockaddr_in sa; sa.sin_family = AF_INET; sa.sin_port = htons(xxxx); sa.sin_addr.s_addr = inet_addr("xxx.xxx.xxx.xxx"); net = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); err = connect(net, (struct sockaddr *)&sa, sizeof(sa)); if(err >= 0){ cout << "Port is Open"; } else { cout << "Port is Closed"; } } ``` I found this on stack overflow but it just doesn't make sense to me using a [select()](https://stackoverflow.com/questions/284748/tuning-socket-connect-call-timeout) command. Question is can we make the connect() function timeout so we dont wait a year for it to come back with an error?
The easiest is to setup an `alarm` and have `connect` be interrupted with a signal (see [UNP](http://www.kohala.com/start/unpv12e.html) 14.2): ``` signal( SIGALRM, connect_alarm ); /* connect_alarm is you signal handler */ alarm( secs ); /* secs is your timeout in seconds */ if ( connect( fs, addr, addrlen ) < 0 ) { if ( errno == EINTR ) /* timeout */ ... } alarm( 0 ); /* cancel alarm */ ``` Though using `select` is not much harder :) You might want to learn about [raw sockets](http://mixter.void.ru/rawip.html) too.
If you're dead-set on using blocking IO to get this done, you should investigate the setsockopt() call, specifically the SO\_SNDTIMEO flag (or other flags, depending on your OS). Be forewarned these flags are not reliable/portable and may be implemented differently on different platforms or different versions of a given platform. The traditional/best way to do this is via the nonblocking approach which uses select(). In the event you're new to sockets, one of the very best books is TCP/IP Illustrated, Volume 1: The Protocols. It's at Amazon at: [http://www.amazon.com/TCP-Illustrated-Protocols-Addison-Wesley-Professional/dp/0201633469](https://rads.stackoverflow.com/amzn/click/com/0201633469)
Socket Timeout in C++ Linux
[ "", "c++", "linux", "sockets", "timeout", "" ]
I've got a bunch of tables that I'm joining using a unique item id. The majority of the where clause conditions will be built programatically from a user sumbitted form (search box) and multiple conditions will often be tested against the same table, in this case item tags. My experience with SQL is minimal, but I understand the basics. I want to find the ids of active (status=1) items that have been tagged with a tag of a certain type, with the values "cats" and "kittens". Tags are stored as (id, product\_id, tag\_type\_id, value), with id being the only column requiring a unique value. My first attempt was; ``` select distinct p2c.product_id from '.TABLE_PRODUCT_TO_CATEGORY.' p2c inner join '.TABLE_PRODUCT.' p on p2c.product_id = p.id inner join '.TABLE_PRODUCT_TAG.' pt on p.id = pt.product_id inner join '.TABLE_TAG_TYPE.' tt on pt.tag_type_id = tt.id where tt.id = '.PRODUCT_TAG_TYPE_FREE_TAG.' and p.status = 1 and lower(pt.value) = "cats" and lower(pt.value) = "kittens" ``` but that returned nothing. I realised that the final AND condition was the problem, so tried using a self-join instead; ``` select distinct p2c.product_id from '.TABLE_PRODUCT_TO_CATEGORY.' p2c inner join '.TABLE_PRODUCT.' p on p2c.product_id = p.id inner join '.TABLE_PRODUCT_TAG.' pt on p.id = pt.product_id inner join '.TABLE_PRODUCT_TAG.' pt2 on p.id = pt2.product_id inner join '.TABLE_TAG_TYPE.' tt on pt.tag_type_id = tt.id where tt.id = '.PRODUCT_TAG_TYPE_FREE_TAG.' and p.status = 1 and lower(pt.value) = "cats" and lower(pt2.value) = "kittens" ``` Now everything works as expected and the result set is correct. So what do I want to know? To re-iterate, the results I'm after are the ids of active (status = 1) items that have been tagged with a tag of a certain type, with the values "cats" AND "kittens"... 1. Are self-joins the best way of achieving these results? 2. This query has the potential to be huge (I've omitted a category condition, of which there may be ~300), so does this self-join approach scale well? If not, is there an alternative? 3. Will the self-join approach be the best way forward (assuming there is an alternative) if I allow users to specify complex tag searches? ie "cats" and ("kittens" or "dogs") not "parrots".
The problem with the initial query was this: ``` and lower(pt.value) = "cats" and lower(pt.value) = "kittens" ``` There exists no tag for which the value is both "cats" and "kittens", therefore no records will be returned. Using an IN clause as SQLMenace suggests would be the solution - that way you're saying, "give me back any active item that has been tagged 'cats' or 'kittens'". But if you want any active item that has BOTH tags - then you need to do something like your second query. It's not perfectly clear from your question if that's what you're after. For something like your Question #3: > "cats" and ("kittens" or "dogs") not "parrots". you would want pt1, pt2, and (in a subquery) pt3, and something like this: ``` and lower(pt1.value) = "cats" and lower(pt2.value) in ("kittens", "dogs") and not exists (select * from '.TABLE_PRODUCT_TAG.' pt3 where pt3.product_id = p.id and lower(pt3.value) = "parrots") ``` The broadly general case could get quite messy...
wouldn't this work in your first query? instead of ``` and lower(pt.value) = "cats" and lower(pt.value) = "kittens" ``` do this ``` and lower(pt.value) in ("cats","kittens") ```
multiple table select using many where clauses, is there a better way than self-join?
[ "", "sql", "mysql", "database", "" ]
The twitter API site lists 4 java twitter libraries. * [Twitter4j](https://github.com/yusuke/twitter4j) * [java-twitter](http://code.google.com/p/java-twitter/) * [jtwitter](http://www.winterwell.com/software/jtwitter.php) * [twittered](https://github.com/redouane59/twittered) Do you know others? What are your experiences in support, ease of use, stability, community, etc.
I think Twitter4j is good one it is most upto date API
I just took a look at them. JTwitter definitely looks like the weakest of the three. It doesn't appear to have been updated lately, doesn't cover much of the Twitter API, and doesn't appear to have any releases besides the initial one. On the upside, it's LPGL licensed, comes packaged with what little extra code it needs, and looks small and simple to understand. The other two, java-twitter and Twtter4J look much closer in quality. Both cover the core API, and both have all the accouterments of normal open-source projects: publicly available source code repository, on-line docs, active mailing lists, and recent development activity. However, Twitter4J looks to be the leader. From the docs, its API coverage appears to be more complete. The mailing list is definitely more active. The docs are much better. And most importantly to me, the releases have been more frequent. java-twitter has one release up, the "0.9-SNAPSHOT" release about 4 months ago. Twitter4J has had several releases in that time period, including 2.0.0 and incremental releases up through 2.0.8, fixing issues and adding support for new Twitter APIs. I'm going to start with Twitter4J; if you don't hear back, assume it was just great for me.
Best java twitter library?
[ "", "java", "twitter", "" ]
I am thinking of creating a debug tool for my Java application. I am wondering if it is possible to get a stack trace, just like `Exception.printStackTrace()` but without actually throwing an exception? My goal is to, in any given method, dump a stack to see who the method caller is.
You can also try `Thread.getAllStackTraces()` to get a map of stack traces for all the threads that are alive.​​​​​​
Yes, simply use ``` Thread.dumpStack() ```
Is there a way to dump a stack trace without throwing an exception in java?
[ "", "java", "debugging", "exception", "logging", "stack-trace", "" ]
I know that I can open html links in a new window by using target="\_blank", but how can I hide/disable all the browser toolbars ?
You should use `window.open('url to open','window name','toolbar=no');`
``` window.open('your url here','name','toolbar=0,status=0'); ``` With Javascript. But it's better and usable, if you create a fake window with javascript.
Open html link in new window with no browser toolbars
[ "", "javascript", "html", "" ]
I'm publishing a feed from a Django application. I subclassed django.contrib.syndication.feeds.Feed, everything works fine, except the date that doesn't get published on the feed. Here's the method I've created on my Feed class ``` def item_pubdate(self, item): return item.date ``` this method never gets called....
I've been banging my head against this one for a while. It seems that the django rss system need a "datetime" object instead of just the date (since it wants a time zone, and the date object doesn't have a time, let alone a time zone...) I might be wrong though, but it's something that I've found via the error logs.
According to the [Feed Class Reference](http://docs.djangoproject.com/en/dev/ref/contrib/syndication/#feed-class-reference) in the Django documentation, the item\_pubdate field is supposed to return a datetime.datetime object. If item.date is just a DateField and not a DateTimeField, that might be causing the problem. If that is the case you could change the method to make a datetime and then return that. ``` import datetime def item_pubdate(self, item): return datetime.datetime.combine(item.date, datetime.time()) ```
Publish feeds using Django
[ "", "python", "django", "rss", "" ]
I'm trying to use a `RefCursor` as an input parameter on an Oracle stored procedure. The idea is to select a group of records, feed them into the stored procedure and then the SP loops over the input `RefCursor`, doing some operations to its records. No, I can't select the records inside the SP and thus avoid having to use the `RefCursor` as an input type. I've found an example on how to do this on (this here would be the link, but it seems I cannot use them yet) Oracle's documentation, but it uses a simple `SELECT` to populate the input `RefCursor`; and therein lies the rub: I've got to populate it from code. You see, in code I have this: ``` [OracleDataParameter("P_INPUT", OracleDbType.RefCursor, ParameterDirection.Input)] private List<MiObject> cursor; ``` And, I've tried populating *cursor* with a `List<T>`, a `DataTable`, even an plain array of `MyObject`, and nothing works. When I try running my tests I get an error: > "Invalid Parameter Linking" Maybe not the exact wording, as I'm translating from Spanish, but that's the message Any ideas?
I'm also in contact with Mark Williams, the author of the article I've tried to link on my post, and he has kinly responded like this: " It is no problem to send me email; however, I think I will disappoint you with my answer on this one. Unfortunately you can't do what you are trying to do (create a refcursor from the client like that). A couple of problems with that are that a refcursor refers to memory owned by Oracle on the server and Oracle has no concept of client items like a DataTable or a .NET List, etc. Do you have any other options available other than using a refcursor? " So basically I'm screwed, and this question is closed. Thanks for reading and/or trying to help, you all.
From memory, isn't there an `OracleCursor` class somewhere in the ODP.NET library that works?
Using a ref cursor as input type with ODP.NET
[ "", "c#", "oracle", "odp.net", "ref-cursor", "" ]
I wrote a program to click on an application automatically at scheduled time using Win32, using `MOUSE_DOWN` and `MOUSE_UP`. It usually works well, except I found that I need to put in a ``` sleep 0.1 ``` between the `MOUSE_DOWN` and `MOUSE_UP`. (using Ruby, which allows sleeping a fraction of a second). Without the sleep, sometimes the click doesn't go through. But I noticed that sometimes, the click is "too long". The click is actually on a Flash app's Right Arrow. This right arrow will go to the next item on a list. So if you `MOUSE_DOWN` for a little longer, it actually will shift 2 or 3 items instead of just 1 item. So I wonder, is there a way to accurately simulate 1 click in this case. Probably there is no `MOUSE_CLICK` event? It has to be simulated using `MOUSE_DOWN` and `MOUSE_UP`? (it is actually called `MOUSEEVENTF_LEFTDOWN` and `MOUSEEVENTF_LEFTUP` on Win32, just for simplicity it is stated as `MOUSE_DOWN` instead.)
You do not decide what delay setting between mouse down and mouse up results in a valid single click, the operating system does. No `sleep` function can guarantee the timing between the mouse down and mouse up events you want. Perl's [Win32::GuiTest](http://search.cpan.org/~karasik/Win32-GuiTest-1.56/) module allows you to send an actual click event rather than messing with the timing of down and up events. **Later:** Looking at the source code, Win32::GuiTest seems to just fire mouse down and up events without any delay between them [see GuiTest.pm](http://cpansearch.perl.org/src/KARASIK/Win32-GuiTest-1.56/lib/Win32/GuiTest.pm): ``` elsif ( $item =~ /leftclick/i ) { SendLButtonDown (); SendLButtonUp (); } ``` In addition, <http://msdn.microsoft.com/en-us/library/ms646260(VS.85).aspx> states that `mouse_event` has been superseded by `SendInput` <http://msdn.microsoft.com/en-us/library/ms646310(VS.85).aspx> which allows you to send a `MOUSEINPUT` event with timestamps etc.
If you're not bound to a specific language you could have a look at [AutoIt](http://www.autoitscript.com/autoit3/) which is made especially for things like this. I had good experiences with it for automating things like mouseclicks or keystrokes.
How can I accurately program an automated "click" on Windows?
[ "", "python", "ruby", "perl", "winapi", "windows", "" ]
I need to turn a text into speech and then save it as wav file.
The following C# code uses the System.Speech namespace in the .Net framework. It is necessary to reference the namespace before using it, because it is not automatically referenced by Visual Studio. ``` SpeechSynthesizer ss = new SpeechSynthesizer(); ss.Volume = 100; ss.SelectVoiceByHints(VoiceGender.Female, VoiceAge.Adult); ss.SetOutputToWaveFile(@"C:\MyAudioFile.wav"); ss.Speak("Hello World"); ``` I hope this is relevant and helpful.
This is from a few moments' play, so caveat emptor. Worked well for me. I did notice that SpFileStream (which doesn't implement IDisposable, thus the try/finally) prefers absolute paths to relative. C#. ``` SpFileStream fs = null; try { SpVoice voice = new SpVoice(); fs = new SpFileStream(); fs.Open(@"c:\hello.wav", SpeechStreamFileMode.SSFMCreateForWrite, false); voice.AudioOutputStream = fs; voice.Speak("Hello world.", SpeechVoiceSpeakFlags.SVSFDefault); } finally { if (fs != null) { fs.Close(); } } ```
How to save text-to-speech as a wav with Microsoft SAPI?
[ "", "c#", "text-to-speech", "sapi", "" ]
Preemptive apologies for the nonsensical table/column names on these queries. If you've ever worked with the DB backend of Remedy, you'll understand. I'm having a problem where a Count Distinct is returning a null value, when I suspect the actual value should be somewhere in the 20's (23, I believe). Below is a series of queries and their return values. ``` SELECT count(distinct t442.c1) FROM t442, t658, t631 WHERE t442.c1 = t658.c536870930 AND t442.c200000003 = 'Network' AND t442.c536871139 < 2 AND t631.c536870913 = t442.c1 AND t658.c536870925 = 1 AND (t442.c7 = 6 OR t442.c7 = 5) AND t442.c536870954 > 1141300800 AND (t442.c240000010 = 0) ``` Result = 497. Add table t649 and make sure it has records linked back to table t442: ``` SELECT COUNT (DISTINCT t442.c1) FROM t442, t658, t631, t649 WHERE t442.c1 = t658.c536870930 AND t442.c200000003 = 'Network' AND t442.c536871139 < 2 AND t631.c536870913 = t442.c1 AND t658.c536870925 = 1 AND (t442.c7 = 6 OR t442.c7 = 5) AND t442.c536870954 > 1141300800 AND (t442.c240000010 = 0) AND t442.c1 = t649.c536870914 ``` Result = 263. Filter out records in table t649 where column c536870939 <= 1: ``` SELECT COUNT (DISTINCT t442.c1) FROM t442, t658, t631, t649 WHERE t442.c1 = t658.c536870930 AND t442.c200000003 = 'Network' AND t442.c536871139 < 2 AND t631.c536870913 = t442.c1 AND t658.c536870925 = 1 AND (t442.c7 = 6 OR t442.c7 = 5) AND t442.c536870954 > 1141300800 AND (t442.c240000010 = 0) AND t442.c1 = t649.c536870914 AND t649.c536870939 > 1 ``` Result = 24. Filter on the HAVING statement: ``` SELECT COUNT (DISTINCT t442.c1) FROM t442, t658, t631, t649 WHERE t442.c1 = t658.c536870930 AND t442.c200000003 = 'Network' AND t442.c536871139 < 2 AND t631.c536870913 = t442.c1 AND t658.c536870925 = 1 AND (t442.c7 = 6 OR t442.c7 = 5) AND t442.c536870954 > 1141300800 AND (t442.c240000010 = 0) AND t442.c1 = t649.c536870914 AND t649.c536870939 > 1 HAVING COUNT (DISTINCT t631.c536870922) = COUNT (DISTINCT t649.c536870931) ``` Result = null. If I run the following query, I can't see anything in the result list that would explain why I'm not getting any kind of return value. This is true even if I remove the DISTINCT from the SELECT. (I get 25 and 4265 rows of data back, respectively). ``` SELECT DISTINCT t442.c1, t631.c536870922, t649.c536870931 FROM t442, t658, t631, t649 WHERE t442.c1 = t658.c536870930 AND t442.c200000003 = 'Network' AND t442.c536871139 < 2 AND t631.c536870913 = t442.c1 AND t658.c536870925 = 1 AND (t442.c7 = 6 OR t442.c7 = 5) AND t442.c536870954 > 1141300800 AND (t442.c240000010 = 0) AND t442.c1 = t649.c536870914 AND t649.c536870939 > 1 ``` I have several other places where I have the query set up exactly like the one that is returning the null value and it work perfectly fine--returning usable numbers that are the correct values. I have to assume that whatever is unique in this situation is related to data and not the actual query, but I'm not sure what to look for in the data to explain it. I haven't been able to find any null values in the raw data before aggregation. I don't know what else would cause this. Any help would be appreciated.
I understand now. Your problem in the original query is that it is highly unusual (if not, in fact, wrong) to use a HAVING clause without a GROUP BY clause. The answer lies in the order of operation the various parts of the query are performed. In the original query, you do this: ``` SELECT COUNT(DISTINCT t442.c1) FROM ... WHERE ... HAVING COUNT(DISTINCT t631.c536870922) = COUNT(DISTINCT t649.c536870931); ``` The database will perform your joins and constraints, at which point it would do any group by and aggregation operations. In this case, you are not grouping, so the COUNT operations are across the whole data set. Based on the values you posted above, COUNT(DISTINCT t631.c536870922) = 25 and COUNT(DISTINCT t649.c536870931) = 24. The HAVING clause now gets applied, resulting in nothing matching - your asking for cases where the count of the total set (even though there are multiple c1s) are equal, and they are not. The DISTINCT gets applied to an empty result set, and you get nothing. What you really want to do is just a version of what you posted in the example that spit out the rows counts: ``` SELECT count(*) FROM (SELECT t442.c1 FROM t442 , t658 , t631 , t649 WHERE t442.c1 = t658.c536870930 AND t442.c200000003 = 'Network' AND t442.c536871139 < 2 AND t631.c536870913 = t442.c1 AND t658.c536870925 = 1 AND ( t442.c7 = 6 OR t442.c7 = 5) AND t442.c536870954 > 1141300800 AND (t442.c240000010 = 0) AND t442.c1 = t649.c536870914 AND t649.c536870939 > 1 GROUP BY t442.c1 HAVING COUNT(DISTINCT t631.c536870922) = COUNT(DISTINCT t649.c536870931) ); ``` This will give you a list of the c1 columns that have equal numbers of the 631 & 649 table entries. Note: You should be very careful about the use of DISTINCT in your queries. For example, in the case where you posted the results above, it is completely unnecessary; oftentimes it acts as a kind of wallpaper to cover over errors in queries that don't return results the way you want due to a missed constraint in the WHERE clause ("Hmm, my query is returning dupes for all these values. Well, a DISTINCT will fix that problem").
What is the result of: ``` SELECT COUNT (DISTINCT t631.c536870922), COUNT (DISTINCT t649.c536870931) FROM t442, t658, t631, t649 WHERE t442.c1 = t658.c536870930 AND t442.c200000003 = 'Network' AND t442.c536871139 < 2 AND t631.c536870913 = t442.c1 AND t658.c536870925 = 1 AND (t442.c7 = 6 OR t442.c7 = 5) AND t442.c536870954 > 1141300800 AND (t442.c240000010 = 0) AND t442.c1 = t649.c536870914 AND t649.c536870939 > 1 ``` If the two columns there never have equal values, then it makes sense that adding the HAVING clause would eliminate all rows from the result set.
Null value returned on Count Distinct (pl sql)
[ "", "sql", "oracle", "null", "count", "distinct", "" ]
### Overview This is the scenario: I'm given a value which represents a portion of the total number of minutes that exist in a standard week (assuming 10,080 minutes a week and 1,440 minutes a day) starting midnight Saturday (so 0 minutes Sunday @ 12am). I need to convert this minute value into an actual time value (like 8:35am) and I want to use Java's Date and/or Calendar classes rather than calculate this by hand. ### Example Below are some example input values: * 720 (720 minutes into the week) so 12pm on Sunday * 3840 (3840 minutes into the week) so 4pm on Tuesday Using Java's Date and Calendar classes how do I retrieve time component for that relative day?
Also, with a Calendar is really easy: ``` SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); int minutesToAdd = 720; Calendar cal = Calendar.getInstance(); cal.setTime(dateFormat.parse("2009/06/21 00:00:00")); // Next sunday cal.add(Calendar.MINUTE, minutesToAdd); Date result = cal.getTime(); // Voila ```
Divide by 24 hours in a day to get number of days. Remainder is number of minutes into that day. Divide by 60 to get hour. Remainder is minutes into that hour. Division and Modulus will get your answer in just a few lines of code. Since this sounds like homework, I'll leave the coding out of this answer.
Convert minutes into a week to time using Java's Date and Calendar classes
[ "", "java", "datetime", "time", "calendar", "" ]
I know that instantiated arrays of value types in C# are automatically populated with the [default value of the type](http://msdn.microsoft.com/en-us/library/83fhsxwc(loband).aspx) (e.g. false for bool, 0 for int, etc.). Is there a way to auto-populate an array with a seed value that's not the default? Either on creation or a built-in method afterwards (like Java's [Arrays.fill()](https://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html#fill-int:A-int-))? Say I wanted a boolean array that was true by default, instead of false. Is there a built-in way to do this, or do you just have to iterate through the array with a for loop? ``` // Example pseudo-code: bool[] abValues = new[1000000]; Array.Populate(abValues, true); // Currently how I'm handling this: bool[] abValues = new[1000000]; for (int i = 0; i < 1000000; i++) { abValues[i] = true; } ``` Having to iterate through the array and "reset" each value to true seems ineffecient. Is there anyway around this? Maybe by flipping all values? After typing this question out and thinking about it, I'm guessing that the default values are simply a result of how C# handles the memory allocation of these objects behind the scenes, so I imagine it's probably not possible to do this. But I'd still like to know for sure!
Don't know of a framework method but you could write a quick helper to do it for you. ``` public static void Populate<T>(this T[] arr, T value ) { for ( int i = 0; i < arr.Length;i++ ) { arr[i] = value; } } ```
``` Enumerable.Repeat(true, 1000000).ToArray(); ```
How to populate/instantiate a C# array with a single value?
[ "", "c#", "arrays", "default-value", "" ]
When I try to run Java application, I receive the following error: > `Exception in thread "main" java.lang.UnsatisfiedLinkError: no ocijdbc9 in java.library.path` I don't have a file `ocijdbc9.*` on my PC, but I have `ocijdbc10.dll` in `%ORACLE_HOME%\bin`. `%ORACLE_HOME%` is correctly specified, so I think the problem is that the application is searching for the wrong version (9 instead of 10). Both Oracle and Java Builder are freshly installed, so the problem may be in project preferences? Do you have any ideas on how to search for the place where the wrong version is specified?
You're missing a file from your java CLASSPATH. You need to add the OCI jar to your classpath. For my oracle 10.0.2 install on windows it's located in ``` %ORACLE_HOME%\jdbc\lib\ojdbc14.jar ``` If your application requires ocijdbc9 then you'll have to download it from somewhere and add it to the CLASSPATH. I don't know where to download it from, try the oracle site
an additional tip: if you're using oci jdbc urls; it is always better to use the jar library of your oracle client version. please check this address for these libraries: <http://www.oracle.com/technology/software/tech/java/sqlj_jdbc/index.html> for example if your client is Oracle 10.2.0.4, then you'd better use this client's `ojdbc14.jar` for java >= 1.4 and `classes12.jar` for java <= 1.3 note that until Oracle 11, jdbc libraries have the same names in every version such as `ojdbc14.jar` and `classes12.jar`.
no ocijdbc9 in java.library.path
[ "", "java", "oracle", "linker", "linker-errors", "" ]
I'm currently working on a project that does a lot of HTTP requests for data that it needs. It works by writing all the data into a buffer, then returning that buffer to the caller. It seems that waiting for the entire file to download data that can essentially streamed is a bad idea. Question 1: Is there already a library / public code that can make HTTP and Authenticated HTTP requests that works as a stream? Question 2: If there is no such library, why not? Is there a reason such a thing was never needed?
I'm not aware of an existing library, but it shouldn't be too hard to wrap [Curl](http://curl.haxx.se/libcurl/) (or [WinInet](http://msdn.microsoft.com/en-us/library/aa383630(VS.85).aspx), if that's your cup of tea) with [Boost.Iostreams](http://www.boost.org/doc/libs/1_39_0/libs/iostreams/doc/index.html).
It wouldn't be too hard to get [boost::asio](http://www.boost.org/doc/libs/1_36_0/doc/html/boost_asio.html) to do this, but as far as I know, it doesn't have HTTP protocol built-in (and I can't think of a library that does, or why not), so you'd have to write header/body parsing (could be tedious and error-prone). Some googling came up with some attempts at this, [like so](http://xtalk.msk.su/~ott/en/cpp/BoostAsioProxy.html).
HTTP inputstream class (C++)
[ "", "c++", "http", "inputstream", "" ]
In just about any formally structured set of information, you start reading either from the start towards the end, or occasionally from the end towards the beginning (street addresses, for example.) But in SQL, especially SELECT queries, in order to properly understand its meaning you have to start in the middle, at the FROM clause. This can make long queries very difficult to read, especially if it contains nested SELECT queries. Usually in programming, when something doesn't seem to make any sense, there's a historical reason behind it. Starting with the SELECT instead of the FROM doesn't make sense. Does anyone know the reason it's done that way?
The [SQL Wikipedia entry](http://en.wikipedia.org/wiki/Sql) briefly describes some history: > During the 1970s, a group at IBM San Jose Research Laboratory developed the System R relational database management system, based on the model introduced by Edgar F. Codd in his influential paper, "A Relational Model of Data for Large Shared Data Banks". Donald D. Chamberlin and Raymond F. Boyce of IBM subsequently created the **Structured English Query Language (SEQUEL)** to manipulate and manage data stored in System R. The acronym SEQUEL was later changed to SQL because "SEQUEL" was a trademark of the UK-based Hawker Siddeley aircraft company. The original name explicitly mentioned *English*, explaining the syntax. Digging a little deeper, we find the [FLOW-MATIC](http://en.wikipedia.org/wiki/FLOW-MATIC) programming language. > FLOW-MATIC, originally known as B-0 (Business Language version 0), **is possibly the first English-like data processing language**. It was invented and specified by Grace Hopper, and development of the commercial variant started at Remington Rand in 1955 for the UNIVAC I. By 1958, the compiler and its documentation were generally available and being used commercially. FLOW-MATIC was the inspiration behind the [Common Business Oriented Language](http://en.wikipedia.org/wiki/COBOL_(programming_language)), one of the oldest programming languages still in active use. Keeping with that spirit, *SEQUEL* was designed with English-like syntax (1970s is modern, compared with 1950s and 1960s). In perspective, "modern" programming systems still access databases using the age old ideas behind ``` MULTIPLY PRICE BY QUANTITY GIVING COST. ```
I think the way in which a SQL statement is structured makes logical sense as far as English sentences are structured. Basically ``` I WANT THIS FROM HERE WHERE WHAT I WANT MEETS THESE CRITERIA ``` I don't think it makes much sense, In English at least, to say ``` FROM HERE I WANT THIS WHERE WHAT I WANT MEETS THESE CRITERIA ```
Why is SQL's grammar inside-out?
[ "", "sql", "history", "grammar", "" ]
In PHP 5, I use intval() whenever I get numbers as an input. This way, I want to ensure that I get no strings or floating numbers. My input numbers should all be in whole numbers. But when I get numbers >= 2147483647, the signed integer limit is crossed. What can I do to have an intval() equivalent for numbers in all sizes? Here's what I want to have: ``` <?php $inputNumber = 3147483647.37; $intNumber = intvalEquivalent($inputNumber); echo $intNumber; // output: 3147483647 ?> ``` Thank you very much in advance! Edit: Based on some answers, I've tried to code an equivalent function. But it doesn't work exactly as intval() does yet. How can I improve it? What is wrong with it? ``` function intval2($text) { $text = trim($text); $result = ctype_digit($text); if ($result == TRUE) { return $text; } else { $newText = sprintf('%.0f', $text); $result = ctype_digit($newText); if ($result == TRUE) { return $newText; } else { return 0; } } } ```
Try this function, it will properly remove any decimal as intval does and remove any non-numeric characters. ``` <?php function bigintval($value) { $value = trim($value); if (ctype_digit($value)) { return $value; } $value = preg_replace("/[^0-9](.*)$/", '', $value); if (ctype_digit($value)) { return $value; } return 0; } // SOME TESTING echo '"3147483647.37" : '.bigintval("3147483647.37")."<br />"; echo '"3498773982793749879873429874.30872974" : '.bigintval("3498773982793749879873429874.30872974")."<br />"; echo '"hi mom!" : '.bigintval("hi mom!")."<br />"; echo '"+0123.45e6" : '.bigintval("+0123.45e6")."<br />"; ?> ``` Here is the produced output: ``` "3147483647.37" : 3147483647 "3498773982793749879873429874.30872974" : 3498773982793749879873429874 "hi mom!" : 0 "+0123.45e6" : 0 ``` Hope that helps!
you can also use regular expressions to remove everything after the intial numeric parts: ``` <?php $inputNumber = "3147483647.37"; $intNumber = preg_replace('/^([0-9]*).*$/', "\\1", $inputNumber); echo $intNumber; // output: 3147483647 ?> ```
PHP: intval() equivalent for numbers >= 2147483647
[ "", "php", "types", "numbers", "integer", "" ]
I would like to create a RESTful app on Google App Engine. I would like to provide XML and JSON services. I have briefly experimented with Restlet, Resteasy, and Jersey. I haven't had much success with any of them, other than some simple examples in Restlet. Could you share your experiences creating a Restful web application on Google App Engine using Java or provide any insight on the aforementioned toolkits on GAE? Thanks! Edit (2009-07-25): I have decided to use Restlet for the time being. It seems to work flawlessly so far. Please post any other insights/opinions you may have. What problems have you encountered? Have you successfully used Jersey/Restlet/Resteasy on GAE/J? If so, we want to hear about it!
I'm happy to report that Restlet M3 works FLAWLESSLY on AppEngine 1.2.2. I have followed the "First steps" and "First resource" tutorials found <http://restlet.com/technical-resources/restlet-framework/guide>. So, it seems to me that Restlet is the answer for your GAE/J Restful applications.
I'm using Jersey on GAE. Here is the link for those who are interested about setting it up: (I'm using GAE SDK v1.4.0): <http://tugdualgrall.blogspot.com/2010/02/create-and-deploy-jax-rs-rest-service.html>
RESTful application on Google App Engine Java?
[ "", "java", "google-app-engine", "rest", "jersey", "restlet", "" ]
How can I get the byte array from some string which can contain numbers, letters and so on? If you are familiar with Java, I am looking for the same functionality of the getBytes() method. I tried a snippet like this one: ``` for($i = 0; $i < strlen($msg); $i++){ $data.=ord($msg[$i]); //or $data[]=ord($msg[$1]); } ``` but without success, so any kind of help will be appreciated. PS: Why do I need this at all!? Well, I need to send a byte array via fputs() to a server written in Java...
@Sparr is right, but I guess you expected byte array like `byte[]` in C#. It's the same solution as Sparr did but instead of HEX you expected `int` presentation (*range from 0 to 255*) of each `char`. You can do as follows: ``` $byte_array = unpack('C*', 'The quick fox jumped over the lazy brown dog'); var_dump($byte_array); // $byte_array should be int[] which can be converted // to byte[] in C# since values are range of 0 - 255 ``` By using `var_dump` you can see that elements are `int` (*not `string`*). ``` array(44) { [1]=> int(84) [2]=> int(104) [3]=> int(101) [4]=> int(32) [5]=> int(113) [6]=> int(117) [7]=> int(105) [8]=> int(99) [9]=> int(107) [10]=> int(32) [11]=> int(102) [12]=> int(111) [13]=> int(120) [14]=> int(32) [15]=> int(106) [16]=> int(117) [17]=> int(109) [18]=> int(112) [19]=> int(101) [20]=> int(100) [21]=> int(32) [22]=> int(111) [23]=> int(118) [24]=> int(101) [25]=> int(114) [26]=> int(32) [27]=> int(116) [28]=> int(104) [29]=> int(101) [30]=> int(32) [31]=> int(108) [32]=> int(97) [33]=> int(122) [34]=> int(121) [35]=> int(32) [36]=> int(98) [37]=> int(114) [38]=> int(111) [39]=> int(119) [40]=> int(110) [41]=> int(32) [42]=> int(100) [43]=> int(111) [44]=> int(103) } ``` Be careful: the output array is of 1-based index (as it was pointed out in the comment)
``` print_r(unpack("H*","The quick fox jumped over the lazy brown dog")) Array ( [1] => 54686520717569636b20666f78206a756d706564206f76657220746865206c617a792062726f776e20646f67 ) ``` T = 0x54, h = 0x68, ... You can split the result into two-hex-character chunks if necessary.
String to byte array in php
[ "", "php", "arrays", "" ]
I just installed JBoss and tried to run it from Eclipse. When I first tried to run it I got an error stating that ports 8080 and 1098 are already being bound to something else. I changed those in the config files. Here is example of where I changes port 1098 to 10098 ``` <bean class="org.jboss.services.binding.ServiceBindingMetadata"> <property name="serviceName">jboss:service=Naming</property> <property name="bindingName">RmiPort</property> <property name="port">10098</property> <property name="description">Socket Naming service uses to receive RMI requests from client proxies</property> </bean> ``` After this the port errors went away but I'm getting the following error: ``` Error installing to Start: name=jboss.remoting:protocol=rmi,service=JMXConnectorServer state=Create mode=Manual requiredState=Installed java.lang.IllegalStateException: BaseClassLoader@dc93be{vfsfile:/C:/jboss-5.1.0.GA/server/default/deploy/jmx-remoting.sar/} classLoader is not connected to a domain (probably undeployed?) for class javax.management.remote.rmi.RMIServerImpl_Stub at org.jboss.classloader.spi.base.BaseClassLoader.loadClassFromDomain(BaseClassLoader.java:793) at org.jboss.classloader.spi.base.BaseClassLoader.loadClass(BaseClassLoader.java:441) ........ ``` Do you know what the problem could be or how to go about approaching it? Thanks, Tam
Changing JBoss's ports is not something to be done lightly, because it talks to itself a lot. If you change the ports it listens on, it loses that communication. Firstly, it is better to try and shut down the other processes that are listening on those ports. It's either going tio be other web servers, application servers, or sometimes things like thunderbird and firefox grab those ports. If that's not an option, then it's better to bind jboss to its own IP address, but that's only practical on unix/linux. So if you really want to shift JBoss on to a different set of ports, then you can [follow the instructions here](http://www.jboss.org/community/wiki/ConfiguringMultipleJBossInstancesOnOneMachine)
look into your processes ps -f and kill the processes that are hanging. That seemed to fix my problem.
jboss problem with JMXConnectorServer
[ "", "java", "jboss", "" ]
I am trying to get a path to a Resource but I have had no luck. This works (both in IDE and with the JAR) but this way I can't get a path to a file, only the file contents: ``` ClassLoader classLoader = getClass().getClassLoader(); PrintInputStream(classLoader.getResourceAsStream("config/netclient.p")); ``` If I do this: ``` ClassLoader classLoader = getClass().getClassLoader(); File file = new File(classLoader.getResource("config/netclient.p").getFile()); ``` The result is: `java.io.FileNotFoundException: file:/path/to/jarfile/bot.jar!/config/netclient.p (No such file or directory)` Is there a way to get a path to a resource file?
This is deliberate. The contents of the "file" may not be available as a file. Remember you are dealing with classes and resources that may be part of a JAR file or other kind of resource. The classloader does not have to provide a file handle to the resource, for example the jar file may not have been expanded into individual files in the file system. Anything you can do by getting a java.io.File could be done by copying the stream out into a temporary file and doing the same, if a java.io.File is absolutely necessary.
When loading a resource make sure you notice the difference between: ``` getClass().getClassLoader().getResource("com/myorg/foo.jpg") //relative path ``` and ``` getClass().getResource("/com/myorg/foo.jpg")); //note the slash at the beginning ``` I guess, this confusion is causing most of problems when loading a resource. --- Also, when you're loading an image it's easier to use `getResourceAsStream()`: ``` BufferedImage image = ImageIO.read(getClass().getResourceAsStream("/com/myorg/foo.jpg")); ``` When you really have to load a (non-image) file from a JAR archive, you might try this: ``` File file = null; String resource = "/com/myorg/foo.xml"; URL res = getClass().getResource(resource); if (res.getProtocol().equals("jar")) { try { InputStream input = getClass().getResourceAsStream(resource); file = File.createTempFile("tempfile", ".tmp"); OutputStream out = new FileOutputStream(file); int read; byte[] bytes = new byte[1024]; while ((read = input.read(bytes)) != -1) { out.write(bytes, 0, read); } out.close(); file.deleteOnExit(); } catch (IOException ex) { Exceptions.printStackTrace(ex); } } else { //this will probably work in your IDE, but not from a JAR file = new File(res.getFile()); } if (file != null && !file.exists()) { throw new RuntimeException("Error: File " + file + " not found!"); } ```
How to get a path to a resource in a Java JAR file
[ "", "java", "resources", "path", "" ]
What does this error mean? > TypeError: cannot concatenate 'str' and 'list' objects Here's part of the code: ``` for j in ('90.','52.62263.','26.5651.','10.8123.'): if j == '90.': z = ('0.') elif j == '52.62263.': z = ('0.', '72.', '144.', '216.', '288.') for k in z: exepath = os.path.join(exe file location here) exepath = '"' + os.path.normpath(exepath) + '"' cmd = [exepath + '-j' + str(j) + '-n' + str(z)] process=Popen('echo ' + cmd, shell=True, stderr=STDOUT ) print process ```
I'm not sure you're aware that `cmd` is a one-element `list`, and not a string. Changing that line to the below would construct a string, and the rest of your code will work: ``` # Just removing the square brackets cmd = exepath + '-j' + str(j) + '-n' + str(z) ``` I assume you used brackets just to group the operations. That's not necessary if everything is on one line. If you wanted to break it up over two lines, you should use parentheses, not brackets: ``` # This returns a one-element list cmd = [exepath + '-j' + str(j) + '-n' + str(z)] # This returns a string cmd = (exepath + '-j' + str(j) + '-n' + str(z)) ``` Anything between square brackets in python is *always* a `list`. Expressions between parentheses are evaluated as normal, unless there is a comma in the expression, in which case the parentheses act as a `tuple` constructor: ``` # This is a string str = ("I'm a string") # This is a tuple tup = ("I'm a string","me too") # This is also a (one-element) tuple tup = ("I'm a string",) ```
string objects can only be concatenated with other strings. Python is a strongly-typed language. It will not coerce types for you. you can do: ``` 'a' + '1' ``` but not: ``` 'a' + 1 ``` in your case, you are trying to concat a string and a list. this won't work. you can append the item to the list though, if that is your desired result: ``` my_list.append('a') ```
What does : TypeError: cannot concatenate 'str' and 'list' objects mean?
[ "", "python", "string", "" ]
I've read quite a few beginner's books on C++, and a little beyond that, but what are some of the more obscure aspects of C++, or where can I find information/tutorials on these?
Herb Sutter's books are an excellent source for this topic -- start with <http://www.gotw.ca/publications/xc++.htm> .
[ADL](http://en.wikipedia.org/wiki/Argument_dependent_name_lookup) (aka Koenig Lookup) is pretty obscure, even though people use it without realizing it in every Hello World program. The "[ScopeGuard](http://www.ddj.com/cpp/184403758) trick", where const references as return values from functions are bound to the scope of something they're assigned to, is also fairly obscure. That article raised awareness about it quite a bit, though. There are also a few properties and usages of sizeof() that count as obscure, especially when used in macros or template metaprograms.
What are some of the more obscure parts of C++?
[ "", "c++", "" ]
This is the scenario: ``` class BaseClass { public virtual string Prop {get; set;} } class ChildClass : BaseClass { public override string Prop {get; set;} } //program ... ChildClass instance = new ChildClass; Console.WriteLine(instance.Prop); //accessing ChildClass.Prop ... ``` The question is how to access BaseClass.Prop in a instance of ChildClass? Will casting do the trick? ``` Console.WriteLine((instance as BaseClass).Prop); //accessing BaseClass.Prop ``` -EDIT- A lot of people suggested casting. In C++ it would not work because polymorphism would still ensure that the child property is called. Isn't that the case in C#? In C++ you would solve the issue by doing: ``` instance.(BaseClass::get_Prop()) ```
The semantics of overriding a property won't let you access the base of an overridden property. And this makes sense. Classes that use ChildClass shouldn't care if the property is overridden or not. When the property is used by another class it's up to ChildClass to return the appropriate value. Usually questions like these indicate an attempt to solve a different problem. What kind of problems are you facing that you need direct access to the base property?
Cast the instance of ChildClass to an instance of BaseClass; i.e. use: ``` ((BaseClass)childClassInstance).Prop ```
Accessing overrriden public property in C#
[ "", "c#", "inheritance", "" ]
In Visual Studio I generated a plain old Win32 application and stripped all the resources and generated code so that my application consists of this: ``` #include "stdafx.h" #include "IcoTest.h" int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { ::MessageBox( NULL, L"Testing", L"Test", MB_OK ); } ``` When I run the application, this is what I see: [![screenshot](https://i.stack.imgur.com/phmpN.png)](https://i.stack.imgur.com/phmpN.png) So the question is can I change that default application icon in the taskbar? If so, what code needs to be added to do it? Edit: Here's what I did, and this kind of works but it isn't ideal. The new icon shows up alright, but the taskbar preview window in Vista doesn't work and the system menu doesn't work so I'm just going to leave it alone for now. ``` HWND CreateDummyWindow(HINSTANCE hInstance, int iconId, LPCTSTR taskbarTitle) { WNDCLASSEX wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = DefWindowProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(iconId)); wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.hbrBackground = 0; wcex.lpszMenuName = 0; wcex.lpszClassName = taskbarTitle, wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(iconId)); ATOM atom = RegisterClassEx(&wcex); HWND wnd = ::CreateWindow( wcex.lpszClassName, taskbarTitle, WS_ICONIC | WS_DISABLED, -1000, -1000, 1, 1, NULL, NULL, hInstance, NULL); return wnd; } int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { HWND wnd = CreateDummyWindow(hInstance, IDI_ICON1, _T("Test") ); ::MessageBox( wnd, _T("Testing"), _T("Test"), MB_OK ); ::DestroyWindow( wnd ); } ```
The icon shown on the task bar is taken from the window itself. If the only window is the standard Windows MesssageBox, then you'll get some sort of OS default. You have to create your own window and give it an icon, then Windows will use that.
This looks like just sample code. If the real code is a non-console Windows application, you can do this: Give your application's main window a task bar icon by calling [SetIcon()](http://msdn.microsoft.com/en-us/library/9cb3b7b5(VS.80).aspx). Then when you call MessageBox(), set the first parameter to the HWND of your application's main window.
How to explicitly set taskbar icon?
[ "", "c++", "winapi", "taskbar", "" ]
I have a 2008 SQL Server Express installed on one of my machines and I'm attempting to establish a remote connection... when I use the MS SQL Server Management Studio I can log into the database without any problems at all (with the same credentials), but when I try to create a connection string in my C# application I get an exception: > A network-related or instance-specific > error occurred while establishing a > connection to SQL Server. The server > was not found or was not accessible. > Verify that the instance name is > correct and that SQL Server is > configured to allow remote > connections. Here is what my connection string looks like (the private information is changed): ``` "Data Source="MACHINENAME\\SQLEXPRESS";User ID="Admin";Password="the_password";Initial Catalog="MyDatabase";Integrated Security=True;Connect Timeout=120"); ``` As I said, **I can login using the Management Studio with the same settings**: same user id, password and data source name, but it fails when I attempt to open a connection with the above connection string. Note: 1. I have enabled the remote connectivity on the server, disabled the firewall, enabled TCP/IP connection to the server, turned on the SQL Browser. 2. The connection string works fine when I'm on the same machine. 3. I looked up the Integrated Security option and I set it to false just to make sure that it's not attempting to use the Windows Login, but it still fails. 4. The database is setup to allow both windows login and database login. 5. I changing the Integrated Security option to SSPI, True, and finally False, all 3 gave me the same error as above. Can anybody tell me if I'm doing something wrong? UPDATE, here is my exact code (this time only the password is removed, and I've added a picture of management studio running on the same machine): ``` string _connectionString = //string.Format("Server=%s;User ID=%s;Password=%s;Database=%s;Connect Timeout=120", // Same problem //string.Format("Server=%s;User ID=%s;Password=%s;Database=%s;Integrated Security=False;Connect Timeout=120", // Same problem string.Format("Data Source=%s;User ID=%s;Password=%s;Initial Catalog=%s;Integrated Security=False;Connect Timeout=120", // Same problem "GANTCHEVI\\SQLEXPRESS", "FinchAdmin", "the_password", "Finch"); ``` [Connected Via Management Studio: See Picture http://s113.photobucket.com/albums/n202/ozpowermo/?action=view&current=ManagementStudio.jpg](http://s113.photobucket.com/albums/n202/ozpowermo/?action=view&current=ManagementStudio.jpg) <http://s113.photobucket.com/albums/n202/ozpowermo/?action=view&current=ManagementStudio.jpg> **I FIGURED IT OUT:** When using the "Data Source=" label one should use the "User Id", if you use User ID it doesn't seem like it works! ``` string _connectionString = "Data Source=GANTCHEVI\\SQLEXPRESS;Initial Catalog=Finch;Integrated Security=False;User Id=FinchAdmin;Password=the_password;Connect Timeout=0";" ```
Remove Integrated Security=True from your connection string and (optional) add Persist Security Info=True; From MSDN: > Integrated Security - When false, User ID and Password are specified in the connection. When true, the current Windows account credentials are used for authentication.
try this ``` string sqlcon=("Data Source="your pc name\\SQLEXPRESS"; UserID=sa; Password=****; Initial Catalog="+MyDatabase+"; IntegratedSecurity=True;"); ```
c# 2008 SQL Server Express Connection String
[ "", "c#", "sql-server", "connection-string", "sql-server-2008-express", "" ]
I'd like to design a GUI using Glade, and generate python code from it. The thing is, I can't find GladeGen. Does anyone know where it can be downloaded from?
Why not use the GUI designer is something like Anjuta or the Glade program, write that out to **glade XML** and use the python bindings for libglade to use the XML file ... Kind of like XAML. **Edit, added some links to Glade.xml->python** <http://glc.sourceforge.net/> <http://www.pygtk.org/> (might help)
Google is your friend. <http://www.linuxjournal.com/article/7558>
where can I find GladeGen?
[ "", "python", "gtk", "glade", "" ]
I am building a game in Visual Studio 2008 and in order to build levels, i will have two types of files (more than that actually but these two are the only ones important to my question) i need to parse. One will dictate the contents of a level and will look something like this: LevelName = "Sample Level" Object1Type = "CustomObject" Object1File = "WideFloor\_DF" Object1Position = 600,600 Object2Type = "Circle" Object2Position = 550, 500 Object2Mass = 5 etc. The other will dictate the properties for custom objects, and look something like this: Name = "Wide Floor" Mass = 1 GeometryMap = "WideFloor\_GM" IsStatic = true etc. I'm not very familiar with regexes (read: i don't like them because the look too much like line noise to easily understand) and i was wondering if there is an easier method than using tons of regexes? edit: i knew i forgot something! i really hate xml files, so i would really prefer not to use them (waaaaaaaay too verbose for me). edit 2: i like the format i've come up with and would prefer not to change.
What about using XML files? You can read and write them easily using XMLReader and XMLWriter objects, and you won't have to deal with Regex at all. ``` <Level name="Sample Level"> <Object type="CustomObject" file="WideFloor_DF" positionX="600" positionY="600" /> <Object type="Circle" file="WideFloor_DF" positionX="500" positionY="500" mass="5" /> </Level> ```
If you are going to have your files in human readable format anyway, why not use XML?
File Parsing in C#
[ "", "c#", "fileparsing", "" ]
I have tables named `Categories`, `Questions` and `Selections`. The relationship of the tables are: there can be 1 or more `Selections` in a `Question` and there can be one or more `Questions` in a `Category`. The table columns are the following: > Categories > - CategoryID (pk) > - Name > > Questions > - QuestionID (pk) > - Question > - CategoryID (fk) > > Selections > - SelectionID (pk) > - Selection > - QuestionID (fk) I want to convert this code from C# to SQL: ``` private int fromCategoryID = 1; private int toCategoryID = 2; Category cat1 = new Category(); //this is the category we will get questions from. Category cat2 = new Category(); //this is the category we copy the questions to. // code to populate the 2 category instances and their children (Questions) and // children's children (Selections) removed for brevity. // copy questions and selections from cat1 to cat2 foreach(Question q from cat1.Questions) { Question newQuestion = new Question(); newQuestion.Question = q.Question; foreach(Selection s in q.Selections) { Selection newSelection = new Selection(); newSelection.Selection = s.Selection; q.Selections.Add(newSelection); } cat2.Questions.Add(newQuestion); } ``` How can this be done in SQL?
Assuming that QuestionID and SelectionID are `IDENTITY` columns you could do something simple like this: ``` INSERT INTO Questions (Question,CategoryID) SELECT q.Question, 2 FROM Questions q WHERE q.CategoryID = 1 ``` which would copy all of the Questions from Category 1 to Category 2. The problem comes with copying the Selections as you don't have any way of relating a Question to it's Selection. So you can say "get me all the Selections from all of the Questions in Category 1", but you've no way of knowing the new QuestionID's for those Questions in Category 2. Based on the schema that you've provided, the way I would tackle this is to write a stored procedure that iterates over the Questions you want to copy in exactly the same way as your C# pseudo code. Whilst some people hate the thought of using a CURSOR in T-SQL, this is the kind of situation that it was made for. A rough stab in the dark (untested) would be something like this: ``` CREATE PROCEDURE PrcCopyQuestions ( @CategoryID_from NUMERIC @CategoryID_to NUMERIC ) AS DECLARE @old_QuestionID NUMERIC(10,0) @new_QuestionID NUMERIC(10,0) @Question VARCHAR(255) DECLARE c_questions CURSOR FOR SELECT QuestionID, Question FROM Questions WHERE CategoryID = @CategoryID_from FOR READ ONLY BEGIN OPEN c_questions WHILE (1=1) BEGIN FETCH c_questions INTO @old_QuestionID, @Question IF @@SQLSTATUS <> 0 BREAK INSERT INTO Questions (Question,CategoryID) SELECT @Question, @CategoryID_to SELECT @new_QuestionID = @@IDENTITY INSERT INTO Selections (Selection, QuestionID) SELECT s.Selection, @new_QuestionID FROM Selections s WHERE QuestionID = @old_QuestionID END CLOSE c_questions DEALLOCATE CURSOR c_questions END ```
You will need 2 inserts if you want to bring both the Questions and the Selections across. Based on the assumption that Question is unique within a category this will do what you want. ``` declare @FromCategoryId int declare @NewCategoryId int set @NewCategoryId = 3 set @FromCategoryId = 2 insert into Questions select Question, @NewCategoryId from Questions where CategoryId = @FromCategoryId insert into Selections select S.Selection, QNew.QuestionId from Questions QOld join Questions QNew on QOld.Question = QNew.Question and QOLD.CategoryId = @FromCategoryId and QNEW.CategoryId = @NewCategoryId join Selections S on S.QuestionId = QOld.QuestionId ``` Otherwise some temp tables where you populate with the Selections and Questions for a given category then push them across to the real tables might also work.
How can I copy data using T-SQL?
[ "", "sql", "t-sql", "" ]
I'm sure this is a really simple question. The following code shows what I'm trying to do: ``` class MemberClass { public: MemberClass(int abc){ } }; class MyClass { public: MemberClass m_class; MyClass(int xyz) { if(xyz == 42) m_class = MemberClass(12); else m_class = MemberClass(32); } }; ``` This doesn't compile, because `m_class` is being created with an empty constructor (which doesn't exist). What is the right way of doing this? My guess is using pointers and instantiating `m_class` using `new`, but I'm hoping there is an easier way. **Edit:** I should have said earlier, but my actual problem has an additional complication: I need to call a method before initializing m\_class, in order to set up the environment. So: ``` class MyClass { public: MemberClass m_class; MyClass(int xyz) { do_something(); // this must happen before m_class is created if(xyz == 42) m_class = MemberClass(12); else m_class = MemberClass(32); } }; ``` Is it possible to achieve this with fancy initialization list tricks?
Use the conditional operator. If the expression is larger, use a function ``` class MyClass { public: MemberClass m_class; MyClass(int xyz) : m_class(xyz == 42 ? 12 : 32) { } }; class MyClass { static int classInit(int n) { ... } public: MemberClass m_class; MyClass(int xyz) : m_class(classInit(xyz)) { } }; ``` To call a function before initializing m\_class, you can place a struct before that member and leverage RAII ``` class MyClass { static int classInit(int n) { ... } struct EnvironmentInitializer { EnvironmentInitializer() { do_something(); } } env_initializer; public: MemberClass m_class; MyClass(int xyz) : m_class(classInit(xyz)) { } }; ``` This will call `do_something()` before initializing `m_class`. Note that you are not allowed to call non-static member functions of `MyClass` before the constructor initializer list has completed. The function would have to be a member of its base class and the base class' ctor must already be completed for that to work. Also note that the function, of course, is always called, for each separate object created - not only for the first object created. If you want to do that, you could create a static variable within the initializer's constructor: ``` class MyClass { static int classInit(int n) { ... } struct EnvironmentInitializer { EnvironmentInitializer() { static int only_once = (do_something(), 0); } } env_initializer; public: MemberClass m_class; MyClass(int xyz) : m_class(classInit(xyz)) { } }; ``` It's using the comma operator. Note that you can catch any exception thrown by `do_something` by using a function-try block ``` class MyClass { static int classInit(int n) { ... } struct EnvironmentInitializer { EnvironmentInitializer() { static int only_once = (do_something(), 0); } } env_initializer; public: MemberClass m_class; MyClass(int xyz) try : m_class(classInit(xyz)) { } catch(...) { /* handle exception */ } }; ``` The `do_something` function will be called again next time, if it threw that exception that caused the `MyClass` object fail to be created. Hope this helps :)
Use the initializer list syntax: ``` class MyClass { public: MemberClass m_class; MyClass(int xyz) : m_class(xyz == 42 ? MemberClass(12) : MemberClass(32) /* see the comments, cleaner as xyz == 42 ? 12 : 32*/) { } }; ``` Probably cleaner with a factory: ``` MemberClass create_member(int x){ if(xyz == 42) return MemberClass(12); // ... } //... MyClass(int xyz) : m_class(create_member(xyz)) ```
Right way to conditionally initialize a C++ member variable?
[ "", "c++", "class", "member-initialization", "" ]
I have an array with a set of elements. I'd like to bring a given element to the front but otherwise leave the order unchanged. Do folks have suggestions as to the cleanest syntax for this? This is the best I've been able to come up with, but it seems like bad form to have an N log N operation when an N operation could do. ``` mylist = sorted(mylist, key=lambda x: x == targetvalue, reverse=True) ```
I would go with: ``` mylist.insert(0, mylist.pop(mylist.index(targetvalue))) ```
To bring (for example) the 6th element to the front, use: ``` mylist.insert(0, mylist.pop(5)) ``` (*python uses the standard 0 based indexing*)
Simple syntax for bringing a list element to the front in python?
[ "", "python", "" ]
I use a VB6/COM+ application which outputs date/time values based on the short date settings in the Control Panel, Regional Settings, for the user that runs it. The program that then parses that output has a configurable setting for the date format it expects, and presents in the UI. e.g. If the regional setting for the user is set to mm/dd/yyyy, and it outputs 06/18/2009, the application expecting "18/06/2009" fails with "String was not recognized as a valid DateTime". As we usually run this application as a service account, which we have not logged in as interactively to create a profile, we generally set the correct date format and then tick the "Apply all settings to the current user account and the default user profile" option. I would like to be make the C# configuration utility I have written for this mess to be able to set the date format programmatically for a given user. **Edit** I would like nothing more than to change the code, but do not have the ability to do so at this time. I also know that what I am asking is a bad thing to do. With regards to "it should be the user's choice" - I **am** that user, as I create it explicitly for the task; I just want to set the date format by a scripted method, rather than having to do the clicking myself.
This is specifically discouraged by Microsoft. Any solution you may come up with will be a filthy hack that will probably stop working soon. Think of it this way: who are you to decide those settings? Don't you think that's the user's decision? Back on topic: find an unambiguous format for the applications to communicate in, such as `YYYYMMDD`. The application that displays can then simply respect the actual user settings, as it should. But, since you can't change it, just poke into the registry: Current user: ``` HKEY_CURRENT_USER\Control Panel\International ``` Specific user: ``` HKEY_USERS\(user SID)\Control Panel\International ``` Default user: ``` HKEY_USERS\.DEFAULT\Control Panel\International ``` `sShortDate` is probably the value you want to change.
If you are going to modify the profile to suit your needs, why not just ignore the profile settings and hardcode the format you want in your app?
How can I change a Windows user's regional settings/date format?
[ "", "c#", "windows", "datetime", "registry", "regional", "" ]
I have a text file,which I use to input information into my application.The problem is that some values are float and sometimes they are null,which is why I get an exception. ``` var s = "0.0"; var f = float.Parse(s); ``` The code above throws an exception at line 2 "Input string was not in a correct format." I believe the solution would be the advanced overloads of float.Parse,which include IFormatProvider as a parameter,but I don't know anything about it yet. How do I parse "0.0"?
Dot symbol "." is not used as separator (this depends on Culture settings). So if you want to be absolutely sure that dot is parsed correctly you need to write something like this: ``` CultureInfo ci = (CultureInfo)CultureInfo.CurrentCulture.Clone(); ci.NumberFormat.CurrencyDecimalSeparator = "."; avarage = double.Parse("0.0",NumberStyles.Any,ci); ```
Following works for me: ``` string stringVal = "0.0"; float floatVal = float.Parse(stringVal , CultureInfo.InvariantCulture.NumberFormat); ``` The reverse case (works for all countries): ``` float floatVal = 0.0f; string stringVal = floatVal.ToString("F1", new CultureInfo("en-US").NumberFormat); ```
float.Parse() doesn't work the way I wanted
[ "", "c#", "" ]
When you use the new C# collection initialization syntax: ``` string[] sarray = new[] { "A", "B", "C", "D" }; ``` does the compiler avoid initializing each array slot to the default value, or is it equivalent to: ``` string[] sarray = new string[4]; // all slots initialized to null sarray[0] = "A"; sarray[1] = "B"; sarray[2] = "C"; sarray[3] = "D"; ```
The compiler still uses the `newarr` IL instruction, so the CLR will still initialize the array. Collection initialization is *just* compiler magic - the CLR doesn't know anything about it, so it'll still assume it has to do sanity clearance. However, this should be really, really quick - it's just wiping memory. I doubt it's a significant overhead in many situations.
Quick test: ``` string[] arr1 = { "A","B","C","D" }; arr1.GetHashCode(); string[] arr2 = new string[4]; arr2[0] = "A"; arr2[1] = "B"; arr2[2] = "C"; arr2[3] = "D"; arr2.GetHashCode(); ``` results in this IL (note, they're both identical) ``` IL_0002: newarr [mscorlib]System.String IL_0007: stloc.2 IL_0008: ldloc.2 IL_0009: ldc.i4.0 IL_000a: ldstr "A" IL_000f: stelem.ref IL_0010: ldloc.2 IL_0011: ldc.i4.1 IL_0012: ldstr "B" IL_0017: stelem.ref IL_0018: ldloc.2 IL_0019: ldc.i4.2 IL_001a: ldstr "C" IL_001f: stelem.ref IL_0020: ldloc.2 IL_0021: ldc.i4.3 IL_0022: ldstr "D" IL_0027: stelem.ref IL_0028: ldloc.2 IL_0029: stloc.0 IL_002a: ldloc.0 IL_002b: callvirt instance int32 [mscorlib]System.Object::GetHashCode() IL_0030: pop IL_0031: ldc.i4.4 IL_0032: newarr [mscorlib]System.String IL_0037: stloc.1 IL_0038: ldloc.1 IL_0039: ldc.i4.0 IL_003a: ldstr "A" IL_003f: stelem.ref IL_0040: ldloc.1 IL_0041: ldc.i4.1 IL_0042: ldstr "B" IL_0047: stelem.ref IL_0048: ldloc.1 IL_0049: ldc.i4.2 IL_004a: ldstr "C" IL_004f: stelem.ref IL_0050: ldloc.1 IL_0051: ldc.i4.3 IL_0052: ldstr "D" IL_0057: stelem.ref IL_0058: ldloc.1 IL_0059: callvirt instance int32 [mscorlib]System.Object::GetHashCode() ```
Does C# Collection Initialization Syntax Avoid Default Initialization Overhead
[ "", "c#", "optimization", "compiler-construction", "c#-3.0", "" ]
I am just started out learning Python and also started looking into Django a little bit. So I copied this piece of code from the tutorial: ``` # Create your models here. class Poll(models.Model): question = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __unicode__(self): return self.question def was_published_today(self): return self.pub_date.date() == datetime.date.today() class Choice(models.Model): poll = models.ForeignKey(Poll) choice = models.CharField(max_length=200) votes = models.IntegerField() def ___unicode__(self): return self.choice #shouldn't this return the choice ``` When I play around with it in the shell, I just get the "question" of the Poll object, but for some reason it won't return of the "choice" of the Choice objects. I fail to see the difference. My output on the shell looks like this: ``` >>> Poll.objects.all() [<Poll: What is up?>] >>> Choice.objects.all() [<Choice: Choice object>, <Choice: Choice object>, <Choice: Choice object>] >>> ``` I was expecting for the Choice objects to return something else than "Choice object". Does anybody have an idea about where I failed and what I should look into? EDIT: Way to make me feel like an idiot. Yes, the three underscores were the problem. I was looking at that for about an hour now.
You have three underscores before "unicode\_\_" on the Choice class, it should be only two like in your Poll class, like this: ``` def __unicode__(self): return u'%s' % self.choice ```
Your Unicode method has too many underscores. It should read: ``` def __unicode__(self): return u'%s' % self.choice ```
Stuck on official Django Tutorial
[ "", "python", "django", "" ]
Can someone please tell me whether AddB below will result in less CLR allocations than AddA? I've examined disassembly and it looks to be the case but I'd like confirmation from the **Experts** please. Can someone **Exchange** this information with me please? Cheers, Charlie. --- ``` namespace A { struct Vec2 { public float x; public float y; public Vec2 AddA(Vec2 other) { Vec2 v = new Vec2(); // Reference variable v.x = x + other.x; v.y = y + other.y; return v; } public Vec2 AddB(Vec2 other) { Vec2 v; // Value variable v.x = x + other.x; v.y = y + other.y; return v; } } } ```
If Vec2 is a `struct` in both examples, by using `Vec2 v = new Vec2();` you are **not** creating a reference to your struct, you are simply creating a new struct on your stack. If you don't use the `new` keyword, your struct is nevertheless created on the stack and you can initialize each field separately. In that case, using the `new` keyword for a struct does't make much sense if your constructor doesn't accept some meaningful parameters to initialize the data in a single line. If the first method uses a `class` instead of a `struct`, then it does create an object for GC to collect, unlike the second method. Since v in `AddB` is allocated on the stack, it is not collected, the stack is simply popped when your method is finished.
There's no guarantee for anything. Value items are not necessarily stored in the heap. See [The Stack Is An Implementation Detail](http://blogs.msdn.com/ericlippert/archive/2009/04/27/the-stack-is-an-implementation-detail.aspx) by Eric Lippert, and the following [second part](http://blogs.msdn.com/ericlippert/archive/2009/05/04/the-stack-is-an-implementation-detail-part-two.aspx).
Trying to reduce GC collections
[ "", "c#", "garbage-collection", "clr", "" ]
I have a class that references a bunch of other classes. I want to be able to add these references incrementally (i.e. not all at the same time on the constructor), and I want to disallow the ability to delete the object underlying these references from my class, also I want to test for NULL-ness on these references so I know a particular reference has not been added. What is a good design to accomplish these requirements?
I agree with other comments that you should use `boost::shared_ptr`. However if you don't want the class holding these references to part-control the lifetime of the objects it references you should consider using `boost::weak_ptr` to hold the references then turn this into a `shared_ptr` when you want to us it. This will allow the referenced objects to be deleted before your class, and you will always know if object has been deleted before using it.
It sounds like you might be trying to build a [Service Locator](http://java.sun.com/blueprints/patterns/ServiceLocator.html). As a side-comment: I would personally recommend not doing that, because [it is going to make testing really, really painful if you ever want to do it](http://www.youtube.com/watch?v=RlfLCWKxHJ0). Constructor injection (Something that you are trying to avoid) will make testing much easier.
how to best deal with a bunch of references in a class
[ "", "c++", "" ]
I'm new to PHP and web scripting in general so this a newb question. Currently i'm a creating an instance to an object, yet when I call the constructor the script slienty shuts down... it doesn't call the next function and I don't know why. Any help would be welcome. Here is the code. ``` <?php class product { var $ssProductName; var $ssVendorName; var $ssDescr; var $ssURI; // Clean constructor, strings must be cleaned before use function __construct($ssProd, $ssVendor, $ssD, $ssU) { $this->$ssProductName = $ssProd; $this->$ssVendorName = $ssVendor; $this->$ssDescr = $ssD; $this->$ssURI = $ssU; } // print a table of the values function DisplayOneEntry() { echo '<table border="1"> <tr> <td>'.$this->$ssProductName.'</td> <td>'.$this->$ssVendorName.'</td> <td>'.$this->$ssDescr.'</td> <td>'.$this->$ssURI.'</td> </tr> </table>'; } } echo "<HTML>"; echo "A"; $newP = new product("Redhat", "Redhat corp", "Leader in", "www.redhat.com"); echo "B"; $newP->DisplayOneEntry(); echo "</HTML>"; ?> ``` But the output is just: ``` <HTML> A ``` Then nothing else. This is running on a hosting provider using php 5.2.9 and Apache 2.2.
You need to access the member variables with: ``` $this->variableName ``` Not: ``` $this->$variableName ```
``` $this->$ssProductName = $ssProd; ``` should be ``` $this->ssProductName = $ssProd; ``` no $ after the ->
PHP class function not working
[ "", "php", "" ]
When class implements Serializable in Eclipse, I have two options: add default `serialVersionUID(1L)` or generated `serialVersionUID(3567653491060394677L)`. I think that first one is cooler, but many times I saw people using the second option. Is there any reason to generate `long serialVersionUID`?
As far as I can tell, that would be only for compatibility with previous releases. This would only be useful if you neglected to use a serialVersionUID before, and then made a change that you know should be [compatible](http://java.sun.com/javase/6/docs/platform/serialization/spec/version.html#6678) but which causes serialization to break. See the [Java Serialization Spec](http://java.sun.com/javase/6/docs/platform/serialization/spec/version.html) for more details.
The purpose of the serialization version UID is to keep track of different versions of a class in order to perform valid serialization of objects. The idea is to generate an ID that is unique to a certain version of an class, which is then changed when there are new details added to the class, such as a new field, which would affect the structure of the serialized object. Always using the same ID, such as `1L` means that in the future, if the class definition is changed which causes changes to the structure of the serialized object, there will be a good chance that problems arise when trying to deserialize an object. If the ID is omitted, Java will actually calculate the ID for you based on fields of the object, but I believe it is an expensive process, so providing one manually will improve performance. Here's are a couple of links to articles which discuss serialization and versioning of classes: * [JDC Tech Tips: February 29, 2000](http://java.sun.com/developer/TechTips/2000/tt0229.html) *(link broken as of February 2013)* * [Discover the secrets of the Java Serialization API](http://www.oracle.com/technetwork/articles/java/javaserial-1536170.html)
Why generate long serialVersionUID instead of a simple 1L?
[ "", "java", "serialization", "code-generation", "serialversionuid", "" ]
I have a table in a SQL Server 2005 Database that is used a lot. It has our product on hand availability information. We get updates every hour from our warehouse and for the past few years we've been running a routine that truncates the table and updates the information. This only takes a few seconds and has not been a problem, until now. We have a lot more people using our systems that query this information now, and as a result we're seeing a lot of timeouts due to blocking processes. ... so ... We researched our options and have come up with an idea to mitigate the problem. 1. We would have two tables. Table A (active) and table B (inactive). 2. We would create a view that points to the active table (table A). 3. All things needing this tables information (4 objects) would now have to go through the view. 4. The hourly routine would truncate the inactive table, update it with the latest information then update the view to point at the inactive table, making it the active one. 5. This routine would determine which table is active and basically switch the view between them. What's wrong with this? Will switching the view mid query cause problems? Can this work? Thank you for your expertise. *Extra Information* * the routine is a SSIS package that peforms many steps and eventually truncates/updates the table in question * The blocking processes are two other stored procedures that query this table.
Have you considered using [snapshot isolation](http://msdn.microsoft.com/en-us/library/ms345124(SQL.90).aspx). It would allow you to begin a big fat transaction for your SSIS stuff and still read from the table. This solution seems much cleaner than switching the tables.
I think this is going about it the wrong way - updating a table has to lock it, although you can limit that locking to per page or even per row. I'd look at not truncating the table and refilling it. That's always going to interfere with users trying to read it. If you did update rather than replace the table you could control this the other way - the reading users shouldn't block the table and may be able to get away with optimistic reads. Try adding the with(nolock) hint to the reading SQL View statement. You should be able to get very large volumes of users reading even with the table being regularly updated.
What's the best way to update data in a table while it's in use without locking the table?
[ "", "sql", "sql-server", "sql-server-2005", "view", "truncate", "" ]
From Schaums C++ text Removal of goto- says use a flag code segment: ``` const int N2 = 5; int i, j, k; for (i = 0; i < N2; i++) { for (j = 0; j < N2; j++) { for (k = 0; k < N2; k++) if (i + j + k > N2) goto esc; else cout << i + j + k << " "; cout << "* "; } esc: cout << "." << endl; } ``` The solution: ``` const int 5; int i, j, k; bool done = false; for (i = 0; i < N2; i++) { for (j = 0; j < N2 && !done; j++) { for (k = 0; k < N2 && !done; k++) if (i + j + k > N2) done true; else cout << i + j + k << " "; cout << "* "; } cout << "." << endl; done = false; } ``` The output of the structured solution does not produce the same result...as the goto one... I can't see the problem 2. Also, what would be another way to eliminate the goto?- Could I not use a flag and just compliment the condition. Thanks ...
``` const int 5; int i, j, k; bool done = false; for (i = 0; i < N2; i++) { for (j = 0; j < N2 && !done; j++) { for (k = 0; k < N2 && !done; k++) if (i + j + k > N2) done = true; else cout << i + j + k << " "; if (!done) // <-- Add this line cout << "* "; } cout << "." << endl; done = false; } ```
A great way to code this kind of loop escape functionality is a return; statement. Take: ``` const int N2 = 5; void inner_loop(const int i) { for (int j = 0; j < N2; ++j) { for (int k = 0; k < N2; ++k) { if (i + j + k > N2) return; cout << i + j + k << " "; } cout << "* "; } } for (int i = 0; i < N2; ++i) { inner_loop(i); cout << "." << endl; } ```
Structured solution without using a jump statement
[ "", "c++", "" ]
I'm building an application that gives users the option to send out an email notification to their friends. The options I would like to give them for this are to: * manually write down which emails they would like to send to * choose contacts from a list of ones already in the database for that user * choose all contacts from facebook, twitter, digg, gmail, or msn to send the email to Is there any way I can retrieve all of the email addresses for a certain contact from these different websites? For example, if I chose the option to send out email notification and I wanted to send it to all of my friends on my facebook account, how could I do this? (Remembering that the user is interacting with a completely separate website and should not have to go onto facebook to send this emails) Any ideas? Thanks in advance for your help! Matt
Google contacts api: <http://code.google.com/apis/contacts/> Windows Live contacts api: <http://msdn.microsoft.com/en-us/library/bb463989.aspx> Facebook's apis are here: <http://wiki.developers.facebook.com/index.php/API>
For each websites (twitter, facebook, etc.) use their API for accessing contacts.
How can I retrieve contacts/emails from things like MSN, Twitter, Facebook, GMail , etc...?
[ "", "asp.net", "javascript", "email", "social-networking", "contacts", "" ]
How to determine the element type in WPF programatically? For example my xaml is consisting of textbox, radio buttons, combo's, list boxes etc. In the load event, say I want to do something related to the controls.(Say for all textbox, the foreground color will be red, for all labels the background color will be green).. something of that sort. So I have to loop through the entire list of controls present in the Xaml and then have to write the control specific logic. Is it by using Framework element? Please give the code in c#. For example please take 3/4 controls of your choice. I am also searching in google! Thanks in advance
if you only have a finite number of types to check against try casting using the "as" operator and then checking for null. ``` Button button = control as Button; if (button != null) { // this is a button) } ... ``` The as operator will not throw an exception if the cast cannot be done. EDIT: IF you are only trying to achieve styling of the controls you should look at the `<Style/>` tag. See [here](http://msmvps.com/blogs/kevinmcneish/archive/2008/01/07/how-to-apply-a-wpf-style-to-all-elements-of-a-particular-type.aspx) for a good example
You can use: ``` if (element is Grid) { } else if (element is Label) ... ```
Determine WPF element type
[ "", "c#", "wpf", "" ]
When you enter a space ' ' while typing into cin, it will take the first string before the space as the first value and the later one as the next. So let's say we have this code: ``` cout << "Enter your Name"; cin >> name; cout << "Enter your age"; cin >> age; ``` Now, let's say a user enters "John Bill". It would take his name to be John and his age to be Bill. Is there a way to: 1. Have the line automatically change it from a ' ' to a '\_'? 2. Have it so that it will read that line as that line and have the space ' ' read as a normal character?
To read a line in C++: ``` #include <iostream> #include <string> using namespace std; int main() { cout << "Enter some stuff: " ; string line; getline( cin, line ); cout << "You entered: " << line << endl; } ```
You want to use cin.getline() which can be used like this: ``` cin.getline(name, 9999, '\n'); ``` And will include everything up to the newline or 9999 characters. This only works for c-style char arrays though. ``` getline(cin, name, '\n'); ``` will work for std::strings. If you want to replace the space with an underscore you're going to have to do that manually. Assuming you are using std::string you could make a function like this: ``` void replace_space(std::string &theString) { std::size_t found = theString.find(" "); while(found != string::npos) { theString[found] = '_'; found = theString.find(" ", found+1); } } ```
Changing C++ cin
[ "", "c++", "cin", "" ]
i want to use jquery UI's datepicker to trigger a POST that would then load information from the date picked on the datepicker from my database. so i guess this is a two-part question is there a way i can make it so the datepicker date, when selected, just gets passed into a POST, so someone would click on jan 1 2010 and it would automatically go to mysite.com?date=01012010 or something like that the way it is now the datepicker just updates a text box with the date, so upon clicking on jan 1 2010, the text box is populated with 01-01-2010 which brings me to part 2 if there is no way to do what i asked in part 1, is there a method that triggers an event on the text box being updated, that way i could just do onTextUpdate{ redirect to - mysite.com?date=$whateverIsInTextBox } or something like that please let me know if you have any solutions or ideas to do this, thanks a lot
You could do something like this if you don't want to use ajax: ``` $("#datepicker").datepicker({ onSelect: function(date, instance) { window.location = "www.example.com/?date="+date; } }); ``` And if you do: ``` $("#datepicker").datepicker({ onSelect: function(date, instance) { $.ajax ({ type: "GET", url: "www.example.com", data: "date="+date, success: function(result) { //do something } }); } }); ```
use the OnSelect event of the date picker ``` $('id').datepicker({ onSelect: function(dateText, ins) { ... } }); ``` you can try other events of the datepicker control based on your requirement
jQuery Datepicker to Trigger a POST
[ "", "javascript", "jquery", "jquery-ui", "datepicker", "uidatepicker", "" ]
Quick Question. Eval in JavaScript is unsafe is it not? I have a JSON object as a string and I need to turn it into an actual object so I can obtain the data: ``` function PopulateSeriesFields(result) { data = eval('(' + result + ')'); var myFakeExample = data.exampleType } ``` If it helps I am using the $.ajax method from jQuery. Thanks
Well, safe or not, when you are using jQuery, you're better to use the [$.getJSON()](http://docs.jquery.com/Ajax/jQuery.getJSON) method, not $.ajax(): ``` $.getJSON(url, function(data){ alert(data.exampleType); }); ``` `eval()` is usually considered safe for JSON parsing when you are only communicating with your own server and especially when you use a good JSON library on server side that guarantees that generated JSON will not contain anything nasty. Even Douglas Crockford, the author of JSON, said that you shouldn't use `eval()` anywhere in your code, except for parsing JSON. See the corresponding section in his book [JavaScript: The Good Parts](http://books.google.com/books?id=PXa2bby0oQ0C&pg=PA139&lpg=PA139&dq=JavaScript:+The+Good+Parts+eval&source=bl&ots=HHpll5r0gG&sig=3OTFEqDnRBVaLXSUDK1JsCGvxIg&hl=et&ei=4pcmSs7FAsG__Qa_2P3XBw&sa=X&oi=book_result&ct=result&resnum=2)
You should use [JSON](http://www.json.org/js.html) and write JSON.parse. "Manual" parsing is too slow, so JSON.parse implementation from the library checks stuff and then ends up using eval, so it is [still unsafe](http://yuiblog.com/blog/2007/04/10/json-and-browser-security/). But, if you are using a newer browser (IE8 or Firefox), the library code is not actually executed. Instead, **native browser support** kicks in, and then you are safe. Read more [here](http://blog.mozilla.com/webdev/2009/02/12/native-json-in-firefox-31/) and [here](http://blogs.msdn.com/ie/archive/2008/09/10/native-json-in-ie8.aspx).
Alternatives to JavaScript eval() for parsing JSON
[ "", "javascript", "jquery", "security", "json", "eval", "" ]
I need to create multiple records in sqlserver, each with the same value in column A, but with a unique value in column B. I have the values for column B in an array. I am using VS2008, aspnet, c# 3.5, sqlserver 2005. Am I better off Option 1. Making 1 call to a stored procedure in sqlserver from c# code, and then doing all the processing work in the stored procedure in tsql? This would involve combining all the values in the c# array into one comma delimited string and passing the string to tsql as a parameter, then looping and breaking the string apart into individual values and inserting a record for each one, all within a stored procedure. From what I can see, this would involve easy rollback if necessary, but very clumsy string processing in tsql. Or Option 2. Doing the looping in c# and passing the data as sqlparams from c# one record at a time to a stored proc to insert each record. Ie, foreach ( int key in myarray) … insert a record I could do this code in my sleep, but how would I be able to rollback if something happened in the middle of processing? And should I do the looping within in a singe connection.open and connection.close? Anyone have any other options for doing this?
this topic is extensively covered here: [Arrays and lists in SQL 2005](http://www.sommarskog.se/arrays-in-sql-2005.html)
The easiest way to implement this is using Option 1: passing the array as a delimited string. I used to do this in the pre-sql2005 days in conjunction with this **[TSQL Split Function](http://blogs.microsoft.co.il/blogs/itai/archive/2009/02/01/t-sql-split-function.aspx)**. I would pass the array using "|" as a delimiter. These days, I serialize the array into XML and then insert the contents into a table variable for processing using the **[`sp_xml_preparedocument`](http://msdn.microsoft.com/en-us/library/ms187367.aspx)** stored procedure. I wouldn't use option 2 since it makes multiple calls to database.
Since there is no Sqlserver array parameter, what's the best way to proceed?
[ "", "c#", "asp.net", "sql-server", "sql-server-2005", "stored-procedures", "" ]
I'm playing with Python Class inheritance and ran into a problem where the inherited `__init__` is not being executed if called from the sub-class (code below) the result I get from Active Python is: --- ``` >>> start Tom Sneed Sue Ann Traceback (most recent call last): File "C:\Python26\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 312, <br>in RunScript exec codeObject in __main__.__dict__ File "C:\temp\classtest.py", line 22, in <module> print y.get_emp() File "C:\temp\classtest.py", line 16, in get_emp return self.FirstName + ' ' + 'abc' AttributeError: Employee instance has no attribute 'FirstName' ``` --- ## Here's the code ``` class Person(): AnotherName = 'Sue Ann' def __init__(self): self.FirstName = 'Tom' self.LastName = 'Sneed' def get_name(self): return self.FirstName + ' ' + self.LastName class Employee(Person): def __init__(self): self.empnum = 'abc123' def get_emp(self): print self.AnotherName return self.FirstName + ' ' + 'abc' x = Person() y = Employee() print 'start' print x.get_name() print y.get_emp() ```
Three things: 1. You need to explicitly call the constructor. It isn't called for you automatically like in C++ 2. Use a new-style class inherited from object 3. With a new-style class, use the super() method available This will look like: ``` class Person(object): AnotherName = 'Sue Ann' def __init__(self): super(Person, self).__init__() self.FirstName = 'Tom' self.LastName = 'Sneed' def get_name(self): return self.FirstName + ' ' + self.LastName class Employee(Person): def __init__(self): super(Employee, self).__init__() self.empnum = 'abc123' def get_emp(self): print self.AnotherName return self.FirstName + ' ' + 'abc' ``` Using super is recommended as it will also deal correctly with calling constructors only once in multiple inheritance cases (as long as each class in the inheritance graph also uses super). It's also one less place you need to change code if/when you change what a class is inherited from (for example, you factor out a base-class and change the derivation and don't need to worry about your classes calling the wrong parent constructors). Also on the MI front, you only need one super call to correctly call all the base-class constructors.
You should explicitely call the superclass' init function: ``` class Employee(Person): def __init__(self): Person.__init__(self) self.empnum = "abc123" ```
Python Class Inheritance issue
[ "", "python", "class", "inheritance", "" ]
I have schema similar to the following: ``` create table bar ( instrument varchar(255) not null, bar_dttm datetime not null, bar_open int not null, bar_close int not null ) ``` I would like to query the table, and return the most recent 5 rows per instrument. I can do it instrument by instrument, with: ``` select top 5 instrument, bar_dttm, bar_open, bar_close from bar where instrument = 'XXX' order by bar_dttm desc ``` I'd like to do this for all instruments at once in one query. Is this possible? I am running SQL Server 2008.
CROSS APPLY is how you usually do this - <http://msdn.microsoft.com/en-us/library/ms175156.aspx> EDIT - add example, something like this: ``` select bar1.instrument ,bar2.* from ( select distinct instrument from bar) as bar1 cross apply ( select top 5 bar2.instrument ,bar2.bar_dttm ,bar2.bar_open ,bar2.bar_close from bar as bar2 where bar2.instrument = bar1.instrument) as bar2 ``` Typically you would want to add an order by in there. Edit - added distinct to the query, hopefully that gives you want you want. Edit - added missing 'select' keyword at top. copy & paste bug FTL!
using SQL 2008, you could use a partitioned row number clause with a CTE... ``` with MyCte AS (SELECT instrument, bar_dttm, bar_open, bar_close, PartitionedRowNum = ROW_NUMBER() OVER (PARTITION BY instrument ORDER BY bar_dttm DESC) from bar) select * from MyCte where PartitionedRowNum <= 5 ```
Selecting the top n rows within a group by clause
[ "", "sql", "sql-server", "" ]
In the following code, there is a memory leak if `Info::addPart1()` is called multiple times by accident: ``` typedef struct { }part1; typedef struct { }part2; class Info { private: part1* _ptr1; part2* _ptr2; public: Info() { _ptr1 = _ptr2 = NULL; } ~Info() { delete _ptr1; delete _ptr2; } addPart1() { _ptr1 = new part1; } addPart2() { _ptr2 = new part2; } }; Info _wrapper; _wrapper.addPart1(); _wrapper.addPart2(); ``` Is there a C++ idiom to handle this problem ? I could rewrite `addPart1` and `addPart2` like this to defend the MLK ``` addPart1() { if(_ptr1 != NULL) delete _ptr1; _ptr1 = new part1; } ``` Is that a good solution?
Use a smart pointer such as [boost:shared\_ptr , boost:scoped\_ptr](http://www.boost.org/doc/libs/1_39_0/libs/smart_ptr/smart_ptr.htm) is recommended to manage the raw pointer. [auto\_ptr](http://www.gotw.ca/publications/using_auto_ptr_effectively.htm) is tricky to work with, you need pay attention to that.
You should read about the [smart pointer idiom](http://www.google.co.il/url?sa=t&source=web&ct=res&cd=1&url=http%3A%2F%2Fen.wikipedia.org%2Fwiki%2FSmart_pointer&ei=12wqSvT8HM-Q_QbLxrXwCg&usg=AFQjCNGeVayKuk2pN0Uck0nTjqtKHgHhMg&sig2=ACD0Z1-zMomIaoPhCXi-Vw) and about [RAII](http://www.google.co.il/url?sa=t&source=web&ct=res&cd=1&url=http%3A%2F%2Fen.wikipedia.org%2Fwiki%2FResource_Acquisition_Is_Initialization&ei=92wqSuvIEpGX_QaDtu3eCg&usg=AFQjCNFKEzMHJRecJDAsT3j7pX_hkMAAYQ&sig2=VFjOs746vaahJKTyuJR0yg). I suggest taking a look into the new technical report (TR1). Take a good look [here](http://beans.seartipy.com/2006/12/10/getting-started-with-c-tr1-libraries/) and [here](http://en.wikipedia.org/wiki/Technical_Report_1). Also take a look at boost's smart pointers. I recommend [loki-lib](http://www.google.co.il/url?sa=t&source=web&ct=res&cd=1&url=http%3A%2F%2Floki-lib.sourceforge.net%2F&ei=r2wqSvWvAdO0sgbl_cyeDA&usg=AFQjCNEjR6zfmUsbZnO_cP3-wB0rqDKTnA&sig2=4jBUZtTLxgyrP0IystDcPQ)'s SmartPtr or StrongPtr classes.
C++ idiom to avoid memory leaks?
[ "", "c++", "" ]
I'm developing a 'TreeDict' class in Python. This is a basically a dict that allows you to retrieve its key-value pairs in sorted order, just like the Treemap collection class in Java. I've implemented some functionality based on the way unique indexes in relational databases can be used, e.g. functions to let you retrieve values corresponding to a range of keys, keys greater than, less than or equal to a particular value in sorted order, strings or tuples that have a specific prefix in sorted order, etc. Unfortunately, I can't think of any real life problem that will require a class like this. I suspect that the reason we don't have sorted dicts in Python is that in practice they aren't required often enough to be worth it, but I want to be proved wrong. Can you think of any specific applications of a 'TreeDict'? Any real life problem that would be best solved by this data structure? I just want to know for sure whether this is worth it.
It's useful when you need to go through a Dictionary in order of the keys; which comes up on occasion. I've actually found its infinitely more common in certain programming contests then anything else (think ACM, etc). The most useful feature of a TreeMap is when you want to quickly find the min or max key; using a sorted dictionary this is often a single method call; and algorithmically can be done in O(log(n)) time, as opposed to iterating over each key looking for a min/max if the collection is unsorted. Basically, a much friendlier interface. One of the more common times I run into it is when objects are identified by a specific name, and you want to print out the objects ordered according to the name; say a mapping from directory name to number of files in a directory. One other place I've used it is in an excel spreadsheet wrapper; mapping from row number to row object. This lets you quickly find the last row index, without looping through each row. Also, it's useful when you can easily define a comparison relation on keys, but not necessarily a hashing function, as needed for HashMaps. The best (though weak) example I can think of is case insensitive string keys.
I've seen several answers pointing to the "walk in ordered sequence" feature, which is indeed important, but none highlighting the other big feature, which is "find first entry with a key >= this". This has many uses even when there's no real need to "walk" from there. For example (this came up in a recent SO answer), say you want to generate pseudo-random values with given relative frequencies -- i.e, you're given, say, a dict `d`: ``` {'wolf': 42, 'sheep': 15, 'dog': 23, 'goat': 15, 'cat': 5} ``` and need a way to generate 'wolf' with a probability of 42 out of 100 (since 100 is the total of the relative frequencies given), 'sheep' 15 out of 100, and so on; and the number of distinct values can be quite large, as can the relative frequencies. Then, store the given values (in whatever order) as the values in a tree map, with the corresponding keys being the "total cumulative frequency" up to that point. I.e.: ``` def preprocess(d): tot = 0 for v in d: tot += d[v] treemap.insert(key=tot, value=v) return tot, treemap ``` Now, generating a value can be pretty fast (`O(log(len(d)))`), as follows: ``` def generate(tot, treemap, r=random): n = r.randrange(tot) return treemap.firstGTkey(n).value ``` where `firstGTKey` is a method that returns the first entry (with `.key` and `.value` attributes, in this hypothetical example) with a key > the given argument. I've used this approach with large files stored as B-Trees, for example (using e.g. `bsddb.bt_open` and the `set_location` method).
What Can A 'TreeDict' (Or Treemap) Be Used For In Practice?
[ "", "python", "dictionary", "collections", "treemap", "" ]
In my localizable app I throw an ArgumentException like this: ``` throw ArgumentException("LocalizedParamName", "LocalizedErrorMessage"); ``` And I catch it like this: ``` catch (Exception ex) { Display(ex.Message); } ``` I'm getting the resulting error message as: LocalizedErrorMessage Parameter name: LocalizedParamName The problem here is "Parameter name: ", which is in english rather than my application's language. I suppoose that string is in the language of the .NET framework. Can anyone confirm that? One workaround is doing this: ``` catch (ArgumentException ex) { Display((ex as Exception).Message + "\n" + "Translated(Parameter name:)"+ ex.ParamName); } catch (Exception ex) { Display(ex.Message); } ``` Is there any other more elegant way?
The message in exceptions should be for developers, not for end users. You should always attempt to catch your exceptions in such a way that you can display a meaningful error message. (No, "The program has encountered an unexpected error and will now exit" is not meaningful.) The reason why you shouldn't display the message of an exception to an end user is because the user doesn't care that the developer passed the wrong argument from function `Foo()` to function `Bar()`, let alone how it was wrong. But when you get around to fixing the bug, you'll need to know that. So, don't worry about internationalizing your exception messages but do internationalize your messages to the user telling them what happened, what you're doing to fix it and hopefully how they can avoid the problem in the future.
You are calling the constructor ArgumentException(string message, string paramName) with a non-empty paramName. When you do this, you get the result you see, that is your message followed by "Parameter Name: yourParamName". The text "Parameter Name: " comes from the .NET Framework resources: the reason you are not getting a localized version is that you presumably haven't installed the relevant .NET Framework language pack(s) on your machine. You can download language packs [here](http://www.microsoft.com/Downloads/details.aspx?familyid=39C8B63B-F64B-4B68-A774-B64ED0C32AE7&displaylang=en). If you install the language pack(s) for the language(s) you're using, you'll get the result you expect. Alternatively, you can use the constructor ArgumentException(string message), and build your own message including the name of the parameter.
Localization of ArgumentException.Message in .NET
[ "", "c#", "localization", "" ]
I'm trying to make a WordPress site that has six lists on a page, each list showing posts from a different category. Simple. But then, if a user selects a tag, taking them to that tag archive page, I want them to still see the six-list template, but all the posts within each category are also filtered by the tag. So lists of posts are filtered first by tag, and then by category. As far as I can tell, there is no way of doing this using query\_posts or anything, it needs more advanced use of the database, but I have no idea how to do this! I think that there's a similar question on here, but because I know very little PHP and no MySQL, I can't make sense of the answers!
Right, I have finally found a relatively simple solution to this. There's a bug in WordPress preventing a query of both category and tags working, so `query_posts('cat=2&tag=bread');` wouldn't work, but a way around this is `query_posts('cat=2&tag=bread+tag=bread');` which magically works. In a tag.php template, I wanted it to pick up the tag from that archive, so I had to do this: ``` <?php query_posts('cat=12&tag='.$_GET['tag'].'+'.$_GET['tag']); ?> ``` which works perfectly.
Try this code: ``` query_posts('tag=selected_tag'); while (have_posts()) : the_post(); foreach((get_the_category()) as $category) { if ($category->cat_name == 'selected_category') { // output any needed post info, for example: echo the_title(); } } endwhile; ```
WordPress - producing a list of posts filtered by tag and then category
[ "", "php", "mysql", "wordpress", "tags", "" ]
I am trying to use javascript, without framework(prototype, jQuery,etc), to insert data passed from a html form to an mysql database. I have managed to get this working but, get a problem with some special characters commonly used in my language(æøå). utf-8 supports these characters, and everything works fine when I skip the javascript. However when I try to pass the content of the html form through javascript post function and executing the query with my working php script, every æøå is converted into æøå. To break it down, does javascript somehow force a specific charset when no other is determined in the code? I have tried to specify charset in the header of the javascript post and the php file as well as the html form. I believe it must be something wrong or missing in my javascript file, formpost.js: ``` function sendText(visbool){ var http =new GetXmlHttpObject(); var url = "sendtext.php"; var ovrskrift = document.form1.overskrift.value; var cont = document.form1.content.value; var params = "overskrift=" + ovrskrift + "&tekst=" + cont + "&visbool=" + visbool; http.open("POST", url, true); //Send the proper header information along with the request http.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); http.setRequestHeader("Content-length", params.length); http.setRequestHeader("Connection", "close"); http.onreadystatechange = function() {//Call a function when the state changes. if(http.readyState == 4 && http.status == 200) { // gjør noe smart her } } http.send(params); } function GetXmlHttpObject() { var objXMLHttp=null; if (window.XMLHttpRequest) { objXMLHttp=new XMLHttpRequest(); } else if (window.ActiveXObject) { objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP"); } return objXMLHttp; } ``` sendtext.php: ``` <?php //variabler for spørring $date= date('Y-m-d'); $overskrift= $_POST["overskrift"]; $ostr='36'; $tekst= $_POST["content"]; //$tekst="test tekst"; $istr='32'; $bilde=""; $style="onlyinfo.css"; //$vis=$_POST['visbool']; $vis=0; require ('../config.php'); // henter informasjon om database tilkoblingen fra config.php if (!$con){die('Could not connect: ' . mysql_error());} // lager feilmelding hvis tilkoblingen mislyktes // spørring for databasen, konstrueres etter variablene som er angitt ovenfor $sql="INSERT INTO tbl_info(dato,overskrift_tekst,overskrift_str,infotekst_tekst,infotekst_str,bilde,style,vismeg) VALUES('" . $date . "','" . $overskrift . "','" . $ostr . "','" . $tekst . "','" . $istr . "','" . $bilde . "','" . $style . "','" . $vis . "')"; $result = mysql_query($sql); // kjører spørring og lagrer resultat i $result mysql_close($con); // lukker database tilkoblingen ?> ``` createslide.php: (reserved .php extension for future code implementation) ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" dir="ltr"> <head> <title>inforMe: Legg til side</title> <link type="text/css" rel="stylesheet" href="./css/style.css" id="adminss"> <script src="./js/formpost.js"></script> <script type="text/javascript" src="./tinymce/jscripts/tiny_mce/tiny_mce.js"></script> <script type="text/javascript"> tinyMCE.init({ mode : "textareas" }); </script> </head> <body> <div class="imgupload"> <input type="button" value="Last opp bilde"> <img src="" /> </div> <div class="form"> <form name="form1" method="post" action="sendtext.php"> <label for="overskrift">Overskrift:</label> <input type="text" size="70" id="overskift" name="overskrift"><br /> <label for="content">Tekst:</label> <textarea id="content" name="content" cols="50" rows="15">This is some content that will be editable with TinyMCE.</textarea> <input type="button" value="save draft" onclick="sendText(0)"/> <input type="button" value="save and publish" onclick="sendText(1)"/> <input type="submit" value="regular submit button"/> </form> </div> </body> </html> ``` **NB!** I don't really know where to put this information so.. well.. I decided to go with it here: First of all thanks for all good suggestions below. I belive the question were answered. As to my problem, it is only partly solved. It seems like the utf-8 charset is lost somewhere along the line here, if I create a new mysql database with Latin-1 charset and change the charset options in my files to iso-8859-1 it works exactly right. Since my test setup is based on all norwegian software(browsers, db server, etc), I suppose wherever it is not otherwise specified it will return iso-8859-1 **NBB!** And now it's all good again. everything works fine when I add: header('Content-Type: text/plain; charset=utf-8'); to the top of my sendtext.php file.
Try appending the charset to the content-type header like this: ``` "application/x-www-form-urlencoded; charset=utf-8;" ``` Also, in your document you should specify it is utf-8 in the header: ``` <META http-equiv="Content-Type" content="text/html; charset=utf-8" /> ``` You should probably also do encodeURI(value) on all your values so it's properly url encoded.
Internally, JavaScript uses Unicode, so it can store your umlauts without problem. Note: Unicode != UTF-8. But then, you try to send that text to your server and here, the trouble starts. The wire (Internet) between the browser and your server doesn't support Unicode, so the browser has to encode the data. So it converts the Unicode to an UTF-8 byte stream. On the server side, you must convert the data back to Unicode.
Does javascript force specific charset?
[ "", "javascript", "html", "forms", "post", "character-encoding", "" ]
``` time_t seconds; time(&seconds); cout << seconds << endl; ``` This gives me a timestamp. How can I get that epoch date into a string? ``` std::string s = seconds; ``` does not work
Try [`std::stringstream`](http://en.cppreference.com/w/cpp/io/basic_stringstream). ``` #include <string> #include <sstream> std::stringstream ss; ss << seconds; std::string ts = ss.str(); ``` A nice wrapper around the above technique is Boost's [`lexical_cast`](http://www.boost.org/doc/libs/release/libs/conversion/lexical_cast.htm): ``` #include <boost/lexical_cast.hpp> #include <string> std::string ts = boost::lexical_cast<std::string>(seconds); ``` And for questions like this, I'm fond of linking [The String Formatters of Manor Farm](http://www.gotw.ca/publications/mill19.htm) by Herb Sutter. UPDATE: With C++11, use [`to_string()`](http://en.cppreference.com/w/cpp/string/basic_string/to_string).
Try this if you want to have the time in a readable string: ``` #include <ctime> std::time_t now = std::time(NULL); std::tm * ptm = std::localtime(&now); char buffer[32]; // Format: Mo, 15.06.2009 20:20:00 std::strftime(buffer, 32, "%a, %d.%m.%Y %H:%M:%S", ptm); ``` For further reference of strftime() check out [cppreference.com](http://en.cppreference.com/w/cpp/chrono/c/strftime)
String representation of time_t?
[ "", "c++", "timestamp", "" ]
In Java, of course. I'm writing a program and running it under a Windows environment, but I need the output (.csv) to be done in Unix format. Any easy solution? Thanks!
**Note: as reported in comments, the approach given below breaks in JDK 9+. Use the approach in James H.'s answer.** --- By "Unix format" do you mean using "\n" as the line terminator instead of "\r\n"? Just set the `line.separator` system property before you create the PrintWriter. Just as a demo: ``` import java.io.*; public class Test { public static void main(String[] args) throws Exception // Just for simplicity { System.setProperty("line.separator", "xxx"); PrintWriter pw = new PrintWriter(System.out); pw.println("foo"); pw.println("bar"); pw.flush(); } } ``` Of course that sets it for the whole JVM, which isn't ideal, but it may be all you happen to need.
To write a file with unix line endings, override println in a class derived from PrintWriter, and use print with \n. ``` PrintWriter out = new PrintWriter("testFile") { @Override public void println() { write('\n'); } }; out.println("This file will always have unix line endings"); out.println(41); out.close(); ``` This avoids having to touch any existing println calls you have in your code.
Is there a way to make PrintWriter output to UNIX format?
[ "", "java", "unix", "" ]
Is there an *inexpensive* way to concatenate integers in csharp? Example: 1039 & 7056 = 10397056
If you can find a situation where this is expensive enough to cause any concern, I'll be very impressed: ``` int a = 1039; int b = 7056; int newNumber = int.Parse(a.ToString() + b.ToString()) ``` Or, if you want it to be a little more ".NET-ish": ``` int newNumber = Convert.ToInt32(string.Format("{0}{1}", a, b)); ``` int.Parse is *not* an expensive operation. Spend your time worrying about network I/O and O^N regexes. Other notes: the overhead of instantiating StringBuilder means there's no point if you're only doing a few concatenations. And very importantly - if you *are* planning to turn this back into an integer, keep in mind it's limited to ~2,000,000,000. Concatenating numbers gets very large very quickly, and possibly well beyond the capacity of a 32-bit int. (signed of course).
I'm a bit late at the party, but recently I had to concatenate integers. With 0 < a,b < 10^9 it can be done quite fast. ``` static ulong concat(uint a, uint b) { if (b < 10U) return 10UL * a + b; if (b < 100U) return 100UL * a + b; if (b < 1000U) return 1000UL * a + b; if (b < 10000U) return 10000UL * a + b; if (b < 100000U) return 100000UL * a + b; if (b < 1000000U) return 1000000UL * a + b; if (b < 10000000U) return 10000000UL * a + b; if (b < 100000000U) return 100000000UL * a + b; return 1000000000UL * a + b; } ``` Edit: the version below might be interesting (platform target: x64). ``` static ulong concat(ulong a, uint b) { const uint c0 = 10, c1 = 100, c2 = 1000, c3 = 10000, c4 = 100000, c5 = 1000000, c6 = 10000000, c7 = 100000000, c8 = 1000000000; a *= b < c0 ? c0 : b < c1 ? c1 : b < c2 ? c2 : b < c3 ? c3 : b < c4 ? c4 : b < c5 ? c5 : b < c6 ? c6 : b < c7 ? c7 : c8; return a + b; } ```
Concatenate integers in C#
[ "", "c#", "" ]
While performing a refactoring, I ended up creating a method like the example below. The datatype has been changed for simplicity's sake. I previous had an assignment statement like this: ``` MyObject myVar = new MyObject(); ``` It was refactored to this by accident: ``` private static new MyObject CreateSomething() { return new MyObject{"Something New"}; } ``` This was a result of a cut/paste error on my part, but the `new` keyword in `private static new` is valid and compiles. **Question**: What does the `new` keyword signify in a method signature? I assume it's something introduced in C# 3.0? How does this differ from `override`?
[`new` modifier reference from MSDN](http://msdn.microsoft.com/en-us/library/435f1dw2.aspx). And here is an example I found on the net from a Microsoft MVP that made good sense ([link to original](http://social.msdn.microsoft.com/forums/en-US/Vsexpressvcs/thread/65e02299-300f-4b74-8f0a-679f490605f5)): ``` public class A { public virtual void One(); public void Two(); } public class B : A { public override void One(); public new void Two(); } B b = new B(); A a = b as A; a.One(); // Calls implementation in B a.Two(); // Calls implementation in A b.One(); // Calls implementation in B b.Two(); // Calls implementation in B ``` `override` can only be used in very specific cases. From MSDN: > You cannot override a non-virtual or > static method. The overridden base > method must be virtual, abstract, or > override. So the `new` keyword is needed to allow you to 'override' non-`virtual` and `static` methods.
No, it's actually not "new" (pardon the pun). It's basically used for "hiding" a method. IE: ``` public class Base { public virtual void Method(){} } public class Derived : Base { public new void Method(){} } ``` If you then do this: ``` Base b = new Derived(); b.Method(); ``` The method in the Base is the one that will be called, NOT the one in the derived. Some more info: <http://www.akadia.com/services/dotnet_polymorphism.html> **Re your edit:** In the example that I gave, if you were to "override" instead of using "new" then when you call b.Method(); the Derived class's Method would be called because of Polymorphism.
new keyword in method signature
[ "", "c#", "methods", "keyword", "" ]
I'm running IIS 5 on a Windows 2000 machine. I have an application setup in my "scripts" directory in my website, because it runs some compiled DLL's. The application is set to run scripts and executables. For some reason, when I try and access any .js files in that directory, I get "The system cannot find the file specified.". I tried adding .js as a "text/javascript" mime type, to both the website and the directory, but it doesn't seem to help. I also checked the web server itself, and the .js mime type was set to application/octet-stream. I changed it to text/javascript, but it still doesn't work. Do I need to restart IIS or the application pool? Or am I looking in the wrong place. I also tried using text/text and text/html but that didn't help. I am able to access .htm, .jpg, and even .asp files in that directory. Any ideas? Thanks in advance!
URLSCAN!!!!! I checked the log directory for URLScan and it was blocking files based on the .js extension. I added it to the urlscan.ini, restarted IIS, and voila! It worked! More Info: Directories: URLScan - C:\WINNT\System32\inetsrv\urlscan\ URLScan logs - C:\WINNT\System32\inetsrv\urlscan\logs\ URLScan INI file - C:\WINNT\System32\inetsrv\urlscan\urlscan.ini
I would use the FileMon tool to see if IIS is even trying to access the JS files. It could be a security problem.
Can’t get IIS to serve .js files from a specified directory
[ "", "javascript", "web-applications", "mime-types", "iis-5", "directory-permissions", "" ]
Visual studio is giving the error **PRJ0019: A tool returned an error code from "Copying DLL...".** The console window includes the output: 'CopyDLL.cmd' is not recognized as an internal or external command. Here is some background as to why I don't know about the tool which is copying. Someone left the company a year ago and forgot to check in their latest version of code for a MS Visual Studio 2008 project using C# and C+\_. Now we need to fix the program, but can't find the code and I've been assigned with trying to clean the mess up.
You should check the Custom Build Step (Project Properties->Configuration Properties->Custom Build Step) for all of the projects and all of the files. It may be easier to open the \*.vcproj files in a text editor and check the tags under individual files in the project. Look for any tags that have a non-empty CommandLine attribute.
Turn up the build output with Tools -> Options -> Projects and Solutions -> Build and Run Set MSBuild project build output verbosity to something higher than the default. I'd step it up one level at a time because the highest level is pathologically verbose.
error PRJ0019: A tool returned an error code from "Copying DLL..."
[ "", ".net", "c++", "visual-studio", "" ]
How do you maintain the #include statements in your C or C++ project? It seems almost inevitable that eventually the set of include statements in a file is either insufficient (but happens to work because of the current state of the project) or includes stuff that is no longer needed. Have you created any tools to spot or rectify problems? Any suggestions? I've been thinking about writing something that compiles each non-header file individually many times, each time removing an #include statement. Continue doing this until a minimal set of includes is achieved. To verify that header files are including everything they need, I would create a source file that all it does is include a header file and try to compile it. If the compile fails, then the header file itself is missing an include. Before I create something though, I thought I should ask here. This seems like a somewhat universal problem.
> To verify that header files are including everything they need, I would creating a source file that all it does is include a header file and try to compile it. If the compile fails, then the header file itself is missing an include. You get the same effect by making the following rule: that the first header file which *foo*.c or *foo*.cpp must include should be the correspondingly-named *foo*.h. Doing this ensures that *foo*.h includes whatever it needs to compile. Furthermore, Lakos' book *Large-Scale C++ Software Design* (for example) lists many, many techniques for moving implementation details out of a header and into the corresponding CPP file. If you take that to its extreme, using techniques like Cheshire Cat (which hides all implementation details) and Factory (which hides the existence of subclasses) then many headers would be able to stand alone without including other headers, and instead make do with just forward declaration to opaque types instead ... except perhaps for template classes. In the end, each header file might need to include: * No header files for types which are data members (instead, data members are defined/hidden in the CPP file using the "cheshire cat" a.k.a. "pimpl" technique) * No header files for types which are parameters to or return types from methods (instead, these are predefined types like `int`; or, if they're user-defined types, then they're references in which case a forward-declared, opaque type declaration like merely `class Foo;` instead of `#include "foo.h"` in the header file is sufficient). What you need then is the header file for: * The superclass, if this is a subclass * Possibly any templated types which are used as method parameters and/or return types: apparently you're supposed to be able to forward-declare template classes too, but some compiler implementations may have a problem with that (though you could also encapsulate any templates e.g. `List<X>` as implementation details of a user-defined type e.g. `ListX`). In practice, I might make a "standard.h" which includes all the system files (e.g. STL headers, O/S-specific types and/or any `#define`s, etc) that are used by any/all header files in the project, and include that as the first header in every application header file (and tell the compiler to treat this "standard.h" as the 'precompiled header file'). --- ``` //contents of foo.h #ifndef INC_FOO_H //or #pragma once #define INC_FOO_H #include "standard.h" class Foo { public: //methods ... Foo-specific methods here ... private: //data struct Impl; Impl* m_impl; }; #endif//INC_FOO_H ``` --- ``` //contents of foo.cpp #include "foo.h" #include "bar.h" Foo::Foo() { m_impl = new Impl(); } struct Foo::Impl { Bar m_bar; ... etc ... }; ... etc ... ```
I have the habit of ordering my includes from high abstraction level to low abstraction level. This requires that headers have to be self-sufficient and hidden dependencies are quickly revealed as compiler errors. For example a class 'Tetris' has a Tetris.h and Tetris.cpp file. The include order for Tetris.cpp would be ``` #include "Tetris.h" // corresponding header first #include "Block.h" // ..then application level includes #include "Utils/Grid.h" // ..then library dependencies #include <vector> // ..then stl #include <windows.h> // ..then system includes ``` And now I realize this doesn't really answer your question since this system does not really help to clean up unneeded includes. Ah well..
Clean up your #include statements?
[ "", "c++", "file", "include", "header", "" ]
I have a class which you pass in a folder and then it goes off and processes a lot of data within the specified folder. For instance: ``` MyClass myClass = new MyClass(@"C:\temp"); ``` Now it goes off and reads say a couple of thousand files and populates the class with data. Should I move this data out from the constructor and have it as a separate method, such as the following? ``` MyClass myClass = new MyClass(); myClass.LoadFromDirectory(@"C:\temp"); ```
Maybe you should try it this way with a static method that returns an instance of the object. ``` var myClass = MyClass.LoadFromDirectory(@"C:\temp"); ``` This will keep the initialization code outside of your constructor, as well as giving you that "one line" declaration you are looking for. --- Going on the comment from below from the poster, by adding State an implementation could be like so: ``` public class MyClass { #region Constructors public MyClass(string directory) { this.Directory = directory; } #endregion #region Properties public MyClassState State {get;private set;} private string _directory; public string Directory { get { return _directory;} private set { _directory = value; if (string.IsNullOrEmpty(value)) this.State = MyClassState.Unknown; else this.State = MyClassState.Initialized; } } #endregion public void LoadFromDirectory() { if (this.State != MyClassState.Initialized || this.State != MyClassState.Loaded) throw new InvalidStateException(); // Do loading this.State = MyClassState.Loaded; } } public class InvalidStateException : Exception {} public enum MyClassState { Unknown, Initialized, Loaded } ```
It depends. You should evaluate the basic purpose of the class. What function does it perform? What I usually prefer is to have a class constructor do the initialization necessary for the functioning of the class. Then I call methods on the class which can safely assume that the necessary initialization has been done. Typically, the initalization phase should not be too intensive. An alternative way of doing the above may be: ``` // Instantiate the class and get ready to load data from files. MyClass myClass = new MyClass(@"C:\temp"); // Parse the file collection and load necessary data. myClass.PopulateData(); ```
C# constructor design
[ "", "c#", "constructor", "" ]
Has anyone ever found any lightbox type javascript / css code that can display PDFs? I have tried many libraries and none have worked for me. The environment needs to be IE6/IE7 compatible. I am looking for something similar to this: [Lightbox 2](http://www.huddletogether.com/projects/lightbox2/)
<http://stickmanlabs.com/lightwindow/> Specifically, check out the demo "Flash Paper" for embedding PDFs
Good luck finding anything that will display a PDF in browser without a plugin. You might consider embedding an IFrame that points to the PDF in a lightbox style. That's about the best you'll be able to do, though.
Javascript and CSS Lightbox that can view PDFs
[ "", "javascript", "css", "pdf", "lightbox", "lightbox2", "" ]
I have a pretty serious multithreaded debugging problem. I have some kind of timing issue when interacting with a serial device, and I need to track it down. I have three threads: 1. The main thread for UI updates. The user can either change one parameter of the device, or many all at once by choosing a preset. 2. The status checking thread that queries to make sure that the device is still attached. If the user shuts off the device or the device itself is interacted with in an interesting way, the status changes need to be reflected in the UI. 3. The thread that reads the serial port where the device responds. My problem actually has to do with debugging this situation. It seems like every single line I have in each thread has to have a breakpoint in order to be debugged; if I break in one thread, the debugger won't step through that thread. I understand that the other threads will continue to update, but shouldn't the thread I'm on execute like normal in the debugger, ie, go from one line to the next? Then, I could use the 'threads' tab to switch between threads. I mention that I'm in WPF because I don't know if that changes the situation at all; maybe it does, maybe it doesn't. The status checking thread is part of a UI control, because the status needs to only be checked while the UI is up. That control is in a library distinct from the main application.
If your code is single stepping in a weird manner, it can sometimes be caused by a simple broken pdb file. A "rebuild all" on your code will regenerate it from scratch and cure any such glitches. Another thing to bear in mind is that stopping one thread in the debugger can cause all kinds of unusual timing that you wouldn't see in a release build. For example: * the Serial port will always continue to operate (on a hardware/driver level) while you have stopped on a breakpoint - when you next try to step your code, it can receive a sudden huge burst of data. With async callbacks this can be "interesting". * Stopping one thread disturbs the normal timeslicing so that thread to thread synchronisation can get screwed up.
When the debugger stops on a breakpoint, by default it will suspend all other threads. But when you step or continue all 3 threads are resumed. When you step through code, the debugger basically sets a temporary breakpoint on the next line and resumes all the threads. The other 2 may get a chance to run before that virtual break point is hit. **You can Freeze the other threads while debugging** When you're at a breakpoint select **Debug | Windows | Threads**. Select the threads you aren't interested in and right-click, select **Freeze**. This will let you focus on the one thread you're stepping through.
Threaded debugging in C# and vs2008
[ "", "c#", "visual-studio-2008", "multithreading", "debugging", "" ]
I have a tuple containing lists and more tuples. I need to convert it to nested lists with the same structure. For example, I want to convert `(1,2,[3,(4,5)])` to `[1,2,[3,[4,5]]]`. How do I do this (in Python)?
``` def listit(t):     return list(map(listit, t)) if isinstance(t, (list, tuple)) else t ``` The shortest solution I can imagine.
As a python newbie I would try this ``` def f(t): if type(t) == list or type(t) == tuple: return [f(i) for i in t] return t t = (1,2,[3,(4,5)]) f(t) >>> [1, 2, [3, [4, 5]]] ``` Or, if you like one liners: ``` def f(t): return [f(i) for i in t] if isinstance(t, (list, tuple)) else t ```
How do I convert a nested tuple of tuples and lists to lists of lists in Python?
[ "", "python", "list", "tuples", "" ]
If a java client calls a remote EJB on a different server, how can you get the client IP address? Note that it is important to get it from the server, because the client is likely behind a NAT firewall, and in this case we need the public IP address. NOTE: Although it would preferably be a generic solution, at a minimum I could use one that retrieves the IP address from an EJB2 call on JBoss 4.2.2
[This article](http://www.jboss.org/community/wiki/HowtogettheClientipaddressinanEJB3Interceptor) on the JBoss community wiki addresses exactly your issue. Prior to JBoss 5 the IP address apparently has to be parsed from the worker thread name. And that seems to be the only way to do it on earlier versions. This is the code snippet doing it (copied from the above link): ``` private String getCurrentClientIpAddress() { String currentThreadName = Thread.currentThread().getName(); System.out.println("Threadname: "+currentThreadName); int begin = currentThreadName.indexOf('[') +1; int end = currentThreadName.indexOf(']')-1; String remoteClient = currentThreadName.substring(begin, end); return remoteClient; } ```
Have you tried: java.rmi.server.RemoteServer.getClientHost() ? <http://java.sun.com/j2se/1.5.0/docs/api/java/rmi/server/RemoteServer.html#getClientHost()>
How can you get the calling ip address on an ejb call?
[ "", "java", "ip-address", "ejb", "" ]
I would like to implement Singular Value Decomposition (SVD) in PHP. I know that there are several external libraries which could do this for me. But I have two questions concerning PHP, though: 1) Do you think it's possible and/or reasonable to code the SVD in PHP? 2) If (1) is yes: Can you help me to code it in PHP? I've already coded some parts of SVD by myself. [Here's the code](http://paste.bradleygill.com/index.php?paste_id=10052) which I made comments to the course of action in. Some parts of this code aren't completely correct. It would be great if you could help me. Thank you very much in advance!
SVD-python Is a very clear, parsimonious implementation of the SVD. It's practically psuedocode and should be fairly easy to understand and compare/draw on for your php implementation, even if you don't know much python. [SVD-python](http://stitchpanorama.sourceforge.net/Python/svd.py) That said, as others have mentioned I wouldn't expect to be able to do very heavy-duty LSA with php implementation what sounds like a pretty limited web-host. Cheers Edit: The module above doesn't do anything all by itself, but there is an example included in the opening comments. Assuming you downloaded the python module, and it was accessible (e.g. in the same folder), you could implement a trivial example as follow, ``` #!/usr/bin/python import svd import math a = [[22.,10., 2., 3., 7.], [14., 7.,10., 0., 8.], [-1.,13.,-1.,-11., 3.], [-3.,-2.,13., -2., 4.], [ 9., 8., 1., -2., 4.], [ 9., 1.,-7., 5.,-1.], [ 2.,-6., 6., 5., 1.], [ 4., 5., 0., -2., 2.]] u,w,vt = svd.svd(a) print w ``` Here 'w' contains your list of singular values. Of course this only gets you part of the way to latent semantic analysis and its relatives. You usually want to reduce the number of singular values, then employ some appropriate distance metric to measure the similarity between your documents, or words, or documents and words, etc. The cosine of the angle between your resultant vectors is pretty popular. [Latent Semantic Mapping (pdf)](http://www.ling.upenn.edu/courses/cogs501/BellegardaIEEE.pdf) is by far the clearest, most concise and informative paper I've read on the remaining steps you need to work out following the SVD. Edit2: also note that if you're working with very large term-document matrices (I'm assuming this is what you are doing) it is almost certainly going to be far more efficient to perform the decomposition in an offline mode, and then perform only the comparisons in a live fashion in response to requests. while svd-python is great for learning, the svdlibc is more what you would want for such heavy computation. finally as mentioned in the bellegarda paper above, remember that you don't have to recompute the svd every single time you get a new document or request. depending on what you are trying to do you could probably get away with performing the svd once every week or so, in an offline mode, a local machine, and then uploading the results (size/bandwidth concerns notwithstanding). anyway good luck!
Be careful when you say "I don't care what the time limits are". SVD is an `O(N^3)` operation (or `O(MN^2)` if it's a rectangular `m*n` matrix) which means that you could very easily be in a situation where your problem can take a very long time. If the 100\*100 case takes one minute, the 1000\*1000 case would 10^3 minutes, or nearly 17 hours (and probably worse, realistically, as you're likely to be out of cache). With something like PHP, the prefactor -- the number multiplying the `N^3` in order to calculate the required FLOP count, could be very, very large. Having said that, of course it's possible to code it in PHP -- the language has the required data structures and operations.
Singular Value Decomposition (SVD) in PHP
[ "", "php", "svd", "eigenvector", "eigenvalue", "" ]
I just installed Java 1.6 on my OSX and everything works brilliantly, except that Eclipse refuses to start. It puts up a huge prompt from which I can't copy/paste, but it's clearly stating that it wants to be using Java 1.5 and can't find it anymore. I don't see anything in its configuration files about which version of Java it should be looking for. Has anyone dealt with this? Thanks in advance.
on /Applications/Eclipse/Eclipse.app right click and choose "Show Package Contents" open Contents/Info.plist with a text editor *NOT* plist editor add `<string>-vm</string> <string>/System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Commands/java</string>` to ``` <key>Eclipse</key> <array> <!-- add it here --> </array> ``` save it and restart.
Unless I'm mistaken, the Java 1.6 vm on the Mac is 64 bit only. To use it, you'll need a 64bit version of Eclipse. The only 64bit port of eclipse on the mac is the new cocoa build, find it [here](http://download.eclipse.org/eclipse/downloads/drops/I20090611-1540/index.php). In a few weeks, the [Galileo release](http://www.eclipse.org/galileo/) will be finished, there you can find the 64 bit cocoa port by going to Eclipse Classic -> Other Downloads. If you want to keep your current eclipse install, you'll have to do as the other answers suggest and change them to use 1.5
How can I get Eclipse on OSX to use Java 1.6?
[ "", "java", "eclipse", "java-6", "" ]
Suppose I have a 400K text file which I want to read from a javascript. The problem is, my target audience have a slow connection, so 400k might take too long to load. I suppose I need to compress the file, but well, how can I decompress it via javascript on the client side? Is it worth it, or will the time needed for decompression negate the time saved in downloading? **UPDATE** Just to be clear, the file is text (data) not code.
You can [GZip](http://weblogs.asp.net/pscott/archive/2003/06/05/8326.aspx) the text file, and sent it to the browser. That way you wont have to do anything on the client side, the browser itself will decompress it.
could you use HTTP compression?
javascript text compression/decompression
[ "", "javascript", "compression", "text-files", "" ]
I am designing a menu bar combining effects with CSS and JavaScript. It is comprised of large icons with text underneath that appears when hovered over. It will be deployed on an intranet so it only has to run in IE 7, 8, and Firefox. Firefox of course seems to perform what I intuitively think the HTML should look like, showing large, block links with a large click area. IE7, however, shows block links that act like links for the Javascript and hover correctly (after I hacked it by adding a transparent background image), but does not provide a finger cursor or follow the href when I click on it. Interestingly, the link area surrounding the image DOES have the finger cursor, but as soon as I hover the image it turns back to the arrow. ``` <div id="navigation"> <ul> <li><a href="#" onMouseOver="vtoggle('txtHome');" onMouseOut="vtoggle('txtHome');"> <span class="icon"><img src="iconImage.png" alt="Home" /></span> <span class="icontxt" id="txtHome" style="visibility:hidden;">Home</span> </a></li> ... </ul> </div> <script type="text/javascript"> function vtoggle(x) { if (document.getElementById(x).style.visibility == 'hidden') { document.getElementById(x).style.visibility = 'visible'; } else { document.getElementById(x).style.visibility = 'hidden'; } } </script> #navigation{ margin:0px auto; padding:0px; padding-left:10px; height:64px; list-style:none; } #navigation li{ float:left; clear:none; list-style:none; } #navigation li a, #navigation li a:link{ color:#fff; display:block; font-size:12px; text-decoration:none; padding:8px 18px; margin:0px; margin-left:-20px; width:80px; height:64px; background:url(../images/transparent.gif); } #navigation li a:hover{ background:url(../images/glow.png); background-repeat:no-repeat; background-position:10px -2px; } .icon{ float:left; width:100%; text-align:center; } .icontxt{ float:left; font-size:10px; color:white; font-weight:bold; clear:left; text-align:center; width:100%; margin-top:-1px; } ``` Any help is much appreciated. -- EDIT -- I solved my problem (I'll post the answer below to fit convention) but I would still like to hear WHY IE does not allow ``` <a href="#"><span><img /></span></a> ```
I solved the problem. I had to remove the SPAN tag around the icons. Here's my new HTML code: ``` <li><a href="#" onMouseOver="vtoggle('txtHome');" onMouseOut="vtoggle('txtHome');"> <img src="images/webapp48/profile.png" alt="Home" /> <span class="icontxt" id="txtHome" style="visibility:hidden;">Home</span> </a></li> ``` I moved some of the CSS in my span tag into the link tag to preserve formatting. Now it works correctly, but I'm still puzzled why the SPAN tag would disable the link.
Make sure your SPAN is not set to BLOCK. Same thing happened to me.
Images Won't Show as Link in Internet Explorer
[ "", "javascript", "html", "css", "internet-explorer", "hyperlink", "" ]
I was wondering which implementation would have better performance: I need to clear all items out of a stack except the first 10 at the head. These 10 must then be placed into the stack in their orginal order. I thought of 2 approaches the first: ``` FilterRecord[] records = new FilterRecord[10]; for (int i = 0; i < records.Length; i++) { records[i] = _InternalCollection.Pop(); } _InternalCollection.Clear(); for (int i = records.Length - 1; i >= 0; i--) { _InternalCollection.Push(records[i]); } ``` The second: ``` int count = _InternalCollection.Count - 10; _InternalCollection.Reverse(); for (int i = 0; i < count; i++) { _InternalCollection.Pop(); } _InternalCollection.Reverse(); ``` Any help or guidelines or other impemenations would be welcome.
I think that avoiding popping items off the stack will improve your code's performance more than the alternative between the two approaches you suggest. I would recommend allocating a new stack with the contents of the last item on the stack using linq like so: ``` var newStack = new Stack<FilterRecord>( _InternalCollection.Take( 10 ) .Reverse() ); _InternalCollection = newStack; ``` If you're not using generics, you can do the same with the built in iterator: ``` var iterator = _InternalCollection.GetEnumerator(); int i = 9; while( iterator.MoveNext() && i-- >= 0 ) { newStack.Push( iterator.Current ); } _InternalCollection = newStack; ```
Your first algorithm has two for-loops, so O(2N). Your second algorithm has one for loop, but we have to assume that internally Reverse() is an O(N) operation, so its O(3N). I'm not sure if the Clear() call is O(N) or O(C) in your first algorithm.
Performance : which is faster calling reverse on a stack or popping items into an array
[ "", "c#", "performance", "" ]
In the code below, sometimes `someFunctionCall()` generates an exception: > Thread was being aborted. How come the code in code Block B never runs? Does ASP.NET start a new thread for each method call? I was suprised to see that when this exception happens the code in Block B never runs, the method returns, and my application keeps running. Can someone please explain this? ``` public void method() { // CODE BLOCK A //... try { someFunctionCall(); // this call is generating thread abort exception } catch(Exception ex) { // log exception message } // CODE BLOCK B // ... } ```
This is a `ThreadAbortException`; it's a special exception that is automatically rethrown at the end of every catch block, unless you call `Thread.ResetAbort()`. ASP .Net methods like `Response.End` or `Response.Redirect` (unless you pass `false`) throw this exception to end processing of the current page; your `someFunctionCall()` is probably calling one of those methods. ASP .Net itself handles this exception and calls `ResetAbort` to continue processing.
To work around this problem, use one of the following methods: For `Response.End`, call the `HttpContext.Current.ApplicationInstance.CompleteRequest` method instead of `Response.End` to bypass the code execution to the `Application_EndRequest` event. For `Response.Redirect`, use an overload, `Response.Redirect(String url, bool endResponse)` that passes false for the `endResponse` parameter to suppress the internal call to `Response.End`. For example: ``` Response.Redirect ("nextpage.aspx", false); ``` If you use this workaround, the code that follows `Response.Redirect` is executed. For `Server.Transfer`, use the `Server.Execute` method instead.
ASP.NET exception "Thread was being aborted" causes method to exit
[ "", "c#", ".net", "asp.net", "" ]
I'm trying to have a callback call a function inside $(document).ready(..) How do I call a function from outside this? Like for example: ``` $(document).ready( function(foo) { var bar = function() { ... }; }); // How do I call bar() from here? ```
That depends on how you want to scope things. If you just want bar to be in the global scope, then just do this: ``` $(document).ready( function(foo) { var bar = function() { ... }; window.bar = bar; }); ``` Remember, in JavaScript the only code blocks that have scope are functions, so variables declared in `if{}`, `while{}`, and other types of code blocks are global to whatever function they are a part of, unless they are not declared. If you use a variable without declaring it, that is the same as doing: ``` // Both of these variables have global scope, assuming // 'bar' was never declared anywhere above this window.foo = "Hello World!"; bar = "Hello World!"; ``` So the example above could be a line shorter by doing: ``` $(document).ready( function(foo) { window.bar = function() { ... }; }); ```
Don't declare everything inside of the ready function ``` $(document).ready( function() { ... bar(); }); function bar() { ... } ```
jQuery function calling
[ "", "javascript", "jquery", "" ]
I seem to go back and forth on this, sometimes it works for me, often it doesn't and I can't figure out how/why I can get it to work sometimes, and at other times it won't. I have 5 databases, and need to grab data from each of them during a maintenance routine. For each of the databases, I have an external file which contains all the db connection code which I include in my page. The includes look like this ``` $SGcon = mysql_connect("localhost","root",""); if (!$SGcon) { die('Could not connect: ' . mysql_error()); } mysql_select_db("sGopen", $SGcon); ``` For each database I provide a different varaible, so the next database will be ``` $PTcon = mysql_connect("localhost","root",""); if (!$PTcon) { die('Could not connect: ' . mysql_error()); } mysql_select_db("pTsecond", $PTcon); ``` Then when i call my query, I use ``` mysql_query($getQuery, $PTcon); mysql_query($secondQuery, $SGcon); ``` The problem I'm running into is that I'm not getting the correct database used for the query , it seems my script is using the databases which was added to the page last. Is there a better way for me to switch the database connection to be used? There is lots of back and forth between the databases as I'm comparing data from one db to data in another, so i'm trying to be efficient with this as well. Thanks Pete
By default, if you pass the same arguments to [mysql\_connect](http://www.php.net/function.mysql-connect) as a previous call it'll return a cached connection if available, rather than creating a new one. So both queries are running against whichever database you last passed to `mysql_select_db`. Passing `new_link=true` will avoid this behaviour, although database connections can be expensive so you should try to keep as few open as reasonably possible. The detailed explanation for new\_link: > If a second call is made to > `mysql_connect()` with the same > arguments, no new link will be > established, but instead, the link > identifier of the already opened link > will be returned. The new\_link > parameter modifies this behavior and > makes `mysql_connect()` always open a > new link, even if `mysql_connect()` was > called before with the same > parameters. In SQL safe mode, this > parameter is ignored.
I think if you close the db connection in between each query you will solve the problem. And if you're doing a lot of compares between databases, then I would just use 1 select statement to query all databases at once.
Changing the connected DB
[ "", "php", "mysql", "database-connection", "" ]