title: UnmarshalException while consuming a web service

text: I have a web service based on a number of entity classes. one of them is shows below               @Entity     @Table(name = "users")     @XmlRootElement     @NamedQueries({     @NamedQuery(name = "Users.findAll", query = "SELECT u FROM Users u"),     @NamedQuery(name = "Users.findByUserName", query = "SELECT u FROM Users u WHERE u.userName = :userName"),     @NamedQuery(name = "Users.findByUserPassword", query = "SELECT u FROM Users u WHERE u.userPassword = :userPassword")})          public class Users implements Serializable {          private static final long serialVersionUID = 1L;          @Id     @Basic(optional = false)     @Column(name = "user_name")     private String userName;          @Basic(optional = false)     @Column(name = "user_password")     private String userPassword;          @JoinColumn(name = "user_category_id", referencedColumnName = "category_id")     @ManyToOne(optional = false)     private UserCategory userCategoryId;          @OneToMany(cascade = CascadeType.ALL, mappedBy = "userName")     private List<UserRecord> userRecordList;          public Users() {     }          public Users(String userName) {         this.userName = userName;     }          public Users(String userName, String userPassword) {         this.userName = userName;         this.userPassword = userPassword;     }          public String getUserName() {         return userName;     }          public void setUserName(String userName) {         this.userName = userName;     }          public String getUserPassword() {         return userPassword;     }          public void setUserPassword(String userPassword) {         this.userPassword = userPassword;     }          public UserCategory getUserCategoryId() {         return userCategoryId;     }          public void setUserCategoryId(UserCategory userCategoryId) {         this.userCategoryId = userCategoryId;     }          @XmlTransient     public List<UserRecord> getUserRecordList() {         return userRecordList;     }          public void setUserRecordList(List<UserRecord> userRecordList) {         this.userRecordList = userRecordList;     }          @Override     public int hashCode() {         int hash = 0;         hash += (userName != null ? userName.hashCode() : 0);         return hash;     }          @Override     public boolean equals(Object object) {         // TODO: Warning - this method won't work in the case the id fields are not set         if (!(object instanceof Users)) {             return false;         }         Users other = (Users) object;         if ((this.userName == null && other.userName != null) || (this.userName != null && !this.userName.equals(other.userName))) {             return false;         }         return true;     }          @Override     public String toString() {         return userName;     }           }      I was able to successfully deploy the web service and then i added a new Restful web client using netbeans, which created the following class               public class Client {     private WebTarget webTarget;     private javax.ws.rs.client.Client client;     private static final String BASE_URI = "http://localhost:31691/ProductionEntitiesService/api";          public Client() {         client = javax.ws.rs.client.ClientBuilder.newClient();         webTarget = client.target(BASE_URI).path("entities.users");     }          ...     public <T> T find_XML(Class<T> responseType, String id) throws ClientErrorException {         WebTarget resource = webTarget;         resource = resource.path(java.text.MessageFormat.format("{0}", new Object[]{id}));         return resource.request(javax.ws.rs.core.MediaType.APPLICATION_XML).get(responseType);     }               public <T> T findAll_XML(Class<T> responseType) throws ClientErrorException {         WebTarget resource = webTarget;         return resource.request(javax.ws.rs.core.MediaType.APPLICATION_XML).get(responseType);     }          public void close() {         client.close();     }          }      This line of code then returned an xml result of the query               result = c.findAll_XML(String.class);      which had this format               <?xml version="1.0" encoding="UTF-8" standalone="yes"?>     <userss>     <users>         <userCategoryId>             <categoryId>2</categoryId>             <userCategory>admin</userCategory>         </userCategoryId>         <userName>admin</userName>         <userPassword>d033e22ae348aeb5660fc2140aec35850c4da997</userPassword>     </users>     </userss>      However, this line of code               List<Users> l = (List<Users>)c.findAll_XML(Users.class);      produces an exception, which seems to be caused by the "userss" tag that surrounds the xml result, I'm not sure how that came about. Can anyone help me resolve this?               Exception in thread "AWT-EventQueue-0" javax.ws.rs.BadRequestException: HTTP 400 Bad Request     at org.glassfish.jersey.message.internal.AbstractRootElementJaxbProvider.readFrom(AbstractRootElementJaxbProvider.java:124)     at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$TerminalReaderInterceptor.aroundReadFrom(ReaderInterceptorExecutor.java:188)     at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor.proceed(ReaderInterceptorExecutor.java:134)     at org.glassfish.jersey.message.internal.MessageBodyFactory.readFrom(MessageBodyFactory.java:988)     at org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:833)     at org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:768)     at org.glassfish.jersey.client.InboundJaxrsResponse.readEntity(InboundJaxrsResponse.java:96)     at org.glassfish.jersey.client.JerseyInvocation.translate(JerseyInvocation.java:740)     at org.glassfish.jersey.client.JerseyInvocation.access$500(JerseyInvocation.java:88)     at org.glassfish.jersey.client.JerseyInvocation$2.call(JerseyInvocation.java:650)     at org.glassfish.jersey.internal.Errors.process(Errors.java:315)     at org.glassfish.jersey.internal.Errors.process(Errors.java:297)     at org.glassfish.jersey.internal.Errors.process(Errors.java:228)     at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:421)     at org.glassfish.jersey.client.JerseyInvocation.invoke(JerseyInvocation.java:646)     at org.glassfish.jersey.client.JerseyInvocation$Builder.method(JerseyInvocation.java:375)     at org.glassfish.jersey.client.JerseyInvocation$Builder.get(JerseyInvocation.java:275)     at service.Client.findAll_XML(Client.java:83)     at examples.Find.<init>(Find.java:44)     at examples.Find$1.run(Find.java:166)     at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)     at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:744)     at java.awt.EventQueue.access$400(EventQueue.java:97)     at java.awt.EventQueue$3.run(EventQueue.java:697)     at java.awt.EventQueue$3.run(EventQueue.java:691)     at java.security.AccessController.doPrivileged(Native Method)     at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)     at java.awt.EventQueue.dispatchEvent(EventQueue.java:714)     at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)     at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)     at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)     at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)     at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)     at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)      Caused by: javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"userss"). Expected elements are <{}userCategory>,<{}users>     at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext.handleEvent(UnmarshallingContext.java:681)     at com.sun.xml.internal.bind.v2.runtime.unmarshaller.Loader.reportError(Loader.java:247)     at com.sun.xml.internal.bind.v2.runtime.unmarshaller.Loader.reportError(Loader.java:242)     at com.sun.xml.internal.bind.v2.runtime.unmarshaller.Loader.reportUnexpectedChildElement(Loader.java:109)     at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext$DefaultRootLoader.childElement(UnmarshallingContext.java:1086)     at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext._startElement(UnmarshallingContext.java:510)     at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext.startElement(UnmarshallingContext.java:492)     at com.sun.xml.internal.bind.v2.runtime.unmarshaller.SAXConnector.startElement(SAXConnector.java:163)     at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.startElement(AbstractSAXParser.java:509)     at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(XMLNSDocumentScannerImpl.java:378)     at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl$NSContentDriver.scanRootElementHook(XMLNSDocumentScannerImpl.java:604)     at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:3122)     at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(XMLDocumentScannerImpl.java:880)     at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:606)     at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:117)     at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:510)     at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:848)     at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:777)     at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:141)     at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1213)     at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:649)     at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:243)     at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:214)     at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:140)     at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:123)     at org.glassfish.jersey.message.internal.XmlRootElementJaxbProvider.readFrom(XmlRootElementJaxbProvider.java:140)     at org.glassfish.jersey.message.internal.AbstractRootElementJaxbProvider.readFrom(AbstractRootElementJaxbProvider.java:122)     ... 33 more


title: Whether to store all numbers or just their ranges in database for this application

text: I'm developing a (`PHP MySQL`) Web App which will sell dynamically generated real time cell phone numbers for cellular companies. A company will ask for, say, a thousand numbers and this app will check for available numbers and provide them. The number will be an 8 digit figure. The first `two digits` of the number will mostly be fixed as specific `codes` for a particular company, rest of the digits will be dynamically generated. My question is whether               a) I should store all the sold numbers in database, if yes then:        i)  Separate number in separate row or        ii) All the numbers in a single row          b) Should store range of numbers i.e 32500001-32510000      Keeping performance and ease of handling the algorithm in mind, kindly suggest me your solution.


title: Adding an update feature to a web application

text: I'm interested in the best approach to adding auto update functionality to a web application. Currently   * The patches are downloaded from the softwares support site   * Uploaded to the host server(s)   * Extracted   * The patch process is run The patch process needs to know a few things, specifically the webroot of the application and the database host, name and user in order to run migrations between the point releases. What I would like to see happen if implement a module inside the application which using some technology similar to cURL fetches the latest package, extracts it and runs the necessary command to apply the patch. However I don't think the end user should be expected to know the specifics of the server. e.g. the location of the application, the database host, user and password. I'm thinking the best way to secure this information would be a separate database table accessed by the update module using the users existing login credentials (provided they had necessary privileges to update the installation) What other considerations do I need to take into account? Are there any factors I have overlooked?


title: What is the relationship between the business logic layer and the data access layer?

text: I'm working on an MVC-ish app _(I'm not very experienced with MVC, hence the "-ish")_. My model and data access layer are hard to test because they're very tightly coupled, so I'm trying to uncouple them. What is the nature of the relationship between them? Should just the model know about the DAL? Should just the DAL know about the model? Or should both the model and the DAL be listeners of the other? * * * In my specific case, it's:   * a web application   * the model is client-side (javascript)   * the data is accessed from the back-end using Ajax   * persistence/back-end is currently PHP/MySQL, but may have to switch to Python/GoogleDataStore on the GAE


title: What to do with a long unfinished project?

text: I am a programmer hobbyist (self learnt), and once in a while I like to make games and interactive scripts (nowadays mostly in JavaScript for its ease). Sometimes I start long projects that end up being forgotten because of other things I have to do. Sometimes a project gets really big (say, 3000 lines is a huge deal to me). My code is mostly uncommented, unorganized, and unoptimised and some of my projects are never finished. **Question:**   * What do programmers (or teams), do with such projects ?   * Is there a recommended practice regarding this issue in the "real world"?


title: Working with CPU cycles in Gameboy Advance

text: I am working on an GBA emulator and stuck at implementing CPU cycles. I just know the basic knowledge about it, each instruction of ARM and THUMB mode as each different set of cycles for each instructions. Currently I am simply saying every ARM instructions cost 4 cycles and THUMB instructions cost 2 cycles. But how do you implement it like the CPU documentation says? Does instruction cycles vary depending on which section of the memory it's currently accessing to? http://nocash.emubase.de/gbatek.htm#cpuinstructioncycletimes According to the above specification, it says different memory areas have different waitstates but I don't know what it exactly mean. Furthermore, what are Non-sequential cycle, Sequential cycle, Internal Cycle, Coprocessor Cycle for? I saw in some GBA source code that they are using PC to figure out how many cycles each instruction takes to complete, but how are they doing it?


title: How can I create Assert.AreEqual(myobject,somevariable) a test in TDD before writing production code?

text: Im researching TDD, I'm not really sure how to write a test before I have written production code. The problem is that TDD states that you make assertions and then write your code so that these assertions pass. But You have not created any classes yet (as part of the production code) so how are you meant to write the tests if you dont have any classes with which to assert. Hope someone can explain....


title: Functional Programming For Embedded Software

text: I was discussing F# and Functional Programming with a friend last night and he brought up an interesting question to me. How would you do embedded software in functional? I mean this seems like a fairly natural fit in terms of stateless code but embedded also entails being very frugal with memory and I'm not sure of the story for functional in that regard. Any suggestions about languages or packages for embedded with functional?


title: How to avoid model duplication in JavaEE web applications with a JSON front end

text: Recently we developed a web app that uses the following tech stack:   * hibernate as orm   * spring   * extjs (MVC javascript front end) For 1 business object, let it be a Personnel, we have: 1) a Personnel class (hibernate) 2) PersonnelDTO (will explain why we needed this) 3) a Personnel javascript model for Extjs (I don't know may be other javascript UI frameworks does not need a model defined) Need for number 2 arised when we couldn't deal with sending hibernate objects back and forth, dealing with sessions and circular references etc. etc. Plus, in some cases you need a fully filled Personnel object (full fields joined), sometimes just a few fields and a relation. Sometimes you need all the info to process a Personnel but you can't send it all the way to the client (security, privacy reasons). So we used DTO's to decouple model objects and objects that will be sent through the wire. Adding-removing a field in such a project design becomes very tedious and error prone. Adding a field requires:   * add to DB tables   * add to model object   * add to DTO   * add to model -> DTO converter (when it's a field that can't be automatically mapped) regarding different scenarios that requires different amount of information about model   * add to Extjs model   * add to CRUD forms on the page   * add to client and server validators... Isn't there a better approach to building similar applications? We are thinking of starting a new project and don't want to make the same mistakes.


title: How does one learn QA?

text: When starting to learn programming you would usually point someone over to Code Academy, or Learn Python the Hard Way or even The C Programming language and tell them start writing code until it works.   But how would one proceed if he wants to learn QA? More specifically, a programmer who wants to learn about the QA process and how to manage a good QA methodology. I was given the role of jumpstarting a QA process in our company and I'm a bit lost, what are the different types of testing (system, integration, white box, black box) and which are most important to implement first? How would one implement them?


title: Creating a web app that authenticates users from two different databases

text: I am in a bit of an awkward programming situation, and it will help me a lot to get your input in this situation. I am building a web app which expects to authenticate users from another, separate application (through API calls), and also authenticate users from it's own database. Essentially, there are two separate user bases. Let's say the app I'm building is App1, and the other app which I'm making API calls to is App2. This communication is only one-way; App1 makes API calls to App2, but App2 does not make calls to App1. Users can register in App1 and create an account in App1's database - but during this process, App1 makes an API call to App2 to make sure the email/username being entered into App1 is not already present in App2. Now, the other side of this. If a user is already registered in App2, they do not need to go and register again in App1. They can simply go to App1 and log in. In doing so, App1 sends an API call to App2 to authenticate the user, and creates a copy of the App2 user's account in it's own (App1) database. Problems arise when there are two distinct users, one in App1, and the other in App2, that share the same username. Now, when the App2 user attempts to log into App1, there will exist two users in App1 with the same username! How can a scenario like this be avoided? Is this even a place I want to be (working with App2's user base)?


