Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I have a code that looks like this: ``` <div id="wrapper"> <img id="first" class="images" src="img/nike.jpg" /> <img id ="second" class = "images" src="img/golden.jpg" /> <img id = "third" class ="images" src ="img/a.jpg" /> <img id = "fourth" class="images" src="img/God__s_Canvas_by_Delacorr.jpg" /> </div> ``` I want to wrap each img with `<a name = n>` dynamically. So my solution was to do this: ``` $(".images").wrap('<a></a>') $("#wrapper a").each(function(n) { $(this).attr('name', n); }) ``` Is it possible to chain the 2 statements into 1 statement? I know that jQuery is particularly do elegant chaining so I think it's definitely possible. I just don't know how to yet.
This isn't exactly the same because it doesn't wrap .images outside of #wrapper, but it's close. It creates the in the loop and immediately applies the attribute. ``` $('#wrapper img').each(function(n) { $(this).wrap($('<a></a>').attr('name', n)); } ```
this might work... ``` $(".images").wrap('<a></a>').parent().each(function(n) {$(this).attr('name', n);}); ```
jQuery: Is there a way to make this shorter and more elegant?
[ "", "javascript", "jquery", "" ]
How can I get the field names of an MS Access database table? Is there an SQL query I can use, or is there C# code to do this?
this will work on sql server 2005 and up: ``` select * from INFORMATION_SCHEMA.COLUMNS where TABLE_Name='YourTableName' order by ORDINAL_POSITION ```
Use [IDataReader.GetSchemaTable()](http://msdn.microsoft.com/de-de/library/system.data.idatareader.getschematable%28VS.80%29.aspx) Here's an actual example that accesses the table schema and prints it plain and in XML (just to see what information you get): ``` class AccessTableSchemaTest { public static DbConnection GetConnection() { return new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=..\\Test.mdb"); } static void Main(string[] args) { using (DbConnection conn = GetConnection()) { conn.Open(); DbCommand command = conn.CreateCommand(); // (1) we're not interested in any data command.CommandText = "select * from Test where 1 = 0"; command.CommandType = CommandType.Text; DbDataReader reader = command.ExecuteReader(); // (2) get the schema of the result set DataTable schemaTable = reader.GetSchemaTable(); conn.Close(); } PrintSchemaPlain(schemaTable); Console.WriteLine(new string('-', 80)); PrintSchemaAsXml(schemaTable); Console.Read(); } private static void PrintSchemaPlain(DataTable schemaTable) { foreach (DataRow row in schemaTable.Rows) { Console.WriteLine("{0}, {1}, {2}", row.Field<string>("ColumnName"), row.Field<Type>("DataType"), row.Field<int>("ColumnSize")); } } private static void PrintSchemaAsXml(DataTable schemaTable) { StringWriter stringWriter = new StringWriter(); schemaTable.WriteXml(stringWriter); Console.WriteLine(stringWriter.ToString()); } } ``` **Points of interest:** 1. Don't return any data by giving a where clause that always evaluates to false. Of course this only applies if you're not interested in the data :-). 2. Use IDataReader.GetSchemaTable() to get a DataTable with detailed info about the actual table. **For my test table the output was:** ``` ID, System.Int32, 4 Field1, System.String, 50 Field2, System.Int32, 4 Field3, System.DateTime, 8 -------------------------------------------------------------------------------- <DocumentElement> <SchemaTable> <ColumnName>ID</ColumnName> <ColumnOrdinal>0</ColumnOrdinal> <ColumnSize>4</ColumnSize> <NumericPrecision>10</NumericPrecision> <NumericScale>255</NumericScale> <DataType>System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</DataType> <ProviderType>3</ProviderType> <IsLong>false</IsLong> <AllowDBNull>true</AllowDBNull> <IsReadOnly>false</IsReadOnly> <IsRowVersion>false</IsRowVersion> <IsUnique>false</IsUnique> <IsKey>false</IsKey> <IsAutoIncrement>false</IsAutoIncrement> </SchemaTable> [...] </DocumentElement> ```
How can I get the field names of a database table?
[ "", "c#", "database", "ms-access", "" ]
Try the following code ``` public enum Color { Blue=1, Red=2, Green=3 } public List<Color> ConvertColorEnum() { var intColor = new List<int>(){1,2,3}; return intColor.Cast<Color>().ToList(); } ``` Do you think the `ConvertColorEnum()` will return a list of color, i.e., `List<Color>(){Color.Blue, Color.Red, Color.Green}`? I tested this on 2 machines, one with .net 3.5 ( mscorlib version 2.0.50727.1433), another with .net 3.5 SP1 ( mscorlib version 2.0.50727.3082). The results were different-- the .net 3.5 threw an `InvalidCastException` because couldn't convert integer to enum, whereas .net 3.5 SP1 could run successfully, with correct results returned. Anyone would like to try this on his/her machine and report the result or explain why this is so?
You can read about the difference between the SP1 and the original release of the .net 3.5 framework [in the release notes](http://msdn.microsoft.com/en-us/library/dd310284.aspx). Here's what it says for this particular issue: > In LINQ query expressions over > non-generic collections such as > System.Collections.ArrayList, the from > clause of the query is rewritten by > the compiler to include a call to the > Cast operator. Cast converts > all element types to the type > specified in the from clause in the > query. In addition, in the original > release version of Visual C# 2008, the > Cast operator also performs some > value type conversions and > user-defined conversions. However, > these conversions are performed by > using the System.Convert class instead > of the standard C# semantics. These > conversions also cause significant > performance issues in certain > scenarios. In Visual C# 2008 SP1, the > Cast operator is modified to throw > an InvalidCastException for numeric > value type and user-defined > conversions. This change eliminates > both the non-standard C# cast > semantics and the performance issue. > This change is illustrated in the > following example. You can also get more details in [this blog post](http://blogs.msdn.com/ed_maurer/archive/2008/02/16/breaking-change-in-linq-queries-using-explicitly-typed-range-variables.aspx).
If you want it to work either way, use `Select` instead. ``` return intColor.Select(i=>(Color)i).ToList(); ``` As for the why...?
Unable ( or able) to List<int>.Cast<Enum>()?
[ "", "c#", "" ]
For homework, I need to build a small java application.The main goal is to learn how to interact with XML. But a second goal is to learn how to build such an application. I have quite some experience on programming, but little experience in designing programs. I've read about designpatterns and designprinciples like Solid and TDD. But I find it hard to know how to implement such ideas. One problem I encounter is segregation between the GUI and the application. On the app, we want to be able to sort on different criteria. For each criteria, there would be a button (like the header of a list). This would then cause an event to be triggered. But how should I pass on what criteria should be sorted, and how would a send back the sorted data? One could define a different event for each button, but then you would have several similar events with the only goal to differentiate between the sorting criteria. Another approach would be to define one event, and then pass a string or int, which would specify on what criteria should be sorted, but then you would get a list of if else statements, and would not adhere to the open closed principle. How would you design such a system. **Edit:** My biggest concern here is trying to get this *'open-closed'*. As someone asked, the data is a collection of objects. Is there some way it's easy to add criteria to sort on? Or is this not really feasible to achieve?
The best approach is to have "one event, and then pass a string or int". Depending on the underlying data structure you use, you will not need to use a switch statement to sort the data. If you have a data table, you can use the string to specify which column to sort by. It's trickier if you have a collection of objects and the columns represent their properties. In .Net you can do neat things with LINQ that let you sort by a property represented as a string. But in java, you could always resort to reflection to get the field value to sort by. If you have your data represented as a multidimensional array passing an int would represent the property-y index of the array to sort by. In any case there is always a technique available to avoid the switch statement for sorting.
If I well understand your question, you need separate GUI and Application logic. Look to MVC pattern. [http://en.wikipedia.org/wiki/MVC](http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller) Maybe better for you is MVP pattern <http://en.wikipedia.org/wiki/Model_View_Presenter> If you have experience with MVC pattern look to some Java MVC Framework for desktop applications (mostly are for web).
Designing interface between application and GUI
[ "", "java", "" ]
Duplicate: [Is there a way to instantiate objects from a string holding their class name?](https://stackoverflow.com/questions/582331/c-is-there-a-way-to-instantiate-objects-from-a-string-holdig-their-class-name) --- Is there a (better) way in C++ to map string id to a class name. I suspect there might be a way via templates but I wasn't able to figure out the correct way. For example if I have multiple messages, each storing in the first byte a character id. So message A12345 would instantiate class A() message B12345 would map to class B(). I have a group of message parsers where each class can parse give message. The issue is that I have to manually generate mapping between class that parses given message (e.g. class A()) and the message id (e.g. the 'A'). This is what I'm doing in the code now, and I'm thinking if there's a nice way to eliminate the switch in c++ (templates magic?): ``` Msg * msg; switch(data[0]) { case 'A': msg = new A(); break; case 'B': msg = new B(); break; ... } msg->parse(data); ``` On the side note, most of the time the id's are actually 2 character long so 'A1' 'B1' and so on. And I'm using the class names the same to keep track of the classes, e.g. 'A1' can be parsed by class A1() and so on. **NOTE**: This seems like duplicate of [C++: Is there a way to instantiate objects from a string holdig their class name?](https://stackoverflow.com/questions/582331/c-is-there-a-way-to-instantiate-objects-from-a-string-holdig-their-class-name) so I suggest to close this question.
As someone else said, it can't be done using templates (templates are computed at compile time. But your character id is compute at runtime). You can use a map from id to constructor function. It boils down to this question: [Instantiate objects from a String holding their class name](https://stackoverflow.com/questions/582331/c-is-there-a-way-to-instantiate-objects-from-a-string-holdig-their-class-name) I recommend you to keep it simple. If a plain switch will do it, keep it that way. If you later really need to have it extensible, you can still introduce some automatic look-up of character ids and so on.
I suggest using [Boost.Any](http://www.boost.org/doc/libs/1_39_0/doc/html/any.html). You can then just interpret your any as an A or a B: ``` if (myAny.type() == typeid(A)) { boost::any_cast<A>(myAny).whatever(); } else if (myAny.type() == typeid(B)) { // do whatever } ```
Mapping from character id to a class name in c++ via templates?
[ "", "c++", "" ]
I work in a team of developers, one of us works specifically under Windows, and I work primarily in Mac OS X. We're wanting to develop C-based applications either in C++ or Objective-C however I'm not really knowledgeable in how to go about a cross-platform development project. Is it viable to work in C++ using Mac OS X? Obviously they're geared towards Objective-C but is there just as much support for C++. What about cross-platform development in these languages? I'd use something like boost and some kind of UI library. Has anyone got any experience in developing for multiple platforms yet allow applications to run natively without the need for a VM? **EDIT**: There's a lot of answers I want to mark as correct now. It seems like Qt is the way to go and develop it in C++. Chances are this will be for \*nix, OS X and Windows so that would be the best option for us personally. If I can avoid writing Objective-C so the team sticks to C++ then all the better. If I have to write the GUI in Objective-C and mix and match then that's not too much bother either.
[You could look at Qt](http://qt.nokia.com/). I've used it successfully on Windows, Linux and Mac OSX projects.
I work for a software company that produces software for Mac OS X and Windows using C++, MFC, and Objective-C. Yes, it is definitely possible. You probably will be best served if you develop the "core" of the application in C++. In a MVC application, the C++ part would be the model, and possibly the controllers. For the code that interfaces to the GUI and other OS-specific interfaces, you should use the native APIs: Objective-C on Mac OS X and C# on Windows XP. The good thing about the Mac is that you can compile C++ and Objective-C together. You can even have Objective-C++ where C++ and Objective-C are compiled in the same compilation unit. Unfortunately you cannot do this with C# (there is something called Managed C++ which is a different beast). I would avoid cross-platform frameworks such as Qt and wxWidgets. They both allow you to develop cross-platform applications, but the look and feel of such applications is sub-par. I have more familiarity with wxWidgets though, its design is heavily geared towards the Windows MFC paradigm of application design. **Edit May 14, 2009, 9:44 AM EST:** If Qt now allows *true* look and feel of the native platform, it could be a good option. I haven't looked at the latest offering so you may want to look at that framework before designing your own. That decision should be made after examining the results of the applications and how comfortable you are with the design paradigms that Qt requires.
Cross-Platform Objective-C / C++ Development
[ "", "c++", "objective-c", "windows", "macos", "" ]
Consider the following class: ``` class Something : ISomething { public void DoesSomething(int x) { if (x == 0) { x = 1; } } } ``` I want to of course remove the magic number - my unit tests are passing etc... but I want to refactor the horrible magic number out. I'm using C# but I guess this problem is pretty generic. Reading from a config file (xml file) is done by something like: ``` ConfigurationManager.AppSettings["MyOldMagicNumber"]... ``` Which of course, would be a sod to test. I could easily make a private function in this class that is marked virtual. Its purpose to encapsulate that above code. This would allow me to access in my unit tests to override and plug in my own value. My question is - Is this bad what I'm doing? See title. **Edit:** This is for a game - therefore is more than likely during development the values will change often and doing a re-build will be a chore. I should have mentioned that, the above code is generic, I made it so to keep the question as simple as possible. A bit of context though - that '0' is the game area bounds. Thanks in advance.
Why don't you create an interface for this like ``` public interface IApplicationSettings { int MyOldMagicNumber { get; } } ``` Then have two implementations of this, one for production that reads from the config file and one fake for unit-tests. ``` public class ApplicationSettings : IApplicationSettings { public int MyOldMagicNumber { get { return ConfigurationManager.AppSettings["MyOldMagicNumber"]; } } } public class FakeApplicationSettings : IApplicationSettings { public int MyOldMagicNumber { get { return 87; /*Or whatever you want :) */ } } } ```
Do you really need to change these values without recompiling the program? If no, I think you should avoid putting it in your config file, otherwise you will end up programming in xml ;) Using constants is good for readability in this case: ``` class Something : ISomething { public const int Zero = 0; public const int One = 1; public void DoesSomething(int x) { if (x == Zero) { x = One; } } } ```
Magic numbers - Reading from a config file the same as global space? Bad for unit testing?
[ "", "c#", "unit-testing", "" ]
I have a particularly slow query due to the vast amount of information being joined together. However I needed to add a where clause in the shape of id in (select id from table). I want to know if there is any gain from the following, and more pressing, will it even give the desired results. ``` select a.* from a where a.id in (select id from b where b.id = a.id) ``` as an alternative to: ``` select a.* from a where a.id in (select id from b) ``` Update: MySQL Can't be more specific sorry table a is effectively a join between 7 different tables. use of \* is for examples Edit, b doesn't get selected
Your question was about the difference between these two: ``` select a.* from a where a.id in (select id from b where b.id = a.id) select a.* from a where a.id in (select id from b) ``` The former is a *correlated* subquery. It may cause MySQL to execute the subquery for each row of `a`. The latter is a *non-correlated* subquery. MySQL should be able to execute it once and cache the results for comparison against each row of `a`. I would use the latter.
Both queries you list are the equivalent of: ``` select a.* from a inner join b on b.id = a.id ``` Almost all optimizers will execute them in the same way. You could post a real execution plan, and someone here might give you a way to speed it up. It helps if you specify what database server you are using.
SQL (any) Request for insight on a query optimization
[ "", "sql", "optimization", "query-optimization", "sql-optimization", "" ]
I have a @ManyToMany mapping where the table self-references through a mapping table, and we want to order on an order id in the actual mapping table, but are finding it difficult to configure this. We could perform it in hibernate xml, so it is natural to assume the support is there in JPA annotations. Does anybody know how we can order on a value in the mapping table? The table is: ``` wap_site_components intid strname intcomponentdef dtmcreated intcustomer ``` and the mapping table that self-references is: ``` wap_site_component_relations intid intparent (references intid in wap_site_components) intchild (references intid in wap_site_components) intorder (this is the value we want to order the collection on) ``` In Hibernate Annotations we have: ``` @ManyToMany (fetch = FetchType.LAZY, cascade = CascadeType.ALL) @JoinTable (name = "wap_site_component_relations", joinColumns = {@JoinColumn (name = "intparent", referencedColumnName = "id") }, inverseJoinColumns = {@JoinColumn (name = "intchild", referencedColumnName = "id") }) public Set<WapComponent> getChildren() { return children; } ``` This is how we performed it in hibernate xml: ``` <set name="children" table="wap_site_component_relations" lazy="true" cascade="none" sort="unsorted" order-by="intorder" mutable="false" > <cache usage="read-only" /> <key column="intparent" > </key> <many-to-many class="se.plusfoursix.im46.data.wap.WapComponent" column="intchild" outer-join="auto" /> </set> ``` So we want to use the @OrderBy tag but cannot reference the intorder value in the mapping table. Any ideas? Thanks. (We have tried an @OrderBy(intorder) over the children collection in code but that hasn't worked out for us)
We ended up just creating the mapping table as a bean. If anyone has a way of performing the above without that, would still be happy to hear from you!
You could create an annotated object to represent the link table, then use @oneToMany to map from the parent to the childlink and then to the child ``` @Entity public class Parent { @id Long id; @OneToMany(targetEntity = ChildLink.class) Set<ChildLink> childLinks; } public class ChildLink { @Id @OrderBy Long orderBy; @ManyToOne Set<Parent> parents; @ManyToOne Set<Child> children; } ``` Just a rough example. You can then programatically produce the set children from the set of childLinks, perhaps in the getChildren method of the parent class.
Ordering By Mapping Table Value in Hibernate
[ "", "java", "hibernate", "jpa", "many-to-many", "sql-order-by", "" ]
Is there a way to get which JSP is currently rendered, with JSTL or Struts (or without)? like \_ \_ file \_ \_ in Python and PHP?
Well ... yes ... in a way ``` String __jspName = this.getClass().getSimpleName().replaceAll("_", "."); ``` I'm using a JSP called `pre.jsp` for that which I include at the top of each JSP in my webapp: ``` <%@page import="org.apache.log4j.Logger"%> <% String __jspName = this.getClass().getSimpleName().replaceAll("_", "."); Logger log = Logger.getLogger(this.getClass().getName()); log.info("BEGIN JSP "+__jspName); %> <!-- BEGIN <%=__jspName %> --> ``` Plus I put this at the end of each JSP: ``` <!-- END <%=__jspName %> --><% log.info("END JSP "+__jspName); %> ``` That gives me a consistent log. To make sure each JSP is "correct", I have a check in my build script which just looks for the two strings `"/pre.jsp"` and ``END <%=\_\_jspName`. Note: There are many characters which are allowed in file names but not in Java class names. If you use them, your class names might look weird. If that's the case, I suggest to create a static helper function which converts class names to File names and call that, i.e. ``` String __jspName = MyJspUtils.getFileName(this.getClass()); ``` Each JSP compiler has it's own rules; here is one example: <http://itdoc.hitachi.co.jp/manuals/3020/30203Y0510e/EY050044.HTM> Kudos go to [Marcus Junius Brutus](https://stackoverflow.com/users/274677/marcus-junius-brutus) for pointing that out.
I succeeded using JSTL as following : ``` <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> ... <!-- <c:out value="${pageScope['javax.servlet.jsp.jspPage']}"></c:out> --> ... ``` And now, you should see as an HTML comment the name of the servlet produced by the container to render your JSP file, which name is very close to the JSP source file.
Get current filename in JSP
[ "", "java", "jsp", "struts", "jstl", "" ]
Why does the following query return 'zero' records: ``` SELECT * FROM records WHERE rownum >= 5 AND rownum <= 10 OR SELECT * FROM records WHERE rownum >= 5 ``` Whereas the following query return proper records: ``` SELECT * FROM records WHERE rownum <= 15 ``` Regards, - Ashish
In Oracle, Rownum values are assigned after the filtering stage of the query - they are not rows of the table, they are rows of the query result set. So the first row that comes back will always be given rownum 1, the second row that comes back rownum 2, etc. The rownum value is only incremented after it is assigned, so any query like ``` select * from t where ROWNUM > 1 ``` will **never** return any results. This query says 'I dont want to see the first row that gets returned to me, only the ones after that' which is sortof a paradox so nothing gets returned. See [Ask Tom:On ROWNUM and Limiting Results](http://www.oracle.com/technetwork/issue-archive/2006/06-sep/o56asktom-086197.html) for more details.
ROWNUM is a pseudocolumn and it's value will not be available at the time of query execution. So you can't filter your results based on this column. With that said, there are work arounds to mitigate it. Please see below (it is not recommended to use if your result is very huge). ``` Select a.* From ( Select COL1, COL2, ROWNUM RowNumber From MyTable ) a Where RowNumber = 5; ```
Oracle/SQL: Why does query "SELECT * FROM records WHERE rownum >= 5 AND rownum <= 10" - return zero rows
[ "", "sql", "oracle", "" ]
I'm currently reading a great book called 'Programming Collective Intelligence' by Toby Segaran (which i highly recommend) The code examples are all written in Python, and as I have already learnt one new language this year (graduating from VB.net to C#) i'm not keen to jump on another learning curve. This leaves my with the issue of translating the python examples into C#. Question is: How critical is it that the code stay in python? Are there thing in python that I can't do in a normal managed statically typed language?
One challenge you'll find is that not only are the algorithms implemented in Python, but the book makes extensive use of Python libraries like BeautifulSoup, Numpy, PIL, and others (see appendix A). I doubt there are any specifics of the algorithms that you couldn't port to another language, but you'll have trouble working through the exercises. Also, to translate the code, you'll have to learn Python at least a little bit, no? I suggest you just dive in and learn Python. You can use IronPython if you have any concern about interoperability with your C# projects.
You can do the same things in all Turing-complete languages. [Here is an example](http://thedailywtf.com/articles/stupid-coding-tricks-the-tsql-madlebrot.aspx) for rendering a Mandelbrot fractal in SQL. The example shows: Even if you can use any language, the effort will be different. So my guess is that the code will become much longer since Python is so flexible and open.
Python and Collective Intelligence
[ "", "python", "collective-intelligence", "" ]
I'm writing a PHP script that does a lot of repetitive work, and when the client executes it, I'd like it to send back HTML in some way, dynamically, as it completes tasks. (without AJAX?) How can this be done?
You can flush the output buffer, using flush(); So something like: ``` taskOne(); echo 'Task one finished'; flush(); ... ``` Hope this helps.
You're better off just polling the server via ajax. Set up a script that can monitor your running tasks and poll that. That way the users's browser isn't always in loading mode, and they can go away from the page and come back if they want.
PHP script that reports progress to Client
[ "", "php", "dynamic-data", "" ]
I need to profile an application compiled with intel's compiler via VC++. I'm using VTune to profile my code. My understanding is that in release mode I won't have the debug information that is necessary for the profiler to profile my code while in debug mode, the result of the profiling will not be pertinent. What should I do ? Is it possible to add debug info in release mode? How can I set this mode? If so, will I still benefit from all the optimization (inlining etc.)?
You should certainly profile with optimisations enabled (compiler option /O3). /Zi is the Intel compiler switch (on Windows) to enabled debugging information. Because of the optimisations, some functions may be missing from the debugging information due to inlining, but VTune will cope with that.
You can generate program database files (PDB) even in release target. Go to project properties, Linker/Debugging and check the option "Generate Program Database File". It is usually something like "$(TargetDir)$(TargetName).pdb". Now, it depends whether VTune knows how to interpret PDB files...
Which compilation option should be set for profiling?
[ "", "c++", "visual-studio", "profiling", "intel-vtune", "" ]
The following practice is fairly commonplace in the inline JavaScript I have to work with: ``` <script type="text/javascript"> <!-- // Code goes here //--> </script> ``` I know that the point is to prevent browsers that are incompatible with JavaScript from rendering the source, but is this still a best practice today? The vast majority of browsers used today can interpret JavaScript; even modern mobile devices usually don't have trouble. As for the 'why not?' question: I recently had to spend several hours debugging an issue where someone had left off the '//' in front of a '-->' at the end of a script tag buried deep in some pages, and this was causing mysterious JavaScript errors. What do you do? Is this still considered a 'best practice?'
The important thing is that nowadays, whether a particular browser supports JavaScript or not is irrelevant (clearly the great majority do) - it is irrelevant because almost *all* understand script blocks, which means that they know to ignore the JavaScript even if they can't interpret it. Matt Kruse gives a slightly [more detailed explanation](http://www.javascripttoolbox.com/bestpractices/#comments) on his *JavaScript Toolbox* site for why specifically *not* to use HTML comments within script blocks. Quoted from that page: --- ## Don't Use HTML Comments In Script Blocks In the ancient days of javascript (1995), some browsers like Netscape 1.0 didn't have any support or knowledge of the script tag. So when javascript was first released, a technique was needed to hide the code from older browsers so they wouldn't show it as text in the page. The 'hack' was to use HTML comments within the script block to hide the code. **Using HTML Comments In Script Is Bad** ``` // DON'T do this! Code is just representative on how things were done <script language="javascript"> <!-- // code here //--> </script> ``` No browsers in common use today are ignorant of the <script> tag, so hiding of javascript source is no longer necessary. In fact, it can be considered harmful for the following reasons: * Within XHTML documents, the source will actually be hidden from all browsers and rendered useless* -- is not allowed within HTML comments, so any decrement operations in script are invalid
I've stopped doing it. At some point you just have to let go of your NCSA Mosaic.
Are HTML comments inside script tags a best practice?
[ "", "javascript", "html", "" ]
How would you write a SQL query to get the size of blob in a more human readable form? The example would be something like a large word document is being stored in a blob on a table. I would want to execute something like: ``` select fnc_getReadableSize(documents.doc) from documents where id = ? ``` output: 23.4 MB
The 'readable' part is what I should have emphasized more. Here is what I put together for now. ``` WITH file_sizes AS (SELECT 1048576 MEGABYTE, 1024 KILOBYTE, DBMS_LOB.GETLENGTH (BLOB_COLUMN) byte_size FROM BLOB_COLUMN) SELECT (CASE TRUNC (byte_size / MEGABYTE) WHEN 0 THEN TO_CHAR ((byte_size / KILOBYTE), '999,999') || ' KB' ELSE TO_CHAR ((byte_size / MEGABYTE), '999,999.00') || ' MB' END ) display_size FROM file_sizes Output: DISPLAY_SIZE -------------- 1.88 MB 433 KB 540 KB 333 KB 1.57 MB 1.17 MB ```
``` SELECT DBMS_LOB.GETLENGTH(COLUMN_NAME) FROM DOCUMENTS ```
What is an elegant way to return a readable 'file size' of a file stored in an oracle blob column using SQL?
[ "", "sql", "oracle", "plsql", "" ]
I have a poll that has five 1-5 star ratings and I need to store the values individually for each user. Is there a method similar to bitfields where I can store these enumerated values (1, 2, 3, 4, or 5 for each rating) and easily extract them? At the moment my best bet would be to store a serialized PHP array, however that would take up a bit of space. Or, create 5 columns, which I would also prefer not to do (wasted space).
My first thought about this is using and storing the values like this: ``` $a="15540"; ``` The user didn't answer the last question. $a[0] is the value of the first vote which is: 1. Maybe not the fastest but simple.
Well, whatever you do, definitely don't denormalize by creating a column per possible answer. If you are using a database, the most flexible way would be to store your data in something like this ``` table polls poll_id description table poll_questions question_id poll_id (foreign key to polls) question_text table question_answers answer_id question_id (foreign key to poll_questions) answer_text table user_answers id user_id (foreign key to users) answer_id (foreign key to question_answers) ``` Easiest to maintain, though not the fastest due to joins you may need to do.
Best way to store multiple question poll results on a per-user basis?
[ "", "php", "mysql", "" ]
I'm a programmer (hobbyist, but looking to make it a career) by nature so when I was asked to design a website I felt a little out of place (most of my applications don't have pretty UI's, they just work because I'm the only one using them). I have been looking into how I could design my website and started wondering how you guys decide. What guidelines can you guys give me? What should I consider before I start coding?
It's pretty hard to sum up the whole field of UI design in an answer. Make the most common tasks the easiest. Figure out what people will want to do, and make that as intuitive and straightforward as possible. [Don't make them think](https://rads.stackoverflow.com/amzn/click/com/0321344758). Make mockups and prototypes. Watch people try to use them (**watch**, don't help them), and fix things that they found awkward. Your first attempt at a design isn't right, don't be too opposed to throwing it away. There's really so much to this field that it can't be explained to anyone easily. Designing is no less complex than programming, but many programmers seem to look at it as an afterthought for some reason. Try some creative googling for design principles, especially as they apply to the web. Look at sites you consider well-designed and try to figure out **why** they feel that way to you.
Read, read read!!! The best thing to do is read up on design techniques, and coding practices! Design sites: * <http://www.smashingmagazine.com/> * <http://www.youthedesigner.com/> * <http://www.psdtuts.com/> Coding sites (design minded): * <http://www.nettuts.com> * <http://cssglobe.com/> All the above answers are great! My advice is to learn as much as you can by studying others (and asking questions).
Choosing the right design for a website?
[ "", "javascript", "html", "css", "" ]
If I bind a WinForms ComboBox to an enum type's values, i.e. ``` combo1.DropDownStyle = ComboBoxStyle.DropDownList; combo1.DataSource = Enum.GetValues(typeof(myEnumType)); ``` Who knows how I could achieve the same result, while, in addition to entries matching each enum value, I can also have a blank entry representing no selection? I cannot simply add a special value to the enum type because this must be flexible to deal with any enum type. I'd appreciate your help. **Edit:** I should make clear that I want to bind the actual enum values and not their names. If the actual enum values are bound, the ComboBox takes care of calling their ToString() to get the text to display.
(Please see my edit to the question where I clarified that I don't want to bind to a collection of strings). After more fiddling, the following monstrosity seems to work. combo1.SelectedItem is of type object and will either be a DBNull or a (boxed?) enum value. Is this code advisable? ``` combo1.DataSource = (new object[] { DBNull.Value } .Concat(Enum.GetValues(refToAnEnumType) .Cast<object>())).ToList() ``` **Edit:** I see Adam and Andrew's methods could easily be adapted to do the same thing. Thanks guys!
Not sure if you guys have tried all of the code that you've been posting or not, but you can't add items do a databound ComboBox. This is winforms, not WPF, so there is no "DataBind" function. You could do this: ``` public static string[] GetEnumValues<T>(bool includeBlank) { List<string> values = new List<string>((Enum.GetValues(typeof(T)) as T[]).Select(t => t.ToString())); if (includeBlank) { values.Insert(0, string.Empty); } return values.ToArray(); } ``` Then ``` combo.DataSource = GetEnumValues<myEnumType>(true); ```
ComboBox bound to an enum type's values while also having a "blank" entry?
[ "", "c#", ".net", "winforms", "combobox", "enums", "" ]
I read on another Stack Overflow question that Python was just like Ruby, as it relates to "everything's an object," and everything in Python was an object, just like Ruby. Is this true? Is everything an object in Python like Ruby? How are the two different in this respect or are they really the same? For example, can you take a number and do the Ruby stuff I've seen like: ``` y = 5.plus 6 ``` Can that be done the same way in Python?
[DiveIntoPython - Everything Is an Object](https://linux.die.net/diveintopython/html/getting_to_know_python/everything_is_an_object.html#d0e4665) > Everything in Python is an object, and almost everything has attributes and methods. All functions have a built-in attribute `__doc__`, which returns the `doc string` defined in the function's source code. The `sys` module is an object which has (among other things) an attribute called `path`. And so forth. > > Still, this begs the question. What is an object? Different programming languages define “object” in different ways. In some, it means that *all* objects *must* have attributes and methods; in others, it means that all objects are subclassable. In Python, the definition is looser; some objects have neither attributes nor methods (more on this in Chapter 3), and not all objects are subclassable (more on this in Chapter 5). But everything is an object in the sense that it can be assigned to a variable or passed as an argument to a function (more in this in Chapter 4). [Ruby Docs - To Ruby From Python](http://www.ruby-lang.org/en/documentation/ruby-from-other-languages/to-ruby-from-python/) > As with Python, in Ruby,... Everything is an object So there you have it from Ruby's own website: in Python everything is an object.
While everything is an object in Python, it differs from Ruby in its approach to resolving names and interacting with objects. For example, while Ruby provides you with a 'to\_s' method on the Object base class, in order to expose that functionality, Python integrates it into the string type itself - you convert a type to a string by constructing a string from it. Instead of `5.to_s`, you have `str(5)`. Don't be fooled, though. There's still a method behind the scenes - which is why this code works: ``` (5).__str__() ``` So in practice, the two are fundamentally similar, but you use them differently. Length for sequences like lists and tuples in Python is another example of this principle at work - the actual feature is built upon [methods with special names](https://docs.python.org/3/reference/datamodel.html#special-method-names), but exposed through a simpler, easier-to-use interface (the `len` function). The Python equivalent to what you wrote in your question would thus be: ``` (5).__add__(6) ``` The other difference that's important is how global functions are implemented. In Python, globals are represented by a dictionary (as are locals). This means that the following: ``` foo(5) ``` Is equivalent to this in Python: ``` globals()["foo"].__call__(5) ``` While Ruby effectively does this: ``` Object.foo(5) ``` This has a large impact on the approach used when writing code in both languages. Ruby libraries tend to grow through the addition of methods to existing types like `Object`, while Python libraries tend to grow through the addition of global functions to a given module.
Is everything an object in Python like Ruby?
[ "", "python", "ruby", "object", "language-comparisons", "" ]
In C#, how do I make an async call to a WCF Web Service? I have a Service Reference set up to generate async. I also modified my calls to use { WebServiceObject.Begin\* () } but there are two parameters at the end, 'AsyncCallback' and 'object asyncState'. What are these and how do I use them? Thanks,
See MSDN here; <http://msdn.microsoft.com/en-us/library/system.asynccallback.aspx> here; <http://msdn.microsoft.com/en-us/library/ms228969.aspx> here; <http://msdn.microsoft.com/en-us/library/ms228975.aspx> and here; <http://msdn.microsoft.com/en-us/library/86wf6409.aspx> Basicly in Begin\* you set an callback, that callback is called when the operation has completed. There you call End\* to retrieve the appropriate data.
You might also want to look at [Async without the Pain](http://marcgravell.blogspot.com/2009/02/async-without-pain.html)
Async call to WCF with C#?
[ "", "c#", "wcf", "asynchronous", "" ]
I need to know if I am working with SharePoint Services or SharePoint Portal Server when using the SP API. Is there a way to do this in code (C#)?
You can check to see if the build version is different using SPFarm.BuildVersion: <http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.administration.spfarm.buildversion.aspx>
Check out Karine Bosch's blog post ["Determine if MOSS is installed by checking the Registry key"](http://www.u2u.info/Blogs/karine/Lists/Posts/Post.aspx?ID=29). This should help.
How to programmatically destinguish between WSS and MOSS
[ "", "c#", "sharepoint", "moss", "sharepoint-api", "" ]
I often find I am writing a class similar to the following (but with a varying number of members, types of members, etc). Is it possible to do this automatically, easily, and for free? So I would like to provide the parameters "Foo", "int", "apples", "bool", "banana", "Bar", and "clementine" and have the rest of code generated for me. ``` public class Foo { public Foo(int apples, bool banana, Bar clementine) { m_Apples = apples; m_Banana = banana; m_Clementine = clementine; } public int Apples { get { return m_Apples; } set { m_Apples = value; } } public bool Banana { get { return m_Banana; } set { m_Banana = value; } } public Bar Clementine { get { return m_Clementine; } set { m_Clementine = value; } } private int m_Apples; private bool m_Banana; private Bar m_Clementine; } ```
If you upgrade to C# 3.5, you can shorten the amount of writing you need to do. For example, you could just do this: ``` public class Foo { public int Apples { get; set; } public bool Banana { get; set; } public Bar Clementine { get; set; } } var myFoo = new Foo { Apples = 1, Banana = true, Clementine = new Bar() }; ``` Or, you could still have the constructor, but you don't have to add all of the private fields. This is pretty quick to type and quicker with code snippits or resharper. A downside is that like this, you can't validate your parameter input without more code. It kind of depends on who will be consuming your classes and how important it is that int Apples is explicitly set rather than just 0.
Take a look at [T4 Engine](http://www.hanselman.com/blog/T4TextTemplateTransformationToolkitCodeGenerationBestKeptVisualStudioSecret.aspx). It's included with VS2005 onwards.
Automatically generate c# class
[ "", "c#", "code-generation", "" ]
I have a problem when assigning the `DataSource` propery on a `DataGridView` control. My `DataSource` is a `DataTable`'s `DefaultView` and, as expected, columns are automatically created in the `DataGridView` to match those in the `DataTable` when I assign it. What happens next is that the columns seem to be automatically removed and recreated a further 2 times by the `DataGridView`. Why would this happen? In a form's constructor: ``` //A DataTable is created with 5 columns //The DataTable is populated with some rows. myDgv.AutoGenerateColumns = true; myDgv.DataSource = myDataTable.DefaultView; // myDgv.ColumnAdded event is fired 5 times. // WHY: myDgv.ColumnRemoved event is fired 5 times. // WHY: myDgv.ColumnAdded event is fired 5 times. // WHY: myDgv.ColumnRemoved event is fired 5 times. // WHY: myDgv.ColumnAdded event is fired 5 times. ``` --- **Edit: Added a (hopefully) self contained example. If I set breakpoints in the event handlers, I hit the 'Added' one 6 times and the 'Removed' one 4 times. The DataTable contains 2 columns and I never ask for any columns to be removed in my code.** ``` using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace asdasdgf { public class Form1 : Form { public Form1() { InitializeComponent(); DataTable dt = new DataTable(); dt.Columns.Add("Col1", typeof(int)); dt.Columns.Add("Col2", typeof(string)); foreach (int i in Enumerable.Range(0, 10)) { var row = dt.NewRow(); row["Col1"] = i; row["Col2"] = "stackoverflow"; dt.Rows.Add(row); } dataGridView1.ColumnAdded += new DataGridViewColumnEventHandler(dataGridView1_ColumnAdded); dataGridView1.ColumnRemoved += new DataGridViewColumnEventHandler(dataGridView1_ColumnRemoved); dataGridView1.DataSource = dt.DefaultView; } void dataGridView1_ColumnRemoved(object sender, DataGridViewColumnEventArgs e) { // Break here } void dataGridView1_ColumnAdded(object sender, DataGridViewColumnEventArgs e) { // Break here } // Form1.Designer.cs contents: #region Windows Form Designer generated code private System.ComponentModel.IContainer components = null; private System.Windows.Forms.DataGridView dataGridView1; protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.dataGridView1 = new System.Windows.Forms.DataGridView(); ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit(); this.SuspendLayout(); // // dataGridView1 // this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dataGridView1.Location = new System.Drawing.Point(12, 41); this.dataGridView1.Name = "dataGridView1"; this.dataGridView1.Size = new System.Drawing.Size(240, 150); this.dataGridView1.TabIndex = 0; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(284, 264); this.Controls.Add(this.dataGridView1); this.Name = "Form1"; this.Text = "Form1"; ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit(); this.ResumeLayout(false); } #endregion } } ```
After a lot of fiddling, this seems to be the way to go. In your form's `Load` event handler: ``` dgv.AutoGenerateColumns = false; dgv.DataSource = myDataSource; ``` In your form's `Shown` event handler: ``` dgv.AutoGenerateColumns = true; ``` Giving the desired result of the `ColumnAdded` event being fired once for each column, and the `ColumnRemoved` event not being fired at all. (If AutoGenerateColumns = true is set in the `Load` event handler, it will do this annoying Add-Remove-Add dance.)
I have an app that uses a DataGridView to display the contents of a DataTable, but I link them like this: ``` dataGridView.DataSource = dataTable; ``` Can you try this? EDIT: I also have the following in the auto generated code: ``` this.dataGridView.EditMode = System.Windows.Forms.DataGridViewEditMode.EditProgrammatically; ``` Not sure why this would make a difference though.
DataGridView repeatedly recreating columns
[ "", "c#", ".net", "winforms", "datagridview", "" ]
In Perl, it's often nice to be able to assign an object, but specify some fall-back value if the variable being assigned from is 'undef'. For instance: ``` my $x = undef; my $y = 2; my $a = $x || $y; ``` After this, ``` $a == 2 ``` Is there a concise way to achieve this in Python if the value x is None, or would a full-on ... ``` if x is not None a = x else a = y ``` ... be the most Pythonic way to achieve this? EDIT: Apologies, as has been pointed out by several commenters, I wasn't really talking about the value being undefined, but 'undef' in Perl, which is not really the same thing. But the question as originally worded didn't make this clear.
Since 2.5: If you want to fall back **only** on None: ``` a = x if x is not None else y ``` If you want to fall back also on empty string, `false`, `0` etc.: ``` a = x if x else y ``` or ``` a = x or y ``` --- As for undefined (as never defined, a.k.a. not bound): ``` try: a = x except NameError: a = y ``` or a bit more hackish (I'd not really recommend that, but it's short): ``` a = vars().get('x',y) ```
first you can do your full-on with a ternary: ``` a = y if x is None else x ``` but it doesn't solve your problem. what you want to do is more closely implemented with: ``` try: a = x except: a = y ```
What is the most Pythonic way to provide a fall-back value in an assignment?
[ "", "python", "" ]
I'm trying to add items to a select drop down at run time. So far it's working in Firefox and Opera, but it doesn't seem to work in IE7 or 8. What is supposed to happen is that when a user selects a center, then the personnel drop down gets populated with the personnel at the center.... ``` //Clear out the all of the exisiting items if (document.getElementById("ddlPersonnel").hasChildNodes) { while (document.getElementById("ddlPersonnel").childNodes.length > 0) { document.getElementById("ddlPersonnel").removeChild(document.getElementById("ddlPersonnel").firstChild); } } //Add the "Select Personnel" option var FirstOpt = document.createElement('OPTION'); FirstOpt.value = ""; FirstOpt.innerText = "Select Personnel"; alert("blah1"); document.getElementById("ddlPersonnel").options.add(FirstOpt, null); //It dies here with a "Type Mismatch" error alert("blah2"); ``` It dies on the line between the two alerts with a "Type Mismatch" error.
Use new Option instead of createElement. ``` var sel = document.getElementById("ddlPersonnel"); var opt = sel.options; opt[opt.length] = new Option("Label","Value") ``` (That should work, but I haven't tested it)
Just replace ``` document.getElementById("ddlPersonnel").options.add(FirstOpt, null); ``` by ``` document.getElementById("ddlPersonnel").add(FirstOpt); ``` Removing the ".options" and the ", null" in the add() function will do the trick
Add Options to select drop down in IE
[ "", "javascript", "html", "" ]
I have a condition in a silverlight application that compares 2 strings, for some reason when I use `==` it returns **false** while `.Equals()` returns **true**. Here is the code: ``` if (((ListBoxItem)lstBaseMenu.SelectedItem).Content.Equals("Energy Attack")) { // Execute code } if (((ListBoxItem)lstBaseMenu.SelectedItem).Content == "Energy Attack") { // Execute code } ``` Any reason as to why this is happening?
When `==` is used on an expression of type `object`, it'll resolve to [`System.Object.ReferenceEquals`](https://msdn.microsoft.com/en-us/library/system.object.referenceequals.aspx). [`Equals`](https://msdn.microsoft.com/en-us/library/bsc2ak47.aspx) is just a `virtual` method and behaves as such, so the overridden version will be used (which, for `string` type compares the contents).
When comparing an object reference to a string (even if the object reference refers to a string), the special behavior of the `==` operator specific to the string class is ignored. Normally (when not dealing with strings, that is), `Equals` compares **values**, while `==` compares **object references**. If two objects you are comparing are referring to the same exact instance of an object, then both will return true, but if one has the same content and came from a different source (is a separate instance with the same data), only Equals will return true. However, as noted in the comments, string is a special case because it overrides the `==` operator so that when dealing purely with string references (and not object references), only the values are compared even if they are separate instances. The following code illustrates the subtle differences in behaviors: ``` string s1 = "test"; string s2 = "test"; string s3 = "test1".Substring(0, 4); object s4 = s3; // Notice: set to object variable! Console.WriteLine($"{object.ReferenceEquals(s1, s2)} {s1 == s2} {s1.Equals(s2)}"); Console.WriteLine($"{object.ReferenceEquals(s1, s3)} {s1 == s3} {s1.Equals(s3)}"); Console.WriteLine($"{object.ReferenceEquals(s1, s4)} {s1 == s4} {s1.Equals(s4)}"); ``` The output is: ``` True True True // s1, s2 False True True // s1, s3 False False True // s1, s4 ``` Summary: | Variables | .ReferenceEquals | == | .Equals | | --- | --- | --- | --- | | s1, s2 | True | True | True | | s1, s3 | False | True | True | | s1, s4 | False | False | True |
C# difference between == and Equals()
[ "", "c#", ".net", "equals", "" ]
I have a table in a sql server 2008 database that contains bunch of records as well as a date column. The date is inserted automatically when a new entry to the table occurs. So, it contains the date of the record that has been created. I am trying to run a query that would return me the earliest date and the latest date in this table. I tried something like; ``` SELECT TOP(1) DateAdded AS firstdate FROM News ORDER BY DateAdded DESC; SELECT TOP(1) DateAdded AS lastdate FROM News ORDER BY DateAdded ASC; ``` but it only returned the 'firstdate'. Can anyone guide me on how to achieve this?
``` SELECT MIN(DateAdded) As FirstDate, MAX(DateAdded) As LastDate FROM News; ```
The answer is to use aggregates. ``` SELECT MIN(DateAdded) AS firstdate, MAX(DateAdded) AS lastdate FROM News; ``` Your query returns 2 results: each works individually though
TSQL query that would return me the earliest date and the latest date in a table
[ "", "sql", "sql-server", "t-sql", "sql-server-2008", "" ]
I'm need a regular expression in Java that I can use to retrieve the domain.tld part from any url. So <https://foo.com/bar>, <http://www.foo.com#bar>, <http://bar.foo.com> will all return foo.com. I wrote this regex, but it's matching the whole url ``` Pattern.compile("[.]?.*[.x][a-z]{2,3}"); ``` I'm not sure I'm matching the "." character right. I tried "." but I get an error from netbeans. **Update:** The tld is not limited to 2 or 3 characters, and <http://www.foo.co.uk/bar> should return foo.co.uk.
I would use the java.net.URI class to extract the host name, and then use a regex to extract the last two parts of the host uri. ``` import java.net.URI; import java.net.URISyntaxException; import java.util.regex.Matcher; import java.util.regex.Pattern; public class RunIt { public static void main(String[] args) throws URISyntaxException { Pattern p = Pattern.compile(".*?([^.]+\\.[^.]+)"); String[] urls = new String[] { "https://foo.com/bar", "http://www.foo.com#bar", "http://bar.foo.com" }; for (String url:urls) { URI uri = new URI(url); //eg: uri.getHost() will return "www.foo.com" Matcher m = p.matcher(uri.getHost()); if (m.matches()) { System.out.println(m.group(1)); } } } } ``` Prints: ``` foo.com foo.com foo.com ```
This is harder than you might imagine. Your example <https://foo.com/bar>, has a comma in it, which is a valid URL character. Here is a great post about some of the troubles: <https://blog.codinghorror.com/the-problem-with-urls/> ``` https?://([-A-Za-z0-9+&@#/%?=~_()|!:,.;]*[-A-Za-z0-9+&@#/%=~_()|]) ``` Is a good starting point Some listings from "Mastering Regular Expressions" on this topic: <http://regex.info/listing.cgi?ed=3&p=207> @sjobe ``` >>> import re >>> pattern = r'https?://([-A-Za-z0-9+&@#/%?=~_()|!:,.;]*[-A-Za-z0-9+&@#/%=~_()|])' >>> url = re.compile(pattern) >>> url.match('http://news.google.com/').groups() ('news.google.com/',) >>> url.match('not a url').groups() Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'NoneType' object has no attribute 'groups' >>> url.match('http://google.com/').groups() ('google.com/',) >>> url.match('http://google.com').groups() ('google.com',) ``` sorry the example is in python not java, it's more brief. Java requires some extraneous escaping of the regex.
Regular expression to retrieve domain.tld
[ "", "java", "regex", "" ]
Kind of the opposite of [this question](https://stackoverflow.com/questions/608316/is-there-commit-analog-in-python-for-writing-into-a-file). Is there a way to tell Python "Do not write to disk until I tell you to." (by closing or flushing the file)? I'm writing to a file on the network, and would rather write the entire file at once. In the meantime, I'm writing to a StringIO buffer, and then writing that to the disk at the end.
No, a glance at the python manual does not indicate an option to set the buffer size to infinity. Your current solution is basically the same concept. You **could** use Alex's idea, but I would hazard against it for the following reasons: 1. The buffer size on open is limited to 2^31-1 or 2 gigs. Any larger will result in "OverflowError: long int too large to convert to int" 2. It doesn't seem to work: ``` a = open("blah.txt", "w", 2 ** 31 - 1) for i in xrange(10000): a.write("a") ``` Open up the file without closing python, and you will see the text
You can open your file with as large a buffer as you want. For example, to use up to a billion bytes for buffering, `x=open('/tmp/za', 'w', 1000*1000*1000)` -- if you have a hundred billion bytes of memory and want to use them all, just add another \*100...;-). Memory will only be consumed in the amount actually needed, so, no worry...
Python: File IO - Disable incremental flush
[ "", "python", "file-io", "" ]
### Duplicate: > [Do web sites really need to cater for browsers that don’t have Javascript enabled?](https://stackoverflow.com/questions/822872/do-web-sites-really-need-to-cater-for-browsers-that-dont-have-javascript-enabled) > [Only supporting users who have Javascript enabled.](https://stackoverflow.com/questions/740243/only-supporting-users-who-have-javascript-enabled) > [How common is it for Javascript to be disabled](https://stackoverflow.com/questions/379735/how-common-is-it-for-javascript-to-be-disabled) > [How many people disable Javascript?](https://stackoverflow.com/questions/121108/how-many-people-disable-javascript) I've been doing web applications on and off for a few years now and each application I write seems to have more javascript than the previous one. A frequent comment is: "But what if the user turns off Javascript?". I take the point, but I've never actually seen a user do this. Not once. Have you?
This comes up about every other week or so. Did you search first? See these: <https://stackoverflow.com/questions/121108/how-many-people-disable-javascript> <https://stackoverflow.com/questions/379735/how-common-is-it-for-javascript-to-be-disabled> [Only supporting users who have Javascript enabled](https://stackoverflow.com/questions/740243/only-supporting-users-who-have-javascript-enabled) [Do web sites really need to cater for browsers that don't have Javascript enabled?](https://stackoverflow.com/questions/822872/do-web-sites-really-need-to-cater-for-browsers-that-dont-have-javascript-enabled) The main points are: * Google doesn't use javascript when indexing * Mobile browsers (smart phones like the iPhone) sometimes have bad or non-existent javascript * Screen readers don't do javascript well, if at all, and many developers are legally required to support them. * Thanks to filters like NoScript, the number of people browsing with javascript disabled (at least initially) may actually be going *up*. So yes, you still need to worry about it.
It depends entirely on what sort of coverage you require. Do you need 80% 90% 100% of users to be able to use your site / application? People DO turn off Javascript. The question is, does your site need to work for those people? Can it just tell them to turn it on if they want to continue?
Is it safe to assume Javascript is always turned on?
[ "", "javascript", "" ]
In the book 'Code Complete' the author talks about programming **into** a language (instead of programming in a language). He means, that you should not limit yourself by the restrictions of the chosen programming-language. A callback is an often used feature. I'm interested: What is the most elegant way to programm callbacks into the java-language?
Check out this article: <http://www.onjava.com/pub/a/onjava/2003/05/21/delegates.html> Callbacks are essentially a special case od Delegates (As C# has them), and the article gives an implementation of something resembling a C# delegate, in java.
Java uses all sorts of callbacks for all sorts of situations. Ever since the oldest old days of AWT listeners, Java has been all about callbacks. There are two basic "flavors" of Java callbacks. The first is the implement an interface method: ``` public class MyThing implements StateChangeListener { //this method is declared in StateChangeListener public void stateChanged() { System.out.println("Callback called!"); } public MyThing() { //Here we declare ourselves as a listener, which will eventually //lead to the stateChanged method being called. SomeLibraryICareAbout.addListener(this); } } ``` The second flavor of Java callback is the anonymous inner class: ``` public class MyThing { public MyThing() { //Here we declare ourselves as a listener, which will eventually //lead to the stateChanged method being called. SomeLibraryICareAbout.addListener( new StateChangeListener() { //this method is declared in StateChangeListener public void stateChanged() { System.out.println("Callback called!"); } }); } } ``` There are other ways, too, including using Reflection, using separate event-handling classes, and the Adapter pattern.
Programming into a language: What is the most elegant way to define callbacks in Java?
[ "", "java", "callback", "" ]
If I have a python class, how can I alias that class-name into another class-name and retain all it's methods and class members and instance members? Is this possible without using inheritance? e.g. I have a class like: ``` class MyReallyBigClassNameWhichIHateToType: def __init__(self): <blah> [...] ``` I'm creating an interactive console session where I don't want my users' fingers to fall off while instantiating the class in the interactive sessions, so I want to alias that really long class name to something tiny like 'C'. Is there an easy way to do this without inheritance?
``` C = MyReallyBigClassNameWhichIHateToType ```
Also, if you're importing the name from another module... ``` from modulename import ReallyLongNameWhichIHateToType as FriendlyName ```
How do you alias a python class to have another name without using inheritance?
[ "", "python", "" ]
I'm trying to get the elements in an HTML doc that contain the following pattern of text: #\S{11} ``` <h2> this is cool #12345678901 </h2> ``` So, the previous would match by using: ``` soup('h2',text=re.compile(r' #\S{11}')) ``` And the results would be something like: ``` [u'blahblah #223409823523', u'thisisinteresting #293845023984'] ``` I'm able to get all the text that matches (see line above). But I want the parent element of the text to match, so I can use that as a starting point for traversing the document tree. In this case, I'd want all the h2 elements to return, not the text matches. Ideas?
``` from BeautifulSoup import BeautifulSoup import re html_text = """ <h2>this is cool #12345678901</h2> <h2>this is nothing</h2> <h1>foo #126666678901</h1> <h2>this is interesting #126666678901</h2> <h2>this is blah #124445678901</h2> """ soup = BeautifulSoup(html_text) for elem in soup(text=re.compile(r' #\S{11}')): print elem.parent ``` Prints: ``` <h2>this is cool #12345678901</h2> <h2>this is interesting #126666678901</h2> <h2>this is blah #124445678901</h2> ```
BeautifulSoup search operations deliver [a list of] `BeautifulSoup.NavigableString` objects when `text=` is used as a criteria as opposed to `BeautifulSoup.Tag` in other cases. Check the object's `__dict__` to see the attributes made available to you. Of these attributes, `parent` is favored over `previous` because of [changes in BS4](http://www.crummy.com/software/BeautifulSoup/bs4/doc/#method-names). ``` from BeautifulSoup import BeautifulSoup from pprint import pprint import re html_text = """ <h2>this is cool #12345678901</h2> <h2>this is nothing</h2> <h2>this is interesting #126666678901</h2> <h2>this is blah #124445678901</h2> """ soup = BeautifulSoup(html_text) # Even though the OP was not looking for 'cool', it's more understandable to work with item zero. pattern = re.compile(r'cool') pprint(soup.find(text=pattern).__dict__) #>> {'next': u'\n', #>> 'nextSibling': None, #>> 'parent': <h2>this is cool #12345678901</h2>, #>> 'previous': <h2>this is cool #12345678901</h2>, #>> 'previousSibling': None} print soup.find('h2') #>> <h2>this is cool #12345678901</h2> print soup.find('h2', text=pattern) #>> this is cool #12345678901 print soup.find('h2', text=pattern).parent #>> <h2>this is cool #12345678901</h2> print soup.find('h2', text=pattern) == soup.find('h2') #>> False print soup.find('h2', text=pattern) == soup.find('h2').text #>> True print soup.find('h2', text=pattern).parent == soup.find('h2') #>> True ```
Using BeautifulSoup to find a HTML tag that contains certain text
[ "", "python", "regex", "beautifulsoup", "html-content-extraction", "" ]
I want to determine if a generic object type ("T") method type parameter is a collection type. I would typically be sending T through as a Generic.List but it could be any collection type as this is used in a helper function. Would I be best to test if it implements IEnumerable<T>? If so, what would the code look like? **Update 14:17 GMT+10 Possibly extending on a solution [here](http://www.devcurry.com/2009/03/determine-if-object-implements.html) (however only works for List<T>'s not IEnumerable<T>'s when it should if List derives ?)** ``` T currentObj; // works if currentObj is List<T> currentObj.GetType().GetGenericTypeDefinition() == typeof(List<>) // does not work if currentObj is List<T> currentObj.GetType().GetGenericTypeDefinition() == typeof(IEnumerable<>) ```
This will be the simplest check.. ``` if(Obj is ICollection) { //Derived from ICollection } else { //Not Derived from ICollection } ```
You can use Type.GetInterface() with the mangled name. ``` private bool IsTAnEnumerable<T>(T x) { return null != typeof(T).GetInterface("IEnumerable`1"); } ```
Determine if object derives from collection type
[ "", "c#", ".net", "reflection", "" ]
I have been tasked with porting a large Java codebase to the Android platform. The project makes extensive use of AWT which isn't' supported on Android. I'm looking for a tool that lets me visualize all of the classes in the project. I'd like to be able to see all of the relationships between classes so that I can get a good idea of where to start the port. If you have any suggestions that would help in this task I'd like to hear about them.
I use Structure101 almost daily to visualize and understand our code base. A great tool and quite reasonably priced too. This question has been touched at StackOverflow many times before and here are some links: * [Is there some tool to visualize java class hierarchies and relations?](https://stackoverflow.com/questions/43344/is-there-some-tool-to-visualize-java-class-heirarchies-and-relations) * [Tool to visualize code flow in Java?](https://stackoverflow.com/questions/153414/tool-to-visualize-code-flow-in-java) * [Recommended Eclipse plugins to generate UML from Java code](https://stackoverflow.com/questions/51786/recommended-eclipse-plugins-to-generate-uml-from-java-code) * [Good free UML tool for Java/Eclipse?](https://stackoverflow.com/questions/390438/good-free-uml-tool-for-java-eclipse) IntelliJ IDEA also has some tools to help, like Graphical Navigator in IDEA 8 and [Code Navigator plugin](http://plugins.intellij.net/plugin/?id=3202).
Netbeans has an OK reverse engineering tool which spits out a heaps of UML. I haven't used it in a while, but when I did it was a tad buggy.
Visualizing Java project
[ "", "java", "android", "" ]
Is there an easy way to use DirectX in Java? In particular, DirectX's video APIs. I know that C# might be a more natural choice, but I have my devious reasons for wanting to do something so perverse.
I don't know about easy, but you could always use JNI to load the DirectX libs and invoke the methods. Using something like [Swig](http://www.swig.org/) you could auto-generate a lot of the code. Not sure how workable something like that would be though.
There seems to be a [standard API](https://java3d.dev.java.net/) about dealing with 3D inside Java. It probably uses some kind of accelerating technology, may be even DirectX. But I'm not sure about direct video support in this framework.
Is DirectX on Java possible?
[ "", "java", "com", "video", "directx", "" ]
Is there a way in JS to get the entire HTML within the *html* tags, as a string? ``` document.documentElement.?? ```
Get the root `<html>` element with [`document.documentElement`](https://developer.mozilla.org/en-US/docs/Web/API/Document/documentElement) then get its [`.innerHTML`](https://developer.mozilla.org/en-US/docs/DOM/element.innerHTML): ``` const txt = document.documentElement.innerHTML; alert(txt); ``` or its [`.outerHTML`](https://developer.mozilla.org/en-US/docs/Web/API/Element/outerHTML) to get the `<html>` tag as well ``` const txt = document.documentElement.outerHTML; alert(txt); ```
You can do ``` new XMLSerializer().serializeToString(document) ``` in browsers newer than IE 9 See <https://caniuse.com/xml-serializer>
How to get the entire document HTML as a string?
[ "", "javascript", "html", "document", "tostring", "" ]
You can define 2 variables of the same type in a for loop: ``` int main() { for (int i = 0, j = 0; i < 10; i += 1, j = 2*i) { cout << j << endl; } } ``` But it is illegal to define variables of different types: ``` int main() { for (int i = 0, float j = 0.0; i < 10; i += 1, j = 2*i) { cout << j << endl; } } ``` Is there a way to do this? (I don't need to use `i` inside the loop, just `j`.) If you have totally hacked and obscure solution, It's OK for me. In this contrived example I know you could just use `double` for both variables. I'm looking for a general answer. Please do not suggest to move any of the variables outside of for body, probably not usable for me as one is an iterator that has to disappear just after the loop and the for statement is to be enclosed in my `foreach` macro: ``` #define foreach(var, iter, instr) { \ typeof(iter) var##IT = iter; \ typeof(iter)::Element var = *var##IT; \ for (; var##_iterIT.is_still_ok(); ++var##IT, var = *var#IT) { \ instr; \ } \ } ``` It can be used thus: ``` foreach(ii, collection, { cout << ii; }). ``` But I need something that will be used like that: ``` foreach(ii, collection) cout << ii; ``` Please do not introduce any runtime overhead (but it might be slow to compile).
Here is a version using boost preprocessor (This is just for fun. For the real-world answer, see @kitchen's one above): ``` FOR((int i = 0)(int j = 0.0), i < 10, (i += 1, j = 2 * i)) { } ``` The first part specifies a sequence of declarations: `(a)(b)...`. The variables declared later can refer to variables declared before them. The second and third part are as usual. Where commas occur in the second and third parts, parentheses can be used to prevent them to separate macro arguments. There are two tricks known to me used to declare variables that are later visible in a compound statement added outside a macro. The first uses conditions, like an if: ``` if(int k = 0) ; else COMPOUND_STATEMENT ``` Then `k` is visible. Naturally, it always have to evaluate to `false`. So it can't be used by us. The other context is this one: ``` for(int k = 0; ...; ...) COMPOUND_STATEMENT ``` That's what i'm going to use here. We'll have to watch to only make one iteration of `COMPOUND_STATEMENT`. The actual `for` loop that does the increment and condition checking has to come at the end, so the appended compound statement appertains to it. ``` #include <boost/preprocessor.hpp> #include <iostream> #define EMIT_DEC_(R,D,DEC) \ for(DEC; !_k; ) #define FOR(DECS, COND, INC) \ if(bool _k = false) ; else \ BOOST_PP_SEQ_FOR_EACH(EMIT_DEC_, DECS, DECS) \ for(_k = true; COND; INC) int main() { FOR((int i = 0)(float j = 0.0f), i < 10, (i += 1, j = 2 * i)) { std::cout << j << std::endl; } } ``` It's creating a bunch of `for` statements, each nested into another one. It expands into: ``` if(bool _k = false) ; else for(int i = 0; !_k; ) for(float j = 0.0f; !_k; ) for(_k = true; i < 10; (i += 1, j = 2 * i)) { std::cout << j << std::endl; } ```
> Please do not suggest to move any of > the variables outside of for body, > probably not usable for me as the > iterator has to disappear just after > the loop. You could do this: ``` #include <iostream> int main( int, char *[] ) { { float j = 0.0; for ( int i = 0; i < 10; i += 1, j = 2*i ) { std::cout << j << std::endl; } } float j = 2.0; // works std::cout << j << std::endl; return 0; } ```
Is there a way to define variables of two different types in a for loop initializer?
[ "", "c++", "for-loop", "scope", "initializer", "variable-declaration", "" ]
What is a Connection Object in JDBC ? How is this Connection maintained(I mean is it a Network connection) ? Are they TCP/IP Connections ? Why is it a costly operation to create a Connection every time ? Why do these connections become stale after sometime and I need to refresh the Pool ? Why can't I use one connection to execute multiple queries ?
These connections are TCP/IP connections. To not have to overhead of creating every time a new connection there are connection pools that expand and shrink dynamically. You can use one connection for multiple queries. I think you mean that you release it to the pool. If you do that you might get back the same connection from the pool. In this case it just doesn't matter if you do one or multiple queries The cost of a connection is to connect which takes some time. ANd the database prepares some stuff like sessions, etc for every connection. That would have to be done every time. Connections become stale through multiple reasons. The most prominent is a firewall in between. Connection problems could lead to connection resetting or there could be simple timeouts
To add to the other answers: Yes, you can reuse the same connection for multiple queries. This is even advisable, as creating a new connection is quite expensive. You can even execute multiple queries concurrently. You just have to use a new java.sql.Statement/PreparedStatement instance for every query. Statements are what JDBC uses to keep track of ongoing queries, so each parallel query needs its own Statement. You can and should reuse Statements for consecutive queries, though.
What is a Connection in JDBC?
[ "", "java", "networking", "jdbc", "tcp", "connection", "" ]
I hear about Haml as a templating engine mostly in the Ruby world. Can it also be used in Java projects?
There's a list of Haml implementations [on the Wikipedia page](http://en.wikipedia.org/wiki/Haml#Implementations). At the moment, there isn't one for Java. # Update There has been a Java implementation for a few years now : <https://github.com/raymyers/JHaml>
2 years after this question was asked (:P) there are: * scaml - <http://scalate.fusesource.org/documentation/scaml-reference.html> * jade - <http://scalate.fusesource.org/documentation/jade.html>
Can Haml be used in Java web apps?
[ "", "java", "haml", "" ]
I'm setting up a very straightforward FAQ page with jQuery. Like so: ``` <h2>What happens when you click on this question?</h2> <p>This answer will appear!</p> ``` This is all inside a very specific div, so I'll be selecting the header with `$('#faq h2')`. Simple, right? Click on the H2, and use `this.next()` to make the next paragraph show up. (The caveat with this page is that a non-programmer will be maintaining it, which is why I'm not using classes: there's no guarantee that any new entries would have the right classes in them.) So! The problem: ``` <h2>What happens when you click on the next question?</h2> <p>That is an interesting conundrum.</p> <p>Because the maintainer is kind of long-winded</p> <p>and many answers will span a few paragraphs.</p> ``` So how, without adding in `div`s and classes and whatnot, can I have my `this.next()` routine select everything between the question-that-was-clicked-on and the next question (H2 header)?
Interesting problem. First let me say that I think the best strategy is to enclose the whole answer in a div and then the problem becomes trivial to solve: ``` <h2>Question here</h2> <div> <p>Answer here</p> </div> </h2>Next Question</h2> ... ``` with: ``` $(function() { $("h2").click(function() { $(this).next().toggleClass("highlighted"); }); }); ``` But that being said, it is solvable without that. ``` $(function() { $("h2").click(function() { $(this).nextAll().each(function() { if (this.tagName == 'H2') { return false; // stop execution } $(this).toggleClass("highlighted"); }); }); }); ``` Not supremely elegant but it'll work. **Note:** This assumes the questions are siblings. If they are not it gets much more complicated.
I realise that this is an old question, but jQuery 1.4 now has [nextUntil](http://api.jquery.com/nextUntil/). So something like this should now work: ``` $('h2').click(function(){ $(this).nextUntil('h2').show(); }) ```
jQuery: How to select "from here until the next H2"?
[ "", "javascript", "jquery", "dom", "jquery-selectors", "css-selectors", "" ]
Let's say I want to read a line from a socket, using the standard `socket` module: ``` def read_line(s): ret = '' while True: c = s.recv(1) if c == '\n' or c == '': break else: ret += c return ret ``` What exactly happens in `s.recv(1)`? Will it issue a system call each time? I guess I should add some buffering, anyway: > For best match with hardware and network realities, the value of *bufsize* should be a relatively small power of 2, for example, 4096. <http://docs.python.org/library/socket.html#socket.socket.recv> But it doesn't seem easy to write efficient and thread-safe buffering. What if I use `file.readline()`? ``` # does this work well, is it efficiently buffered? s.makefile().readline() ```
The `recv()` call is handled directly by calling the C library function. It will block waiting for the socket to have data. In reality it will just let the `recv()` system call block. `file.readline()` is an efficient buffered implementation. It is not threadsafe, because it presumes it's the only one reading the file. (For example by buffering upcoming input.) If you are using the file object, every time `read()` is called with a positive argument, the underlying code will `recv()` only the amount of data requested, unless it's already buffered. It would be buffered if: * you had called readline(), which reads a full buffer * the end of the line was before the end of the buffer Thus leaving data in the buffer. Otherwise the buffer is generally not overfilled. The goal of the question is not clear. if you need to see if data is available before reading, you can `select()` or set the socket to nonblocking mode with `s.setblocking(False)`. Then, reads will return empty, rather than blocking, if there is no waiting data. Are you reading one file or socket with multiple threads? I would put a single worker on reading the socket and feeding received items into a queue for handling by other threads. Suggest consulting [Python Socket Module source](http://svn.python.org/view/python/tags/r262/Lib/socket.py?revision=71601&view=markup#readline) and [C Source that makes the system calls](http://svn.python.org/view/python/tags/r262/Modules/socketmodule.c?revision=71601&view=markup).
If you are concerned with performance and control the socket completely (you are not passing it into a library for example) then try implementing your own buffering in Python -- Python string.find and string.split and such can be amazingly fast. ``` def linesplit(socket): buffer = socket.recv(4096) buffering = True while buffering: if "\n" in buffer: (line, buffer) = buffer.split("\n", 1) yield line + "\n" else: more = socket.recv(4096) if not more: buffering = False else: buffer += more if buffer: yield buffer ``` If you expect the payload to consist of lines that are not too huge, that should run pretty fast, and avoid jumping through too many layers of function calls unnecessarily. I'd be interesting in knowing how this compares to file.readline() or using socket.recv(1).
Python sockets buffering
[ "", "python", "sockets", "buffering", "" ]
Could anyone please tell what are the important use cases of `IdentityHashMap`?
The [documentations](http://java.sun.com/javase/6/docs/api/java/util/IdentityHashMap.html) says: > A typical use of this class is > topology-preserving object graph > transformations, such as serialization > or deep-copying. To perform such a > transformation, a program must > maintain a "node table" that keeps > track of all the object references > that have already been processed. The > node table must not equate distinct > objects even if they happen to be > equal. Another typical use of this > class is to maintain proxy objects. > For example, a debugging facility > might wish to maintain a proxy object > for each object in the program being > debugged.
Whenever you want your keys not to be compared by `equals` but by `==` you would use an IdentityHashMap. This can be very useful if you're doing a lot of reference-handling but it's limited to very special cases only.
Use cases for IdentityHashMap
[ "", "java", "" ]
I have 2 images inside a folder called Pics..... Image1.jpg and Image2.jpg. What code must i place inside my Submit button to just delete Image1.jpg located here "~/Pics/Image1.jpg" Any help would be great!!!
You need to use [System.IO.File.Delete](http://msdn.microsoft.com/en-us/library/system.io.file.delete.aspx) not System.IO.Delete ``` string path = "~/Pics/Image1.jpg"; System.IO.File.Delete(Server.MapPath(path)) ```
The syntax is: ``` System.IO.File.Delete(Server.MapPath("~/Pics/Image1.jpg")); ``` You will need to make sure the user your web app is running as has delete (change) permissions on the file you are deleting, however.
Using System.IO.Delete to remove certain files from a directory?
[ "", "c#", "asp.net", "vb.net", "image", "directory", "" ]
I have a set of 6 bits that represent a 7bit ASCII character. How can I get the correct 7bit ASCII code out of the 6 bits I have? Just append a zero and do an bitwise OR? Thanks for your help. Lennart
ASCII is inherently a 7-bit character set, so what you have is not "6-bit ASCII". What characters make up your character set? The simplest decoding approach is probably something like: ``` char From6Bit( char c6 ) { // array of all 64 characters that appear in your 6-bit set static SixBitSet[] = { 'A', 'B', ... }; return SixBitSet[ c6 ]; } ``` A footnote: 6-bit character sets were quite popular on old DEC hardware, some of which, like the DEC-10, had a 36-bit architecture where 6-bit characters made some sense.
You must tell us how your 6-bit set of characters looks, I don't think there is a standard. The easiest way to do the reverse mapping would probably be to just use a lookup table, like so: ``` static const char sixToSeven[] = { ' ', 'A', 'B', ... }; ``` This assumes that space is encoded as (binary) 000000, capital A as 000001, and so on. You index into `sixToSeven` with one of your six-bit characters, and get the local 7-bit character back.
C/C++: How to convert 6bit ASCII to 7bit ASCII
[ "", "c++", "c", "ascii", "" ]
I am retrieving 3 fields from a database, and by default, only the username field will have content. The other information will be added in from a user application. I want to show the field as "No Info" if there is no entry in the field. I am trying to use both empty() and is\_null() to no avail. A var\_dump of $row['firstname'] and $row['lastname'] returns NULL in both cases. ``` <?php if (isset($_GET["subcat"])) $subcat = $_GET["subcat"]; if (isset($_GET["searchstring"])) { $searchstring = $_GET["searchstring"]; } $con = mysqli_connect("localhost","user","password", "database"); if (!$con) { echo "Can't connect to MySQL Server. Errorcode: %s\n". mysqli_connect_error(); exit; } $table = 'USERS'; $brand = '%' . $searchstring . '%'; $rows = getRowsByArticleSearch($brand, $table); echo "<table border='0' width='100%'><tr>" . "\n"; echo "<td width='15%'>Username</td>" . "\n"; echo "<td width='15%'>Firstname</td>" . "\n"; echo "<td width='15%'>Surname</td>" . "\n"; echo "</tr>\n"; foreach ($rows as $row) { if (is_null($row['firstname']) || $row['firstname'] == "") { $row['firstname'] == "No Info"; } if ($row['lastname'] == null || $row['lastname'] == "") { $row['firstname'] == "No Info"; } var_dump($row['firstname']); var_dump($row['lastname']); echo '<tr>' . "\n"; echo '<td><a href="#" onclick="updateByUser(\''. $row['username'] .'\',\''.$subcat.'\')">'.$row['username'].'</a></td>' . "\n"; echo '<td><a href="#" onclick="updateByUser(\''. $row['username'] .'\', \''.$subcat.'\')">'.$row['firstname'].'</a></td>' . "\n"; echo '<td><a href="#" onclick="updateByUser(\''. $row['username'] .'\', \''.$subcat.'\')">'.$row['lastname'].'</a></td>' . "\n"; echo '</tr>' . "\n"; } echo "</table>\n"; function getRowsByArticleSearch($searchString, $table) { $con = mysqli_connect("localhost","user","password", "database"); $recordsQuery = "SELECT username, firstname, lastname FROM $table WHERE lower(username) LIKE ? "; if ($getRecords = $con->prepare($recordsQuery)) { $getRecords->bind_param("s", $searchString); $getRecords->execute(); $getRecords->bind_result($username, $firstname, $lastname); $rows = array(); while ($getRecords->fetch()) { $row = array( 'username' => $username, 'firstname' => $firstname, 'lastname' => $lastname, ); $rows[] = $row; } return $rows; } else { print_r($con->error); } } ```
Turn on display\_errors and set error\_reporting to E\_ALL (either in php.ini or in a htaccess). This should reveal any non-obvious mistakes. Try the following for checking if something is empty: ``` <?php if(!isset($row['...']) || empty($row['...'])) { $row['firstname'] = 'No Info'; } ?> ``` Also, **please note you're using '==' to set the $row things to 'No Info'**. Al this does is return 'true' (or 1). Use a single '=' to set variables.
First and your main issue: You are using comparison operators in $row['firstname'] == "No Info"; instead of assignement operators $row['firstname'] **=** "No Info"; Other issues: * Why do you establish the connection twice? Or actually multiple times? Find a way to let your functions know the connection! * Factor the connection out into an include. * Why do you do that while loop, if you can access the returned array directly?
Check for a null value from a database -- failing
[ "", "php", "mysql", "" ]
Just wondering, because of a problem I am running into, is it possible to create a vector of pointers? And if so, how? Specifically concerning using iterators and .begin() with it, ie: How would I turn this vector into a vector of pointers: ``` class c { void virtual func(); }; class sc:public c { void func(){cout<<"using func";} }; sc cobj; vector<c>cvect cvect.push_back(cobj); vector<c>::iterator citer for(citer=cvect.begin();citer<cvect.end();citer++) { citer->func(); } ```
`vector <c> cvect` is not a vector of pointers. It is a vector of objects of type c. You want `vector <c*> cvect`. and the you probably want: ``` cvect.push_back( new c ); ``` And then, given an iterator, you want something like: ``` (*it)->func(); ``` Of course, it's quite probable you didn't want a vector of pointers in the first place...
Sure. ``` vector<c*> cvect; cvect.push_back(new sc); vector<c*>::iterator citer; for(citer=cvect.begin(); citer != cvect.end(); citer++) { (*citer)->func(); } ``` Things to keep in mind: You'll need to cleanup after your self if you use dynamically allocated memory as I did in my example e.g.: ``` for(...) { delete *i; } ``` This can be simplified by using a vector of `shared_ptr`s (like `boost::shared_ptr`). Do not attempt to use `std::auto_ptr` for this, it will not work (won't even compile). Another thing to keep in mind, you should avoid using `<` to compare iterators in your loop when possible, it will only work for iterators that model a random access iterator, which means you can't change out your code to use e.g. a `std::list`.
Is it possible to create a vector of pointers?
[ "", "c++", "stl", "pointers", "vector", "pure-virtual", "" ]
I'm creating a specialised proxy class that implements `IList<T>` and wraps an internal `List<T>` instance. `List<T>` itself implements `IList<T>`, which declares a member **bool IsReadOnly**, but when I try to access that member from my own class, I can't because in `List<T>`, IsReadOnly is private. So my question is; if an implementation of an interface requires all implemented members to be public, why does `List<T>` get to implement IsReadOnly as private and thus deny me access to it?
It implements the interface member explicitly. <http://msdn.microsoft.com/en-us/library/aa288461(VS.71).aspx> Note that this does not make the interface member `private`. It's still available publicly, but only if you look at the object through the interface (with casting).
The reason it's able to do this is that it uses explicit interface implementation. ``` bool IList<T>.IsReadOnly { get { ... } } ``` This member is still accessible, but it can only be accessed via the `IList<T>` type. ``` List<T> list = ...; bool isReadOnly = ((IList<T>)list).IsReadOnly; ``` When implementing `IList<T>`, the type has not promised to provide an IsReadOnly value itself. Instead it's promised to provide an IsReadOnly property when viewed as an `IList<T>`. Whether or not it provides it on the actual class is purerly a choice of the type author.
How does List<T> make IsReadOnly private when IsReadOnly is an interface member?
[ "", "c#", ".net", "" ]
I'm developing software using the Google App Engine. I have some considerations about the optimal design regarding the following issue: I need to create and save snapshots of some entities at regular intervals. In the conventional relational db world, I would create db jobs which would insert new summary records. For example, a job would insert a record for every active user that would contain his current score to the "userrank" table, say, every hour. I'd like to know what's the best method to achieve this in Google App Engine. I know that there is the Cron service, but does it allow us to execute jobs which will insert/update thousands of records?
Have you considered using the [remote api](http://code.google.com/appengine/articles/remote_api.html) instead? This way you could get a shell to your datastore and avoid the timeouts. The Mapper class they demonstrate in that link is quite useful and I've used it successfully to do batch operations on ~1500 objects. That said, cron should work fine too. You do have a limit on the time of each individual request so you can't just chew through them all at once, but you can use redirection to loop over as many users as you want, processing one user at a time. There should be an example of this in the docs somewhere if you need help with this approach.
I think you'll find that snapshotting every user's state every hour isn't something that will scale well no matter what your framework. A more ordinary environment will disguise this by letting you have longer running tasks, but you'll still reach the point where it's not practical to take a snapshot of every user's data, every hour. My suggestion would be this: Add a 'last snapshot' field, and subclass the put() function of your model (assuming you're using Python; the same is possible in Java, but I don't know the syntax), such that whenever you update a record, it checks if it's been more than an hour since the last snapshot, and if so, creates and writes a snapshot record. In order to prevent concurrent updates creating two identical snapshots, you'll want to give the snapshots a key name derived from the time at which the snapshot was taken. That way, if two concurrent updates try to write a snapshot, one will harmlessly overwrite the other. To get the snapshot for a given hour, simply query for the oldest snapshot newer than the requested period. As an added bonus, since inactive records aren't snapshotted, you're saving a lot of space, too.
Google App Engine - design considerations about cron tasks
[ "", "python", "database", "google-app-engine", "cron", "" ]
I'll try to explain this problem the best way i can with code: ``` double power = 5000; //picked up 5 power ups, now need to increase power by 10% per powerup power += 5 * (power * .10); //later on...ran into 5 power downs need to decrease power back to initial hp power -= 5 * (power * .10);//7500 - 3750 -- doesn't work ``` So what i need is a scaleable solution that gets back to the original value using only the count. Any ideas?
The best way to do this is using a function. It doesn't have to look exactly like this, but: ``` class Whatever { private double basePower = 5000; public int numPowerUps = 5; public double GetActualPower() { return basePower + (numPowerUps * basePower * 0.1); } } ``` Just change numPowerUps back to 0 when they run out. This way, it looks a whole lot neater. An aside: The reason it's not working is because of the fact that adding and then subtracting percentages doesn't work. For instance: ``` 1. What is 10% of 100? --> 10 2. Add that to the 100 --> 110 3. What is 10% of 110? --> 11 4. Subtract that from 110 --> 99 ``` You'll always end up with 99% of your original value. If you really want to take a shortcut, you could instead do this: ``` 1. What is 10% of 100? --> 10 2. Add that to the 100 --> 110 3. What is (100/11) = 9.09090909...% of 110? --> 10 4. Subtract that from 110 --> 100 ``` But then you're potentially susceptible to floating point errors. The function way of doing it is not only neater and clearer, but potentially less error-prone.
To reverse a %age increase, you must *divide* by the original %age, not *subtract*. i.e.: ``` 100 + 5% = 100 * 1.05 = 105 ``` to reverse it: ``` 105 / 1.05 = 100 ``` The more usual '5% off' formula would instead give you: ``` 105 - 5% = (105 * 0.95) = 99.75 ```
Increment, decrement by percentage
[ "", "c#", "math", "" ]
I'm reading an xml file and want to make it from a relative directory based on the location of the application, similar to ASP.NET with Server.MapPath or using the tilda. How can you get the relative path in WPF? ``` WORKS: XDocument xmlDoc = XDocument.Load(@"c:\testdata\customers.xml"); DOES NOT WORK: XDocument xmlDoc = XDocument.Load(@"~\Data\customers.xml"); DOES NOT WORK: XDocument xmlDoc = XDocument.Load(@"~/Data/customers.xml"); ```
``` XDocument xmlDoc = XDocument.Load(@"Data\customers.xml"); ``` OR ``` XDocument xmlDoc = XDocument.Load(@".\Data\customers.xml"); ``` BTW, this has nothing to do with WPF and everything to do with Windows paths.
``` XDocument xmlDoc = XDocument.Load( Path.Combine( AppDomain.CurrentDomain.BaseDirectory, @"Data\customers.xml")); ``` I assume the `Data` directory is going to get deployed with your app, in the same root directory as your EXE. This is generally safe, except where shadow copying is involved; for example, when you use NUnit to test this code. (With shadow copying, the assemblies that make up your app get copied to a temporary directory, but files like this get left behind.) Assuming you're not planning to modify `customers.xml` after deployment, the safest way to handle this is to embed the file as a resource within your assembly.
How to load from relative path in WPF application?
[ "", "c#", "windows", "path", "" ]
I am writing a CSV exporter in Java that should respect the user's custom settings, especially the "List separator" to use as a delimiter. In Windows, one can set this List separator in ``` Control Panel -> Regional and Language Options -> Regional Options -> Customize ``` I don't know about the other operating systems, but I'm pretty sure that you can change that on other OSes, too. What is the best way to get this custom setting from the OS into Java? I am in an Eclipse RCP environment, so I might use RCP-related solutions if there is something available.
From comments of [this answer](https://stackoverflow.com/questions/838590/how-to-read-list-separator-from-os-in-java/838718#838718): > Reading the OS-specific setting is a need I *have* to meet. So what if OSs other than Windows *don't have* such a setting? I suggest you read it from registry on Windows (as alluded [here](https://stackoverflow.com/questions/838590/how-to-read-list-separator-from-os-in-java/838641#838641)): [Read/write to Windows Registry using Java](https://stackoverflow.com/questions/62289/read-write-to-windows-registry-using-java). On other platforms just use a good default, and perhaps, at least on Unix, also support configuring it via a custom environment variable (which you document well): [How can my java code read OS environment variables?](https://stackoverflow.com/questions/461018/how-can-my-java-code-read-os-environment-variables). My gut feeling that OSs universally do not have a (system-wide or user-specific) "List separator" setting may be wrong, of course, but I doubt that.
Without resorting to a platform specific solution I think that the best approach to take is going to be to allow users to specify their preference of list separator *within your own application*. Either in a preferences panel, a dialog box on export or via an optional command line argument.
How to read 'List separator' from OS in Java?
[ "", "java", "csv", "operating-system", "regional", "list-separator", "" ]
What is the best way to check if there is atleast a selected item in a listview or not in an if statement?
I'm not entirely sure what you are asking. Do you want to make sure at least 1 item is selected before running an action? If so the following should work ``` if ( listView.SelectedItems.Count > 0 ) { // Do something } ``` Or are you curious if a particular item is selected? If so try the following ``` if ( listView.SelectedItems.Contains(someItem)) { // Do something } ```
``` if( listView.SelectedItems.Count > 0 ){ // do stuff here } ```
C#: How do you make sure that a row or item is selected in ListView before performing an action?
[ "", "c#", ".net", "winforms", "" ]
So basically, [this](http://github.com/a2h/Ze-Very-Flat-Pancaek-CMS/blob/1630d6337d93fd7cc7612020ac136fb3edef8b00/trunk/zvfpcms/admin/admin.php) is what I have. But is this a good practice? I started splitting up my admin.php file due to it growing in size. However, I have a slight concern over how many files I could potentially end up with, and also problems to work with in case something may need to be updated over all the files.
I had similar thoughts developing my own CMS engine. Eventually I end up with basicaly same solution as you did, but with Smarty, for logic-presentation separation. But now after some time I have different and much better solution. Make use of [Command Pattern](http://en.wikipedia.org/wiki/Command_pattern). You will need to separate your code into classes not in files like you did. You must establish Command Interface which all of your classes will implement. This way your admin page will act as [Front Controler](http://en.wikipedia.org/wiki/Front_Controller_pattern) (another design pattern). Responsibilty of Front Controler is to gather all input from your page, that is in your case $\_GET["action"] , according to this actions you will have to instantiate Command objects and after this switch statement you will call $command->execute(); that will execute code contained in your Command classes. For your examle you will have : EditPageCommand, DeletePageCommand, NewPageCommand, etc. Avoid code separation in files. Try to use classes for everything and learn patterns. ;)
use classes in php, try to split your project into logical modules. Then you need not to make manual updates over all the files.
Is the way I have my admin panel set up good?
[ "", "php", "" ]
I was looking for some utility class/code that would take a java bean and initialize all its values to random values. It could be done via reflection as some libraries already create the toString() or equals() methods. Is is useful while developing the UI to have some data for example. Other possible nice to haves: 1. recursively initialize non primitive or simple (string, date) members too 2. initialize a collection of beans 3. maybe give some way to limit the values generated, for example for numbers we could give ranges, for strings regexps or wildcards... somebody knows something like this? thanks EDIT: resolving...Got Apocalisp's sample working and definitively is what I was looking for. It has some drawbacks IMHO: * The library has a much larger scope than that use, but this is not a problem for me * It's quite complicated to understand how to build the Arbitrary for your objects unless you invest some time to study the whole thing. This is a drawback. * And it could be more succint I guess, but that is fine too. thanks!
Take a look at the [Gen class from the Reductio library](http://functionaljava.googlecode.com/svn/artifacts/2.19/javadoc/fj/test/Gen.html). This is part of a highly configurable framework for generating [arbitrary values](http://functionaljava.googlecode.com/svn/artifacts/2.19/javadoc/fj/test/Arbitrary.html) of more or less any type. Generators for primitive types and most of the Java collections classes are provided. You should be able to create `Arbitrary` instances for your classes fairly easily. **EDIT** Here's the example, corrected: ``` import static fj.test.Arbitrary.*; import static fj.Function.*; static final Arbitrary<Person> personArbitrary = arbitrary(arbInteger.gen.bind(arbString.gen, arbBoolean.gen, curry(new F3<Integer, String, Boolean, Person>() { public Person f(final Integer age, final String name, final Boolean male) {return new Person(age, name, male);}}))); ``` Then generate an arbitrary Person of "size 100" like so. I.e. it will have a name of 100 characters at most. ``` Person p = personArbitrary.gen.gen(100, Rand.standard); ```
Take a look at Easy Random: <https://github.com/j-easy/easy-random>. It allows you to populate a Java Object graph with random data. Disclaimer: I'm the author of that library
way to initialize a javabean to random values
[ "", "java", "random", "javabeans", "" ]
Is there a straighforward way to set additional text to appear in a tooltip when a user's mouse is held over an item in a CheckedListBox? What I would *expect* to be able to do in code is: ``` uiChkLstTables.DisplayOnHoverMember = "DisplayOnHoverProperty"; //Property contains extended details ``` Can anyone point me in the right direction to do this? I've already found a couple of articles that involve detecting which item the mouse is currently over and creating a new tooltip instance, but this sounds a little too contrived to be the best way. Thanks in advance.
Add a Tooltip object to your form and then add an event handler for the CheckedListBox.MouseHover that calls a method ShowToolTip(); Add MouseMove event of your CheckedListBox which has the following code: ``` //Make ttIndex a global integer variable to store index of item currently showing tooltip. //Check if current location is different from item having tooltip, if so call method if (ttIndex != checkedListBox1.IndexFromPoint(e.Location)) ShowToolTip(); ``` Then create the ShowToolTip method: ``` private void ShowToolTip() { ttIndex = checkedListBox1.IndexFromPoint(checkedListBox1.PointToClient(MousePosition)); if (ttIndex > -1) { Point p = PointToClient(MousePosition); toolTip1.ToolTipTitle = "Tooltip Title"; toolTip1.SetToolTip(checkedListBox1, checkedListBox1.Items[ttIndex].ToString()); } } ```
Alternately, you could use a [`ListView`](http://msdn.microsoft.com/en-us/library/system.windows.forms.listview.aspx) with checkboxes instead. This control has *builtin* support for *tooltips*.
Tooltips for CheckedListBox items?
[ "", "c#", "winforms", "user-interface", "tooltip", "checkedlistbox", "" ]
Suppose I have any data stored in bytes. For example: > 0110001100010101100101110101101 How can I store it as *printable* text? The obvious way would be to convert every 0 to the character '0' and every 1 to the character '1'. In fact this is what I'm currently doing. I'd like to know how I could pack them more tightly, without losing information. I thought of converting bits in groups of eight to ASCII, but some bit combinations are not accepted in that format. Any other ideas?
What about an encoding that only uses "safe" characters like base64? <http://en.wikipedia.org/wiki/Base64> EDIT: That is assuming that you want to safely store the data in text files and such? In Python 2.x, strings should be fine (Python doesn't use null terminated strings, so don't worry about that). Else in 3.x check out the bytes and bytearray objects. <http://docs.python.org/3.0/library/stdtypes.html#bytes-methods>
Not sure what you're talking about. ``` >>> sample = "".join( chr(c) for c in range(256) ) >>> len(sample) 256 >>> sample '\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\ x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !"#$%&\'()*+,-./0123456789:;<=>?@ABC DEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f\x80\x81\x82\x83 \x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97 \x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab \xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf \xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3 \xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7 \xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb \xfc\xfd\xfe\xff' ``` The string `sample` contains all 256 distinct bytes. There is no such thing as a "bit combinations ... not accepted". To make it *printable*, simply use `repr(sample)` -- non-ASCII characters are escaped. As you see above.
How do you store raw bytes as text without losing information in python 2.x?
[ "", "python", "python-2.7", "storage", "bit", "compression", "" ]
I've got a Java web service in JAX-WS that returns an OutputStream from another method. I can't seem to figure out how to stream the OutputStream into the returned DataHandler any other way than to create a temporary file, write to it, then open it back up again as an InputStream. Here's an example: ``` @MTOM @WebService class Example { @WebMethod public @XmlMimeType("application/octet-stream") DataHandler service() { // Create a temporary file to write to File fTemp = File.createTempFile("my", "tmp"); OutputStream out = new FileOutputStream(fTemp); // Method takes an output stream and writes to it writeToOut(out); out.close(); // Create a data source and data handler based on that temporary file DataSource ds = new FileDataSource(fTemp); DataHandler dh = new DataHandler(ds); return dh; } } ``` The main issue is that the writeToOut() method can return data that are far larger than the computer's memory. That's why the method is using MTOM in the first place - to stream the data. I can't seem to wrap my head around how to stream the data directly from the OutputStream that I need to provide to the returned DataHandler (and ultimately the client, who receives the StreamingDataHandler). I've tried playing around with PipedInputStream and PipedOutputStream, but those don't seem to be quite what I need, because the DataHandler would need to be returned after the PipedOutputStream is written to. Any ideas?
I figured out the answer, along the lines that Christian was talking about (creating a new thread to execute writeToOut()): ``` @MTOM @WebService class Example { @WebMethod public @XmlMimeType("application/octet-stream") DataHandler service() { // Create piped output stream, wrap it in a final array so that the // OutputStream doesn't need to be finalized before sending to new Thread. PipedOutputStream out = new PipedOutputStream(); InputStream in = new PipedInputStream(out); final Object[] args = { out }; // Create a new thread which writes to out. new Thread( new Runnable(){ public void run() { writeToOut(args); ((OutputStream)args[0]).close(); } } ).start(); // Return the InputStream to the client. DataSource ds = new ByteArrayDataSource(in, "application/octet-stream"); DataHandler dh = new DataHandler(ds); return dh; } } ``` It is a tad more complex due to `final` variables, but as far as I can tell this is correct. When the thread is started, it blocks when it first tries to call `out.write()`; at the same time, the input stream is returned to the client, who unblocks the write by reading the data. (The problem with my previous implementations of this solution was that I wasn't properly closing the stream, and thus running into errors.)
Sorry, I only did this for C# and not java, but I think your method should launch a thread to run "writeToOut(out);" in parralel. You need to create a special stream and pass it to the new thread which gives that stream to writeToOut. After starting the thread you return that stream-object to your caller. If you only have a method that writes to a stream and returns afterwards and another method that consumes a stream and returns afterwards, there is no other way. Of coure the tricky part is to get hold of such a -multithreading safe- stream: It shall block each side if an internal buffer is too full. Don't know if a Java-pipe-stream works for that.
How can you pipe an OutputStream to a StreamingDataHandler?
[ "", "java", "stream", "jax-ws", "" ]
When a compiler finds a signed / unsigned mismatch, what action does it take? Is the signed number cast to an unsigned or vice versa? and why?
If operand are integral and there is an unsigned value, then conversion to unsigned is done. For example: ``` -1 > (unsigned int)1 // as -1 will be converted to 2^nbits-1 ``` Conversion int->unsigned int is: n>=0 -> n; n<0 -> n (mod 2^nbits), for example -1 goes to 2^nbits-1 Conversion unsigned int->int is: n <= INT\_MAX -> n; n > INT\_MAX -> implementation defined > If the destination type is unsigned, > the resulting value is the least > unsigned integer congruent to the > source integer (modulo 2^n where n is > the number of bits used to represent > the unsigned type). > > If the destination type is signed, the > value is unchanged if it can be > represented in the destination type > (and bit-field width); otherwise, the > value is implementation-defined.
I don't think C++ deviates from the way C handles signed/unsigned conversions: > Conversion rules are more complicated > when `unsigned` operands are involved. > The problem is that comparisons > between signed and unsigned values are > machine-dependent, because they depend > on the sizes of the various integer > types. (K&R) One important factor to consider is whether one of the types is a `long` integer or not, because that will affect integer promotions. For example, if a `long int` is compared to an `unsigned int`, and a `long int` can represent all the values of an `unsigned int`, then the `unsigned int` will be converted to a `long int`. (Otherwise, they're both just converted to an `unsigned long int`.) In most cases, though, the compiler should convert signed integers to unsigned integers if it finds a mismatch.
What cast occurs when there is a signed/unsigned mismatch?
[ "", "c++", "casting", "warnings", "" ]
I have data in an MYSQL database that looks like this: ``` Project Date Time A 2009-01-01 15 A 2009-01-02 10 B 2009-01-02 30 A 2009-01-09 15 C 2009-01-07 5 ``` I would like to produce output from this data like this: ``` Date Project A Time Project B Time Project C Time 2009-01-01 15 0 0 2009-01-02 10 30 0 2009-01-07 15 0 5 ``` Can this be done with an SQL query, or do I need to write an external script to itterate through the DB and organize the output? (Also, if someone has a better suggestion for a subject line let me know and I'll edit the question; I'm not sure of the proper terms to describe the current and desired formats, which makes searching for this information difficult)
You're looking for pivot / crosstab support. Here is a good link. <http://en.wikibooks.org/wiki/MySQL/Pivot_table>
I believe this is called Pivot table. Just google for it.
SQL - convert data to a date/source/value "grid"
[ "", "sql", "mysql", "" ]
BlockingQueue has the method called drainTo() but it is not blocked. I need a queue that I want to block but also able to retrieve queued objects in a single method. ``` Object first = blockingQueue.take(); if ( blockingQueue.size() > 0 ) blockingQueue.drainTo( list ); ``` I guess the above code will work but I'm looking for an elegant solution.
Are you referring to the comment in the [JavaDoc](http://java.sun.com/javase/6/docs/api/java/util/concurrent/BlockingQueue.html#drainTo(java.util.Collection)): > Further, the behavior of this operation is undefined if the specified collection > is modified while the operation is in progress. I believe that this refers to the collection `list` in your example: ``` blockingQueue.drainTo(list); ``` meaning that you cannot modify `list` at the same time you are draining from `blockingQueue` into `list`. However, the blocking queue internally synchronizes so that when `drainTo` is called, puts and (see note below) gets will block. If it did not do this, then it would not be truly Thread-safe. You can look at the source code and verify that `drainTo` is Thread-safe regarding the blocking queue itself. Alternately, do you mean that when you call `drainTo` that you want it to block until at least one object has been added to the queue? In that case, you have little choice other than: ``` list.add(blockingQueue.take()); blockingQueue.drainTo(list); ``` to block until one or more items have been added, and then drain the entire queue into the collection `list`. Note: As of Java 7, a separate lock is used for gets and puts. Put operations are now permitted during a drainTo (and a number of other take operations).
If you happen to use Google Guava, there's a nifty [`Queues.drain()`](https://google.github.io/guava/releases/snapshot-jre/api/docs/com/google/common/collect/Queues.html#drain-java.util.concurrent.BlockingQueue-java.util.Collection-int-long-java.util.concurrent.TimeUnit-) method. > Drains the queue as `BlockingQueue.drainTo(Collection, int)`, but if the > requested `numElements` elements are not available, it will wait for > them up to the specified timeout.
BlockingQueue - blocked drainTo() methods
[ "", "java", "concurrency", "" ]
Just noticed this on OSX and I found it curious as I expected long to be bigger than int. Is there any good reason for making them the same size?
This is a result of the loose nature of size definitions in the C and C++ language specifications. I believe C has specific minimum sizes, but the only rule in C++ is this: ``` 1 == sizeof(char) <= sizeof(short) <= sizeof(int) <= sizeof(long) ``` Moreover, `sizeof(int)` and `sizeof(long)` are not the same size on all platforms. Every 64-bit platform I've worked with has had `long` fit the natural word size, so 32 bits on a 32-bit architecture, and 64 bits on a 64-bit architecture.
* `int` is essentially *the most convenient and efficient integer type* * `long` is/was the *largest integer type* * `short` is the *smallest integer type* If the longest integer type is also the most efficient, the `int` is the same as `long`. A while ago (think pre-32 bit), `sizeof(int) == sizeof(short)` on a number of platforms since 16-bit was the widest *natural* integer.
I notice ints and longs have the same size. Why?
[ "", "c++", "" ]
Can anyone tell me how to raise click event of button control (or for that matter for any event). Platform: .net 2.0/3.0/3.5 Language: c# Domain: Windows Application, WinForms, etc.
You can use the [Button.PerformClick](http://msdn.microsoft.com/en-us/library/system.windows.forms.button.performclick(VS.80).aspx) method.
Maybe the solution is much more simple: Maybe you don't really want your code "to click the button". Do you just want to run the code which is behind the button from another place in the form? If yes, put the code into a separate method (like "DoActionXXX") and call the method from the button and from everywhere else where you need it.
Raise button (or any control) click event manually. C#
[ "", "c#", ".net", "winforms", "events", "click", "" ]
I'm connecting to a web site, logging in. The website redirects me to new pages and Mechanize deals with all cookie and redirection jobs, but, I can't get the last page. I used Firebug and did same job again and saw that there are two more pages I had to pass with Mechanize. I took a quick look at the pages and saw that there is some JavaScript and HTML code but couldn't understand it because it doesn't look like normal page code. What are those pages for? How they can redirect to other pages? What should I do to pass these?
If you need to handle pages with Javascript, try [WATIR](http://watir.com/) or [Selenium](http://docs.seleniumhq.org/) - those drive a real web browser, and can thus handle any Javascript. WATIR Classic requires either IE or Firefox with a certain extension installed, and you will see the pages flash on the screen as it works. Your other option would be understanding what the Javascript on the offending page does and bypassing it manually, but that seems onerous.
At present, Mechanize doesn't handle JavaScript. There's talk of eventually merging [Johnson](http://wiki.github.com/jbarnette/johnson)'s capabilities into Mechanize, but until that happens, you have two options: 1. Figure out the JavaScript well enough to understand how to traverse those pages. 2. Automate an actual browser that *does* understand JavaScript using [Watir](http://wtr.rubyforge.org/).
How do I use Mechanize to process JavaScript?
[ "", "javascript", "html", "ruby", "mechanize", "" ]
In my C# .NET application I have an issue with the Trace.WriteLine()-method. I uses this method alot, and want to add a TimeStamp every time I use it. Instead of Trace.WriteLine(DateTime.Now + " Something wrong!"), is there a solution where the DateTime is on default?
Just write your own "`TraceLine(string msg)`" method and start calling that: ``` void TraceLine(string msg, bool OmitDate) { if (!OmitDate) msg = DateTime.Now + " " + msg; Trace.WriteLine(msg); } void TraceLine(string msg) {TraceLine(msg, false);} ```
# Via code You can configure the TraceOutputOptions flags enum. ``` var listener = new ConsoleTraceListener() { TraceOutputOptions = TraceOptions.Timestamp | TraceOptions.Callstack }; Trace.Listeners.Add(listener); Trace.TraceInformation("hello world"); ``` This does not work for Write and WriteLine, you have use the TraceXXX methods. # Via app.config This can also be configured in your App.config with a somewhat equivalent and using TraceSource: ``` <configuration> <system.diagnostics> <trace autoflush="true"> <sources> <source name="TraceSourceApp"> <listeners> <add name="myListener" type="System.Diagnostics.ConsoleTraceListener" traceOutputOptions="Timestamp" /> </listeners> </source> </sources> </trace> </system.diagnostics> </configuration> ``` And in code you can: ``` private static TraceSource mySource = new TraceSource("TraceSourceApp"); static void Main(string[] args) { mySource.TraceInformation("hello world"); } ```
Add Timestamp to Trace.WriteLine()
[ "", "c#", "debugging", "timestamp", "trace", "" ]
Just wanted to know if anyone is really using Objects and Collections in Oracle ? Is this something that should be avoided ? eg ``` create type t_person as object ( id integer, first_name varchar2(30), last_name varchar2(30) ); ```
If you are seriously into PL/SQL programming, you can hardly live without collections and objects. That said, I keep my database tables "clean", i.e. all columns contain atomic values, no nested tables etc.
I'm sure lots of programmers are using such extensions; personally I try to stick close to the "reasonably standard SQL" core in my use of relational DBs, because it's happened often that I need to port my SQL code to some other DB engine, and if I've splurged in using proprietary extensions the port becomes much harder (while the proprietary extensions often add very little functionality or speed anyway).
oracle objects and collections
[ "", "sql", "oracle", "" ]
I have a situation where i need to enforce a unique constraint on a set of columns, but only for one value of a column. So for example I have a table like Table(ID, Name, RecordStatus). RecordStatus can only have a value 1 or 2 (active or deleted), and I want to create a unique constraint on (ID, RecordStatus) only when RecordStatus = 1, since I don't care if there are multiple deleted records with the same ID. Apart from writing triggers, can I do that? I am using SQL Server 2005.
Add a check constraint like this. The difference is, you'll return false if Status = 1 and Count > 0. <http://msdn.microsoft.com/en-us/library/ms188258.aspx> ``` CREATE TABLE CheckConstraint ( Id TINYINT, Name VARCHAR(50), RecordStatus TINYINT ) GO CREATE FUNCTION CheckActiveCount( @Id INT ) RETURNS INT AS BEGIN DECLARE @ret INT; SELECT @ret = COUNT(*) FROM CheckConstraint WHERE Id = @Id AND RecordStatus = 1; RETURN @ret; END; GO ALTER TABLE CheckConstraint ADD CONSTRAINT CheckActiveCountConstraint CHECK (NOT (dbo.CheckActiveCount(Id) > 1 AND RecordStatus = 1)); INSERT INTO CheckConstraint VALUES (1, 'No Problems', 2); INSERT INTO CheckConstraint VALUES (1, 'No Problems', 2); INSERT INTO CheckConstraint VALUES (1, 'No Problems', 2); INSERT INTO CheckConstraint VALUES (1, 'No Problems', 1); INSERT INTO CheckConstraint VALUES (2, 'Oh no!', 1); INSERT INTO CheckConstraint VALUES (2, 'Oh no!', 2); -- Msg 547, Level 16, State 0, Line 14 -- The INSERT statement conflicted with the CHECK constraint "CheckActiveCountConstraint". The conflict occurred in database "TestSchema", table "dbo.CheckConstraint". INSERT INTO CheckConstraint VALUES (2, 'Oh no!', 1); SELECT * FROM CheckConstraint; -- Id Name RecordStatus -- ---- ------------ ------------ -- 1 No Problems 2 -- 1 No Problems 2 -- 1 No Problems 2 -- 1 No Problems 1 -- 2 Oh no! 1 -- 2 Oh no! 2 ALTER TABLE CheckConstraint DROP CONSTRAINT CheckActiveCountConstraint; DROP FUNCTION CheckActiveCount; DROP TABLE CheckConstraint; ```
Behold, [the filtered index](http://technet.microsoft.com/en-us/library/cc280372.aspx). From the documentation (emphasis mine): > A filtered index is an optimized nonclustered index especially suited to cover queries that select from a well-defined subset of data. **It uses a filter predicate to index a portion of rows in the table.** A well-designed filtered index can improve query performance as well as reduce index maintenance and storage costs compared with full-table indexes. And here's an example combining a unique index with a filter predicate: ``` create unique index MyIndex on MyTable(ID) where RecordStatus = 1; ``` This essentially enforces uniqueness of `ID` when `RecordStatus` is `1`. Following the creation of that index, a uniqueness violation will raise an arror: > Msg 2601, Level 14, State 1, Line 13 > Cannot insert duplicate key row in object 'dbo.MyTable' with unique index 'MyIndex'. The duplicate key value is (9999). Note: the filtered index was introduced in SQL Server 2008. For earlier versions of SQL Server, please see [this answer](https://stackoverflow.com/a/866100/621962).
conditional unique constraint
[ "", "sql", "sql-server", "sql-server-2005", "" ]
In Java, suppose I have 3 classes, C extends from B which extends from A. ``` class X { interface A {} interface B extends A {} interface C extends B {} void f(A a) {} void test() { C c = new C() B b = (B) c; f(b); } } ``` If I do something like this as shown in `test()` above: ``` C c = new C() B b = (B) c; f(b); ``` `f()` accepts `b` as type `C` since `C` and `B` both extend from `A`. I wanted `f()` to receive `b` as type `B` and not type `C`. Is there anyway to force this upcasting?
`f()` will *always* receive something typed as A (despite under the covers it's actually a B or C, and can be downcast appropriately). You can define an additional f() thus ``` f(B b); ``` and if necessary ``` f(C c); ``` and the correct one will be called depending on the class of the argument. i.e. the compiler determines which function is called depending on the type of the argument. This is different from a dynamic dispatch (or polymorphism) which would occur at runtime. Note that your cast in the question is redundant. You can write: ``` C c = new C() B b = c; f(b); ``` since C extends from B, C *is a* B.
You seem to be confused about the difference between compile time type and runtime type. You are creating an object (pointed at by the references c and b) of type C, and it will *stay* a C, because it is impossible to change an object's runtime type and therefore behaviour; by casting you can merely change its compile time type, which affects how the compiler treats it. Can you give some more information about the concrete problem you're trying to solve? Most likely there is a way to achieve your goal by changing the design.
Upcasting in java
[ "", "java", "casting", "" ]
Whenever I run my program, I get: NullReferenceException was unhandled, Object Reference not set to an instance of an object. When I start the program, I have a form appear called MaxScore where the user enters the max score and presses OK. In the OK event, I call a method from MainForm to update the maxGameCountLabel on MainForm with the value entered for the max score, as a parameter. When I press ok, I get the NullReferenceException at ``` myGameCountLbl.Text = maxGames.ToString(); ``` of my maxGameCountLblUpdate method. Here is the maxGameCountLblUpdate method code which resides in MainForm: ``` //Update game count label public void maxGameCountLblUpdate(decimal maxGames) { maxGames = decimal.ToInt32(maxGames); myGameCountLbl.Text = maxGames.ToString(); compGameCountLbl.Text = maxGames.ToString(); } ``` Here is my OK Button event on MaxScore: ``` private void okBtn_Click(object sender, EventArgs e) { MainForm.maxGameCountLblUpdate(max); } ``` Note, I have set ``` public Form1 MainForm { get; set; } ``` in MaxScore And I create MaxScore in MainForm with: ``` using (MaxScore scoreForm = new MaxScore()) { scoreForm.MainForm = this; scoreForm.ShowDialog(); } ``` I can't get this to work.. I have tried many things.. Thanks! EDIT: After adding a breakpoint at myGameCountLbl.Text = maxGames.ToString(); myGameCountLbl appears to be coming up as null... Im sorry for being a newb... How do I fix this? maxGames, indeed, does come up as 1, so that is not the problem
Did you remove: `InitializeComponent();` from the constructor? If you are using the designer to build the form UI, Visual Studio builds a method in the background (Class.designer.cs) to initialize the controls. If you don't call `InitializeComponent()` before you access the UI elements, you will get a NullReferenceException.
Well if this is the line that's causing the problem: ``` myGameCountLbl.Text = maxGames.ToString(); ``` then either `myGameCountLbl` is null, or `maxGames` is. Given that `maxGames` is a decimal, that suggests that `myGameCountLbl` is null. What happens when you debug into this and put a breakpoint on the appropriate line? What does that show for `myGameCountLbl`?
NullReferenceException was unhandled, Object Reference not set to an instance of an object
[ "", "c#", "exception", "reference", "null", "instance", "" ]
First of all, I've been researching this "Operation Aborted" error / bug for what seems like weeks, so here are a couple related questions and good articles if you are not familiar with it: [Why does ASP.NET cause the “Operation Aborted” Error in IE7?](https://stackoverflow.com/questions/266585/operation-aborted-error-in-ie7) (so question) [Detecting cause of IE’s Operation Aborted Issue](https://stackoverflow.com/questions/778983/detecting-cause-of-ies-operation-aborted-issue) (so question) [Official Microsoft Knowledge base](http://support.microsoft.com/kb/927917) [Official IE Blog](http://blogs.msdn.com/ie/archive/2008/04/23/what-happened-to-operation-aborted.aspx) **Now here's my problem:** First I tried moving all my <script> elements to the end of my body tag. Didn't work. Then I refactored all my js functions to an external file that is linked in the <head>, all of my js functions are called from onclick or onkeypress anyway. Still getting the error. The last line of one of my .js files is ``` document.onload = setTimeout("foo()",500); ``` so I moved that to <body onload="setTimeout('foo()',500);">. I'm still getting this error. I don't know what to do. The only place I'm editing DOM elements is in foo(). Please help! **About my setup:** Java, Hibernate, Struts, JSPs ... I think that's all that is relevant. What am I missing here? Thanks in advance.
There are several causes for this. Two of the most common are: 1) scripts attempting to modify the DOM before the document has completely loaded 2) [Trailing commas](http://www.pluralsight.com/community/blogs/fritz/archive/2007/06/19/47771.aspx) in object or array declarations Number two is usually relatively easy to find, while number one is much tougher. Generally the best way to track down IE Javascript problems is to install [Microsoft Script Debugger](http://www.microsoft.com/downloads/details.aspx?familyid=2f465be0-94fd-4569-b3c4-dffdf19ccd99&displaylang=en), so at least you can see what lines are causing the problem. With Script Debugger, IE will halt execution inside the browser and kick the script to a Script Debugger console, which will show the problem line. Much more informative than regular IE error messages.
Please see my [answer to this question in another thread](https://stackoverflow.com/questions/778983/detecting-cause-of-ies-operation-aborted-issue/779026#779026). I love this little trick and it has never failed me (when the cause is DOM manipulation before IE is ready, I mean). And as written, it doesn't affect the DOM-compliant browsers.
IE Operation Aborted - None of the regular fixes work
[ "", "javascript", "jsp", "internet-explorer", "" ]
We are working on a datawarehouse for a bank and have pretty much followed the standard Kimball model of staging tables, a star schema and an ETL to pull the data through the process. > Kimball talks about using the staging area for import, cleaning, processing and everything until you are ready to put the data into the star schema. In practice this typically means uploading data from the sources into a set of tables with little or no modification, followed by taking data optionally through intermediate tables until it is ready to go into the star schema. That's a lot of work for a single entity, no single responsibility here. Previous systems I have worked on have made a distinction between the different sets of tables, to the extent of having: * **Upload tables**: raw source system data, unmodified * **Staging tables**: intermediate processing, typed and cleansed * **Warehouse tables** You can stick these in separate schemas and then apply differing policies for archive/backup/security etc. One of the other guys has worked on a warehouse where there is a *StagingInput* and a *StagingOutput*, similar story. The team as a whole has a lot of experience, both datawarehouse and otherwise. However, despite all this, looking through Kimball and the web there seems to be absolutely nothing in writing about giving any kind of structure to the staging database. One would be forgiven for believing that Mr Kimball would have us all work with staging as this big deep dark unstructured pool of data. Whilst of course it is pretty obvious how to go about it if we want to add some more structure to the staging area, it seems very odd that there seems to be nothing written about it. So, what is everyone else out there doing? Is staging just this big unstructured mess or do folk have some interesting designs on it?
I have experienced the same problem. We have a large HR DataWarehouse and I am pulling data from systems all over the enterprise. I've got a nice collection of Fact and Dimension tables, but the staging area is a mess. I don't know of any standards for design of this. I would follow the same path you are on and come up with a standard set of names to keep things in order. Your suggestion is pretty good for the naming. I'd keep working with that.
Just a note, there is a book called "The Data Warehouse ETL Toolkit" by Raph Kimball and Joe Caserta, so Mr. Kimball did put some effort into this. :)
Structure within staging area of data warehouse
[ "", "sql", "database-design", "data-warehouse", "" ]
It would seem these days that everyone just goes with MySQL because that's just what everyone goes with. I'm working on a web application that will be handling a large quantity of incoming data and am wondering if I should "just go with MySQL" or if I should take a look at other open-source databases or even commercial databases? EDIT: Should have mentioned, am looking for optimal performance, integration with ruby + rails running on debian 5 and money is tight although if it will save money in the long run I would consider making an investment into something more expensive.
I've posted this before, but I have no reason to change this advice: MySQL is easier to start using. Nicer UI tools. Faster, if you don't use ACID. More tolerant of invalid data. Autoincrement columns are as easy as typing autoincrement. Permissions aren't as tied to the file systems and OS users. Setting a delimiter is easier than using PG's "dollar sign quoting" when writing a stored proc. In MySQL, you connect to all databases, not just one at a time. Postgres (PG) is much more standards compliant, but it's uglier and more complicated, especially from a UI perspective. It used to require manual vacuuming, and actually enforces referential integrity (which is a great thing that can be a pain in the ass). Autoincrement is much more flexible, but requires sequences (which can me masked by using serial), and wait, what's an OID? So if you don't really know or care much about databases, data validity, ACID compliance, etc, but you do care about ease and speed, you tend to go with MySQL. Too many (not all, but many) "web programmers" know a lot about "web 2.0" or PHP or Java, but don't know much about database theory or practice ("an index? what's that?"). They tend to see a database as just a fancy hashtable or bag of data, and indeed one that's not anywhere as dynamically changeable or forgiving as a hashtable. For these folks, MySQL -- because until 5.0 it wasn't really an RDBMS, and in many ways still is not -- is a godsend. It's "faster" than the competition, and doesn't "waste time" on "esoteric" database stuff a web programmer doesn't want, understand, or see the value of. For somebody with a database background, on the other hand, MySQL is a minefield: stuff that should work (complicated views, group bys, order bys in group bys) may work or may if you're lucky crash the server, or if you're unlucky just give results with incorrect data. I've spent days working around some of these things in admittedly complicated by not extraordinarily complex views and group bys. And MySQL isn't really faster. If you're using InnoDb tables for ACID (or just because at more than 30 Million rows, MyISAM tables tend to get crappy), yes a straight one-table select is probably faster than in PG. But add in joins, and PG is suddenly significantly faster. (MySQL is especially bad at outer joins.) In summary: if to you the database is a bag, if you never intend to do data mining or reporting, if you're mostly interested in serving up big hunks of text with few relations or updates -- that is, if you're using a database to power a blog, MySQL is a great choice. But if you're actually managing data, if you understand that data lives longer and is more valuable to a business than front-end programs and middle-tier business rules , if you need the features of a real database, use PG. A "web programmer" who has decided all his table structures can be auto-generated by Hibernate (or some other ORM) looks at that and says, "too complicated" and "I bet complicated means more cost and slower speed" and so he goes with MySQL. As I said, PG is far superior, and I hate mucking with MySQL's bizarre bugs, and I think that overall PG performance is probably better than MySQL for any even slightly complicated query. But MySQL makes things look (deceptively) simple, so you get a lot of people who don't really understand database design figuring that MySQL is a great choice. Use PG. It's consistent, it's reliable, it's standards-compliant, it's faster on (even moderately) complicated queries, it doesn't completely throw off your schedule with weird bugs.
I think [PostgreSQL](http://www.postgresql.org/) is a very viable alternative to MySQL. It's much more Oracle-like.
Choosing the right database: MySQL vs. Everything else
[ "", "sql", "mysql", "oracle", "postgresql", "database", "" ]
So is it possible to snag the entire content of a page in its current state. For example, if interacting with a page, via jquery, I've modified the document by either inserting content, or by adding or removing class names. Is it possible to get the markup of this document in its current form from starting html tag to html tag?
Can't you just get the root object in the DOM and call innerHTML to get it all?
Something like ``` document.documentElement.innerHTML ``` This doesn't include the <html> opening and closing tags
Get entire content of page?
[ "", "javascript", "html", "" ]
> **Possible Duplicate:** > [Create a temporary directory in Java](https://stackoverflow.com/questions/617414/create-a-temporary-directory-in-java) Duplicate: [stackoverflow.com/questions/375910](https://stackoverflow.com/questions/375910) Is there a way of creating a temporary folder in java ? I know of File's static method createTempFile, but this will only give me a temporary file.
I've never seen a good solution for this, but this is how I've done it. ``` File temp = File.createTempFile("folder-name",""); temp.delete(); temp.mkdir(); ```
Any reason you can't use the directory defined by the java.io.tmpdir property? ie ``` String dirName = System.getProperty("java.io.tmpdir"); ```
how can I create a temporary folder in java 6?
[ "", "java", "temporary-directory", "" ]
What exactly is an "assert", or more specifically, how do I get rid of an error. When I create a vector of pointers to a class with data member int x, and then do this: ``` for(I=antiviral_data.begin();I<antiviral_data.end();I++) { if((*I)->x>maxx) { antiviral_data.erase(I); } } ``` And run the program, I get no errors until x is greater than maxx and I use .erase(), at which point I get this error: > Debug Assertion Failed! > > Program: ...My Documents\O.exe File: > ...include\vector Line: 116 > > Expression: > ("this->\_Has\_container()",0) > > For information on how your program > can cause an assertion failure, see > the Visual C++ documentation on > asserts. > > (Press Retry to debug the application) > > [Abort][Retry][Ignore] Also, if I try to use cout: ``` cout<<(*antiviral_data.begin())->x<<endl; ``` I get this error: > Debug Assertion Failed! > > Program: ...My Documents\O.exe File: > ...include\vector Line: 98 > > Expression: vector iterator not > deferencable > > For information on how your program > can cause an assertion failure, see > the Visual C++ documentation on > asserts. > > (Press Retry to debug the application) > > [Abort][Retry][Ignore] Could somebody please tell me why I can't USE any of the data in the vector, and how to fix it? ALSO: antiviral\_data is a vector of pointers, with a single element: ``` antiviral_data.push_back(new aX1(player.x,player.y,'>')); ``` If that helps.
The most probable reason why you get the assertion is that you increment I after an erase. Try this instead: ``` for(I=antiviral_data.begin();I!=antiviral_data.end();) { if((*I)->x>maxx) I=antiviral_data.erase(I); else ++I; } ``` See also <http://www.cppreference.com/wiki/stl/vector/erase> , search for *invalid iterators* on that page.
An assert is typically an expression entered by a developer for debug and error control purposes - you put different "sanity checks" in your code, and have it crash the program if the check is not reached. For example, imagine you had code that was going to divide two numbers somewhere down the road. Even though you always expect a division by non-zero, you put at assert before the division in case an argument got miscalculated. If the assert fails, it means somewhere up the road there was a failure. Assertions typically appear only in the debug version in the code (If you use visual C++ you can compile for debug and release). While compiling in release mode would eliminate the results, it is a very bad idea, since you would still have an error and probably really bad results. Somewhere in the implementation of Vector (is it standard), and speciifcally in line 98, there is an assert. If you have access to the vector code, look to see what the assert is or debug up to that point. This could indicate an error in the vector implementation, or in the code that calls vector. The stuff you posted gives us some hints of what's going on, but it would be useful if you could paste more of the program, including where the vectors are defined.
Why is my vector code asserting? What is an assert anyway?
[ "", "c++", "vector", "assertions", "" ]
I have a many-to-many relationship between photos and tags: A photo can have multiple tags and several photos can share the same tags. I have a loop that scans the photos in a directory and then adds them to NHibernate. Some tags are added to the photos during that process, e.g. a 2009-tag when the photo is taken in 2009. The Tag class implements Equals and GetHashCode and uses the Name property as the only signature property. Both Photo and Tag have surrogate keys and are versioned. I have some code similar to the following: ``` public void Import() { ... foreach (var fileName in fileNames) { var photo = new Photo { FileName = fileName }; AddDefaultTags(_session, photo, fileName); _session.Save(photo); } ... } private void AddDefaultTags(…) { ... var tag =_session.CreateCriteria(typeof(Tag)) .Add(Restriction.Eq(“Name”, year.ToString())) .UniqueResult<Tag>(); if (tag != null) { photo.AddTag(tag); } else { var tag = new Tag { Name = year.ToString()) }; _session.Save(tag); photo.AddTag(tag); } } ``` My problem is when the tag does not exist, e.g. the first photo of a new year. The AddDefaultTags method checks to see if the tag exists in the database and then creates it and adds it to NHibernate. That works great when adding a single photo but when importing multiple photos in the new year and within the same unit of work it fails since it still doesn’t exist in the database and is added again. When completing the unit of work it fails since it tries to add two entries in the Tags table with the same name... My question is how to make sure that NHibernate only tries to create a single tag in the database in the above situation. Do I need to maintain a list of newly added tags myself or can I set up the mapping in such a way that it works?
You need to run `_session.Flush()` if your criteria should not return stale data. Or you should be able to do it correctly by setting the `_session.FlushMode` to Auto. With FlushMode.Auto, the session will automatically be flushed before the criteria is executed. EDIT: And important! When reading the code you've shown, it does not look like you're using a transaction for your unit of work. I would recommend wrapping your unit of work in a transaction - that is required for FlushMode.Auto to work if you're using NH2.0+ ! Read further here: [NHibernate ISession Flush: Where and when to use it, and why?](https://stackoverflow.com/questions/43320/nhibernate-isession-flush-where-and-when-to-use-it-and-why)
This is that typical "lock something that is not there" problem. I faced it already several times and still do not have a simple solution for it. This are the options I know until now: * Optimistic: have a unique constraint on the name and let one of the sessions throw on commit. Then you try it again. You have to make sure that you don't end in a infinite loop when another error occurs. * Pessimistic: When you add a new Tag, you lock the whole Tag table using TSQL. * .NET Locking: you synchronize the threads using .NET locks. This only works if you parallel transactions are in the same process. * Create Tags using a own session (see bellow) Example: ``` public static Tag CreateTag(string name) { try { using (ISession session = factors.CreateSession()) { session.BeginTransaction(); Tag existingTag = session.CreateCriteria(typeof(Tag)) /* .... */ if (existingtag != null) return existingTag; { session.Save(new Tag(name)); } session.Transaction.Commit(); } } // catch the unique constraint exception you get catch (WhatEverException ex) { // try again return CreateTag(name); } } ``` This looks simple, but has some problems. You get always a tag, that is either existing or created (and committed immediately). But the tag you get is from another session, so it is detached for your main session. You need to attach it to your session using cascades (which you probably don't want to) or update. Creating tags is not coupled to your main transaction anymore, this was the goal but also means that rolling back your transaction leaves all created tags in the database. In other words: creating tags is not part of your transaction anymore.
Which algorithm to use with many-to-many relation in NHibernate
[ "", "c#", "nhibernate", "many-to-many", "design-patterns", "" ]
I'm trying to figure out the best way to estimate the maximum size of the browser viewable area. i.e. the screen dimensions less toolbars, bookmarks, etc. Obviously it wont be perfect for cases when the window isn't maximized and due to the fact that people do actually use different browsers - I'm just looking for a good estimate here. The purpose is to then figure out the maximum size for an image.
You can also use [jQuery's](http://docs.jquery.com/CSS/width) `width()` function on anything: `$(window).width()`. Keep in mind though that if the window is resized, this will change and will probably through off whatever layout it was originally based on. You can [watch for that event](http://docs.jquery.com/Events/resize), but that could hurt performance if you're doing complicated things.
In Firefox you can use this code ``` <html> <body> <script type="text/javascript"> document.write("<p>Width: " + window.innerWidth + "</p>") document.write("<p>Height: " + window.innerHeight + "</p>") </script> </body> </html> ``` For IE you may try document.body.offsetWidth and document.body.offsetHeight properties. The screen object will get screen properties (it might help), check its properties here: [link text](http://www.w3schools.com/htmldom/dom_obj_screen.asp)
Good way to estimate available browser area
[ "", "javascript", "html", "css", "" ]
As a web systems programmer, I'd like to generate some reports and be able to send it to the printer directly from my user's browser, wich is in the client side, not needing to generate PDFs or something like this. I would like to be able to: * Print user friendly paging, something like "Page 1 of 3" * Print some things in the bottom of every page, like "Generated in 2009-02-20" * *not* printing the URL Is all this possible? Javascript? CSS? What are the best practices here?
All those things are controlled exclusively through browser preferences. If you want to be able to specify that, then you probably should be looking at PDF instead of HTML.
You're out of luck using the browser there... I think it is impossible to not print in the corners the URL, Date/Time Accessed etc. However, Page 1 or 3 etc is generally always printed somewhere (bottom right corner I believe in FireFox) Printing a 'Generated in 2009-02-20' is easy enough, however printing it at the bottom of every page will be difficult. Most browsers, IIRC, display the date and time accessed in a corner (though not in that format, in a more readily human readable format). Anything you want to appear in print but not in the normal screen view, will need to be shown using a print stylesheet. For what you want here (complete control of the printing output), I'd recommend generating a PDF. Perhaps if this is an internal tool, you might be able to program a plugin for Firefox that may print your pdfs automatically, but I'm not that familiar with the capabilities of Firefox plugins so you'd need to experiment.
Report decent printing in the web
[ "", "javascript", "html", "css", "printing", "report", "" ]
In a DirectoryWalker class I want to find out if a File instance is actually a symbolic link to a directory (assuming, the walker walks on UNIX systems). Given, I already know the instance is a directory, would the following be a reliable condition to determine the symbolic link? ``` File file; // ... if (file.getAbsolutePath().equals(file.getCanonicalPath())) { // real directory ---> do normal stuff } else { // possible symbolic link ---> do link stuff } ```
The technique used in Apache Commons uses the canonical path to the parent directory, not the file itself. I don't think that you can guarantee that a mismatch is due to a symbolic link, but it's a good indication that the file needs special treatment. This is [Apache code](https://github.com/apache/commons-io/blob/master/src/main/java/org/apache/commons/io/FileUtils.java) (subject to [their license](http://www.apache.org/licenses/LICENSE-2.0)), modified for compactness. ``` public static boolean isSymlink(File file) throws IOException { if (file == null) throw new NullPointerException("File must not be null"); File canon; if (file.getParent() == null) { canon = file; } else { File canonDir = file.getParentFile().getCanonicalFile(); canon = new File(canonDir, file.getName()); } return !canon.getCanonicalFile().equals(canon.getAbsoluteFile()); } ```
Java 1.6 does not provide such low level access to the file system. Looks like [NIO 2](http://jcp.org/en/jsr/detail?id=203), which should be included in Java 1.7, will have support for symbolic links. [A draft of the new API](http://openjdk.java.net/projects/nio/javadoc/index.html) is available. Symbolic links [are mentioned there](http://openjdk.java.net/projects/nio/javadoc/java/nio/file/package-summary.html#links), [creating](http://openjdk.java.net/projects/nio/javadoc/java/nio/file/Path.html#createSymbolicLink(java.nio.file.Path,%20java.nio.file.attribute.FileAttribute...)) and [following](http://openjdk.java.net/projects/nio/javadoc/java/nio/file/Path.html#readSymbolicLink()) them is possible. I'm not exactly sure that which method should be used to find out whether a file is a symbolic link. There's [a mailing list](http://groups.google.com/group/jsr203-interest) for discussing NIO 2 - maybe they will know.
Java 1.6 - determine symbolic links
[ "", "java", "java-6", "" ]
I'm running my own LAMP server locally. Something i need to setup? Should it be able to send email using php-mail, without havin to configure smtp.
Ah fixed it, well i didn't-one of our developers did. Apparently Drupal only uses 'Send Mail' so you have to have it installed, wont use php-mail.
Check your phpinfo() information for STMP and the port. Do a test.php file and try to execute this. ``` mail('email@example.com', 'My Subject', 'Hello World'); ```
Drupal 6 won't send email, for account activation etc
[ "", "php", "email", "drupal-6", "smtp", "send", "" ]
I use Notepad++ and Aptana for editing my CakePHP code? Is there any way to get basic html syntax highlighting for CakePHP's .ctp template files? It's a lot harder for me without any coloring going on. Any ideas?
**Configuring in Aptana Editor** > Quoted from aptana docs 1. From the Window menu, select Preferences..., and then choose General > Editors > File Associations. 2. Add the appropriate file type. 3. Next to the File Types list, click the Add button. 4. In the New File Type pop-up window, type the appropriate file extension (e.g. "*.ctp" or "*.thtml"). 5. Click OK to add the New File Type to the List. 6. Associate the new file type with Aptana. 7. On the File Types list, select the file type that you just added. 8. Next to the Editor Associations list, click the Add button. 9. On the Editor Selection pop-up window, select the editor that you want to associate with your file type. 10. Click OK to add the editor. 11. The new is now associated with the specified file type. 12. Click OK to apply your changes and close the Preferences window. ***Check out this [link](http://www.aptana.com/docs/index.php/Using_Aptana_with_PHP,_ASP,_and_other_non-HTML_files)***
You probably just have to select Language -> Html in the menu bar. You can set the association in Settings -> Style Configurator -> Html
How can I get HTML syntax highlighting in my editor for CakePHP?
[ "", "php", "cakephp", "syntax-highlighting", "notepad++", "aptana", "" ]
Why is it that ~2 is equal to -3? How does `~` operator work?
Remember that negative numbers are stored as the **two's complement** of the positive counterpart. As an example, here's the representation of -2 in two's complement: (8 bits) ``` 1111 1110 ``` The way you get this is by taking the binary representation of a number, taking its complement (inverting all the bits) and adding one. Two starts as 0000 0010, and by inverting the bits we get 1111 1101. Adding one gets us the result above. The first bit is the sign bit, implying a negative. So let's take a look at how we get ~2 = -3: Here's two again: ``` 0000 0010 ``` Simply flip all the bits and we get: ``` 1111 1101 ``` Well, what's -3 look like in two's complement? Start with positive 3: 0000 0011, flip all the bits to 1111 1100, and add one to become negative value (-3), 1111 1101. So if you simply invert the bits in 2, you get the two's complement representation of -3. ## The complement operator (~) JUST FLIPS BITS. It is up to the machine to interpret these bits.
`~` flips the bits in the value. Why `~2` is `-3` has to do with how numbers are represented bitwise. Numbers are represented as [two's complement](http://en.wikipedia.org/wiki/Two's_complement). So, 2 is the binary value ``` 00000010 ``` And ~2 flips the bits so the value is now: ``` 11111101 ``` Which, is the binary representation of -3.
How does Python's bitwise complement operator (~ tilde) work?
[ "", "python", "operators", "bitwise-operators", "complement", "" ]
I work for a school district in which the teachers submit their lesson plans to their principals online. They do this using an online form I wrote using PHP/MySQL and it uses TinyMCE for its textareas. One of the major features that was requested was for teachers to be able to save their incomplete forms as drafts to submit later. This was implemented, but the new problem I'm facing is that not all teachers have access to the internet at home, thus they cannot work on their lesson plans while at home. Of course, they could cut and paste out of a word document or text file that they save on their laptops, but then they have to cut/paste one textarea at a time, and they complain about it. So what I was thinking about trying, is making an offline application that looks like the online form, but saves the form in an xml format on their computer. Then they could open this file to keep working on it, or upload it to the online form later. My question is: being that my programming experience is currently limited to a few web-related languages (php, javascript, html) what should I use to attempt to write this offline app? Winbinder? Adobe AIR?
I've actually gone with Adobe AIR to do this. With AIR, the form looks nearly identical to the one that's used online and even uses the same TinyMCE library. And I didn't have to learn much to get it going, just the AIR javascript API. I'm also using AIR to write a few other apps and I love it.
I think your best bet will be to ask them to install [Google Gears](http://gears.google.com/) on their browser (comes by default with Google Toolbar iirc), which is ideal for storing content offline. And then as soon as they go online it's easy to sync the stored content back to your online server. Gears API Documentation can be found [here](http://code.google.com/apis/gears/).
Suggestions for making an offline version of an online form?
[ "", "php", "xml", "web-applications", "tinymce", "" ]
How do I get a property in a PHP based on a string? I'll call it `magic`. So what is `magic`? ``` $obj->Name = 'something'; $get = $obj->Name; ``` would be like... ``` magic($obj, 'Name', 'something'); $get = magic($obj, 'Name'); ```
Like this ``` <?php $prop = 'Name'; echo $obj->$prop; ``` Or, if you have control over the class, implement the [ArrayAccess](https://www.php.net/manual/en/class.arrayaccess.php) interface and just do this ``` echo $obj['Name']; ```
If you want to access the property without creating an intermediate variable, use the `{}` notation: ``` $something = $object->{'something'}; ``` That also allows you to build the property name in a loop for example: ``` for ($i = 0; $i < 5; $i++) { $something = $object->{'something' . $i}; // ... } ```
Get PHP class property by string
[ "", "php", "string", "oop", "properties", "" ]
Chances are i will need to do a lot of userid->username lookups. So i was thinking, instead of having a table like the below ``` userid int PK username text userpass_salthash int user_someopt1 int user_sig text ``` to have it broken up as the below ``` //table1 userid int PK username text //table2 userid int //fk userpass_salthash int user_someopt1 int user_sig text ``` reasoning i would do this is because i suspect a less complex table (i can also make names no longer then 32bytes if i like) is faster for lookups along with less data as a bonus. But i know i could be wrong so, which version should i do and what reasons beside optimization?
You should do the first option (single table) for both normalization and performance. Performance: * If you put an index on `(UserId, Username)`, you'll have a covering index - so you won't ever need to go to the table to get the Username anyway. * If you put your clustered index on `UserId`, you'll get a clustered index seek - which will end up at the row data anyway. Normalization: * Your second option allows for a user to exist in table1, but not table2. Since you likely don't want a user without a password (that can't login), I'd consider that broken. My suggestion would be a clustered index on UserId. If you need the clustered index somewhere else, a covering index would be almost as good.
I agree that for a table that narrow, a single table is almost certainly the best bet. One more thing to add - a text datatype (if you're using MS SQL Server) is awfully wide. nvarchar(200) should be more than wide enough. Use LOB data with discretion.
sql userid + name + profile optimize question
[ "", "sql", "database", "optimization", "" ]
Profiling my C++ code with gprof, I discovered that a significant portion of my time is spent calling one virtual method over and over. The method itself is short and could probably be inlined if it wasn't virtual. What are some ways I could speed this up short of rewriting it all to not be virtual?
It's sometimes instructive to consider how you'd write the code in good old 'C' if you didn't have C++'s syntactic sugar available. Sometimes the answer isn't using an indirect call. See [this answer](https://stackoverflow.com/questions/584544/are-there-alternatives-to-polymorphism-in-c/586051#586051) for an example.
Are you sure the time is all call-related? Could it be the function itself where the cost is? If this is the case simply inlining things might make the function vanish from your profiler but you won't see much speed-up. Assuming it really is the overhead of making so many virtual calls there's a limit to what you can do without making things non-virtual. If the call has early-outs for things like time/flags then I'll often use a two-level approach. The checking is inlined with a non-virtual call, with the class-specific behavior only called if necessary. E.g. ``` class Foo { public: inline void update( void ) { if (can_early_out) return; updateImpl(); } protected: virtual void updateImpl( void ) = 0; }; ```
Speeding up virtual function calls in gcc
[ "", "c++", "virtual-functions", "gprof", "" ]
My problem is that I have to set a variable in a try statement otherwise I get a compile error. Later on I need to use that variable but it is now out of scope, or so I believe. I initialise the variable outside the try statement and set it to null, I thought that it might then be accessible outside, but I still get a `NullPointerException`. The code is below, with lots of it taken out to make reading easier - I know it's bad code, but I am new to Servlets and just wanted to see it running with all the moving parts doing what they are supposed to. I have created another class that calls createDocs(...) and passes in the required parameters, and it works fine. So that is making me curious as to why when I call `rs.getString("name")` I get the `NullPointerException`, as this is exactly what I do from the other class (run from a main method for convenience) and it works as expected. The variable in question is the ResultSet variable "rs" - ``` public class AgReportServlet extends HttpServlet { private static final long serialVersionUID = 1L; public AgReportServlet() { super(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ResultSet rs = null; try { rs = docs.getDocs(con, start, end, zone, locality); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } response.setContentType("text/xml"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n" + out.println( "<table border=\"0\" cellspacing=\"0\" cellpadding=\"6\">\n"); // I have a resultset object need to iterate through it to display the file names try { while (rs.next()) { // page through the result set out.println( " <tr>\n" + " <td>: " + rs.getString("name") + "</td>\n" + " </tr>\n" ); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } out.println( "</table></body>\n" + "</html>" ); out.flush(); out.close(); } } ```
Your problem is that if this statement: ``` rs = docs.getDocs(con, start, end, zone, locality); ``` throws an exception then the value of rs is still `null`. So what I would do is move the loop inside the same try-catch block. Alternatively you can check whether it's still null before trying to use it. Setting the value to null outside the try-catch block isn't bad code though. That's just what you have to do if you want the rs variable outside the try block (and that includes inside one of the catch clauses). Your rs while loop should probably just be within the same try block.
The way you are declaring the rs variable and the first try/catch block are ok. Its just that after the first try/catch you need to remember that rs will *still* be null if there was an error in the first try/catch. So just make sure you test rs for null before you try to access it.
How to avoid setting variable in a try statement
[ "", "java", "scope", "try-catch", "" ]
So for a type like: ``` CoolCollection<T> ``` you could have: ``` foreach (T item in coolCollection) { ... } foreach (CoolNode node in coolCollection) { ... } ``` If this isn't possible, maybe like foreach2, or some other way to iterate. Often times, I would really like more than 1 way of iterating on a type. EDIT: Sorry if it wasn't clear. Basically CoolNode is a node that makes CoolCollection. CoolNode has a property called value to return T, but I need another iterator to return only CoolNodes. EDIT2: I can't do coolCollection.Something to iterate, because CoolNodes are connected via a property called Next, like a LinkedList. So I need to implement 2 iterators.
Just make `CoolCollection<T>` explicitly implement `IEnumerable<CoolNode<T>>` as well as `IEnumerable<T>`. (I'm guessing it's really `CoolNode<T>`, but if not, just take the extra `<T>` out everywhere.) This will let you iterate in both manners, although you'll need a cast. To do this, you'd need something like: ``` class CoolCollection<T> : ICollection<T>, IEnumerable<CoolNode<T>> { IEnumerator<CoolNode<T>> IEnumerable<CoolNode<T>>.GetEnumerator() { ///...Do work here... } IEnumerator<T> GetEnumerator() { ///...Do work here... } } ``` Using this would be like so: ``` foreach (T item in coolCollection) { ... } foreach (CoolNode<T> node in (IEnumerable<CoolNode<T>>)coolCollection) { ... } ``` The other option would be to expose a property for the "nodes", so you could do: ``` foreach(var nodes in coolCollection.Nodes) { ... } ``` To implement this, you'd change things around a little bit. You'd need to make a private class that implemented the enumerator... something like: ``` class CoolCollection<T> : ICollection<T> { private List<CoolNode<T>> nodes; IEnumerable<CoolNode<T>> Nodes { get { foreach(var node in this.nodes) { yield return node; } } } } ```
If I understand the question correctly... You could do it similar to the some of the other collection objects do it: for example: ``` foreach (int key in IDictionary.Keys) { } foreach (object value in IDictionary.Values) { } ``` But I don't think there is a way to do exactly the way you have it written...
Is it possible to write multiple iterators for a type in C#?
[ "", "c#", ".net", "iterator", "" ]
This code works correctly to make a web service call: ``` int numberOfGuests = Convert.ToInt32(search.Guest); var list = new List<Guest>(); Guest adult = new Guest(); adult.Id = 1; adult.Title = "Mr"; adult.Firstname = "Test"; adult.Surname = "Test"; list.Add(adult); Guest adult2 = new Guest(); adult2.Id = 2; adult2.Title = "Mr"; adult2.Firstname = "Test"; adult2.Surname = "Test"; list.Add(adult2); Guest[] adults = list.ToArray(); ``` How do I build the list dynamically using the `numberofguests` variable to create the list? The output has to match the output shown exactly else the web service call fails, so adult.id = 1, adult2.id = 2, adult3.id = 3, etc...
Do you know about loops? ``` for (int i = 1; i <= numberofGuests; i++) { var adult = new Guest(); adult.Id = i; adult.Title = "Mr"; adult.Firstname = "Test"; adult.Surname = "Test"; list.Add(adult) } ``` This runs the code within the loop once from 1 to `numberOfGuests`, setting the variable `i` to the current value.
The Linq way :-) ``` var list = (from i in Enumerable.Range(1, numberOfGuests) select new Guest { Id = i, Title = "Mr.", Firstname = "Test", Surname = "Test" }).ToList(); ```
Build dynamic list c#
[ "", "c#", "list", "" ]
The computer is connected to measuring device via a physical COM1. I have simple form where I open a serial port, tell the device that I'm alive and occasionally the device sends data. (every some minutes) ``` Thread _readThread = new Thread(Read); SerialPort _serialPort = new SerialPort("COM1", 9600); _serialPort.Parity = Parity.None; _serialPort.DataBits = 8; _serialPort.StopBits = StopBits.One; _serialPort.Handshake = Handshake.None; _serialPort.DtrEnable = true; _serialPort.Open(); _readThread.Start(); _serialPort.Write("#listening"); ``` The read function (which works): ``` public void Read() { string message = _serialPort.ReadLine(); } ``` After approximately one minute the application crashes (even while debugging). It reports an ObjectDisposedException (for the underlying stream?). The message tells that the SafeHandle was closed. Stack strace is below: *at Microsoft.Win32.UnsafeNativeMethods.GetOverlappedResult(SafeFileHandle hFile, NativeOverlapped* lpOverlapped, Int32& lpNumberOfBytesTransferred, Boolean bWait) at System.IO.Ports.SerialStream.EventLoopRunner.WaitForCommEvent() at System.Threading.ThreadHelper.ThreadStart\_Context(Object state) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart()\* Any ideas? The problem is reported widely but usually involve the device beeing physically detached from the PC.
It seemed like the RS232 cable (adapter) caused the crashes of the underlying serial port stream. Switched to an FTDI cable, that worked. A look into the .NET Framework source code helped a lot. But I think the thrown ObjectDisposedException should be caught by the SerialPort, not by the user.
Try checking IsOpen before reading. Also, is there any chance the object containing \_serialPort has been dereferenced and garbage collected? If you're never accessing \_serialPort from another thread, try making it a private variable in Read().
Opened SerialPort crashes C# application
[ "", "c#", ".net", "serial-port", "objectdisposedexception", "" ]
When you call dict.values() the order of the returned items is dependent on the has value of the keys. This seems to be very consistent in all versions of cPython, however the python manual for dict [simply states that the ordering is "arbitrary"](http://docs.python.org/library/stdtypes.html#dict.items). I remember reading somewhere that there is actually a PEP which specifically states the expected ordering of the items() and values() methods. FYI, if this behavior is indeed a guaranteed behavior of a class I am working on I could greatly simplify and speed up a class I am working on. On the other hand if this is merely an accidental and undocumented feature of cPython then it's probably best not to trust it.
I suppose [PEP-3106](http://www.python.org/dev/peps/pep-3106/) is as close as it gets: > The specification implies that the order in which items are returned by > .keys(), .values() and .items() is the > same (just as it was in Python 2.x), > because the order is all derived from > the dict iterator (which is presumably > arbitrary but stable as long as a dict > isn't modified). This can be expressed > by the following invariant: > > `list(d.items()) == list(zip(d.keys(), > d.values()))`
From <http://docs.python.org/library/stdtypes.html>: > Keys and values are listed in an > arbitrary order which is non-random, > varies across Python implementations, > and depends on the dictionary’s > history of insertions and deletions.
Which PEP governs the ordering of dict.values()?
[ "", "python", "dictionary", "" ]
Using C#, is there a better way to handle multiple types of exceptions rather than a bunch of ugly catch blocks? What is considered best practice for this type of situation? For example: ``` try { // Many types of exceptions can be thrown } catch (CustomException ce) { ... } catch (AnotherCustomException ace) { ... } catch (Exception ex) { ... } ```
In my opinion, a bunch of "ugly" catch blocks IS the best way to handle that situation. The reason I prefer this is that it is very explicit. You are explicitly stating which exceptions you want to handle, and how they should be handled. Other forms of trying to merge handling into more concise forms lose readability in most cases. My advice would be to stick to this, and handle the exceptions you wish to handle explicitly, each in their own catch block.
I agree with Reed: this is the best approach. I would add these comments: Only catch something you're going to do something about. If you can't fix the problem, there's no point in catching a specific exception. Don't overdo use of catch blocks. In many cases where you can't resolve the exception, it's best to just let the exception bubble up to a central point (such as Page\_Error) and catch it there. Then, you log the exception and display a message to the user.
More Elegant Exception Handling Than Multiple Catch Blocks?
[ "", "c#", ".net", "exception", "error-handling", "" ]
How is SAML SSO typically implemented? I've read [this](https://developers.google.com/google-apps/sso/saml_reference_implementation_web) (n.b. obsolete) about using SAML with Google Apps, and the wikipedia entry on [SAML](http://en.wikipedia.org/wiki/SAML). The wikipedia entry talks about responding with forms containing details of the SAMLRequest and SAMLResponse. Does this mean that the user has to physically submit the form in order to proceed with the single sign on? The google entry talks about using redirects, which seems more seemless to me. However, it also talks about using a form for the response which the user must submit (although it does talk about using JavaScript to automatically submit the form). Is this the standard way of doing this? Using redirects and JavaScript for form submission? Does anyone know of any other good resources about how to go about implementing SSO between a Windows Domain and a J2EE web application. The web application is on a separate network/domain. My client wants to use [CA Siteminder](http://www.ca.com/us/internet-access-control.aspx) (with SAML).
The way this works is that, after authenticating the user, the SAML identity provider (IdP) renders a form to the browser containing the SAML response - the form's 'action' (i.e. target) is the service provider (SP). In the HTML, there is a JavaScript onLoad event that submits the form, so the net effect is that the user is automatically taken from the IdP to the SP, SAML response in hand. The only time a user would have to click anything to submit the form is if they have JavaScript disabled. In this case, SAML implementations typically provide a message with a button to press in the `<noscript>` tag. For more detail see [this article I wrote a few years ago](http://www.oracle.com/technetwork/java/lightbulb-140176.html) - but note, 'Lightbulb' is long obsolete now - for PHP SAML see [simpleSAMLphp](http://rnd.feide.no/simplesamlphp). It's a shame your client wants to use CA SiteMinder - the open source [OpenAM](http://forgerock.com/openam.html) (formerly known as OpenSSO) does this pretty easily.
[This article](https://web.archive.org/web/20120122063550/http://support.onelogin.com/entries/20186386) explains is very well. There are examples for different platforms too.
How to implement SAML SSO
[ "", "java", "security", "single-sign-on", "saml", "" ]
What is the difference between composition and aggregation? can anybody give me a sample of this OOAD?
[Found here](http://www.jguru.com/faq/view.jsp?EID=51520) "Both aggregation and composition are special kinds of associations. Aggregation is used to represent ownership or a whole/part relationship, and composition is used to represent an even stronger form of ownership. With composition, we get coincident lifetime of part with the whole. The composite object has sole responsibility for the disposition of its parts in terms of creation and destruction. Moreover, the multiplicity of the aggregate end may not exceed one; i.e., it is unshared. An object may be part of only one composite at a time. If the composite is destroyed, it must either destroy all its parts or else give responsibility for them to some other object. A composite object can be designed with the knowledge that no other object will destroy its parts. Composition can be used to model by-value aggregation, which is semantically equivalent to an attribute. In fact, composition was originally called aggregation-by-value in an earlier UML draft, with “normal” aggregation being thought of as aggregation-by-reference. The definitions have changed slightly, but the general ideas still apply. The distinction between aggregation and composition is more of a design concept and is not usually relevant during analysis." John Moore
Consider a student, the student's brain, and the school the student attends. The brain *is a part of* the student. If the student is destroyed, so is the brain. This is **composition**. The student *has a* school. The student survives the school's destruction, and vice versa. This is **aggregation**.
What is the difference between composition and aggregation?
[ "", "java", "ooad", "" ]
What RegKey can you get the default browser application's path from? Best way to get to it from C#/.NET?
Here's the key you want: > HKEY\_LOCAL\_MACHINE\SOFTWARE\Classes\http\shell\open\command And here's a quick [registry tutorial for C#](http://www.codeproject.com/KB/system/modifyregistry.aspx), if you need it. **Edit**: For per-user settings, use this key: > HKEY\_CLASSES\_ROOT\http\shell\open\command (HKCR has both machine and user settings, user takes priority). **Note that this might not work on Vista**. For more info, [see here](http://newoldthing.wordpress.com/2007/03/23/how-does-your-browsers-know-that-its-not-the-default-browser/).
for windows 7 default browser path save in following registry key ``` HKEY_CURRENT_USER\Software\Microsoft\Windows\Shell\ Associations\UrlAssociations\http ``` by using c# you can get it as follows - ``` RegistryKey regkey = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\shell\\Associations\\UrlAssociations\\http\\UserChoice", false); string browser = regkey.GetValue("Progid").ToString(); ```
Windows RegKey - Default Browser Application Path
[ "", "c#", ".net", "windows", "registry", "" ]
How do you protect non-open source code against leaks? Today with technologies such as USB drives, Internet drives and E-mail, how do people protect software assets?
Copyright and contract law seem to work for most companies. The technological fix is not always the right one.
In contrast to unwind's answer, I would say that restricting internet access and forbidding useful kit like USB drives is exactly the kind of thing which is going to demoralise and aggravate your employees into stealing your IP. Ultimately if someone inside your organisation wants to steal your IP they will. I think the better approach is to **treat your employees with a little respect** and give them no reason to steal IP. If they want to work at a company they'll also want to protect that company themselves. Then recognise that the value of your IP is seldom in the software itself (which will quickly become old and inert) and instead is usually in the heads of the people who wrote it, and moreso in the collective thought and experience of the people as a whole. It is not the spoon which bends. It is yourself.
Methods to protect intellectual property (Code) in a software company
[ "", "c#", "security", "" ]
Other being able to sanity check values in a setter is there a more underlying reason to prefer properties to public variables?
We've had this subject before but I can't find anything now. In brief: your needs might change: where there's no sanity check now, one might be required in the future. However, if you change your public fields to properties, this breaks binary compatiblity: every client who uses your code/library would have to re-compile. This is *bad* because it potentially costs a lot of money. Using properties from the beginning avoids this problem. This even counts for code that is not part of a library. Why? Because you never know: the code (even if highly domain-specific!) might prove useful so you want to refactor it to a library. This refactoring process is obviously made much easier if you are already using properties in place of public/protected fields. Additionally, writing public properties is easy in C# 3.0 because you can just use the auto-implemented properties, saving you quite a bit of code: ``` public DataType MyProperty { get; set; } ``` Will implement the necessary backing field and getter/setter code for you. I will add a personal note: .NET's behaviour in this regard is somewhat lazy. The compiler could just change public fields to properties on the fly, thus avoiding the problem. VB6 already did this for COM-exposed classes and I see absolutely no reason for VB.NET and C# not to do the same. Perhaps someone on the compiler teams (Jared?) could comment on this.
In a nutshell: * You can control acces (readonly, writeonly, read/write) * You can validate values when setting a property (check for null etc) * You can do additional processing, such as lazy initialization * You can change the underlying implementation. For example, a property may be backed by a member variable now, but you can change it to be backed by a DB row without breaking any user code.
Why prefer Properties to public variables?
[ "", "c#", "syntax", "" ]
Hi I have Card class... In another class I create an arrayList of Card objects. How would I go about sorting the arrayList based on the value of the card? The ace is the lowest card value and the king is the highest. A,2,3,4,5,6,7,8,9,T,J,Q,K ``` public class Card { char rank, suit; public Card(char rank, char suit){ this.rank = rank; this.suit = suit; } public void setCard(char rank, char suit){ this.rank = rank; this.suit = suit; } public char getRank(){ return rank; } public char getSuit(){ return suit; } public void setRank(char rank){ this.rank = rank; } public void setSuit(char suit){ this.suit = suit; } public String toString(){ String str = ""; str += this.getRank(); str += this.getSuit(); return str; } public boolean equals(Object obj){ Card card = (Card) obj; if(this.rank == card.getRank() && this.suit == card.getSuit()){ return true; } return false; } public boolean isValidCard(Card card){ char s = card.getSuit(); char r = card.getRank(); if(s=='H' || s=='S' || s=='D' || s=='C'){ if(r=='A' || r=='2' || r=='3' || r=='4' || r=='5' || r=='6' || r=='7' || r=='8' || r=='9' || r=='T' || r=='J' || r=='Q' || r=='K'){ return true; } } return false; } public boolean allowedInHigherPiles(Card card, Game game, int pile){ if(pile>=5 && game.getPile(pile).cards.size()==0){ if(card.getRank()!='K') return false; } return true; } } ```
One option is to implement the Comparable interface and then override compareTo Once you've done that, sorting the list is easy with Collections.sort(myCollection); You may be better of avoiding implementing Comparable and create a [Comparator](http://java.sun.com/javase/6/docs/api/) object, and there's a version of Collections.sort that takes the comparator. Your comparison function can can then simply check the rank of the cards, and return the result while ignoring the suit. You may want to read the Java tutorial on [all this ordering business](http://java.sun.com/docs/books/tutorial/collections/interfaces/order.html). Update: Bjorn points out correctly that Comparable should be used when the class has a natural sorting order. My personal view is that for cards there isn't really a "natural order" since different games differ in their interpretation of the Ace, so it might be better to avoid assigning "semantics" by offering Comparable as part of the class.
The code would be much cleaner if you use enum to represent rank and suite instead of char. In fact, <http://jcp.org/aboutJava/communityprocess/jsr/tiger/enum.html> has a Card sample illustrates use of Enum The relevant code bit is copied below ``` public class Card implements Comparable, java.io.Serializable { public enum Rank { deuce, three, four, five, six, seven, eight, nine, ten, jack, queen, king, ace } public enum Suit { clubs, diamonds, hearts, spades } private final Rank rank; private final Suit suit; private Card(Rank rank, Suit suit) { if (rank == null || suit == null) throw new NullPointerException(rank + ", " + suit); this.rank = rank; this.suit = suit; } public Rank rank() { return rank; } public Suit suit() { return suit; } public String toString() { return rank + " of " + suit; } public int compareTo(Object o) { Card c = (Card)o; int rankCompare = rank.compareTo(c.rank); return rankCompare != 0 ? rankCompare : suit.compareTo(c.suit); } private static List<Card> sortedDeck = new ArrayList<Card>(52); static { for (Iterator<Rank> i = Rank.VALUES.iterator(); i.hasNext(); ) { Rank rank = i.next(); for (Iterator<Suit> j = Suit.VALUES.iterator(); j.hasNext(); ) sortedDeck.add(new Card(rank, j.next())); } } // Returns a shuffled deck public static List<Card> newDeck() { List<Card> result = new ArrayList<Card>(sortedDeck); Collections.shuffle(result); return result; } } ```
Java Sorting object in ArrayList
[ "", "java", "collections", "" ]
I have table with some fields that the value will be 1 0. This tables will be extremely large overtime. Is it good to use bit datatype or its better to use different type for performance? Of course all fields should be indexed.
Officially bit will be fastest, especially if you don't allow nulls. In practice it may not matter, even at large usages. But if the value will only be 0 or 1, why not use a bit? Sounds like the the best way to ensure that the value won't get filled with invalid stuff, like 2 or -1.
I can't give you any stats on performance, however, you should always use the type that is best representative of your data. If all you want is 1-0 then absolutely you should use the bit field. The more information you can give your database the more likely it is to get it's "guesses" right.
Is BIT field faster than int field in SQL Server?
[ "", "sql", "performance", "bit", "" ]