title: Public API Facade with Micro Services

text: Consider a micro service infrastructure in which each service is responsible for one set of activities, and exposes a RESTful interface to its functionality. For example, assume a chat application. We might have one service which is responsible for creating users, and a second service that is responsible for creating messages. Now, we want to create a public-facing REST interface to the application. Are there any best practices for creating this public facade to the micro services? I'm interested in a couple of things, mainly:   1. Which layer should handle authentication/authorization (if the underlying services - do they share this data or each implement their own auth)   2. Clearly in this application messages are sent from users to users. However the message service can easily be written in such a way to be usable for anything. Should the public proxy be the one to determine the user information and then delegate to a message service?


title: Which JSON Module Should I Download?

text: I see there are many modules available to use with Python for using JSON. Now I am a bit confused! I see people are talking about SimpleJSON also there are references to DemJSON and also good words for Metamagic JSON. Now my question is which one is best module for Python? Specially for Python 3.4 version???


title: How does the CPU know when it received RAM data and instructions?

text: Well, the title is pretty much self explanatory, but I'll expound it a bit, and say the origin of my question. So, I've been wondering as to how the CPU knows when it received the RAM. I'm pretty sure it doesn't OR the RAM outputs together, because 0x00 is still a number, yet ORing that together says that the RAM has not outputed anything. Does the RAM have some kind of "request acknowledged" line? Well, my friend was making an MC CPU, and he used interrupts for RAM reading, so that's where I got this idea. Anyways, the origin of my problem is probably when I was thinking about Virtual Memory. In virtual memory, you have to fetch from the disk and to the RAM. How does one compensate for the gap between the speeds? May this be answered too?


title: What sources of sample work should be used in a job interview?

text: One of my friends has been laid off. When I talked to him, he said they didn't let him take a copy of anything he worked on. When he asked how to show what he worked on to another employer in an interview, he was told that he will have some explaining to do. Should we, as programmers, be allowed to take samples of our previous work former employers? What sources of code should we be expected to show off in an interview? When almost every employer asks for sample work, how are we to justify what can be sent? Is it our responsibility to maintain after-work projects for our entire life so we have code we can legally show to our next employer?


title: Using prefix incremented loops in C#

text: Back when I started programming in college, a friend encouraged me to use the prefix incrementation operator `++i` instead of the postfix `i++`, citing that there was a slight chance of better performance with no real chance of a downside. I realize this is true in C++, and it's become a general habit that I continue to do. I'm led to believe that it makes little to no difference when used in a loop in C#, regardless of data type. Apparently the ++ operator can't be overridden. Nevertheless, I like the appearance more, and don't see a direct downside to it. It did astonish a coworker just a moment ago though, he made the (fairly logical) assumption that my loop would terminate early as a result. He's a self-taught programmer, and apparently never came across the C++ convention. That made me question whether or not the equivalent behavior of pre- and post- fix increment and decrement operators in loops is well known enough. **Is it acceptable for me to continue using`++i` in looping constructs because of style preference, even though it has no real performance benefit? Or is it likely to cause confusion amongst other programmers?** * * *   * Note: This is assuming the `++i` convention is used consistently throughout all code.


title: Getting URLs from search results

text: After 1 months research I basically give up on getting all URL's from a search results programmatically, I looked at Google Search API to find a way to get millions of search results "URL's" to be specific to a text file or something relative but no success, but I am 100% there must be a way or trick of doing it. Real Question : Is there anyway programmatically or manually I can get 1000+ search results (URLs using search query e.g. "Apple" returns million of results on google and I want as much as possible URLs of them results in a text file) Note : Don't care for any specific search engine or programming language or technique or software or just point me to right direction, but yeah I tried it with google API i can't get more then 100 results at all.


title: Roadblock-confused about structure of program

text: I'm new to programming, and I'm working in C. I know that this is structured programming but if I use blocks, say for local variables:               {      int i;      for(i=0; i<25; i++){        printf("testing...\n");        }     }      Doesnt this make it kind of object oriented-like? Is this still structured?


title: Who should train new programmers? Junior or senior programmers?

text: On my team, we often require the most senior programmers to train/mentor the brand new junior programmers. However, these same senior programmers are the ones who are doing the bulk of the real, important work. I've tried to argue to my manager that it makes sense to have the junior programmers, who are showing a high aptitude, take the new programmers under their wing. First off, it will free up the senior developers to work on more important initiatives (not that mentoring isn't important). Next, it will give the junior programmers a bit of pride in their job that they would be looked to for such a responsibility and they may learn something in teaching. Finally, it will save the company money, as senior developers cost a great deal more than juniors. My boss has failed to be persuaded since this is how it has worked on this team since the beginning of time, apparently. Assuming that the decision has been made that some sort of training/mentoring is mandatory, can anyone provide me with some better arguments or tell me why I am wrong? What does your team do? **We can all agree that seniority does not necessarily denote competence so just assume by "senior programmers" i mean "top programmers".


title: Can I re-license Academic Free License code under 2-Clause BSD / ITC?

text: I want to fork a piece of code licensed under the Academic Free License. For the project, it would be preferable to re-license it under the ISC License or the 2-Clause BSD license, which are equivalent. I understand that the AFL grants me things such as limitation of liability, but licensing consistency is much more important to the project, especially since we're talking about just 800 lines of code, a quarter of which I've modified in some way. And it's very important for me to give these changes back to the community, given the fact that this is software relevant to security - I need the public scrutiny that I'll get by creating a public fork. In short: At the top of the file I want to say this, or something like it:               # Licensed under the Academic Free License, version 3     # Copyright (C) 2009 Original Author          # Licensed under the ISC License     # Copyright (C) 2012 Stefano Palazzo     # Copyright (C) 2012 Company      Am I allowed to do this? My research so far indicates that it's not clear whether the AFL is GPL- Compatible, and I can't really understand any of the stuff concerning re- licensing to other permissive licenses. As a stop gap, I would also be okay with re-licensing under the GPL, however: I can find no consensus (though I can find disagreement) on whether this is allowed at all, and I don't want to risk it, of course. * * *   * Wikipedia: ISC License   * Wikipedia: Academic Free License


title: GPL - what is distribution?

text: An interesting point came up on another thread about _alleged_ misappropriation of a GPL project. In this case the enterprise software was used by some large companies who essentially took the code, changed the name, removed the GPL notices and used the result. The point was - if the company did this **and** only used the software internally then there isn't any distribution and that's perfectly legal under GPL. Modifications by their own employees for internal use would also be allowed. _So At what point does it become a distribution?_   Presumably if they brought in outside contractors under 'work for hire' their modifications would also be internal and so not a distribution. If they hired an external software outfit to do modifications and those changes were only used internally by the company - would those changes be distributed? Does the GPL apply to the client or to the external developers? If the company then give the result to another department, another business unit, another company? What if the other company is a wholly owned subsidiary? ps. yes I know the _answer_ is ask a lawyer. But all the discussion I have seen over GPL2/GPL3 _distribution_ has been about webservices - not about internal use.


title: Python Coding standards vs. productivity

text: I work for a large humanitarian organisation, on a project building software that could help save lives in emergencies by speeding up the distribution of food. Many NGOs desperately need our software and we are weeks behind schedule. One thing that worries me in this project is what I think is an excessive focus on coding standards. We write in python/django and use a version of PEP0008, with various modifications e.g. line lengths can go up to 160 chars and all lines should go that long if possible, no blank lines between imports, line wrapping rules that apply only to certain kinds of classes, lots of templates that we must use, even if they aren't the best way to solve a problem etc. etc. One core dev spent a week rewriting a major part of the system to meet the then new coding standards, throwing away several suites of tests in the process, as the rewrite meant they were 'invalid'. We spent two weeks rewriting all the functionality that was lost, and fixing bugs. He is the lead dev and his word carries weight, so he has convinced the project manager that these standards are necessary. The junior devs do as they are told. I sense that the project manager has a strong feeling of cognitive dissonance about all this but nevertheless agrees with it vehemently as he feels unsure what else to do. Today I got in serious trouble because I had forgotten to put some spaces after commas in a keyword argument. I was literally shouted at by two other devs and the project manager during a Skype call. Personally I think coding standards are important but also think that we are wasting a lot of time obsessing with them, and when I verbalized this it provoked rage. I'm seen as a troublemaker in the team, a team that is looking for scapegoats for its failings. Since the introduction of the coding standards, the team's productivity has measurably plummeted, however this only reinforces the obsession, i.e. the lead dev simply blames our non-adherence to standards for the lack of progress. He believes that we can't read each other's code if we don't adhere to the conventions. This is starting to turn sticky. Now I am trying to modify various scripts, autopep8, pep8ify and PythonTidy to try to match the conventions. We also run pep8 against source code but there are so many implicit amendments to our standard that it's hard to track them all. The lead dev simple picks faults that the pep8 script doesn't pick up and shouts at us in the next stand-up meeting. Every week there are new additions to the coding standards that force us to rewrite existing, working, tested code. Thank heavens we still have tests, (I reverted some commits and fixed a bunch of the ones he removed). All the while there is increasing pressure to meet the deadline. I believe a fundamental issue is that the lead dev and another core dev refuse to trust other developers to do their job. But how to deal with that? We can't do our job because we are too busy rewriting everything. I've never encountered this dynamic in a software engineering team. Am I wrong to question their adherence to coding standards? Has anyone else experienced a similar situation and how have they dealt with it successfully? (I'm not looking for a discussion just actual solutions people have found)


title: How do I Export to excel on aspx page?

text: I am trying to take data that I request from an access database and put it into and excel file on the client computer. I usually use ajax to request a summary of the data I need. It is formatted into an html table. I need that table to be in an excel format for the user to download. What I have tried already is to use the vb.net code to open excel and silently save the data to a file, however I realized it's the server side that opens excel, not the client side, in my locally testing of the code, excel would open on my machine and create the file. When running this on the network, I realized excel isn't on the server, I am not sure if I should just install it or try stream the file?


title: Laptops or Notebooks in a meeting?

text: Is taking the laptop to the meeting a good idea? Of course, the project leader needs to have one -- but the programmers -- especially those who only need to get straight instructions on what to do next on the project -- do they need to take laptops? I feel it takes longer to save notes in a software -- and it's lot easier to just jot down "things to do" in a simple note book. That way you can keep up with the discussion and not lose track of what someone else is saying by spending too much time entering text in the machine.


title: is Microsoft LC random generator patented?

text: I need a _very_ simple pseudo random generator (no any specific quality requirements) and I found Microsoft's variant of LCG algorithm used for rand() C runtime library function fit my needs (gcc's one seems too complex). I found the algorithm here: http://rosettacode.org/wiki/Linear_congruential_generator#C However, I worry the algorithm (including its "magic numbers" i.e coefficients) may by patented or restricted for use in some another way. Is it allowed to use this algorithm without any licence or patent restrictions or not? I can't use library rand() because I need my results to be exactly reproducible on different platforms


title: Rails-API gem, Is there such thing as an API only application?

text: I've built a few API's using the complete rails stack. In each project there have been multiple uses for rails core features. Each of the API has had management screens for monitoring usage, managing authentication keys, etc. Is there such thing as an API without a management front end?


title: Why use typedefs for structs?

text: in C (ANSI, C99, etc.), structs live in their own namespace. A struct for a linked list might look something like this:               struct my_buffer_type {        struct my_buffer_type * next;        struct my_buffer_type * prev;        void * data;     };      It seems quite natural however for most C programmers to automatically typdef those structs like the following               typedef struct tag_buffer_type {        struct my_buffer_type * next;        struct my_buffer_type * prev;        void * data;     } my_buffer_type;      And then reference the struct like a normal type, i.e. `get_next_element(my_buffer_type * ptr)`. Now my question is: Is there a specific reason for this? Wikipedia says http://en.wikipedia.org/wiki/Typedef#Usage_concerns > Some people are opposed to the extensive use of typedefs. Most arguments > center on the idea that typedefs simply hide the actual data type of a > variable. For example, Greg Kroah-Hartman, a Linux kernel hacker and > documenter, discourages their use for anything except function prototype > declarations. He argues that this practice not only unnecessarily obfuscates > code, it can also cause programmers to accidentally misuse large structures > thinking them to be simple types.[4] > > Others argue that the use of typedefs can make code easier to maintain. K&R > states that there are two reasons for using a typedef. First, it provides a > means to make a program more portable. Instead of having to change a type > everywhere it appears throughout the program's source files, only a single > typedef statement needs to be changed. Second, a typedef can make a complex > declaration easier to understand. I personally wonder if there is not enough benefit of having the separate `struct` namespace to sometimes not use typedef'd structs and since there are several C programming cultures around (Windows C programming has different traditions than Linux C programming in my experience) if there are other traditions that I am not aware of. Then I am interested in historical considerations (predecessors, first versions of C).


title: Why does Javascript use JSON.stringify instead of JSON.serialize?

text: I'm just wondering about _"stringify"_ vs _"serialize"_. To me they're the same thing (though I could be wrong), but in my past experience (mostly with asp.net) I use `Serialize()` and never use `Stringify()`. I know I can create a simple alias in Javascript,               // either     JSON.serialize = function(input) {         return JSON.stringify(input);     };          // or     JSON.serialize = JSON.stringify;      http://jsfiddle.net/HKKUb/ but I'm just wondering about the difference between the two and why stringify was chosen. * * * for comparison purpose, here's how you serialize XML to a String in C#               public static string SerializeObject<T>(this T toSerialize)     {         XmlSerializer xmlSerializer = new XmlSerializer(toSerialize.GetType());         StringWriter textWriter = new StringWriter();              xmlSerializer.Serialize(textWriter, toSerialize);         return textWriter.ToString();     }


title: Naming variables with fixed point units

text: What should I name a variable that has units with a fixed point?               int herpLimitLo_psig2 = 6000; // 60.00 psig     int derpLimitLoPsigwithtwodigits;     int herpLimitHiPsigfixedtwo;     int herpLimitHi_psig_timesOneHundred;      Apparently I suck at naming things.


title: Use Generic of Specific Function names for similar objects

text: Is there a school of thought on putting focus on using generic names for functions, opposed to naming functions based on the things they do? **Example** Say we have a `Bill / Price Sheet` object, that has line items               Bill:     * Shipping Charge  $5.00     * Crate Charge $6.00     * Tax Charge $8.00      Generic function names would be:               //function's code knows how to add a line item     bill->addLineItem("Shipping Charge", 5);     bill->addLineItem("Crate Charge", 6);     bill->addLineItem("Tax Charge", 8);      Specific function names would be:               //function's code reflects knowledge of this specific line item     bill->addShippingCharge(5);       bill->addCrateCharge(6);     bill->addTaxCharge(8);      This can be extended to any set of similar actions where something similar is being done. A more generic function takes the actual parameter, and can be deemed more flexible - any new line item can be added using the same function. A more specific function can only be used for that particular line item. Adding a new type of line item requires a new function. Something tells me that the specific way is more preferred, but I can't verbalize why, and maybe I am wrong. But perhaps it makes the code more clear as to what this line item is intended to do. So if specific naming is superior, and I am writing code for a restaurant with 600 items on the menu (such restaurants do exist), I am not sure I want to have 600 unique functions for each menu item. But in that case maybe a different approach is warranted. So what I am asking here, is if I have a reasonable class of items (i.e. 10-20) for my specific possible line item list, would you recommend any particular approach from the ones described (specific vs general), or does it all depend on my project specifics?


title: Is there a general pattern that could be used to describe Data Migration?

text: In our company we have to dismiss a software and introduce a new one. I have received the task to follow and take care of the whole data migration.   We use 3 different data sources (each containing different kind of information), whose records have to be merged into a unique target DB. Since the new DB has a different schema also some mapping steps are required to coincile data from the two environments. Technically it is everything clear, but I have to describe in a "proof of concept" the migration process. **About data migration is there a general pattern that could be used to describe it?** I will describe the involved systems, which data will be moved, the mapping tables used and the planned tests to ensure data quality. However can anyone suggest a different approach? Maybe in this way I can realize that I am missing something in my documentation.


title: Javascript MVC application design (canvas)

text: I'm having difficulty grasping how to structure/architect a canvas application using an MVC like approach in Javascript. UI will be fairly fluid and animated, the games fairly simplistic but with heavy emphasis on tweening and animation. I get how MVC works in principle but not in practice. I've googled the buggery out of this, read an awful lot, and am now as confused as I was when I started. Some details about the application area:   * multi screen game framework - multiple games will sit within this framework common UI "screens" include: settings, info, choose difficulty, main menu etc.   * multiple input methods   * common UI elements such as top menu bar on some screens   * possibility of using different rendering methods (canvas/DOM/webGL) At the moment I have an AppModel, AppController and AppView. From here I was planning to add each of the "screens" and attach it to the AppView. But what about things like the top menu bar, should they be another MVC triad? Where and how would I attach it without tightly coupling components? Is it an accepted practice to have one MVC triad within another? i.e. can I add each "screen" to the AppView? Is "triad" even an accepted MVC term?! My mind is melting under the options... I feel like I'm missing something fundamental here. I've got a solution already up and running without using an MVC approach, but have ended up with tightly coupled soup - logic and views and currently combined. The idea was to open it up and allow easier change of views (for e.g. swapping out a canvas view with a DOM based view). Current libraries used: require.js, createJS, underscore, GSAP, hand rolled MVC implementation Any pointers, examples etc., particularly with regards to the actual design of the thing and splitting the "screens" into proper M, V or C would be appreciated. ...or a more appropriate method other than MVC _[NB, if you've seen this question before it's because I asked it in 2 other incorrect stackexchange communities... my brain has stopped functioning]_


title: Jenkins: .NET website XML transforms, but no .sln or build file

text: We're setting up Jenkins for CI and deployments. We have .NET website that isn't managed through visual studio. Its a Logi Analytics application, so we develop exclusively through LogiStudio. As such, there are no build files (.sln). However, there are web config and other XML files that need to change depending on the environment they are deployed in. Slow Cheetah looks like a good solution for transforming non-web.config xml files, but again the problem is we aren't managing this as a visual studio solution, ergo no .sln file. In the past I would have used NAnt for this kind of thing, but I like the MS convention used by slow cheetah for defining transformations. I'd hate to have to put the application in a solution just to make this work, and I'm hoping to get away from NAnt since I'm the only one around here that is comfortable using and maintaining NAnt scripts. Are there any great options out there that I'm missing?


title: Mimicking a bluetooth disconnection

text: I've written a program to control a bluetooth device. I'm trying to test cases when the bluetooth disconnects, i.e. if its out of range. Physically taking the device out of range is one possibility, but its quite cumbersome and I have to go outside my office to achieve this. What can I do to trigger a disconnection? Is there, for example, an interferer I can setup, say with an Android phone, that would make the connection drop? Or limit the Bluetooth transmit power? Any other possibilities?


title: Why are exception specifications bad?

text: Back in school some 10+ years ago, they were teaching you to use exception specifiers. Since my background is as one of them Torvaldish C programmers who stubbornly avoids C++ unless forced to, I only end up in C++ sporadically, and when I do I still use exception specifiers since that's what I was taught. However, the majority of C++ programmers seem to frown upon exception specifiers. I have read the debate and the arguments from various C++ gurus, like these. As far as I understand it, it boils down to three things:   1. Exception specifiers use a type system that is inconsistent with the rest of the language ("shadow type system").   2. If your function with an exception specifier throws anything else except what you have specified, the program will get terminated in bad, unexpected ways.   3. Exception specifiers will be removed in the upcoming C++ standard. Am I missing something here or are these all the reasons? My own opinions: Regarding 1): So what. C++ is probably the most inconsistent programming language ever made, syntax-wise. We have the macros, the goto/labels, the horde (hoard?) of undefined-/unspecified-/implementation-defined behavior, the poorly-defined integer types, all the implicit type promotion rules, special- case keywords like friend, auto, register, explicit... And so on. Someone could probably write several thick books of all the weirdness in C/C++. So why are people reacting against this particular inconsistency, which is a minor flaw in comparison to many other far more dangerous features of the language? Regarding 2): Isn't that my own responsibility? There are so many other ways I can write a fatal bug in C++, why is this particular case any worse? Instead of writing `throw(int)` and then throwing Crash_t, I may as well claim that my function returns a pointer to int, then make a wild, explicit typecast and return a pointer to a Crash_t. The spirit of C/C++ has always been to leave most of the responsibility to the programmer. What about advantages then? The most obvious is that if your function tries to explicitly throw any type other than what you specified, the compiler will give you an error. I believe that the standard is clear regarding this(?). Bugs will only happen when your function calls other functions that in turn throw the wrong type. Coming from a world of deterministic, embedded C programs, I would most certainly prefer to know exactly what a function will throw at me. If there is something in the language supporting that, why not use it? The alternatives seem to be:               void func() throw(Egg_t);      and               void func(); // This function throws an Egg_t      I think there is a big chance that the caller ignores/forgets to implement the try-catch in the second case, less so in the first case. As I understand it, if either one of these two forms decides to suddenly throw another kind of exception, the program will crash. In the first case because it isn't allowed to throw another exception, in the second case because nobody expected it to throw a SpanishInquisition_t and therefore that expression isn't caught where it should have been. In case of the latter, to have some last resort catch(...) at the highest level of the program doesn't really seem any better than a program crash: "Hey, somewhere in your program something throwed a strange, unhandled exception.". You can't recover the program once you are that far from where the exception was thrown, the only thing you can do is to exit the program. And from the user's point-of-view they couldn't care less if they get an evil message box from the OS saying "Program terminated. Blablabla at address 0x12345" or an evil message box from your program saying "Unhandled exception: myclass.func.something". The bug is still there. * * * With the upcoming C++ standard I'll have no other option but to abandon exception specifiers. But I would rather hear some solid argument why they are bad, rather than "His Holiness has stated it and thus it is so". Perhaps there are more arguments against them than the ones I listed, or perhaps there is more to them than I realize?


title: Function declaration as var instead of function

text: More and more I'm seeing functions being declared like               var foo = function() {              // things     };      Instead of how I had learned, like               function foo() {              // things     }      What's the difference? Better performance? Scope? Should I be using this method?


title: Handling internal IT issues

text: In the company I work at, developers also serve as internal tech support. This means we have to do three types of things:   * **Development:** writing actual code to implement new features and new products   * **Maintenance:** handle bugs and minor changes with existing customer-facing software   * **Tech support:** handle internal issues other employees have e.g. locked out of AD, network drive is missing, internet is down, new software installation, need permissions changes, etc. The tech support aspect of my job is the most troubling right now. This is because:   * someone with a problem will likely interrupt you immediately, taking you away from development   * problems come in too many ways: email, google chat, phone call, post-it notes on your desk, etc.   * people often cannot or do not determine the severity or scope of their problem before asking for help, i.e. simple problems that inconvenience one person might come in the same way -- and often with the same urgency -- as major customer-facing issues that could affect thousands **My question is: What are the proven methods for dealing with internal IT issues?** Should we use software designed for this purpose? If so, how should it be separated from any software used for customer-facing issues or bug tracking software? How can the IT/development department ensure it's used properly? Also, is it a problem that developers handle these internal problems in the first place? Would it be ideal to have a separate person or department to handle these types of problems?


title: Sequel vs S-Q-L

text: > **Possible Duplicate:**   >  What's the history of the non-official pronunciation of SQL? I hear it every so often, "In sequel server...", and for some reason I cringe every time. Maybe it's because SQL doesn't mean sequel, it means Structured Query Language. However, I hesitate to mention anything because it is a little bit nitpicking after all. I do see the resemblance between SQL and sequel, but it's still wrong, is it not? Where does this way of phrasing come from?


title: PHP function __autoload($class_name) how to Load two class path directories

text: I am using following function to autoload classes, it works fine if i am using only one directory called 'classes' however when i try to use Smarty lib also it fails and give me the error               Fatal error: Class 'Database' not found in /home/...      for ex:               require_once(DOC_ROOT."/libs/Smarty.class.php");     function __autoload($class_name) {            require_once( CLASS_LIB."/".$class_name . '.class.php');     }     $db = new Database();     $session=new Session();     $smarty = new Smarty();      but if i do this it give me the error unable to load the smarty class..               function __autoload($class_name) {            require_once( CLASS_LIB."/".$class_name . '.class.php');         require_once(DOC_ROOT."/libs/Smarty.class.php");     }          $db = new Database();     $session=new Session();     $smarty = new Smarty();          Warning: require_once(/home/.../classes/Smarty_Internal_TemplateCompilerBase.class.php) [function.require-once]: failed to open stream: No such file or directory in /home/.../includes/init.php       Any idea what i am i doing wrong here ? i need to be able to load classes directory automatically but needs to make sure i dont loose smarty path too..


title: How to validate information on server without using database or session

text: Each user has multiple sites they can access reporting data for in an application I am working on. To prevent having to go to the database on every single request, I validate that they have access to the site only when they change sites and I then store the the current site id in the session. **I am trying to eliminate session state so that my async ajax requests are not synchronized and also so that the user can have a different site open on each browser tab. I also don't want to go back to calling the database on every request to validate that the user has access to the given site making a request.** I've seen implementations where people will encrypt the id on the client, but it's not sure what would prevent a third party from looking over someone's shoulder (seeing the id on the query string perhaps) then using that same id with their own login to make a request. **I have two ideas:** 1) Encrypt the id with the persons authenticated user name as the seed... Then encrypt it again with some private key. When the request comes in I would decrypt with the private key then try to decrypt with the current user name and get the id back. Or perhaps I would combine the user name with the id like username@username.com_[SITEID] then encrypt that with the private key and split them to see if the current username matches the first part. The problem with this though is that it never expires really, so they could in the future make a request even if they have lost access as long as they have the id around. 2) Similar to idea 1, but I would use the session id with encryption as a third key perhaps. The problem here though is if the session expires and they leave a tab open, all the requests would fail from the tab that was left open even though a session is active. 3) Use a cache so that async requests are not affected and just store keys like username@username.com_[VALIDATED_SITE_ID] then see if the key exists when the request comes in and if not, hit the database to establish the validation key. **Has anyone addressed this type of scenario where you need to validate the user can make a specific type of request, yet you doing it without session or hitting the database every time a request is made?**


title: What's in the "contrib" folder?

text: Often open-source software projects have a folder called "contrib". For example, Django has one. What is it for?


title: Where should you put functions and variables that are only needed by one function in a class?

text: Say you have a Car class. Properties that make sense for a Car class might be:               var make;     var model;     var year;     var turnOn; // a function      But the `turnOn` function is very complicated and ends up needing a static variable and a couple sub functions:               var isTurningOn; // too specific to be a class variable     function turnOn() {         // 30 lines to start the engine         // 30 lines to start the air conditioner         // 30 lines to start the radio     }      So now we have a function that maybe isn't really suitable to be made into its own class and it's polluting the Car class with a variable that only the `turnOn` function ever uses. Plus the function contains sections of code that should be made into their own functions. So what do you do in situations like this?


title: What is the proper way to implement the OnClickListener interface for many buttons

text: My Android Activity contains multiple buttons that all need an OnClickListener. I've seen lots of different ways of doing this such as::   * Implementing the interface in activity class   * Creating a separate class that implements the interface   * Defining an anonymous inner class for each button. I've seen many examples of each approach. However, its not clear to me why one approach would be used instead of another. Are the differences between these approaches stylistic or are there reasons that make one approach better?


title: How do mashups work with same-orgin policy?

text: If Javascript is only allowed to access scripts from the same domain, how can a website create mashups which must read and modify content from another domain?


title: How can I design an efficient moderation system for comments?

text: Here's the job I want to do: My project is a website where there will be a **lot** of comments. Those comments will be moderated: a moderator will connect, see comments and accept or refuse them. I need those things:   * the comments won't have any "moderator" associated. Which implies that when a moderator connects, the system "assigns" the 20 first comments to this moderator then sends them via an AJAX/JSON request   * of course, this implies that those comments musn't be assigned to other moderators How can I make a design so that I'll be sure "getting the 20 first comments for a moderator" can be an atomic operation? And there's another thing to think of (I don't know if it may have an impact or not on my problem): if there are say 10 moderators connected, one of them has 20 comments to validate, and this guy leaves his PC for the whole day. I may implement kindof a "timeout" for this moderator, then, when he tries to validate, a message will tell him "sorry this comment has already been moderated by another moderator", and the AJAX script will get a "fresh new 20 comments). My first idea was the simplest idea:   * a moderator connects   * a jQuery AJAX script asks the server for 20 comments   * the server (1) makes immediately a request of the 20 first free comments to the database   * the server (2) "freezes" the 20 free comments   * the server (3) makes up a JSON response and sends it But the operations (2) and (3) are not atomic, what happens if, in-between, another operator asks for the 20 first free comments? They both will get the 20 first free comments. That's not a good solution. I think this is a classical problem of atomic operation on db. Any idea how to design this (or where to look)? Thank you very much indeed!


title: How to gradually improve on an old IBM Host C++ framework

text: Imagine a C++ framework as a business layer, but with controlling logic as well. E.g. user rights, state of the webflow etc. With some plain C code to access DB2. The whole framework is host based. We are looking for a way to replace the existing framework gradually with a java framework. The main challenges are: the application is already huge, there are several application clients connected to the c++ framework at the same time (it's one web application with many instances), my knowledge of what is possible today with java on host is very limited (since all people I work with stick with C++) Do some good ideas exist for gradually moving the old framework without breaking existing code? I guess as entry one would expect a web service or RMI server for transactions. But how to replace the business/controlling logic gradually is still a black box to me.


title: i am "scared" to learn a new language

text: I have be developing in c# for the last about the last 8 years.   I feel that i am quite experienced and knowledgeable in the whole .net platform. I have got to the point where i want to start learning objective-c. I have been watching dev videos, reading books and researching online. So far i am getting a good idea of the development principals. BUT. I have not written 1 line of code. For some silly reason i have some type of mental block about writing code. I keep thinking: But what if i am not as good as when i do c# coding.   This leaves me in a endless spiral where i cannot code. If you have been in this kind of situation what was the best way to get out of it.


title: What does the term day-one-bug mean?

text: I came across this term recently in a mail chain. Google tells me there is a term zero-day bug and that Microsoft and Adobe are the frontrunners :) Is there such a term as **day one bug**? What might that mean?


I am programming in Windows Forms and MySQL. If I declare this in the program, I can use the connection and command objects in the whole .cs page:                MySqlConnection connection = null;      MySqlCommand command = null;      MySqlDataReader Reader;      But if I write the code below, connection and command objects are declared twice:                private void cmbo_class_SelectedValueChanged(object sender, EventArgs e)             {                 string clas = cmbo_class.SelectedItem.ToString();                                  try                 {                     MySqlConnection connection = new MySqlConnection(hp.myConnStr);                     MySqlCommand command = connection.CreateCommand();                     MySqlDataReader Reader;                     command.CommandText = "select id,code from reg_class_master where name ='" + clas + "' and Delete_Status=0";                     connection.Open();                     Reader = command.ExecuteReader();                     while (Reader.Read())                     {                         class_id = Convert.ToInt32(Reader[0].ToString());                         class_code = Reader[1].ToString();                     }                     connection.Close();                 }                 catch(Exception ex)                 {                     MessageBox.Show("Error in ","Information",MessageBoxButtons.OK,MessageBoxIcon.Information);                 }                      cmbo_division.Items.Clear();                      try                 {                     MySqlConnection connection = new MySqlConnection(hp.myConnStr);                     MySqlCommand command = connection.CreateCommand();                     MySqlDataReader Reader;                     command.CommandText = "select name from reg_division_master where class_id = " + class_id + " and Delete_Status=0 order by display_index";                     connection.Open();                     Reader = command.ExecuteReader();                     while (Reader.Read())                     {                         cmbo_division.Items.Add(Reader[0].ToString());                     }                     connection.Close();                 }                 catch                 {                 }      I think one object declaration is the best way. Do more object declarations affect the program?


title: Does having more classes necessarily increase the memory requirements of the app?

text: When we add .edmx files to a DLL, the physical size of the DLL increases. DLL's are loaded into memory. However, the .NET infrastructure with functionality such as JIT compilation and the GAC complicates things. Is it true that having a larger DLL automatically increase the memory requirements of an application? In other words, are memory concerns a good reason to split generated code such as entity framework into N DLL's?


title: Am I misusing instance initialization?

text: I often write tests when I need to set data object for integration tests involving a few pages with forms. Herein each form on a page could be represented by a different data object class. There are are times when test end up in filling same data for a specific page while varying it for other pages and validating the overall flow. I thought instead of setting data object each time from test method I can take advantage of instance initialization block to set data for tests. Herein I have listed a smaller version of tests I usually write - This my data class which holds data for form values - textbox, drop down etc. I have not kept setters for sake of brevity -               public class DataClass {          private int i;     private int j;          public DataClass() {         i=1;         j=1;     }             public int getI(){         return i;     }          public int getJ(){         return j;     }     }      Following is the helper class which is used by test class to fill form data on page -               public class WorkerClass {          private DataClass data;          public void setData(DataClass data){         this.data = data;            }          public int add() {         return data.getI()+data.getJ();     }          public int substract() {         return data.getI()-data.getJ();     }     }      And here is the test method. Notice that instead of calling setData of WorkerClass in each test method I used instance initialization block -               public class TestClass {          private DataClass data = new DataClass();     WorkerClass workerClass = new WorkerClass();          {         workerClass.setData(data);     }          @Test     public void testAddition() {         assert workerClass.add()==0:"addition Failed";          }          @Test     public void testSubstraction() {         assert workerClass.substract()==0:"substraction failed";             }        }      My question is, am I misusing instance initialization block and should rather be calling it from each test method, even if all the test method require same set of data?


title: Is it worth listing testing or self-learning repositories on my résumé?

text: I have a GitHub repository with toy programs that I write when I learn something. For example, when I read an about an algorithms or data structures, I write up a quick implementation of of it to make sure that it works and I understand it. I sometimes solve algorithm and data structure puzzles and that gets pushed into the repository. Would this repository be worth linking on my résumé, or would it actually be a detriment to my chances of getting hired?


title: What is the biggest weakness of students graduating with degrees in Computer Science?

text: This question is directed more toward employers and graduate student advisors/professors but all opinions are welcome. What do you find is a common weakness of new hires and/or new grad students? Is it entirely variable dependent on the student and his or her university? Is there a particular skill or skillset that you wish new hires/researchers had expertise in and how can we remedey this deficiency? I realize that this question is general and really encapsulates two questions, one more about the weaknesses of new software engineers and one about the weaknesses of new researchers. However, both types of people tend to come from similar courses of study so I'm wondering if there is any overlap. Note: I am not a professor but I'm interested in how best to revise the undergraduate curriculum in CS.


title: How can I gauge a candidate's ability to learn in an interview?

text: We are hiring for a small development department within a medium sized company for which software is not the main line of business. As such, we are attempting to recruit what we have labeled a _Senior Programmer_. The goal is to find someone that can design, implement and maintain entire new and existing systems from the database through to the front-end. Regardless of a candidates claim to experience (read: massively spun CVs), or the results of the technical test, what I really care about is their ability to learn and the speed at which they will pick up technologies or concepts they are not familiar with to fill any gaps they might have in their knowledge. How can I go about getting an idea as to a candidates ability to (or speed of) learning?


title: How is Python used in the real world?

text: I'm looking to get a job as a Python programmer. I know the basics of the language and have created a few games with it using pygame. I've also started to experiment with Django. However, looking at the job market, it doesn't seem very many Python jobs are web-related. On the desktop side of things, it doesn't seem like very many companies use the popular GUI libraries like pyQt or wxPython. How are companies actually using Python? What areas should one focus on to land a job as a Python programmer?


title: What scenarios are implementations of Object Management Group (OMG) Data Distribution Service best suited for?

text: I've always been a big fan of asynchronous messaging and pub/sub implementations, but coming from a Java background, I'm most familiar with using JMS based messaging systems, such as JBoss MQ, HornetQ, ActiveMQ, OpenMQ, etc. I've also loosely followed the discussion of AMQP. But I recently became aware of the Data Distribution Service Specification from the Object Management Group, and found there are a couple of open-source implementations: OpenSplice OpenDDS It sounds like this stuff is focused on the kind of high-volume scenarios one tends to associate with financial trading exchanges and what-not. My current interest is more along the lines of notifications related to activity stream processing (think Twitter / Facebook) and am wondering if the DDS servers are worth looking into further. Could anyone who has practical experience with this technology, and/or a deep understanding of it, comment on how useful it is, and what scenarios it is best suited for? How does it stack up against more "traditional" JMS servers, and/or AMQP (or even STOMP or OpenWire, etc?) Edit: FWIW, I found some information at this StackOverflow thread. Not a complete answer, but anybody else finding this question might also find that thread useful, hence the added link.


title: Use null object as argument to method

text: Consider the following piece of code               class Foo         {         public:         //...             bool valueFirstGet(int& value) const                 {                 if(this==nullptr)                     {return 0;}                 value=values[0];                 return 1;                 }         //...              private:             int* values;             size_t n_values;         };          int main()         {         Foo* obj=findObject("key");         int value;         if(!obj->valueFirstGet(value))             {printf("key does not exist\n");}              return 0;         }      findObject returns nullptr if it cannot find the object. Is it ok to let the member function do the null check instead of its caller. In my code, there are several calls to findObject directly followed by a call to valueFirstGet so leaving the check to the caller makes the code ugly. EDIT: Is there a cleaner way to avoid all null checking besides having findObject to throw an exception instead of returning null? EDIT 2: What about a static wrapper?


title: Best Method of function parameter validation

text: I've been dabbling with the idea of creating my own CMS for the experience and because it would be fun to run my website off my own code base. One of the decisions I keep coming back to is how best to validate incoming parameters for functions. This is mostly in reference to simple data types since object validation would be quite a bit more complex. At first I debated creating a naming convention that would contain information about what the parameters should be, (int, string, bool, etc) then I also figured I could create options to validate against. But then in every function I still need to run some sort of parameter validation that parses the parameter name to determine what the value can be then validate against it, granted this would be handled by passing the list of parameters to function but that still needs to happen and one of my goals is to remove the parameter validation from the function itself so that you can only have the actual function code that accomplishes the intended task without the additional code for validation. Is there any good way of handling this, or is it so low level that typically parameter validation is just done at the start of the function call anyway, so I should stick with doing that.


title: What is the best way to understand code in a project with null documentation?

text: It is our first game and we are a start-up. We had a programmer who suddenly is seeming to be a dead weight. Though we knew him personally we thought that he was as motivated as we are and hence I never looked for a code review or documentation. Now it seems that he is slacking a lot and we want him out. Now during a conversation he said that he would not document the code so as we could be dependent on him. I looked at the code and there is no documentation. The code is all over the place. What would be the best way to understand his code? Details of the code:   * Written in C# and targeting a mobile platform using Unity3D.   * The game play mechanic and camera is scripts are the main and they have no documentation.   * Too much of Send/Broadcast messages so I am not able to see the references through Mono.   * Again hefty use of strings in either invoking methods or passing parameters   * Update function everywhere which could have been reduced to coroutines.   * Naming is poor and inconsistet    * Absolutely no pooling with usage of destroy and instantiation. I am expecting memory leaks. What protocols should I adopt to understand the code and work on top it?


title: Why are brackets required for try-catch?

text: In various languages (Java at least, think also C#?) you can do things like               if( condition )         singleStatement;          while( condition )         singleStatement;          for( var; condition; increment )         singleStatement;      So when I have just one statement, I don't need to add a new scope with `{ }`. Why can't I do this with try-catch?               try         singleStatement;     catch(Exception e)         singleStatement;      Is there something special about try-catch which requires always having a new scope or something? And if so, couldn't the compiler fix that?


title: Get system info from C program?

text: I'm writing a little program in C that I want to use to output some system stats to my HD44780 16x2 character display. The system I'll be working with is a Debian ARM system and, although irrelevant, the display is on the GPIO header.(The system is a Raspberry Pi). As an initial (somewhat unambitious) attempt, I'd like to start with something simple like RAM and CPU usage (I'm new to C). I understand that if I make external command calls I need to fork() and execve() (or some equiv that will let me return the results), what I would like to know is how I go about getting the information I want in a nice clean format that I can use. Surely I will not have to call (for e.g);               free -h      And then use awk or similar to chop out the piece I want? There must be a cleaner way? The question should be seen as more of a generic, what is best practice for getting info about the system in C (the RAM/CPU usage are just an initial example).


title: Asp.Net MVC CMS or Shopping Cart or any other type of System

text: I have been learning Asp.Net MVC for a while now and have gone through numerous tutorial ranging from MVC Music Store to Code-First to Custom Membership to Data Annotations. In essence, I have a firm grip on how things work in this new framework. But, there are few things which i am not able to realize and understand on my own. Stuffs like achieving pagination, product Catalog, AJAX and some other things. Therefore i was thinking of learning and knowing these aspects via any opensource CMS, shopping cart or any other type of system. This way I can see the code and understand how these things can be achieved in Asp.Net MVC. Things were pretty easier in regular Asp.Net as we weren't dealing with the HTML so i am bit sluggish in these departments and need help in small matters like pagination. **So, Are there any available opensource Asp.Net MVC CMS or any other type of system utilizing razor ?**


title: Multiple threads and single output source

text: For the sake of an exercise, say you have an input file with a series of lines of text with the objective of reversing their respective character sequences. Now introduce 5 threads that will each do the reversing, thread 1 taking care of line 1, thread 2 taking care of line 2 and so on. If the aim is to save these reversed lines in order, how would you save them to the same file ? P.S: I've thought of having some kind of queue but there is no guarantee on the order. Also, I'm wondering if there's some way to lock the file temporarily and have a thread wait it's turn. I imagine I should keep track of which line is being saved.


title: Abstracting a zip as a filesystem - C++

text: I would like to access in read and write mode to a zip without decompressing it on disk: what options do I have? I need to perform the usual IO actions reserved for a filesystem like reading, writing new file, deleting them. If it's possible I would like to stick with the zlib library.


title: How to read and understand ER diagrams

text: I've been handed the ER diagram for a quite complex database. Complex to me at least, 849 tables. One of the architects says to understand the code, you need to understand the database and relationships. Now I am basically a Java programmer hence not too familiar with this How do I start? Should I start from something basic like USER or ORDER and see which relationships they have with other tables around them? Any tips or tutorials would help a lot


title: What would you define as sensitive user data?

text: A recent previous question of mine had an answer that sparked a different and unrelated question in my mind: Customer wants to modify the .properties files packaged in our WAR file The question that I thought of after reading this answer is, just how low-risk is the data being collected on people (non-users, lets just say, "people") in my application?   * A first name and last name   * Company or organization that person currently is employed at.   * (Optional) An email address   * (Optional) A persons phone number   * A photograph of the persons face   * An digitally signed PDF document physically signed with electronic signature pad (a persons hand written signature) No other sensitive data like social security numbers, credit card numbers or anything that can accurately identify a person with 100% accuracy. How sensitive would you rate the data types listed above? Is identity theft even remotely possible with the above information? In light of all the recent news outbreaks of hacking successes and data breaches, if such a thing were to happen to my application (assume that I have reasonable security measures, SSL, encrypted passwords with salt, account lock after so many failed attempts, etc...), what kind of a response would be appropriate for my organization in your opinion? Should every attempt be made to notify the persons that this information has been compromised? Is it worth it? Thanks for sharing your thoughts.


title: Is it worth it to translate an Android app into Spanish and other languages?

text: I have the "user's side" of the story, I think they want it better if it's on Spanish. But, what about the programmers? Do you make your programs multi- language? Why? Why not? Who translate your software? Are you ok with paying somebody to translate your app or you prefer doing it yourselves? Is the benefit bigger than the costs?


title: Area calculation of irregular shapes

text: Is there any algo that can help splitting irregular shape into regular shapes, and eventually calculate the area of the main object by summing the areas of those regular objects?


title: Does a group of Select Statements count as a valid model?

text: I'm making a facebook app and I'm trying to follow MVC properly. But I was wondering if I had a class that was a bunch of fql queries (getting data from facebook) should I have keep these in a controller or a model? According to Codeigniter's user guide "Models are PHP classes that are designed to work with information in your database". Since fql interacts with facebook's databases and not my own, would having a class full of what is basically just SQL Select statements count as valid model?


title: what is best way to learn latest technology

text: We have too many technologies in IT world today. How can be best be able to clear technical funda conceptually ? How do we able to find all the concept available within technology & required to be learnt ? Programming Experince always matters, but I want to know the ideas keeping experince aside. I mean like if I start developing a project on my own hand, how do I be able to find out about which latest technology & concepts tha I should use with ? Please suggest.


title: What problems can be solved using Generics?

text: I haven't used Generics in C# for a long while. Every time I think I need to use them I either go in the wrong direction and give up or find that I don't really need them. I feel that I'm missing out or ignoring a technique which could be useful and powerful. I'm aware of how generics are meant to be used (or at least I think I am). If you have three methods that are all doing the same thing with different types, then using generics enables you to have just one method that will work with these three types. EDIT (in response to comment) **Are there any code smells or patterns that I should be looking out for?** Note I use `List<>` a lot, so I'm not ignoring generics in the the standard library. It's just that I've not written custom code using Generics for a while.


title: Audit trails and recording actions

text: **Background** A discussion that has come up at work recently is how we handle audit logging and the recording of events. We are integrating with a 3rd party app so triggers are a no no from the off so we are handling it in code. We've written a number of prototype components for handling it but nothing feels right as yet. The main issue being we want to create Facebook style time lines for the users to see what action have happened recently but these don't seem to fit well with how we record audits. My question is how would be best to handle this type of scenario?   * Should we tailor the audit log tables to fit the requirements of the front end?   * Should we have separate tables to handle the "Actions" and have the events and auditing separate   * Should we look to a more message based architecture so this will be more like an Event sourcing type component?  Input from somebody who has done this type of system would be much appreciated.


title: Want to do some damage control

text: I applied for a job in a company. The initial conversation went well.They sent me an assignment and asked me to write a web application, and send it in a specified time. It seemed fairly simple. I completed and sent it to them. Now my mind is completely revolving on the code that I wrote, and now I feel that, there was one small requirement which I did not fulfill. Before they give the verdict shall I be proactive and admit it. Definitely they will find it and I am certain of it. I can send them email saying that I forgot to add that. What shall I do? Is there anything I do for damage control?


title: For Which Kind of Cache will this Program not run well? How can it be optimized?

text: Consider the following code fragment:               int a[8192], b[8192], c[8192];     int i;     for(i = 0; i < 8192; i++)         c[i] = a[i] + b[i];      For what kind of cache will this program not run well (set associative, direct, associative)? I've been thinking about how to optimize this, but can't really see how it can be done. How can I change this code to have fewer cache misses?


title: Correct terminology in type theory: types, type constructors, kinds/sorts and values

text: In an answer to a previous question, a small debate started about correct terminology for certain constructs. As I did not find a question (other than this or that, which is not quite the right thing) to address this clearly, I am making this new one. The questionable terms and their relationships are: _type, type constructor, type parameter, kinds or sorts, and values_. I also checked wikipedia for type theory, but that didn't clarify it much either. So for the sake of having a good reference answer and to check my own understanding:   * How are these things defined properly?   * What is the difference between each of these things?   * How are they related to each other?


title: How and when do you scale Azure instances?

text: When dealing with Azure instances that are under-performing, how do you decide when to scale the instances? Do you scale horizontally by adding more instances or vertically by making the existing instances more powerful?


title: Function that modifies an argument, should I return the modified object?

text: We have a function that modifies a JS object, by adding some custom properties to it. The function doesn't return antyhing               addTransaction: function (obj) {          obj.transactionId = this.getTransactionId;          obj.id = this.recordId;     },      Somebody said they preferred that `addTransaction` return the `obj`. Here's what I thought   * If I don't return anything (and document that the object is going to be modified), it's kind of clear that the object is going to be modified, as if the name were addTransactionToObj   * If I do want to add a return value, I shouldn't modify the incoming object, I should clone the given object, add my properties to the clone and return the clone.   * Having a return value that just returns one of the (modified) parameter just sounds wrong Does anybody have a preference in this matter?


title: Naming classes, methods, functions and variables

text: There are 3 important naming conventions:   1. `with_underscores`   2. `PascalCased`   3. `camelCased` Other variants are not important because they are not commonly used. For variables it seems that the one with underscores is the most used by developers so I'll stick with that. I think it's the same for functions. But what about class, and method names? Which of these 3 is the most used by developers for such constructs? (personally, it's 3. for methods and 2. for classes) Please do not post things like "use what you feel is right", because the code I'm writing is API for other developers, and I'd like to adopt the most popular coding style :)


title: ASP.Net MVC ambigious action methods - why the path choosen

text: Is there someone who could shed a light on why ambiguous methods are not allowed in ASP.Net MVC?   I updated my question just to clarify it (using Carson63000 example from his answer), the question itself remains the same. So, lets say we have the following action               /article/list/sport      which calls               public ActionResult List(string category) { }      and want to be able to have the following action as well:               /article/list/sport/20110904      which we would like to call accompanying method               public ActionResult List(string category, DateTime date) { }      Currently the framework throws an `AmbiguousMatchException` since it found two methods called List. That's the only reason for throwing the exception, that more than one method with was found that matches the actions name. After the framework has figured out what method to use and decided that it is not ambigious, it will then try to map the supplied data from the request to the parameters of the method. Why not do this the other way around? First get all applicable methods, and then try to find the best fit by mapping parameters. If ambiguous methods where allowed, I think the following is still possible to do.   Given that `/article/list/sport` uses the route `/{controller}/{action}/{category}` and that `/article/list/sport/20110903` uses the route `/{controller}/{action}/{category}/{date}`   it would then still be possible to map data for url `/article/list/sport?date=20110903` since it will match the route for just category, but can still map the data for method `public ActionResult List(string category, DateTime date) { }`. At the moment I fail to see the reason for not allowing ambiguous methods from a design perspective. The only thing I can think of myself is that it will slow down the framework too much, and therefor the current solution is the more logical one. Or am I missing another point here?


title: Is it ever OK for a conditional to have side effects?

text: I'm taking intermediate data structures course as a prereq for entry into the CS MS program at a University everyone in America has heard of. One line of code that was written in class caught my eye: `if (a > 33 | b++ < 54) {...}` This would never pass a code review at my workplace. If you wrote code like this in an interview, you would not be hired. This is not an exaggeration. (In addition to being a conditional with side effects, it's being clever at the expense of clarity.) In fact, I've never seen a conditional with side effects, and Googling doesn't turn up much, either. Another student stayed behind after class to ask about it, too, so I'm not the only one who thought this was weird. But the professor was pretty adamant that this was acceptable code, and that he would write something like that at work. (His FT job is as a Principal SWE at a company you've all heard of.) I cannot imagine a world in which this line of code would ever be acceptable, let alone desirable. Am I wrong? Is this OK? What about the more general case: conditionals with side effects? Are those ever OK?


title: Where to start in developing a game engine as a web app

text: I have to create a web application, preferably I would host that on Google App Engine. it is a multiplayer game, So it needs to be interactive. I am only familiar with C/C++ coding, and have started learning python. I have made multiplayer games before too(multi-player and single player) but with no GUI. Someone told me that the webapp interface would have to be written in JavaScript. And the back end could be in python or any other language. Please note, I have no issues in coding up the back-end, the game engine, of thew web app. Just that I do not know what are and how to, etc about web apps. And basically how to integrate the back end code into the web application (which I have to build from scratch) (I would also be writing the back end, so there is complete flexibility as of now) So please show me the light! I have absolutely no clue about where to start! Please tell me where to begin, and what all to read up which can quickly give me some insight into development work! How to go about the GUI. And what all possible language combinations can I use? The easier to use, the better.


title: Seperable Kernel, MMX/SSE and TCP Transmittal of them?

text: So I was reading about Java Convolve and someone said that it may be faster than the MMX / SSE implementation. In it one of the comments had a kernal array and said it was seperable.   1. What is a seperable kernel? How is this useful for image processing?   2. What is MMX/SSE? The wikipedia page lists them as instruction sets. Are they specificially designed for image processing?   3. How would you transmit a MMX/SSE format (I assume) data set through TCP? Thanks.


title: How do you read other's code?

text: Almost every advanced programmer says that it's very useful to read the code of other professionals. Usually they advice open source. Do you read it or not? If you do, how often and what's the procedure of reading the code? Also, it's a bit difficult for newbies to deal with SVN - a bunches of files. What's the solution?


title: How to stop a .NET application from being duplicated?

text: I have created a .net windows form application that I want to restrict from being duplicated. I want this application to be portable, so I would like to allow it to be moved. How would I be able to do this without managing it through a remote server?


title: Writing jenkins plugin: where is the documentation?

text: On my current project we're using Jenkins to monitor our builds. Now they want me to write a Jenkins plugin to add some more monitoring parameters. I've taken a look at how the status monitor plugin works, and I can't figure some things out. I've tried to look for documentation for writing a plugin, but that seems to be sorely lacking. (the site only mentions how to generate the base project, and refers to a tutorial that's not that informative) What I'm trying to do is just add some options to each build, add a link, and a monitoring page. Adding to the main page is apparently done by adding the action, but I'm still trying to figure out the rest. And how it all ties in. Does anyone have any pointers, or a place where I can find some decent documentation?


title: Stuff to read up on pricing applications

text: I'm about to release an app and I have no idea what would be the ideal pricing point. I'm not sure how pricing high and selling few copies will compare in revenue to pricing low and selling lots of copies in my case. Can somebody point me to books/articles/blog posts/etc that elaborate on the subject, preferably taking into account stuff like competition, number of features, being the first one to the market, research if this kind of app is even needed, etc?


title: Use switch statements for application flow?

text: I generally use switch statements to simplify a block of multiple if statements - for example - returning a feedback string to a user based on a multiple choice input. I also tend to construct classes so that there is one "management" method, to avoid sequential steps or chained method invocation within other methods of the class. I've found this helps to keep methods flexible and focussed - i.e.               class MyClass{              // this method does nothing more than invoke the relevant method         // depending on the status following the previous. It's entire purpose         // is to control application flow         public function manageFlow($input){             $status = $this->stepOne($input);             if($status == false){                 //exit routine             }                  $status = $this->stepTwo($input);             if($status == false){                 //exit routine            }         }              // this method has several sequential steps implemented direcly within it,          // for example to a user logging in         // it makes it impossible to re-use any of the intermediary steps         public function tangledFlow($input){              if($input == 'something){              //100 lines of code              }              //then handing on to the next bit              if($this->User->Authenticated){              //another 100 lines...              }         }     }      Then it occurred to me that I could use a switch statement to control this kind of sequential execution - so my question is: has anyone used a switch statement for this kind of flow control?


title: Object-Oriented Operating System

text: As I thought about writing an operating system, I came across a point that I really couldn't figure out on my own: Can an operating system truly be written in an Object-Oriented Programming (OOP) Language? Being that these types of languages do not allow for direct accessing of memory, wouldn't this make it impossible for a developer to write an entire operating system using only an OOP Language? Take, for example, the Android Operating System that runs many phones and some tablets in use around the world. I believe that this operating system uses only Java, an Object-Oriented language. In Java, I have been unsuccessful in trying to point at and manipulate a specific memory address that the run-time environment (JRE) has not assigned to my program implicitly. In C, C++, and other non-OOP languages, I can do this in a few lines. So this makes me question whether or not an operating system can be written in an OOP, especially Java. Any counterexamples or other information is appreciated.


title: Best way to estimate cost related to porting code from language A to language B?

text: Have a client thinking about estimating the cost of porting a project from language A to language B. What's the best way to put together an request for proposal to do this?


title: How should I approach doing similar work on the side to what I do at work during the day?

text: Currently got a good job, spending 70% of my day doing what I love, the downside of this is of course that I am working for someone else and not my self. Ideally would love to get something of my own going, a night project etc which could trickle in some funds. The downside of this of course if that it would be a conflict of interest. I could of course just go ahead an start up my own little thing but if it got discovered I could risk my job. I could quit my job, but then I would miss the income (family + mortgage) and my ideas might not pan out. Thinking about it tonight, I will discuss it with my boss tomorrow - he's a good guy but I just hope he doesn't burry it or just offer over time. Anyone in this boat? Do what you love during the day (for someone else) and can't peruse it during the night.... Edit: Just to clarify, that what I want to do at night is very similar to what I do during the day. It's not a 'I love programming' in general, but I like doing data mining - and thats what I do at work. Very closely related.