text stringlengths 8 267k | meta dict |
|---|---|
Q: Low Friction Minimal Requirements Gathering How can our team gather requirements from our "Product Owner" in as low friction yet useable of a way as possible?
Now here's the guidelines- No posts that it can't be done or that the business needs to make a decision that it cares about quality, yada yada. The product I work for is a small group that has been successful for years. I just want to help them step it up a notch.
Basically, I'm on a 6 or 7 person team with one Product Owner. She does a great job but is juggling a few different roles (as I believe is common on extremely small teams). Usually requirements are given at sporadic times (email convos, face to face discussions, meetings, etc). They are never entered into a system and sometimes this results in features missing a release or the release getting pushed back since everyone forgot about the necessary feature.
If you're in a similar situation but you found a way to overcome this, I'd love to hear it. I'm happy to write code to help ease this situation but it can't be a web site that the Product Owner has to go to in order to get anything done. She is extremely busy and we need some way of working together as a team in order to gather these requirements.
I'm currently thinking of something like this: Developers and team members gather requirements discussed in face to face meetings and write some quick notes on the features discussed on a wiki page. Product owner is notified whenever these pages are updated and it then becomes her responsibility to ensure accuracy.
Pros: We'll have some record of the features. Cons: The developers are taking responsibility for something that they ordinarily wouldn't. I'm okay with that here. I think in this situation it's teamwork.
Of course once we do this, then we're going to see that the product owner probably doesn't have enough time to ensure feature accuracy. Ultimately she is overburdened and I think this will help showcase that fact, but I just need to be able to draw attention to that first.
So any suggestions?
P.S. her time is extremely limited so it is considered unreasonable to expect her to need to type in the requirements after discussion. She only has time to discuss them once and move on.
A: Although the concept of "product owner" is a littl ambiguous to me, I think I am working in very similar circumstances: the customer is extremely buzy and always is a bottleneck in developing requirements.
On the surface, what we try to do in this situation is quite obvious and seemingly simple: we try to make sure that the customer is involved in "read-only / talk-only" mode. No writing. Minimum reading. Mostly talking.
The devil, of course, is in details. So, here are some specifics about our process (in no particular order):
*
*We often start from recording problem statements, which are the ultimate sources of requirements. In fact, sometimes a problem statement is all that we record initially, just to make sure it does not get lost.
NB: It is important to distinguish problem statements from requirements. Although a problem statement sometimes clearly implies some requirement, in general a single problem statement may yield a whole bunch of requirements (each having its own severity and priority); moreover, sometimes a given requirement my define a solution (usually just a partial one) to multiple problems.
One of the main reasons of recording problem statements (and this is very relevant to your question!) is that semantically they are somewhat "closer to the customer's skin" and more stable than requirements derived from them. I believe those problem statements make it much easier and quicker to put the customer into proper context whenever he has time to provide feedback to the development team.
*We do record all the requirements (and back-track them to problem statements), regardless of when are we going to implement them. Priorities govern the order in which requirements get implemented. Of course, they also govern the order in which customer reviews unfinished requirements.
NB: A single fat document containing all requirements is an absolute no-no! All the requirements are placed in "problem tracking database", along with bug reports. (A bug is just a special case of a problem in our book.)
*We always try to do our best to minimize the number of iterations necessary to "finalize" each requirement (or a group of related requirements). Ideally, a customer should have to review a requirement only once.
Whenever the first review turns out to be insufficient (happens all the time), and the requirement in question is complex enough to require a lot of text and/or illustrations, we make sure that the customer does not have to re-read everything from scratch. All the important changes/additions/deletions since the previous reviwed version are highlighted.
While a problem or requirement remains in an unfinished state, all the open issues (mostly questions to customer) are embedded into the document and highlighted. As a result, whenever the customer has time to review requirements, he does not have to call a meeting and solicit questions from the team; instead the customer can open any unfinished document first, see what exactly is expected from him, and then decide what's the best way and time (for him) to address any of the open issues. Sometimes the customer chooses to write a email or add a comment directly to the problem document.
*We try our best to establish and maintain official domain vocabulary (even if it gets scattered across the documentation). Most importantly, we practically force the customer to stick to that vocabulary.
NB: This is one of the most difficult parts of the process, and customer tries to "rebel" from time to time. However, at the end of the day everybody agrees that it is the only way to make precious meetings with the customer as efficient as possible. If you ever attended one-hour meetings where 30 minutes were being spent just to get everybody on the same page (again), I'm sure you would appreciate having a vocabulary.
NB: Whenever possible, any changes in the official vocabulary get reflected in the very next release of the software.
*Sometimes, a given problem can be solved in multiple ways, and the right choice is not obvious without consulting with the customer. It means that there will be a "menu of requirements" for the customer to pick from. We document such "menus", not just the finally chosen requirement.
This may seem controversial and look like an unnecessary overhead. However, this approach saves a lot of time whenever the customer (usually few weeks or months down the road) suddenly jumps in with a question like "why the heck did we do it this way and not that way?" Also, it is not such a big deal to hide "rejected branches" using proper organization/formatting of requirements documentation. Boring but doable. :-)
NB: When preparing "menus of requirements", it is very important not to overdo them. Too many choices or too many choice nesting levels - and the next review may require much more customer's time than really necessary. Needless to say that the time spent on elaborated branches may be totally wasted. Yes, it is difficult to find some balance here (it greatly depends on the always-in-a-hurry customer's ability to think two or more steps ahead and do it quickly). But, what can I say? If you really want to do your job well, I am sure that after some time you will find the right balance. :-)
*Our customer is a very "visual" guy. Therefore, whenever we discuss any significant user interface elements, screen mockups (or even lightweight prototypes) often are extremely helpful. Real time savers sometimes!
NB: We do screen mockups exclusively for the customer, only in order to facilitate discussions. They may be used by developers too, but in no way do they substitute user interface specifications! More often than not, there are some very important UI details that get specified in writing (now - primarily for developers).
*We are lucky enough to have a customer with a very technical background. So we do not hesitate to use UML diagrams as discussion aid. All kinds of UML diagrams - as long as they help customer to get into proper context quicker and stay there.
I am talking about requirements-level UML diagrams, of course. Not about implementation-level ones. I believe that even not very technical people can start digging requirements-level UML diagrams sooner or later; you just have to be patient and know what to put on a diagram.
Obviously, the cost of such process greatly depends on analytical and writing skills of the team, and of course on the tools that you have at your disposal. And I must admit that in our case this process appears to be quite expensive and slow. But, taking into account the very low rate of bugs and low rate of "vapor-features"... I think, in the long run, we get very good payback.
FWIW: According to Joel's nice classification of software products, this project is an "internal" one. So we can afford to be as agile as our customer can handle. :-)
A: "Developers and team members gather requirements discussed in face to face meetings and write some quick notes"
Start with that. If you aren't taking notes, just make one small change. Take Notes. Later, you might post them to a wiki or create a feature backlog or start using Scrum or bugzilla or something.
First, however, make small changes. Write stuff down sounds like something you're not doing, so just do that and see what improves and what you can do next. Be Agile. Work Incrementally.
A: You might want to be careful of the HiPPO in the room. The Highest Paid Person's Opinion is not always a good one. We've tended to focus more on providing great tools and support for developers. These things, done right, take some of the hassle out of development, so that it becomes faster and more fun. Developers are then more flexible in terms of their workload, and more amenable to late-breaking changes.
One-Click testing and deployment are a couple of good ones to start with; make sure every developer can run up their own software stack in a few seconds and try out ideas directly. Developers are then able to make revisions quickly or run down side paths they find interesting, and these paths are often the most successful. And by successful I mean measured success based on real metrics gathered right in the system and made readily available to all concerned. The owner is then able to set the metrics, which they probably care about, rather than the requirements, which they either don't care about or have no experience in defining.
Of course it depends on the owner and your particular situation, but we've found that metrics are easier to discuss than requirements, and that developers are pretty good at interpreting them too. A typical problem might be that customers seem to spend a long time filling their shopping carts but don't go on to checkout.
1) A marketing requirement might be to make the checkout button bigger and redder. 2) The CEO's requirement might be to take the customer straight to checkout, as the CEO only ever buys one item at a time anyway. 3) The UI designer's requirement might be to place a second checkout button at the top of the cart as well as the existing one at the bottom. 4) The developer's requirement might be some Web 2.0 AJAX widget that follows the mouse pointer around the screen. Who's right?
Who cares... the customer probably saw the ridiculous cost of delivery and ran away. But redefine the problem as a metric, instead of a requirement, and suddenly the developer becomes interested. The developer doesn't have to do 10 rounds with the CMO on what shade of red the button should be. He can play with his Web 2.0 thing all week, and then rush off the other 3 solutions on Monday morning. Each one gets deployed live for 48 hours and the cart-to-checkout rate gets measured and reported instantly. None of it makes any difference, but the developer got to do their job and the business shifts it's focus onto the crappy products they sell and the price they gauge on delivery.
Well, ok, so the example is contrived. There's a lot of work in there to make sure that the project is small, the team is experienced, hot deployment is simple, instant rollback is provided, and that everyone's on board. What we wanted to get to is a state where the developer's full potential is not wasted, so that's why they're involved not just from the start, but also in the success. Start out with an issue like the number of clicks during registration is too high, run it through a design committee, and we found that the number of clicks actually went up in the design specification. That was our experience anyway. But leave the developer some freedom to just reduce the number of clicks and you might actually end up with a patented solution, as we did. Not that the developer cares about patents, but it had merit - and no clicks!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147182",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: RoR + SMS: Rails web app architecture to send/receive SMS? What web app architecture works well receiving/sending SMS text messages? By "architecture, I mean specific architecture, not generally, such as MVC.
Background: I'm building a web app that receives queries from/sends answers to cell phones. The app design (and business model) expects to communicate with cell devices via SMS text messages. IOW: There is no MVC web page "view". The cell phone screen is effectively the "view".
A: I would question whether this is really a web application. If the view layer is SMS, you don't have to use the internet as a transport, you could use hardware to connect to the cell phone network.
If you are thinking of using a commercial http/sms gateway, there is a good article on using the Ruby Clicktell gem from a Rails application. Seems like a good route to try.
A: This depends on how you will be receiving and sending the SMS messages.
There is a specific Short message protocol (SMPP - http://en.wikipedia.org/wiki/SMPP).
For that you will need an SMPP server.
If you are using a one of the various SMS over HTTP providers (such as Clickatell - http://www.clickatell.com), then a web framework such as RoR is fine as both the sending and receiving of SMS messages are actually web requests.
In this case your system view is the HTTP response to the gateway, not the cellphone screen. There are actually quite a few steps involved:
Cellphone -> Cellular Network -> Gateway -> Your Service and the reply: Cellphone <- Cellular Network <- Gateway <- Your Service
A: I've made one of these before using rails. I created a budget tracker I could send commands to with my cell phone. I used it to create a list of items i needed to buy/take care of on the upcoming paycheck. When the check came in, I would send commands to mark each item off the list. I included commands to query a list as well. The commands looked something like "lc mar4" to create the fourth paycheck in march's budget list. Once a list was created, I could send commands without specifying the list and I made the script just apply the command to the last list if no list was specified and crunch down the other arguments. "la court 50 p" would add too the mar4 list an item named "court" with a value of 50 and a tag "p" which I called pending. When I took care of court that friday, I could send "lu court 50 d" which would update the court item with the same value with the tag "d" for done. I had a command called "lp" which would print the current list. "lp d" would print all the "d" tagged items on the current list. "lsum p" would print all the pending items on the current list.
I made an empty rails app. Made my database schema and my models but had no controllers. I had a script in scripts that included a pop/ssl library i found somewhere to download email from a gmail account i had setup for this. From then on it was pretty easy, just check the new messages for each message make sure it came from my cell phone and parse the message and optionally send back a response. (I had programmed that email address into my cellphone, and sent text commands to that email address). I added a cron job and set it to run every minute.
I don't know what that architecture is, but its basically a service that queries a 3rd party and does different things dependent on the response. If you did true SMS with shortcodes, I'll let you know now that I think there is a sizeable investment necessary to do those for real. Might be easier to start develop with email text messaging through sms gateways.
I'm not saying this is the best way to do it by far, It would have been cooler to have had the messages "pushed" to me instead of checking every minute, but hey I just wanted to balance my budget with my phone.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147184",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Why do we need anything more than HTTP GET, PUT, POST? What is the practical benefit of using HTTP GET, PUT, DELETE, POST, HEAD? Why not focus on their behavioral benefits (safety and idempotency), forgetting their names, and use GET, PUT or POST depending on which behavior we want?
Why shouldn't we only use GET, PUT and POST (and drop HEAD, DELETE)?
A: Why do we need more than POST? It allows data to flow both ways, so why would GET be needed? The answer is basically the same as for your question. By standardizing the basic expectations of the various methods other processes can better know what to do.
For example, intervening caching proxies can have a better chance of doing the correct thing.
Think about HEAD for instance. If the proxy server knows what HEAD means then it can process the result from a previous GET request to provide the proper answer to a HEAD request. And it can know that POST, PUT and DELETE should not be cached.
A: No one posted the kind of answer I was looking for so I will try to summarize the points myself.
"RESTful Web Services" chapter 8 section "Overloading POST" reads: "If you want to do without PUT and DELETE altogether, it’s entirely RESTful to expose safe operations on resources through GET, and all other operations through overloaded POST. Doing this violates my Resource-Oriented Architecture, but it conforms to the less restrictive rules of REST."
In short, replacing PUT/DELETE in favor of POST makes the API harder to read and PUT/DELETE calls are no longer idempotent.
A: The [REST][1] approach uses POST, GET, PUT and DELETE to implement the CRUD rules for a web resource. It's a simple and tidy way to expose objects to requests on the web. It's web services without the overheads.
Just to clarify the semantic differences. Each operation is rather different. The point is to have nice HTTP methods that have clear, distinct meanings.
POST creates new objects. The URI has no key; it accepts a message body that defines the object. SQL Insert. [Edit While there's no technical reason for POST to have no key, the REST folks suggest strongly that for POST to have distinct meaning as CREATE, it should not have a key.]
GET retrieves existing objects. The URI may have a key, depends on whether you are doing singleton GET or list GET. SQL Select
PUT updates an existing object. The URI has a key; It accepts a message body that updates an object. SQL Update.
DELETE deletes an existing object. The URI has a key. SQL Delete.
Can you update a record with POST instead of PUT? Not without introducing some ambiguity. Verbs should have unambiguous effects. Further, POST URI's have no key, where PUT must have a key.
When I POST, I expect a 201 CREATED. If I don't get that, something's wrong. Similarly, when I PUT, I expect a 200 OK. If I don't get that, something's wrong.
I suppose you could insist on some ambiguity where POST does either POST or PUT. The URI has to be different; also the associated message could be different. Generally, the REST folks take their cue from SQL where INSERT and UPDATE are different verbs.
You could make the case that UPDATE should insert if the record doesn't exist or update if the record does exist. However, it's simpler if UPDATE means UPDATE and failure to update means something's wrong. A secret fall-back to INSERT makes the operation ambiguous.
If you're not building a RESTful interface, then it's typical to only use GET and POST for retrieve and create/update. It's common to have URI differences or message content differences to distinguish between POST and PUT when a person is clicking submit on a form. It, however, isn't very clean because your code has to determine if you're in the POST=create case or POST=update case.
A: In a word:
idempotency
In a few more words:
GET = safe + idempotent
PUT = idempotent
DELETE = idempotent
POST = neither safe or idempotent
'Idempotent' just means you can do it over and over again and it will always do exactly the same thing.
You can reissue a PUT (update) or DELETE request as many times as you want and it will have the same effect every time, however the desired effect will modify a resource so it is not considered 'safe'.
A POST request should create a new resource with every request, meaning the effect will be different every time. Therefore POST is not considered safe or idempotent.
Methods like GET and HEAD are just read operations and are therefore considered 'safe' aswell as idempotent.
This is actually a pretty important concept because it provides a standard/consistent way to interpret HTTP transactions; this is particularly useful in a security context.
A: POST has no guarantees of safety or idempotency. That's one reason for PUT and DELETE—both PUT and DELETE are idempotent (i.e., 1+N identical requests have the same end result as just 1 request).
PUT is used for setting the state of a resource at a given URI. When you send a POST request to a resource at a particular URI, that resource should not be replaced by the content. At most, it should be appended to. This is why POST isn't idempotent—in the case of appending POSTS, every request will add to the resource (e.g., post a new message to a discussion forum each time).
DELETE is used for making sure that a resource at a given URI is removed from the server. POST shouldn't normally be used for deleting except for the case of submitting a request to delete. Again, the URI of the resource you would POST to in that case shouldn't be the URI for the resource you want to delete. Any resource for which you POST to is a resource that accepts the POSTed data to append to itself, add to a collection, or to process in some other way.
HEAD is used if all you care about is the headers of a GET request and you don't want to waste bandwidth on the actual content. This is nice to have.
A: Not all hosters don't support PUT, DELETE.
I asked this question, in an ideal world we'd have all the verbs but....:
RESTful web services and HTTP verbs
A: HEAD is really useful for determining what a given server's clock is set to (accurate to within the 1 second or the network round-trip time, whichever is greater). It's also great for getting Futurama quotes from Slashdot:
~$ curl -I slashdot.org
HTTP/1.1 200 OK
Date: Wed, 29 Oct 2008 05:35:13 GMT
Server: Apache/1.3.41 (Unix) mod_perl/1.31-rc4
SLASH_LOG_DATA: shtml
X-Powered-By: Slash 2.005001227
X-Fry: That's a chick show. I prefer programs of the genre: World's Blankiest Blank.
Cache-Control: private
Pragma: private
Connection: close
Content-Type: text/html; charset=iso-8859-1
For cURL, -I is the option for performing a HEAD request. To get the current date and time of a given server, just do
curl -I $server | grep ^Date
A: To limit ambiguity which will allow for better/easier reuse of our simple REST apis.
A: You could use only GET and POST but then you are losing out on some of the precision and clarity that PUT and DELETE bring. POST is a wildcard operation that could mean anything.
PUT and DELETE's behaviour is very well defined.
If you think of a resource management API then GET, PUT and DELETE probably cover 80%-90% of the required functionality. If you limit yourself to GET and POST then 40%-60% of your api is accessed using the poorly specified POST.
A: Web applications using GET and POST allow users to create, view, modify and delete their data, but do so at a layer above the HTTP commands originally created for these purposes. One of the ideas behind REST is a return to the original intent of the design of the Web, whereby there are specific HTTP operations for each CRUD verb.
Also, the HEAD command can be used to improve the user experience for (potentially large) file downloads. You call HEAD to find out how large the response is going to be and then call GET to actually retrieve the content.
A: See the following link for an illustrative example. It also suggests one way to use the OPTIONS http method, which hasn't yet been discussed here.
A: There are http extensions like WebDAV that require additional functionally.
http://en.wikipedia.org/wiki/WebDAV
A: GET, PUT, DELETE and POST are holdovers from an era when sophomores thought that a web page could be reduced to a few hoighty-toity principles.
Nowadays, most web pages are composite entities, which contain some or all of these primitive operations. For instance, a page could have forms for viewing or updating customer information, which perhaps spans a number of tables.
I usually use $_REQUEST[] in php, not really caring how the information arrived. I would choose to use GET or PUT methods based on efficiency, not the underlying (multiple) paradigms.
A: The web server war from the earlier days probably caused it.
In HTTP 1.0 written in 1996, there were only GET, HEAD, and POST. But as you can see in Appendix D, vendors started to add their own things. So, to keep HTTP compatible, they were forced to make HTTP 1.1 in 1999.
However, HTTP/1.0 does not sufficiently take into consideration
the effects of hierarchical proxies, caching, the need for
persistent connections, or virtual hosts. In addition, the proliferation
of incompletely-implemented applications calling themselves
"HTTP/1.0" has necessitated a protocol version change in order for
two communicating applications to determine each other's true capabilities.
This specification defines the protocol referred to as "HTTP/1.1". This protocol includes more stringent requirements than HTTP/1.0 in order
to ensure reliable implementation of its features.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147187",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: Transactions in REST? I'm wondering how you'd implement the following use-case in REST. Is it even possible to do without compromising the conceptual model?
Read or update multiple resources within the scope of a single transaction. For example, transfer $100 from Bob's bank account into John's account.
As far as I can tell, the only way to implement this is by cheating. You could POST to the resource associated with either John or Bob and carry out the entire operation using a single transaction. As far as I'm concerned this breaks the REST architecture because you're essentially tunneling an RPC call through POST instead of really operating on individual resources.
A: Consider a RESTful shopping basket scenario. The shopping basket is conceptually your transaction wrapper. In the same way that you can add multiple items to a shopping basket and then submit that basket to process the order, you can add Bob's account entry to the transaction wrapper and then Bill's account entry to the wrapper. When all the pieces are in place then you can POST/PUT the transaction wrapper with all the component pieces.
A: There are a few important cases that aren't answered by this question, which I think is too bad, because it has a high ranking on Google for the search terms :-)
Specifically, a nice propertly would be: If you POST twice (because some cache hiccupped in the intermediate) you should not transfer the amount twice.
To get to this, you create a transaction as an object. This could contain all the data you know already, and put the transaction in a pending state.
POST /transfer/txn
{"source":"john's account", "destination":"bob's account", "amount":10}
{"id":"/transfer/txn/12345", "state":"pending", "source":...}
Once you have this transaction, you can commit it, something like:
PUT /transfer/txn/12345
{"id":"/transfer/txn/12345", "state":"committed", ...}
{"id":"/transfer/txn/12345", "state":"committed", ...}
Note that multiple puts don't matter at this point; even a GET on the txn would return the current state. Specifically, the second PUT would detect that the first was already in the appropriate state, and just return it -- or, if you try to put it into the "rolledback" state after it's already in "committed" state, you would get an error, and the actual committed transaction back.
As long as you talk to a single database, or a database with an integrated transaction monitor, this mechanism will actually work just fine. You might additionally introduce time-outs for transactions, which you could even express using Expires headers if you wanted to.
A: In REST terms, resources are nouns that can be acted on with CRUD (create/read/update/delete) verbs. Since there is no "transfer money" verb, we need to define a "transaction" resource that can be acted upon with CRUD. Here's an example in HTTP+POX. First step is to CREATE (HTTP POST method) a new empty transaction:
POST /transaction
This returns a transaction ID, e.g. "1234" and according URL "/transaction/1234". Note that firing this POST multiple times will not create the same transaction with multiple IDs and also avoids introduction of a "pending" state. Also, POST can't always be idempotent (a REST requirement), so it's generally good practice to minimize data in POSTs.
You could leave the generation of a transaction ID up to the client. In this case, you would POST /transaction/1234 to create transaction "1234" and the server would return an error if it already existed. In the error response, the server could return a currently unused ID with an appropriate URL. It's not a good idea to query the server for a new ID with a GET method, since GET should never alter server state, and creating/reserving a new ID would alter server state.
Next up, we UPDATE (PUT HTTP method) the transaction with all data, implicitly committing it:
PUT /transaction/1234
<transaction>
<from>/account/john</from>
<to>/account/bob</to>
<amount>100</amount>
</transaction>
If a transaction with ID "1234" has been PUT before, the server gives an error response, otherwise an OK response and a URL to view the completed transaction.
NB: in /account/john , "john" should really be John's unique account number.
A: First of all transferring money is nothing that you can not do in a single resource call. The action you want to do is sending money. So you add a money transfer resource to the account of the sender.
POST: accounts/alice, new Transfer {target:"BOB", abmount:100, currency:"CHF"}.
Done. You do not need to know that this is a transaction that must be atomic etc. You just transfer money aka. send money from A to B.
But for the rare cases here a general solution:
If you want to do something very complex involving many resources in a defined context with a lot of restrictions that actually cross the what vs. why barrier (business vs. implementation knowledge) you need to transfer state. Since REST should be stateless you as a client need to transfer the state around.
If you transfer state you need to hide the information inside from the client. The client should not know internal information only needed by the implementation but does not carry information relevant in terms of business. If those information have no business value the state should be encrypted and a metaphor like token, pass or something need to be used.
This way one can pass internal state around and using encryption and signing the system can be still be secure and sound. Finding the right abstraction for the client why he passes around state information is something that is up to the design and architecture.
The real solution:
Remember REST is talking HTTP and HTTP comes with the concept of using cookies. Those cookies are often forgotten when people talk about REST API and workflows and interactions spanning multiple resources or requests.
Remember what is written in the Wikipedia about HTTP cookies:
Cookies were designed to be a reliable mechanism for websites to remember stateful information (such as items in a shopping cart) or to record the user's browsing activity (including clicking particular buttons, logging in, or recording which pages were visited by the user as far back as months or years ago).
So basically if you need to pass on state, use a cookie. It is designed for exactly the very same reason, it is HTTP and therefore it is compatible to REST by design :).
The better solution:
If you talk about a client performing a workflow involving multiple requests you usually talk about protocol. Every form of protocol comes with a set of preconditions for each potential step like perform step A before you can do B.
This is natural but exposing protocol to clients makes everything more complex. In order to avoid it just think what we do when we have to do complex interactions and things in the real world... . We use an Agent.
Using the Agent metaphor you can provide a resource that can perform all necessary steps for you and store the actual assignment / instructions it is acting upon in its list (so we can use POST on the agent or an 'agency').
A complex example:
Buying a house:
You need to prove your credibility (like providing your police record entries), you need to ensure financial details, you need to buy the actual house using a lawyer and a trusted third party storing the funds, verify that the house now belongs to you and add the buying stuff to your tax records etc. (just as an example, some steps may be wrong or whatever).
These steps might take several days to be completed, some can be done in parallel etc.
In order to do this, you just give the agent the task buy house like:
POST: agency.com/ { task: "buy house", target:"link:toHouse", credibilities:"IamMe"}.
Done. The agency sends you back a reference to you that you can use to see and track the status of this job and the rest is done automatically by the agents of the agency.
Think about a bug tracker for instance. Basically you report the bug and can use the bug id to check whats going on. You can even use a service to listen to changes of this resource. Mission Done.
A: Great question, REST is mostly explained with database-like examples, where something is stored, updated, retrieved, deleted. There are few examples like this one, where the server is supposed to process the data in some way. I don't think Roy Fielding included any in his thesis, which was based on http after all.
But he does talk about "representational state transfer" as a state machine, with links moving to the next state. In this way, the documents (the representations) keep track of the client state, instead of the server having to do it. In this way, there is no client state, only state in terms of which link you are on.
I've been thinking about this, and it seems to me reasonable that to get the server to process something for you, when you upload, the server would automatically create related resources, and give you the links to them (in fact, it wouldn't need to automatically create them: it could just tell you the links, and it only create them when and if you follow them - lazy creation). And to also give you links to create new related resources - a related resource has the same URI but is longer (adds a suffix). For example:
*
*You upload (POST) the representation of the concept of a transaction with all the information. This looks just like a RPC call, but it's really creating the "proposed transaction resource". e.g URI: /transaction
Glitches will cause multiple such resources to be created, each with a different URI.
*The server's response states the created resource's URI, its representation - this includes the link (URI) to create the related resource of a new "committed transaction resource". Other related resources are the link to delete the proposed transaction. These are states in the state-machine, which the client can follow. Logically, these are part of the resource that has been created on the server, beyond the information the client supplied. e.g URIs: /transaction/1234/proposed, /transaction/1234/committed
*You POST to the link to create the "committed transaction resource", which creates that resource, changing the state of the server (the balances of the two accounts)**. By its nature, this resource can only be created once, and can't be updated. Therefore, glitches committing many transactions can't occur.
*You can GET those two resources, to see what their state is. Assuming that a POST can change other resources, the proposal would now be flagged as "committed" (or perhaps, not available at all).
This is similar to how webpages operate, with the final webpage saying "are you sure you want to do this?" That final webpage is itself a representation of the state of the transaction, which includes a link to go to the next state. Not just financial transactions; also (eg) preview then commit on wikipedia. I guess the distinction in REST is that each stage in the sequence of states has an explicit name (its URI).
In real-life transactions/sales, there are often different physical documents for different stages of a transaction (proposal, purchase order, receipt etc). Even more for buying a house, with settlement etc.
OTOH This feels like playing with semantics to me; I'm uncomfortable with the nominalization of converting verbs into nouns to make it RESTful, "because it uses nouns (URIs) instead of verbs (RPC calls)". i.e. the noun "committed transaction resource" instead of the verb "commit this transaction". I guess one advantage of nominalization is you can refer to the resource by name, instead of needing to specify it in some other way (such as maintaining session state, so you know what "this" transaction is...)
But the important question is: What are the benefits of this approach? i.e. In what way is this REST-style better than RPC-style? Is a technique that's great for webpages also helpful for processing information, beyond store/retrieve/update/delete? I think that the key benefit of REST is scalability; one aspect of that is not needing to maintain client state explicitly (but making it implicit in the URI of the resource, and the next states as links in its representation). In that sense it helps. Perhaps this helps in layering/pipelining too? OTOH only the one user will look at their specific transaction, so there's no advantage in caching it so others can read it, the big win for http.
A: You must not use server side transactions in REST.
One of the REST contraints:
Stateless
The client–server communication is further constrained by no client context being stored on the server between requests. Each request from any client contains all of the information necessary to service the request, and any session state is held in the client.
The only RESTful way is to create a transaction redo log and put it into the client state. With the requests the client sends the redo log and the server redoes the transaction and
*
*rolls the transaction back but provides a new transaction redo log (one step further)
*or finally complete the transaction.
But maybe it's simpler to use a server session based technology which supports server side transactions.
A: I've drifted away from this topic for 10 years. Coming back, I can't believe the religion masquerading as science that you wade into when you google rest+reliable. The confusion is mythic.
I would divide this broad question into three:
*
*Downstream services. Any web service you develop will have downstream services that you use, and whose transaction syntax you have no choice but to follow. You should try and hide all this from users of your service, and make sure all parts of your operation succeed or fail as a group, then return this result to your users.
*Your services. Clients want unambiguous outcomes to web-service calls, and the usual REST pattern of making POST, PUT or DELETE requests directly on substantive resources strikes me as a poor, and easily improved, way of providing this certainty. If you care about reliability, you need to identify action requests. This id can be a guid created on the client, or a seed value from a relational DB on the server, it doesn't matter. For server generated ID's, use a 'preflight' request-response to exchange the id of the action. If this request fails or half succeeds, no problem, the client just repeats the request. Unused ids do no harm.This is important because it lets all subsequent requests be fully idempotent, in the sense that if they are repeated n times they return the same result and cause nothing further to happen. The server stores all responses against the action id, and if it sees the same request, it replays the same response. A fuller treatment of the pattern is in this google doc. The doc suggests an implementation that, I believe(!), broadly follows REST principals. Experts will surely tell me how it violates others. This pattern can be usefully employed for any unsafe call to your web-service, whether or not there are downstream transactions involved.
*Integration of your service into "transactions" controlled by upstream services. In the context of web-services, full ACID transactions are considered as usually not worth the effort, but you can greatly help consumers of your service by providing cancel and/or confirm links in your confirmation response, and thus achieve transactions by compensation.
Your requirement is a fundamental one. Don't let people tell you your solution is not kosher. Judge their architectures in the light of how well, and how simply, they address your problem.
A: If you stand back to summarize the discussion here, it's pretty clear that REST is not appropriate for many APIs, particularly when the client-server interaction is inherently stateful, as it is with non-trivial transactions. Why jump through all the hoops suggested, for client and server both, in order to pedantically follow some principle that doesn't fit the problem? A better principle is to give the client the easiest, most natural, productive way to compose with the application.
In summary, if you're really doing a lot of transactions (types, not instances) in your application, you really shouldn't be creating a RESTful API.
A: You'd have to roll your own "transaction id" type of tx management. So it would be 4 calls:
http://service/transaction (some sort of tx request)
http://service/bankaccount/bob (give tx id)
http://service/bankaccount/john (give tx id)
http://service/transaction (request to commit)
You'd have to handle the storing of the actions in a DB (if load balanced) or in memory or such, then handling commit, rollback, timeout.
Not really a RESTful day in the park.
A: I think that in this case it is totally acceptable to break the pure theory of REST in this situation. In any case, I don't think there is anything actually in REST that says you can't touch dependent objects in business cases that require it.
I really think it's not worth the extra hoops you would jump through to create a custom transaction manager, when you could just leverage the database to do it.
A: In the simple case (without distributed resources), you could consider the transaction as a resource, where the act of creating it attains the end objective.
So, to transfer between <url-base>/account/a and <url-base>/account/b, you could post the following to <url-base>/transfer.
<transfer>
<from><url-base>/account/a</from>
<to><url-base>/account/b</to>
<amount>50</amount>
</transfer>
This would create a new transfer resource and return the new url of the transfer - for example <url-base>/transfer/256.
At the moment of successful post, then, the 'real' transaction is carried out on the server, and the amount removed from one account and added to another.
This, however, doesn't cover a distributed transaction (if, say 'a' is held at one bank behind one service, and 'b' is held at another bank behind another service) - other than to say "try to phrase all operations in ways that don't require distributed transactions".
A: I believe that would be the case of using a unique identifier generated on the client to ensure that the connection hiccup not imply in an duplicity saved by the API.
I think using a client generated GUID field along with the transfer object and ensuring that the same GUID was not reinserted again would be a simpler solution to the bank transfer matter.
Do not know about more complex scenarios, such as multiple airline ticket booking or micro architectures.
I found a paper about the subject, relating the experiences of dealing with the transaction atomicity in RESTful services.
A: I guess you could include the TAN in the URL/resource:
*
*PUT /transaction to get the ID (e.g. "1")
*[PUT, GET, POST, whatever] /1/account/bob
*[PUT, GET, POST, whatever] /1/account/bill
*DELETE /transaction with ID 1
Just an idea.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147207",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "162"
} |
Q: How to hide table rows without resizing overall width? Is there a way to hide table rows without affecting the overall table width? I've got some javascript that shows/hides some table rows, but when the rows are set to display: none;, the table with shrinks to fit the contents of the visible rows.
A: If you are looking to preserve the overall width of the table, you can check it prior to hiding a row, and explicitly set the width style property to this value:
table.style.width = table.clientWidth + "px";
table.rows[3].style.display = "none";
However, this may cause the individual columns to reflow when you hide the row. A possible way to mitigate this is by adding a style to your table:
table {
table-layout: fixed;
}
A: CSS rule visibility: collapse was designed exactly for that.
tbody.collapsed > tr {
visibility: collapse;
}
After adding this CSS you could trigger visibility from JS with:
tbody.classList.toggle('collapsed');
A: For reference, levik's solution works perfectly. In my case, using jQuery, the solution looked something like this:
$('#tableId').width($('#tableId').width());
A: In CSS, table-layout: fixed; on your table instructs the browser to honor the sizes you've specified for heights and widths. This generally suppresses auto-resizing by the browser unless you haven't given any hints as to the preferred sizes of your rows and columns.
A: You can do it using pure HTML
<table border="1">
<colgroup>
<col width="150px" />
<col width="10px" />
<col width="220px" />
</colgroup>
<tr>
<td valign="top">1</td>
<td> </td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td> </td>
<td>4</td>
</tr>
</table>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147208",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: How can I reseed an identity column in a T-SQL table variable? I have a T-SQL table variable (not a table) which has an auto incrementing identity column. I want to clear all data from this variable and reset the identity column value to 1. How can this be done?
A: If you're using a table variable, you can't do it. If it were a table, you could truncate it or use DBCC CHECKIDENT. But, if you have to use a table variable, you have to use something other than an identity column. Or, more accurately, use the identity column in your table variable but output using ROWNUMBER:
DECLARE @t table (pkint int IDENTITY(1,1), somevalue nvarchar(50))
INSERT INTO @t (somevalue) VALUES( 'one')
INSERT INTO @t (somevalue) VALUES('twp')
INSERT INTO @t (somevalue) VALUES('three')
SELECT row_number() OVER (ORDER BY pkint), somevalue FROM @t
DELETE FROM @t
INSERT INTO @t (somevalue) VALUES('four')
SELECT row_number() OVER (ORDER BY pkint), somevalue FROM @t
It's the best you can do with the table variable.
A: Truncating the table will dump ALL the data, and reset the identity seed.
Otherwise, you can use this call to reset the identity while retaining any of the data:
DBCC CHECKIDENT (yourtableName, reseed, @NewStartSeedValue)
A: I suggest you use two table variables. The @Table1 has an identity seed on the first column. @Table2 has the same first column but no identity seed on it.
As you loop through your process,
Insert into @Table2 from @Table1
then Delete From both Tables as your Process Loops.
On your first pass, the @Table2 will have a a sequential number in the first row starting at 1.
The second time through the loop your second table might have sequential numbers in the first column starting at say 1081. But if you select the minimum value to a variable
(Select @FixSeed = min(RowID) From @Table2)
Then you can update @Table2 to make RowID start at 1 as follows:
Update @Table2 Set RowID = RowID - @FixSeed +1
Hope this helps
A: declare @tb table (recid int,lineof int identity(1,1))
insert into @tb(recid)
select recid from tabledata
delete from @tb where lineof>(select min(lineof) from @tb)+@maxlimit
I did this when I wanted to use a TOP and a variable when using SQL 2000. Basically, you add in the records and then look at the minimum one. I had the same problem and noticed this thread. Deleting the table doesn't reset the seed although I imagine using GO should drop the table and variable to reset the seed.
@maxlimit in the query above was to get the top 900 of the query and since the table variable would have a different starting identity key, this would solve that issue.
Any subsequent query can subtract that derived procedure to make it insert as "1", etc.
A: If you need to truncate the table variable in each turn of a while loop, you can put the declare @myTbl (...) statement in the loop. This will recreate the table and reset the identity column on each turn of the loop. However, it has a heavy performance hit. I had fairly tight loop, and redeclaring the table variable relative to delete @myTbl was several times slower.
*
*Dan
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147210",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "37"
} |
Q: Ruby isPrime Method ('1' * N) !~ /^1?$|^(11+?)\1+$/
On the net, I found this piece of Ruby code that works for N >= 0 that determines whether or not N is a prime. From what I can tell, it looks like play with regex but I have no idea how it works. Could someone tell me how it works?
A: require 'prime'
Prime.prime?(4)
# => false
Prime.prime?(5)
# => true
Or:
require 'prime'
Prime.instance.prime?(4)
# => false
Prime.instance.prime?(5)
# => true
A: You can find a lengthy explanation of this code here:
http://www.noulakaz.net/weblog/2007/03/18/a-regular-expression-to-check-for-prime-numbers/
A: This is probably rather off-topic, but in Ruby 1.9, you can do this:
require 'mathn'
38749711234868463.prime?
=> false
A: See also What is the most brilliant regex you’ve ever used? (and yes, I can confirm that this regexp was originally written by Abigail. I've even heard her explain how it works :)
A: Greatest Common Divisor (gcd):
/^(1+)\1*=\1+$/.match('1' * x + '=' + '1' * y)[1].length
Both this and the is_prime one works in about the same way. It tries all combinations before giving up.
This one will try to split the first number in even parts, and match the second number with one or more of those parts. If it finds a match it returns the length of the selected part.
A: Yet another blog with a pretty good explanation: Famous Perl One-Liners Explained (part III)
A: If the length of a string of 1's is composite, then the string can be decomposed into multiple identical substrings, like 111111 -> 11 11 11
For example, 1111111111, has 10 1's, and it matches (11){5} or (11111){2}, where {2} means repeated 2 times.
111111111, has 9 1's, and it matches (111){3}.
By generalizing the count of 1's and the number in {}, the regexp is
/(1{2,}){2,}/.
However, 1{2,} can also be written as 11+, and (...){2,} can be rewritten as (...)\1+, with backreferences.
The ^1?$ part in the first alternation checks for 0 and 1-cases.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147240",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "24"
} |
Q: How can I remotely (via web services) determine date format of SharePoint 2003 site, for use in Versions.asmx returned XML? The GetVersions() call to the Versions.asmx web service in SharePoint 2003 returns a localised date format, with no way of determining what the format is. It's the site regional setting of date format, but I can't find a way to get even that out of SharePoint 2003. Locally, it looks like SPRegionalSettings can be used (http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spregionalsettings.aspx) but what about a web service version of this?
A: Sadly, it isn't available. However, you can specify a query option to specify that you want the values returned in UTC:
http://www.sharepointblogs.com/pm4everyone/archive/2006/10/03/sharepoint-2003-querying-with-gmt-datetime.aspx
A: Unfortunately, the parameter that asks for the values in UTC is not supported for this call. I've just had to look for a month greater than 12 and use that as the hint to switch date formats. It'll mess up some dates, but I can't see a way around that. The code is at http://sourceforge.net/projects/splistcp/ if anyone is interested.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147245",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Can I have non-measure codes mixed with measures in my fact table? We're doing a complex bit of data accumulation. Our customer sends us some stuff that includes two dimensions (time and a business unit). Time is mostly year-month. The business unit dimension has just a few attributes: a name, and a few categories to which BU's can belong for reporting and analysis purposes.
The stuff they send us includes some current state information (dates and codes). These seem fact-like. They also send some information that characterizes the relationship with the business unit (mostly additional codes). Again, these are unique to the business unit and time period.
Finally, they send us stuff that is clearly additive facts. It includes currency and counts that have proper units.
Should I commingle this qualitative information in a single fact table with the additive facts? Or should I separate the qualitative stuff (which can only be used with counts) from the quantitative stuff (which can be used with sum)?
A: If the data is both directly related to the additive fact and is not something you want to be grouping/sorting/search on, then putting it in the fact table is okay.
Be aware, though, that non-additive data in the fact table will either prevent roll-ups or will become a lossy operation.
A: Only put things in the fact table if they are degenerate (causing a high-cardinality/uniqueness problems in your dimension where it takes the dimension to a 1-1 relationship to the fact table). Kimball recommends avoiding the temptation to put anything but degenerate dimensions in with the facts (unique order number, for instance).
You can always put these in what Kimball calls a "junk" dimension. All those codes can simply be lumped into a junk dimension. Most dates would go in the fact table as keys into your date dimension in a particular role (usually with a natural int key of the form YYYYMMDD - one of the only times we don't use a non-identity meaningless surrogate key)
I like to naively view the star as all the facts and then which columns go into which dimensions is simply determined by convenience. One should not necessarily view them as corresponding to a particular business entity - remember, the star is not an ERD-style normalized OLTP database.
A: Brad Wilson accurately describes the risk of adding them to your fact table. In the past, I've added junk attributes to my fact table only to require refactoring later.
The stuff they send us includes some
current state information (dates and
codes). These seem fact-like. They
also send some information that
characterizes the relationship with
the business unit (mostly additional
codes). Again, these are unique to the
business unit and time period.
What business purpose do the dates serve? Offhand, I'd recommend making these their own dimensions and describe them accurately.
How volatile are the extra codes that come in? If the grain of your fact table is date and BU, why can't they be included in the BU dimension and treated as slowly changing attributes?
Without more details I can't make a firm recommendation but these would be the first questions I'd ask myself.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147260",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: jQuery - Triggering Events from Clicking on a Link Issue I'd like to trigger an event when a link is clicked both by clicking on it normally or by opening it in a new tab (e.g., middle click, ctrl + click, etc)
I've tried the following so far:
$('a').click(myfunc) Doesn't capture middle clicks.
$('a').mousedown(myfunc) works, but it seems to be preventing the link from being followed even though my function doesn't call event.preventDefault.
Any ideas how to do this then?
A: Try returning true from your handler function. Returning nothing can be interpreted by the browser as a void return and thus prevent the default action from being carried out.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147264",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Easy way to use variables of enum types as string in C? Here's what I am trying to do:
typedef enum { ONE, TWO, THREE } Numbers;
I am trying to write a function that would do a switch case similar to the following:
char num_str[10];
int process_numbers_str(Numbers num) {
switch(num) {
case ONE:
case TWO:
case THREE:
{
strcpy(num_str, num); //some way to get the symbolic constant name in here?
} break;
default:
return 0; //no match
return 1;
}
Instead of defining at every case, is there a way to set it using the enum variable like I am trying to do above?
A: I know you have a couple good solid answers, but do you know about the # operator in the C preprocessor?
It lets you do this:
#define MACROSTR(k) #k
typedef enum {
kZero,
kOne,
kTwo,
kThree
} kConst;
static char *kConstStr[] = {
MACROSTR(kZero),
MACROSTR(kOne),
MACROSTR(kTwo),
MACROSTR(kThree)
};
static void kConstPrinter(kConst k)
{
printf("%s", kConstStr[k]);
}
A: The technique from Making something both a C identifier and a string? can be used here.
As usual with such preprocessor stuff, writing and understanding the preprocessor part can be hard, and includes passing macros to other macros and involves using # and ## operators, but using it is real easy. I find this style very useful for long enums, where maintaining the same list twice can be really troublesome.
Factory code - typed only once, usually hidden in the header:
enumFactory.h:
// expansion macro for enum value definition
#define ENUM_VALUE(name,assign) name assign,
// expansion macro for enum to string conversion
#define ENUM_CASE(name,assign) case name: return #name;
// expansion macro for string to enum conversion
#define ENUM_STRCMP(name,assign) if (!strcmp(str,#name)) return name;
/// declare the access function and define enum values
#define DECLARE_ENUM(EnumType,ENUM_DEF) \
enum EnumType { \
ENUM_DEF(ENUM_VALUE) \
}; \
const char *GetString(EnumType dummy); \
EnumType Get##EnumType##Value(const char *string); \
/// define the access function names
#define DEFINE_ENUM(EnumType,ENUM_DEF) \
const char *GetString(EnumType value) \
{ \
switch(value) \
{ \
ENUM_DEF(ENUM_CASE) \
default: return ""; /* handle input error */ \
} \
} \
EnumType Get##EnumType##Value(const char *str) \
{ \
ENUM_DEF(ENUM_STRCMP) \
return (EnumType)0; /* handle input error */ \
} \
Factory used
someEnum.h:
#include "enumFactory.h"
#define SOME_ENUM(XX) \
XX(FirstValue,) \
XX(SecondValue,) \
XX(SomeOtherValue,=50) \
XX(OneMoreValue,=100) \
DECLARE_ENUM(SomeEnum,SOME_ENUM)
someEnum.cpp:
#include "someEnum.h"
DEFINE_ENUM(SomeEnum,SOME_ENUM)
The technique can be easily extended so that XX macros accepts more arguments, and you can also have prepared more macros to substitute for XX for different needs, similar to the three I have provided in this sample.
Comparison to X-Macros using #include / #define / #undef
While this is similar to X-Macros others have mentioned, I think this solution is more elegant in that it does not require #undefing anything, which allows you to hide more of the complicated stuff is in the factory the header file - the header file is something you are not touching at all when you need to define a new enum, therefore new enum definition is a lot shorter and cleaner.
A: // Define your enumeration like this (in say numbers.h);
ENUM_BEGIN( Numbers )
ENUM(ONE),
ENUM(TWO),
ENUM(FOUR)
ENUM_END( Numbers )
// The macros are defined in a more fundamental .h file (say defs.h);
#define ENUM_BEGIN(typ) enum typ {
#define ENUM(nam) nam
#define ENUM_END(typ) };
// Now in one and only one .c file, redefine the ENUM macros and reinclude
// the numbers.h file to build a string table
#undef ENUM_BEGIN
#undef ENUM
#undef ENUM_END
#define ENUM_BEGIN(typ) const char * typ ## _name_table [] = {
#define ENUM(nam) #nam
#define ENUM_END(typ) };
#undef NUMBERS_H_INCLUDED // whatever you need to do to enable reinclusion
#include "numbers.h"
// Now you can do exactly what you want to do, with no retyping, and for any
// number of enumerated types defined with the ENUM macro family
// Your code follows;
char num_str[10];
int process_numbers_str(Numbers num) {
switch(num) {
case ONE:
case TWO:
case THREE:
{
strcpy(num_str, Numbers_name_table[num]); // eg TWO -> "TWO"
} break;
default:
return 0; //no match
return 1;
}
// Sweet no ? After being frustrated by this for years, I finally came up
// with this solution for my most recent project and plan to reuse the idea
// forever
A: C or C++ does not provide this functionality, although I've needed it often.
The following code works, although it's best suited for non-sparse enums.
typedef enum { ONE, TWO, THREE } Numbers;
char *strNumbers[] = {"one","two","three"};
printf ("Value for TWO is %s\n",strNumbers[TWO]);
By non-sparse, I mean not of the form
typedef enum { ONE, FOUR_THOUSAND = 4000 } Numbers;
since that has huge gaps in it.
The advantage of this method is that it put the definitions of the enums and strings near each other; having a switch statement in a function spearates them. This means you're less likely to change one without the other.
A: KISS. You will be doing all sorts of other switch/case things with your enums so why should printing be different? Forgetting a case in your print routine isn't a huge deal when you consider there are about 100 other places you can forget a case. Just compile -Wall, which will warn of non-exhaustive case matches. Don't use "default" because that will make the switch exhaustive and you wont get warnings. Instead, let the switch exit and deal with the default case like so...
const char *myenum_str(myenum e)
{
switch(e) {
case ONE: return "one";
case TWO: return "two";
}
return "invalid";
}
A: Try Converting C++ enums to strings. The comments have improvements that solve the problem when enum items have arbitrary values.
A: The use of boost::preprocessor makes possible an elegant solution like the following:
Step 1: include the header file:
#include "EnumUtilities.h"
Step 2: declare the enumeration object with the following syntax:
MakeEnum( TestData,
(x)
(y)
(z)
);
Step 3: use your data:
Getting the number of elements:
td::cout << "Number of Elements: " << TestDataCount << std::endl;
Getting the associated string:
std::cout << "Value of " << TestData2String(x) << " is " << x << std::endl;
std::cout << "Value of " << TestData2String(y) << " is " << y << std::endl;
std::cout << "Value of " << TestData2String(z) << " is " << z << std::endl;
Getting the enum value from the associated string:
std::cout << "Value of x is " << TestData2Enum("x") << std::endl;
std::cout << "Value of y is " << TestData2Enum("y") << std::endl;
std::cout << "Value of z is " << TestData2Enum("z") << std::endl;
This looks clean and compact, with no extra files to include.
The code I wrote within EnumUtilities.h is the following:
#include <boost/preprocessor/seq/for_each.hpp>
#include <string>
#define REALLY_MAKE_STRING(x) #x
#define MAKE_STRING(x) REALLY_MAKE_STRING(x)
#define MACRO1(r, data, elem) elem,
#define MACRO1_STRING(r, data, elem) case elem: return REALLY_MAKE_STRING(elem);
#define MACRO1_ENUM(r, data, elem) if (REALLY_MAKE_STRING(elem) == eStrEl) return elem;
#define MakeEnum(eName, SEQ) \
enum eName { BOOST_PP_SEQ_FOR_EACH(MACRO1, , SEQ) \
last_##eName##_enum}; \
const int eName##Count = BOOST_PP_SEQ_SIZE(SEQ); \
static std::string eName##2String(const enum eName eel) \
{ \
switch (eel) \
{ \
BOOST_PP_SEQ_FOR_EACH(MACRO1_STRING, , SEQ) \
default: return "Unknown enumerator value."; \
}; \
}; \
static enum eName eName##2Enum(const std::string eStrEl) \
{ \
BOOST_PP_SEQ_FOR_EACH(MACRO1_ENUM, , SEQ) \
return (enum eName)0; \
};
There are some limitation, i.e. the ones of boost::preprocessor. In this case, the list of constants cannot be larger than 64 elements.
Following the same logic, you could also think to create sparse enum:
#define EnumName(Tuple) BOOST_PP_TUPLE_ELEM(2, 0, Tuple)
#define EnumValue(Tuple) BOOST_PP_TUPLE_ELEM(2, 1, Tuple)
#define MACRO2(r, data, elem) EnumName(elem) EnumValue(elem),
#define MACRO2_STRING(r, data, elem) case EnumName(elem): return BOOST_PP_STRINGIZE(EnumName(elem));
#define MakeEnumEx(eName, SEQ) \
enum eName { \
BOOST_PP_SEQ_FOR_EACH(MACRO2, _, SEQ) \
last_##eName##_enum }; \
const int eName##Count = BOOST_PP_SEQ_SIZE(SEQ); \
static std::string eName##2String(const enum eName eel) \
{ \
switch (eel) \
{ \
BOOST_PP_SEQ_FOR_EACH(MACRO2_STRING, _, SEQ) \
default: return "Unknown enumerator value."; \
}; \
};
In this case, the syntax is:
MakeEnumEx(TestEnum,
((x,))
((y,=1000))
((z,))
);
Usage is similar as above (minus the eName##2Enum function, that you could try to extrapolate from the previous syntax).
I tested it on mac and linux, but be aware that boost::preprocessor may not be fully portable.
A: By merging some of the techniques over here I came up with the simplest form:
#define MACROSTR(k) #k
#define X_NUMBERS \
X(kZero ) \
X(kOne ) \
X(kTwo ) \
X(kThree ) \
X(kFour ) \
X(kMax )
enum {
#define X(Enum) Enum,
X_NUMBERS
#undef X
} kConst;
static char *kConstStr[] = {
#define X(String) MACROSTR(String),
X_NUMBERS
#undef X
};
int main(void)
{
int k;
printf("Hello World!\n\n");
for (k = 0; k < kMax; k++)
{
printf("%s\n", kConstStr[k]);
}
return 0;
}
A: If you are using gcc, it's possible to use:
const char * enum_to_string_map[]={ [enum1]='string1', [enum2]='string2'};
Then just call for instance
enum_to_string_map[enum1]
A: There's no built-in solution. The easiest way is with an array of char* where the enum's int value indexes to a string containing the descriptive name of that enum. If you have a sparse enum (one that doesn't start at 0 or has gaps in the numbering) where some of the int mappings are high enough to make an array-based mapping impractical then you could use a hash table instead.
A: There is definitely a way to do this -- use X() macros. These macros use the C preprocessor to construct enums, arrays and code blocks from a list of source data. You only need to add new items to the #define containing the X() macro. The switch statement would expand automatically.
Your example can be written as follows:
// Source data -- Enum, String
#define X_NUMBERS \
X(ONE, "one") \
X(TWO, "two") \
X(THREE, "three")
...
// Use preprocessor to create the Enum
typedef enum {
#define X(Enum, String) Enum,
X_NUMBERS
#undef X
} Numbers;
...
// Use Preprocessor to expand data into switch statement cases
switch(num)
{
#define X(Enum, String) \
case Enum: strcpy(num_str, String); break;
X_NUMBERS
#undef X
default: return 0; break;
}
return 1;
There are more efficient ways (i.e. using X Macros to create an string array and enum index), but this is the simplest demo.
A: Check out the ideas at Mu Dynamics Research Labs - Blog Archive. I found this earlier this year - I forget the exact context where I came across it - and have adapted it into this code. We can debate the merits of adding an E at the front; it is applicable to the specific problem addressed, but not part of a general solution. I stashed this away in my 'vignettes' folder - where I keep interesting scraps of code in case I want them later. I'm embarrassed to say that I didn't keep a note of where this idea came from at the time.
Header: paste1.h
/*
@(#)File: $RCSfile: paste1.h,v $
@(#)Version: $Revision: 1.1 $
@(#)Last changed: $Date: 2008/05/17 21:38:05 $
@(#)Purpose: Automated Token Pasting
*/
#ifndef JLSS_ID_PASTE_H
#define JLSS_ID_PASTE_H
/*
* Common case when someone just includes this file. In this case,
* they just get the various E* tokens as good old enums.
*/
#if !defined(ETYPE)
#define ETYPE(val, desc) E##val,
#define ETYPE_ENUM
enum {
#endif /* ETYPE */
ETYPE(PERM, "Operation not permitted")
ETYPE(NOENT, "No such file or directory")
ETYPE(SRCH, "No such process")
ETYPE(INTR, "Interrupted system call")
ETYPE(IO, "I/O error")
ETYPE(NXIO, "No such device or address")
ETYPE(2BIG, "Arg list too long")
/*
* Close up the enum block in the common case of someone including
* this file.
*/
#if defined(ETYPE_ENUM)
#undef ETYPE_ENUM
#undef ETYPE
ETYPE_MAX
};
#endif /* ETYPE_ENUM */
#endif /* JLSS_ID_PASTE_H */
Example source:
/*
@(#)File: $RCSfile: paste1.c,v $
@(#)Version: $Revision: 1.2 $
@(#)Last changed: $Date: 2008/06/24 01:03:38 $
@(#)Purpose: Automated Token Pasting
*/
#include "paste1.h"
static const char *sys_errlist_internal[] = {
#undef JLSS_ID_PASTE_H
#define ETYPE(val, desc) desc,
#include "paste1.h"
0
#undef ETYPE
};
static const char *xerror(int err)
{
if (err >= ETYPE_MAX || err <= 0)
return "Unknown error";
return sys_errlist_internal[err];
}
static const char*errlist_mnemonics[] = {
#undef JLSS_ID_PASTE_H
#define ETYPE(val, desc) [E ## val] = "E" #val,
#include "paste1.h"
#undef ETYPE
};
#include <stdio.h>
int main(void)
{
int i;
for (i = 0; i < ETYPE_MAX; i++)
{
printf("%d: %-6s: %s\n", i, errlist_mnemonics[i], xerror(i));
}
return(0);
}
Not necessarily the world's cleanest use of the C pre-processor - but it does prevent writing the material out multiple times.
A: Making something both a C identifier and a string
A: #define stringify( name ) # name
enum MyEnum {
ENUMVAL1
};
...stuff...
stringify(EnumName::ENUMVAL1); // Returns MyEnum::ENUMVAL1
Further discussion on this method
Preprocessor directive tricks for newcomers
A: If the enum index is 0-based, you can put the names in an array of char*, and index them with the enum value.
A: I thought that a solution like Boost.Fusion one for adapting structs and classes would be nice, they even had it at some point, to use enums as a fusion sequence.
So I made just some small macros to generate the code to print the enums. This is not perfect and has nothing to see with Boost.Fusion generated boilerplate code, but can be used like the Boost Fusion macros. I want to really do generate the types needed by Boost.Fusion to integrate in this infrastructure which allows to print names of struct members, but this will happen later, for now this is just macros :
#ifndef SWISSARMYKNIFE_ENUMS_ADAPT_ENUM_HPP
#define SWISSARMYKNIFE_ENUMS_ADAPT_ENUM_HPP
#include <swissarmyknife/detail/config.hpp>
#include <string>
#include <ostream>
#include <boost/preprocessor/cat.hpp>
#include <boost/preprocessor/stringize.hpp>
#include <boost/preprocessor/seq/for_each.hpp>
#define SWISSARMYKNIFE_ADAPT_ENUM_EACH_ENUMERATION_ENTRY_C( \
R, unused, ENUMERATION_ENTRY) \
case ENUMERATION_ENTRY: \
return BOOST_PP_STRINGIZE(ENUMERATION_ENTRY); \
break;
/**
* \brief Adapts ENUM to reflectable types.
*
* \param ENUM_TYPE To be adapted
* \param ENUMERATION_SEQ Sequence of enum states
*/
#define SWISSARMYKNIFE_ADAPT_ENUM(ENUM_TYPE, ENUMERATION_SEQ) \
inline std::string to_string(const ENUM_TYPE& enum_value) { \
switch (enum_value) { \
BOOST_PP_SEQ_FOR_EACH( \
SWISSARMYKNIFE_ADAPT_ENUM_EACH_ENUMERATION_ENTRY_C, \
unused, ENUMERATION_SEQ) \
default: \
return BOOST_PP_STRINGIZE(ENUM_TYPE); \
} \
} \
\
inline std::ostream& operator<<(std::ostream& os, const ENUM_TYPE& value) { \
os << to_string(value); \
return os; \
}
#endif
The old answer below is pretty bad, please don't use that. :)
Old answer:
I've been searching a way which solves this problem without changing too much the enums declaration syntax. I came to a solution which uses the preprocessor to retrieve a string from a stringified enum declaration.
I'm able to define non-sparse enums like this :
SMART_ENUM(State,
enum State {
RUNNING,
SLEEPING,
FAULT,
UNKNOWN
})
And I can interact with them in different ways:
// With a stringstream
std::stringstream ss;
ss << State::FAULT;
std::string myEnumStr = ss.str();
//Directly to stdout
std::cout << State::FAULT << std::endl;
//to a string
std::string myStr = State::to_string(State::FAULT);
//from a string
State::State myEnumVal = State::from_string(State::FAULT);
Based on the following definitions :
#define SMART_ENUM(enumTypeArg, ...) \
namespace enumTypeArg { \
__VA_ARGS__; \
std::ostream& operator<<(std::ostream& os, const enumTypeArg& val) { \
os << swissarmyknife::enums::to_string(#__VA_ARGS__, val); \
return os; \
} \
\
std::string to_string(const enumTypeArg& val) { \
return swissarmyknife::enums::to_string(#__VA_ARGS__, val); \
} \
\
enumTypeArg from_string(const std::string &str) { \
return swissarmyknife::enums::from_string<enumTypeArg>(#__VA_ARGS__, str); \
} \
} \
namespace swissarmyknife { namespace enums {
static inline std::string to_string(const std::string completeEnumDeclaration, size_t enumVal) throw (std::runtime_error) {
size_t begin = completeEnumDeclaration.find_first_of('{');
size_t end = completeEnumDeclaration.find_last_of('}');
const std::string identifiers = completeEnumDeclaration.substr(begin + 1, end );
size_t count = 0;
size_t found = 0;
do {
found = identifiers.find_first_of(",}", found+1);
if (enumVal == count) {
std::string identifiersSubset = identifiers.substr(0, found);
size_t beginId = identifiersSubset.find_last_of("{,");
identifiersSubset = identifiersSubset.substr(beginId+1);
boost::algorithm::trim(identifiersSubset);
return identifiersSubset;
}
++count;
} while (found != std::string::npos);
throw std::runtime_error("The enum declaration provided doesn't contains this state.");
}
template <typename EnumType>
static inline EnumType from_string(const std::string completeEnumDeclaration, const std::string &enumStr) throw (std::runtime_error) {
size_t begin = completeEnumDeclaration.find_first_of('{');
size_t end = completeEnumDeclaration.find_last_of('}');
const std::string identifiers = completeEnumDeclaration.substr(begin + 1, end );
size_t count = 0;
size_t found = 0;
do {
found = identifiers.find_first_of(",}", found+1);
std::string identifiersSubset = identifiers.substr(0, found);
size_t beginId = identifiersSubset.find_last_of("{,");
identifiersSubset = identifiersSubset.substr(beginId+1);
boost::algorithm::trim(identifiersSubset);
if (identifiersSubset == enumStr) {
return static_cast<EnumType>(count);
}
++count;
} while (found != std::string::npos);
throw std::runtime_error("No valid enum value for the provided string");
}
}}
When I'll need support for sparse enum and when I'll have more time I'll improve the to_string and from_string implementations with boost::xpressive, but this will costs in compilation time because of the important templating performed and the executable generated is likely to be really bigger. But this has the advantage that it will be more readable and maintanable than this ugly manual string manipulation code. :D
Otherwise I always used boost::bimap to perform such mappings between enums value and string, but it has to be maintained manually.
A: I have created a simple templated class streamable_enum that uses stream operators << and >> and is based on the std::map<Enum, std::string>:
#ifndef STREAMABLE_ENUM_HPP
#define STREAMABLE_ENUM_HPP
#include <iostream>
#include <string>
#include <map>
template <typename E>
class streamable_enum
{
public:
typedef typename std::map<E, std::string> tostr_map_t;
typedef typename std::map<std::string, E> fromstr_map_t;
streamable_enum()
{}
streamable_enum(E val) :
Val_(val)
{}
operator E() {
return Val_;
}
bool operator==(const streamable_enum<E>& e) {
return this->Val_ == e.Val_;
}
bool operator==(const E& e) {
return this->Val_ == e;
}
static const tostr_map_t& to_string_map() {
static tostr_map_t to_str_(get_enum_strings<E>());
return to_str_;
}
static const fromstr_map_t& from_string_map() {
static fromstr_map_t from_str_(reverse_map(to_string_map()));
return from_str_;
}
private:
E Val_;
static fromstr_map_t reverse_map(const tostr_map_t& eToS) {
fromstr_map_t sToE;
for (auto pr : eToS) {
sToE.emplace(pr.second, pr.first);
}
return sToE;
}
};
template <typename E>
streamable_enum<E> stream_enum(E e) {
return streamable_enum<E>(e);
}
template <typename E>
typename streamable_enum<E>::tostr_map_t get_enum_strings() {
// \todo throw an appropriate exception or display compile error/warning
return {};
}
template <typename E>
std::ostream& operator<<(std::ostream& os, streamable_enum<E> e) {
auto& mp = streamable_enum<E>::to_string_map();
auto res = mp.find(e);
if (res != mp.end()) {
os << res->second;
} else {
os.setstate(std::ios_base::failbit);
}
return os;
}
template <typename E>
std::istream& operator>>(std::istream& is, streamable_enum<E>& e) {
std::string str;
is >> str;
if (str.empty()) {
is.setstate(std::ios_base::failbit);
}
auto& mp = streamable_enum<E>::from_string_map();
auto res = mp.find(str);
if (res != mp.end()) {
e = res->second;
} else {
is.setstate(std::ios_base::failbit);
}
return is;
}
#endif
Usage:
#include "streamable_enum.hpp"
using std::cout;
using std::cin;
using std::endl;
enum Animal {
CAT,
DOG,
TIGER,
RABBIT
};
template <>
streamable_enum<Animal>::tostr_map_t get_enum_strings<Animal>() {
return {
{ CAT, "Cat"},
{ DOG, "Dog" },
{ TIGER, "Tiger" },
{ RABBIT, "Rabbit" }
};
}
int main(int argc, char* argv []) {
cout << "What animal do you want to buy? Our offering:" << endl;
for (auto pr : streamable_enum<Animal>::to_string_map()) { // Use from_string_map() and pr.first instead
cout << " " << pr.second << endl; // to have them sorted in alphabetical order
}
streamable_enum<Animal> anim;
cin >> anim;
if (!cin) {
cout << "We don't have such animal here." << endl;
} else if (anim == Animal::TIGER) {
cout << stream_enum(Animal::TIGER) << " was a joke..." << endl;
} else {
cout << "Here you are!" << endl;
}
return 0;
}
A: Here is a solution using macros with the following features:
*
*only write each value of the enum once, so there are no double lists to maintain
*don't keep the enum values in a separate file that is later #included, so I can write it wherever I want
*don't replace the enum itself, I still want to have the enum type defined, but in addition to it I want to be able to map every enum name to the corresponding string (to not affect legacy code)
*the searching should be fast, so preferably no switch-case, for those huge enums
https://stackoverflow.com/a/20134475/1812866
A: Because I prefer not to use macros for all the usual reasons, I used a more limited macro solution that has the advantage of keeping the enum declaration macro free. Disadvantages include having to copy paste the macro defintion for each enum, and having to explicitly add a macro invocation when adding values to the enum.
std::ostream& operator<<(std::ostream& os, provenance_wrapper::CaptureState cs)
{
#define HANDLE(x) case x: os << #x; break;
switch (cs) {
HANDLE(CaptureState::UNUSED)
HANDLE(CaptureState::ACTIVE)
HANDLE(CaptureState::CLOSED)
}
return os;
#undef HANDLE
}
A: There's a way simpler and imo sorta clearer approach
that was missing on this thread:
#define ENUM_PUSH(ENUM) ENUM,
#define STRING_PUSH(STR) #STR,
#define FETCH_MSG(X) \
X(string1) \
X(string2) \
static const char * msgStr[] = {
FETCH_MSG(STRING_PUSH)
};
enum msg {
FETCH_MSG(ENUM_PUSH)
};
static enum msg message;
void iterate(void) {
switch (message) {
case string1:
// do your thing here
break;
case string2:
break;
}
}
The only downside is that the last cell will be postceded by a comma,
though it appears to be acceptable by C/C++ compilers.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147267",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "96"
} |
Q: Multithreaded Memory Allocators for C/C++ I currently have heavily multi-threaded server application, and I'm shopping around for a good multi-threaded memory allocator.
So far I'm torn between:
*
*Sun's umem
*Google's tcmalloc
*Intel's threading building blocks allocator
*Emery Berger's hoard
From what I've found hoard might be the fastest, but I hadn't heard of it before today, so I'm skeptical if its really as good as it seems. Anyone have personal experience trying out these allocators?
A: I personally prefer and recommend ptmalloc as a multithreaded allocator. Hoard is good, but in the evaluation my team did between Hoard and ptmalloc a few years ago, ptmalloc was better. From what I know, ptmalloc has been around for a number of years and is quite widely used as a multithreaded allocator.
You might find this comparison useful.
A: Maybe this is the wrong way to approach what you are asking, but maybe a different tactic could be employed altogether. If you are looking for a really fast memory allocator maybe you should ask why you need to be spending all that time allocating memory when you could perhaps just get away with stack allocation of variables. Stack allocation, while way more annoying, done right could save you lots in the way of mutex contention, as well as keeping strange memory corruption issues out of your code. Also, you potentially have less fragmentation which could help.
A: We used hoard on a project where I worked a few years ago. It seemed to work great. I have no experience iwth the other allocators. It should be pretty easy to try different ones and do load testing, no?
A: The locklessinc allocator is very good and the developer is responsive if you have questions. There's an article he wrote about some of the optimization tricks used, it's an interesting read: http://locklessinc.com/articles/allocator_tricks/. I've used it in the past with excellent results.
A: Probably a late response to your question , but
why to do mallocs if you have performance hick ups ?
Better way would be to do a malloc of a big memory window at the initialization and then come up with a light weight Memory manager that would lease out the memory chunks at run time.
This avoids any possibility of system calls if your heap expansion.
A: You can try ltalloc (general purpose global memory allocator with speed of fast pool allocator).
A: I've used tcmalloc and read about Hoard. Both have similar implementations and both achieve roughly linear performance scaling with respect to the number of threads/CPUs (according to the graphs on their respective sites).
So: if performance is really that incredibly crucial, then do performance/load testing. Otherwise, just roll a dice and pick one of the listed (weighted by ease of use on your target platform).
And from trshiv's link, it looks like Hoard, tcmalloc, and ptmalloc are all roughly comparable for speed. Overall, tt looks like ptmalloc is optimized for taking as little room as possible, Hoard is optimized for a trade-off of speed + memory usage, and tcmalloc is optimized for pure speed.
A: The only way to really tell which memory allocator is right for your application is to try a few out. All of the allocators mentioned were written by smart folks and will beat the others on one particular microbenchmark or another. If all your application does all day long is malloc one 8 byte chunk in thread A and free it in thread B, and doesn't need to handle anything else at all, you could probably write a memory allocator that beats the pants off any of those listed so far. It just won't be very useful for much else. :)
I have some experience using Hoard where I work (enough so that one of the more obscure bugs addressed in the recent 3.8 release was found as a result of that experience). It's a very good allocator - but how good, for you, depends on your workload. And you do have to pay for Hoard (though it's not too expensive) in order to use it in a commercial project without GPL'ing your code.
A very slightly adapted ptmalloc2 has been the allocator behind glibc's malloc for quite a while now, and so it's incredibly widely used and tested. If stability is important above all things, it might be a good choice, but you didn't mention it in your list, so I'll assume it's out. For certain workloads, it's terrible - but the same is true of any general purpose malloc.
If you're willing to pay for it (and the price is reasonable, in my experience), SmartHeap SMP is also a good choice. Most of the other allocators mentioned are designed as drop-in malloc/free new/delete replacements that can be LD_PRELOAD'd. SmartHeap can be used that way as well, but it also includes an entire allocation-related API that lets you fine-tune your allocators to your heart's content. In tests that we've done (again, very specific to a particular application), SmartHeap was about the same as Hoard for performance when acting as a drop-in malloc replacement; the real difference between the two is the degree of customization. You can get better performance the less general-purpose you need your allocator to be.
And depending on your use case, a general-purpose multithreaded allocator might not be what you want to use at all; if you're constantly malloc & free'ing objects that are all the same size, you might want to just write a simple slab allocator. Slab allocation is used in several places in the Linux kernel that fit that description. (I would give you a couple more useful links, but I'm a "new user" and Stack Overflow has decided that new users are not allowed to be too helpful all in one answer. Google can help out well enough, though.)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147298",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "37"
} |
Q: .NET : How to set user information in an EventLog Entry? The System.Diagnostics.EventLog class provides a way to interact with a windows event log. I use it all the time for simple logging...
System.Diagnostics.EventLog.WriteEntry("MyEventSource", "My Special Message")
Is there a way to set the user information in the resulting event log entry using .NET?
A: Toughie ...
I looked for a way to fill the user field with a .NET method. Unfortunately there is none, and you must import the plain old Win32 API [ReportEvent function](http://msdn.microsoft.com/en-us/library/aa363679(VS.85).aspx) with a DLLImportAttribute
You must also redeclare the function with the right types, as Platform Invoke Data Types says
So
BOOL ReportEvent(
__in HANDLE hEventLog,
__in WORD wType,
__in WORD wCategory,
__in DWORD dwEventID,
__in PSID lpUserSid,
__in WORD wNumStrings,
__in DWORD dwDataSize,
__in LPCTSTR *lpStrings,
__in LPVOID lpRawData
);
becomes
[DllImport("Advapi32.dll", EntryPoint="ReportEventW", SetLastError=true,
CharSet=CharSet.Unicode)]
bool WriteEvent(
IntPtr hEventLog, //Where to find it ?
ushort wType,
ushort wCategory,
ulong dwEventID,
IntPtr lpUserSid, // We'll leave this struct alone, so just feed it a pointer
ushort wNumStrings,
ushort dwDataSize,
string[] lpStrings,
IntPtr lpRawData
);
You also want to look at [OpenEventLog](http://msdn.microsoft.com/en-us/library/aa363672(VS.85).aspx) and [ConvertStringSidToSid](http://msdn.microsoft.com/en-us/library/aa376402(VS.85).aspx)
Oh, and you're writing unmanaged code now... Watch out for memory leaks.Good luck :p
A: You need to add it yourself into the event message.
Use the System.Security.Principal namespace to get the current identity of the thread logging the event.
A: Usually, the user executing the code that calls the EventLog.WriteEntry method will be the user displayed in the event log for the entry.
You could try impersonating another user by creating your own Principal and Identity and associating it with the current thread, however this is not advised as it could introduce security issues and will definitely complicate your application.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147307",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: MySQL Row Format: Difference between fixed and dynamic? MySQL specifies the row format of a table as either fixed or dynamic, depending on the column data types. If a table has a variable-length column data type, such as TEXT or VARCHAR, the row format is dynamic; otherwise, it's fixed.
My question is, what's the difference between the two row formats? Is one more efficient than the other?
A: This page in MySQL's documentation seems to contradict the top answer here, in that DYNAMIC row format means something for InnoDB tables as well:
https://dev.mysql.com/doc/refman/5.7/en/innodb-row-format.html
A: The difference really only matters for MyISAM, other storage engines do not care about the difference.
EDIT : Many users commented that InnoDB does care: link 1 by steampowered, link 2 by Kaan.
With MyISAM with fixed width rows, there are a few advantages:
*
*No row fragmentation: It is possible with variable width rows to get single rows split into multiple sections across the data file. This can increase disk seeks and slow down operations. It is possible to defrag it with OPTIMIZE TABLE, but this isn't always practical.
*Data file pointer size: In MyISAM, there is a concept of a data file pointer which is used when it needs to reference the data file. For example, this is used in indexes when they refer to where the row actually is present. With fixed width sizes, this pointer is based on the row offset in the file (ie. rows are 1, 2, 3 regardless of their size). With variable width, the pointer is based on the byte offset (ie. rows might be 1, 57, 163). The result is that with large tables, the pointer needs to be larger which then adds potentially a lot more overhead to the table.
*Easier to fix in the case of corruption. Since every row is the same size, if your MyISAM table gets corrupted it is much easier to repair, so you will only lose data that is actually corrupted. With variable width, in theory it is possible that the variable width pointers get messed up, which can result in hosing data in a bad way.
Now the primary drawback of fixed width is that it wastes more space. For example, you need to use CHAR fields instead of VARCHAR fields, so you end up with extra space taken up.
Normally, you won't have much choice in the format, since it is dictated based on the schema. However, it might be worth if you only have a few varchar's or a single blob/text to try to optimize towards this. For example, consider switching the only varchar into a char, or split the blob into it's own table.
You can read even more about this at:
http://dev.mysql.com/doc/refman/5.0/en/static-format.html
http://dev.mysql.com/doc/refman/5.0/en/dynamic-format.html
A: Fixed means that every row is exactly the same size. That means that if the 3rd row on a data page needs to be loaded, it will be at exactly PageHeader+2*RowSize, saving some access time.
In order to find the beginning of a dynamic record, the list of record offsets must be consulted, which involves an extra indirection.
In short, yes, there's a slight performance hit for dynamic rows. No, it's not a very big one. If you think it will be a problem, test for it.
A: One key difference occurs when you update a record. If the row format is fixed, there is no change in the length of the record. In contrast, if the row format is dynamic and the new data causes the record to increase in length, a link is used to point to the "overflow" data (i.e. it's called the overflow pointer).
This fragments the table and generally slows things down. There is a command to defragment (OPTIMIZE TABLE), which somewhat mitigates the issue.
A: Fixed should be faster and more secure than dynamic, with the drawback of having a fixed char-lenght.
You can find this information here: http://dev.mysql.com/doc/refman/5.0/en/static-format.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147315",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "51"
} |
Q: CScrollView and window size (MFC Question) What's the best way to determine the current displayed client area in a CScrollView? I only need the size of the visible portion, so GetClientRect() won't work here.
A: You do need to use GetClientRect(), but I think you're asking the wrong question. It is not so that in a scrolled view there is a very big client window that is physically scrolled. Instead, when you scroll, the DC's viewportext and mapping mode are adjusted, which make it seem like your view is bigger than it actually is. So, if you want to draw a line from the top left corner of the bottom right corner of the current viewport, you do need GetViewPortOrg() and GetViewportExt(). If these return the wrong values, something is wrong in your use of CScrollView. Did you call SetScrollSizes()?
A: Inside your OnDraw() function, you could call pDC->GetViewportOrg and pDC->GetViewportExt.
EDIT: Sorry, I forgot that Viewport extents are only scaling factors. I agree that what you really need here is the client rect.
A: Yep, you're both right. GetClientRect was exactly what I needed. A brain fart on my part...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147323",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Accepting form fields via HTTP Post in WCF I need to accept form data to a WCF-based service. Here's the interface:
[OperationContract]
[WebInvoke(UriTemplate = "lead/inff",
BodyStyle = WebMessageBodyStyle.WrappedRequest)]
int Inff(Stream input);
Here's the implementation (sample - no error handling and other safeguards):
public int Inff(Stream input)
{
StreamReader sr = new StreamReader(input);
string s = sr.ReadToEnd();
sr.Dispose();
NameValueCollection qs = HttpUtility.ParseQueryString(s);
Debug.WriteLine(qs["field1"]);
Debug.WriteLine(qs["field2"]);
return 0;
}
Assuming WCF, is there a better way to accomplish this besides parsing the incoming stream?
A: I remember speaking to you about this at DevLink.
Since you have to support form fields the mechanics of getting those (what you are currently doing) don't change.
Something that might be helpful, especially if you want to reuse your service for new applications that don't require the form fields is to create a channel that deconstructs your stream and repackages it to XML/JSON/SOAP/Whatever and have your form clients communicate with the service through that while clients that don't use forms can use another channel stack. Just an idea...
Hope that helps. If you need help with the channel feel free to let me know.
A: You can serialize your form fields with jquery and package it as json request to wcf service.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147328",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Visual Studio 6 tips and tricks Some of us would invariably have to support 'legacy' code using Microsoft's Visual Studio 6.0 IDEs which - although opinions would differ - are generally regarded to be less user friendly compared to the later incarnations of the Visual Studio series of IDEs.
So I'd like to hear about some of your best hidden/poorly documented IDE features (could be for either C++ or VB). As is the usual practice one feature per post, please.
A: Custom Code Templates in VB6
I don't know if this is really a "hidden" feature or not, but always thought it was a nice time-saver.
You can create your own custom templates for classes, modules, forms, etc. and make them available in the IDE. For example, I usually like to use strongly-typed Collection classes in my VB6 code. So I might want a FooCollection that holds Foo objects and nothing else, instead of a plain old Collection. I don't want to have to reimplement the Collection interface every time I need a new strongly-typed Collection, so I created a new class template that contained all the boiler-plate Collection code. Now whenever I go to add a new class module to my project, my custom TypedCollection template is available as an option. Then I just rename the newly-added class FooCollection and replace all occurences of "As Object" with "As Foo" (where Foo is the type of object I want to store in the collection) and I'm done.
Keeping with my custom class template example, here's what you do:
*
*Open up the IDE and start a new project (I usually just do Standard EXE, because it doesn't really matter what you pick here).
*Add a new class to the project. This will become your template.
*Code your template class. Basically just write any boiler-plate code that you would like to be able to reuse in other projects. This is straight VB code, nothing special.
*When you're finished save your file in your C:\Program Files\Microsoft Visual Studio\VB6\Template\Classes folder (Note: the other subfolders, such as Forms, etc. are for other kinds of templates). The name of the .cls file minus the extension is what will appear in the IDE, so I normally include spaces in the file name for readability.
*The next time you open up your IDE and click Project->Add Class Module, your template class will appear in the list of available class templates.
A: You can edit the file C:\Program Files\Microsoft Visual Studio\Common\MSDev98\Bin\AUTOEXP.DAT to add rules for displaying meaningful values of your custom classes in the Debug Watch Window.
What I mean is this. We have a date structure defined like this:
typedef struct tagMHDATE
{
short int nDay; // Day of the Month 1..31
short int nMonth; // Month of the Year 1..12
short int nYear; // Year
} MHDATE, FAR *LPMHDATE;
If I have this code:
MHDATE today;
GetDate(&today);
...and drop today in the watch window, I'll see something like this:
today {...}
Now go and add this to the end of AUTOEXP.DAT (it's just a text file)
tagMHDATE=date=<nMonth>/<nDay>/<nYear>
...and now I see this in the Watch window:
today {date=10/8/2008}
A: I'll kick this off a VS C++ feature which has saved me lots of time: appending a ",su" (without the quotes) to a unicode string in the watch window of a debugger enables you to view the value of the string (rather than the memory address of that string)
A: The Erl function in VB6. If you put line numbers in your VB6 code, you can, in your error handler, access the line number at which your error occurred via the return value of the function Erl.
A: There are quite a few tips and tricks here. My favorite one is placing @err,hr
in the Watch window to get error messages.
A: For VC6, get a copy of Visual Assist X by Whole Tomato. It contains a smart (and usable) Intellisense replacement, much richer code coloring, some refactoring support, and many more features. Most definitely worth the investment.
A: Change the "Start in" property on the shortcut that you use to start VB6 to the root of your source code directory. This will save many wasted mouse clicks every time you open a project from within the IDE.
A: CodeShine: VB6 code refactoring add-in (free). Includes refactorings such as Extract Method, Introduce Explaining Variable, Extract Function, Introduce Explaining Variable, Rename, etc
http://www.wsdesigns.com/CodeShine/default.htm
A: Quick macros was always a personal favorite of mine; not really a hidden feature per-se, but very useful, and VC6 was the last version where they were quick enough to be useful (before MS rewrote the macro engine to use .NET).
A: Last time I had to use VB6, I wanted to jump out of my skin in anger because the scroll wheel on my mouse, which literally works with every other program in Windows, didn't work. This has something to do with the age of VB6 and how Microsoft has changed scroll wheel functionality over the years.
This guy wrote a program to make it work.
(and it looks like in the years since Microsoft made a fix as well)
A: For VB6, MZ-Tools is a fantastic free add-in. My favorite features are its find feature and its ability to find all callers of a given routine with a click of the button. It has several other features as well, several of which I've found helpful on occasion.
A: Shift-Alt-Enter to increase the size of the editor window
A: My answer to the question "If you are not satisfied with answers on someone else’s question, should you start your own?" shows how to pre-populate VC++ with all your source paths. It's useful for those of us who build from the command line, but debug using msdev.
A: Not really a VB6 IDE feature, but if you have to fill an unbound listview with a lot of data then making it invisible during the filling process speeds it up by maybe a factor of 10.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147339",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: Converting Win16 C code to Win32 In general, what needs to be done to convert a 16 bit Windows program to Win32? I'm sure I'm not the only person to inherit a codebase and be stunned to find 16-bit code lurking in the corners.
The code in question is C.
A: Apart from getting your build environment right, Here are few specifics you will need to address:
*
*structs containing ints will need to change to short or widen from 16 to 32 bits. If you change the size of the structure and this is loaded/saved to disk you will need write data file upgrade code.
*Per window data is often stored with the window handle using GWL_USERDATA. If you widen some of the data to 32 bits, your offsets will change.
*POINT & SIZE structures are 64 bits in Win32. In Win16 they were 32 bits and could be returned as a DWORD (caller would split return value into two 16 bit values). This no longer works in Win32 (i.e. Win32 does not return 64 bit results) and the functions were changed to accept a pointers to store the return values. You will need to edit all of these. APIs like GetTextExtent are affected by this. This same issue also applies to some Windows messages.
*The use of INI files is discouraged in Win32 in favour of the registry. While the INI file functions still work you will need to be careful with Vista issues. 16 bit programs often stored their INI file in the Windows system directory.
This is just a few of the issues I can recall. It has been over a decade since I did any Win32 porting. Once you get into it it is quite quick. Each codebase will have its own "feel" when it comes to porting which you will get used to. You will probably even find a few bugs along the way.
A: There was a definitive guide in the article Porting 16-Bit Code to 32-Bit Windows on MSDN.
A: *
*The meanings of wParam and lParam have changed in many places. I strongly encourage you to be paranoid and convert as much as possible to use message crackers. They will save you no end of headaches. If there is only one piece of advice I could give you, this would be it.
*As long as you're using message crackers, also enable STRICT. It'll help you catch the Win16 code base using int where it should be using HWND, HANDLE, or something else. Converting these will greatly help with #9 on this list.
*hPrevInstance is useless. Make sure it's not used.
*Make sure you're using Unicode-friendly calls. That doesn't mean you need to convert everything to TCHARs, but means you better replace OpenFile, _lopen, and _lcreat with CreateFile, to name the obvious
*LibMain is now DllMain, and the entire library format and export conventions are different
*Win16 had no VMM. GlobalAlloc, LocalAlloc, GlobalFree, and LocalFree should be replaced with more modern equivalents. When done, clean up calls to LocalLock, LocalUnlock and friends; they're now useless. Not that I can imagine your app doing this, but make sure you don't depend on WM_COMPACTING while you're there.
*Win16 also had no memory protection. Make sure you're not using SendMessage or PostMessage to send pointers to out-of-process windows. You'll need to switch to a more modern IPC mechanism, such as pipes or memory-mapped files.
*Win16 also lacked preemptive multitasking. If you wanted a quick answer from another window, it was totally cool to call SendMessage and wait for the message to be processed. That may be a bad idea now. Consider whether PostMessage isn't a better option.
*Pointer and integer sizes change. Remember to check carefully anywhere you're reading or writing data to disk—especially if they're Win16 structures. You'll need to manually redo them to handle the shorter values. Again, the least painful way to deal with this will be to use message crackers where possible. Otherwise, you'll need to manually hunt down and convert int to DWORD and so on where applicable.
*Finally, when you've nailed the obvious, consider enabling 64-bit compilation checks. A lot of the issues faced with going from 16 to 32 bits are the same as going from 32 to 64, and Visual C++ is actually pretty smart these days. Not only will you catch some lingering issues; you'll get yourself ready for your eventual Win64 migration, too.
EDIT: As @ChrisN points out, the official guide for porting Win16 apps to Win32 is available archived, and both fleshes out and adds to my points above.
A: The original win32 sdk had a tool that scanned source code and flagged lines that needed to be changed, but I can't remember the name of the tool.
When I've had to do this in the past, I've used a brute force technique - i.e.:
1 - update makefiles or build environment to use 32 bit compiler and linker. Optionally, just create a new project in your IDE (I use Visual Studio), and add the files manually.
2 - build
3 - fix errors
4 - repeat 2&3 until done
The pain of the process depends on the application you are migrating. I've converted 10,000 line programs in an hour, and 75,000 line programs in less than a week. I've also had some small utilities that I just gave up on and rewrote (mostly) from scratch.
A: I agree with Alan that trial and error is probably the best way.
Here are some good tips.
A: Agreed that the compiler will probably catch most of the errors. Also, if you are using "near" and "far" pointers you can remove those designations -- a pointer is just a pointer in Win32.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147351",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
} |
Q: How to save an encrypted string to the database? I have this function in VB.net "ENCRYPT" (see below)
Private key() As Byte = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24}
Private iv() As Byte = {65, 110, 68, 26, 69, 178, 200, 219}
Public Function Encrypt(ByVal plainText As String) As Byte()
' Declare a UTF8Encoding object so we may use the GetByte
' method to transform the plainText into a Byte array.
Dim utf8encoder As UTF8Encoding = New UTF8Encoding()
Dim inputInBytes() As Byte = utf8encoder.GetBytes(plainText)
' Create a new TripleDES service provider
Dim tdesProvider As TripleDESCryptoServiceProvider = New TripleDESCryptoServiceProvider()
' The ICryptTransform interface uses the TripleDES
' crypt provider along with encryption key and init vector
' information
Dim cryptoTransform As ICryptoTransform = tdesProvider.CreateEncryptor(Me.key, Me.iv)
' All cryptographic functions need a stream to output the
' encrypted information. Here we declare a memory stream
' for this purpose.
Dim encryptedStream As MemoryStream = New MemoryStream()
Dim cryptStream As CryptoStream = New CryptoStream(encryptedStream, cryptoTransform, CryptoStreamMode.Write)
' Write the encrypted information to the stream. Flush the information
' when done to ensure everything is out of the buffer.
cryptStream.Write(inputInBytes, 0, inputInBytes.Length)
cryptStream.FlushFinalBlock()
encryptedStream.Position = 0
' Read the stream back into a Byte array and return it to the calling method.
Dim result(encryptedStream.Length - 1) As Byte
encryptedStream.Read(result, 0, encryptedStream.Length)
cryptStream.Close()
Return result
End Function
I want to save the encrypted string in the SQL database. How do I do it?
A: Simply store in a binary column. (Mostly done from memory, corrections welcome!)
CREATE TABLE [Test]
(
[Id] NOT NULL IDENTITY(1,1) PRIMARY KEY,
[Username] NOT NULL VARCHAR(500),
[Password] NOT NULL VARBINARY(500)
)
Then insert such:
Dim conn As SqlConnection
Try
conn = New SqlConnection("<connectionstring>")
Dim command As New SqlCommand("INSERT INTO [Test] ([Username], [Password]) VALUES (@Username, @Password)", conn)
Dim usernameParameter = New SqlParameter("@Username", SqlDbType.VarChar)
usernameParameter.Value = username
command.Parameters.Add(usernameParameter)
Dim passwordParameter = New SqlParameter("@Password", SqlDbType.VarBinary)
passwordParameter.Value = password
command.Parameters.Add(passwordParameter)
command.ExecuteNonQuery()
Finally
If (Not (conn Is Nothing)) Then
conn.Close()
End If
End Try
A: Encode the array of byte into a string. 0x00 can be "00" and 0xFF can be "FF." Or you can take at look at Base64.
A: An encripted string should be no different to any binary data.
If you know the results are going to be small you could uuencode it and save it in a text field.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147359",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: What is the best way to test a stored procedure? Like many companies that require all access be through stored procedures, we seem to have a lot of business logic locked away in sprocs. These things are just plain hard to test, and some of them have become silly long. Does anyone out there have a set of best practices that can make it a little easier to confidently test these things?
At present we maintain 30 or so "Problem" databases that we run against. This isn't always particularly well documented and it sure isn't automated.
A: We had a very thin Data Access layer which basically facaded stored procedures to look like C# methods. Our NUnit test-suite then had SetUp/TearDown to create/rollback a transaction and test methods that called into DAL. Nothing fancy, and proved to be easier to maintain than TSQLUnit test-suite.
A: Not sure if this is what you're looking for, but since you're using SQL Server: I've found LINQ to be a great tool test stored procs. You can just drag the stored procedures onto a DBML diagram and then call them as methods on your datacontext. Beats setting up ADO connections etc for a test harness. If you set up a test project in Visual Studio for example, you can simply test your procedures like methods on another object. If your stored procs return result sets, I think LINQ will translate that into anonymous variables that you should be able to access via IEnumerable or IQueryable (somebody pls verify this). But if you're returning return codes only, this should be a quick and fairly easy way.
A: I noticed your post was tagged as SqlServer. If that's the case, then you should look at the Team Edition for Database Professionals that is part of Visual Studio. Here's some articles:
*
*A tutorial I wrote on TDDing Stored Procs with DBPro
*an MSDN magazine article which goes more in-depth
*DbFit, a framework which integrates with FIT and Fitnesse to do functional testing of databases
The last one is actually cross-DB platform, while DBPro is solely SQL Server for now.
A: One method that I've used is to write a 'temporary' unit test for refactoring a particular stored procedure. You save the data from a set of queries from a database, and store them somewhere where a unit test can get at them.
Then, refactor your proc stock. The data returned should be the same, and can be compared directly against the saved data, automatically or manually.
An alternative is to run the two stored procedures in parallel, and compare the result sets.
This works particularly well for select-only stored procedures, but updates, inserts & deletes are more complex.
I've used this method to get the code to a state where it is more susceptible to unit testing, or simpler, or both.
A: Try TST. You can download and install it from: http://tst.codeplex.com/
A: A colleague swears by the TSQLUnit testing framework. May be worth a look for your needs.
A: That seems like a terrible policy. Perhaps you can write a stored procedure that executes SQL and begin to transition your code to run through there.
In any case, I would test calling the stored procedures via a traditional automation framework. As the gateway between the application and the data, these should be handled as integration tests, rather than pure unit tests. However, you can use an xUnit based unit testing framework to drive them. As long as your tests have access to run SQL against the database, perhaps through the method I mentioned previously, you should be able to assert that the correct changes were made.
One challenge is that you indicate they are getting lengthy. I would recommend breaking them into subroutines and making them as small as possible. It makes it easier to test, and easier to maintain.
A: Here's my low-tech, quickie method of just keeping example inputs conveniently located in the DDL
USE [SpacelySprockets]
GO
/****** Object: StoredProcedure [dbo].[uspBrownNoseMrSpacely] Script Date: 02/03/3000 00:24:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--================================
--Stored Procedure DDL:
--================================
--Example Inputs
/*
DECLARE @SuckupPloyId int
DECLARE @SuckupIdentityRecordId int
SET @SuckupPloyId = 3
*/
-- =============================================
-- Author: 6eorge Jetson
-- Create date: 01/02/3000
-- Description: Sucks up to the boss
-- =============================================
CREATE PROCEDURE [dbo].[uspBrownNoseMrSpacely]
@SuckupPloyId int
,@SuckupIdentityRecordId int OUTPUT
AS
BEGIN
DECLARE @EmployeeId int
DECLARE @SuckupPoints int
DECLARE @DateTimeStamp datetime
SET @EmployeeId = dbo.svfGetEmployeeId('6eorge Jetson')
SET @SuckupPoints = dbo.svfGetSuckupPoints(@SuckupPloyId)
SET @DateTimeStamp = getdate()
--Data state-changing statement in sproc
INSERT INTO [dbo].[tblSuckupPointsEarned]([EmployeeId], [SuckupPoints], [DateTimeStamp] )
VALUES (@EmployeeId, @SuckupPoints, @DateTimeStamp)
SET @SuckupIdentityRecordId = @@Identity
END
--Unit Test Evidence Display
/*
SELECT
@EmployeeId as EmployeeId
,@SuckupPoints as SuckupPoints
,@DateTimeStamp as DateTimeStamp
*/
--==========================================================================
--After editing for low-tech, non-state changing "unit-like" test invocation
--==========================================================================
--Example Inputs
DECLARE @SuckupPloyId int
DECLARE @SuckupIdentityRecordId int
SET @SuckupPloyId = 3
/*
-- =============================================
-- Author: 6eorge Jetson
-- Create date: 01/02/3000
-- Description: Sucks up to the boss
-- =============================================
CREATE PROCEDURE [dbo].[uspBrownNoseMrSpacely]
@SuckupPloyId int
,@SuckupIdentityRecordId int OUTPUT
AS
BEGIN
*/
DECLARE @EmployeeId int
DECLARE @SuckupPoints int
DECLARE @DateTimeStamp datetime
SET @EmployeeId = dbo.svfGetEmployeeId('6eorge Jetson')
SET @SuckupPoints = dbo.svfGetSuckupPoints(@SuckupPloyId)
SET @DateTimeStamp = getdate()
--Data state-changing statement now commented out to prevent data state change
-- INSERT INTO [dbo].[tblSuckupPointsEarned]([EmployeeId], [SuckupPoints], [DateTimeStamp] )
-- VALUES (@EmployeeId, @SuckupPoints, @DateTimeStamp)
SET @SuckupIdentityRecordId = @@Identity
--END --Need to comment out the sproc "END" also
--Unit Test Evidence Display
SELECT
@EmployeeId as EmployeeId
,@SuckupPoints as SuckupPoints
,@DateTimeStamp as DateTimeStamp
It works even better for udfs as there is no change of state to worry about.
Clearly, I wouldn't recommend this in lieu of a testing framework,
but if I stick to this simple seconds-costing discipline of
Assert that my managable-sized sproc passes at least a simple "unit test"
prior to executing CREATE PROCEDURE, I find that I make fewer mistakes (likely due to discipline more than the test itself).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147362",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "32"
} |
Q: Totaling a GridView in ASP.NET In one of my ASP.NET Web Applications, I am using a BulkEditGridView (a GridView which allows all rows to be edited at the same time) to implement an order form. In my grid, I have a column which calculates the total for each item (cost x quantity) and a grand total field at the bottom of the page. Currently, however, these fields are only refreshed on every post-back. I need to have these fields updated dynamically so that as users change quantities, the totals and grand total update to reflect the new values. I have attempted to use AJAX solutions to accomplish this, but the asynchronous post-backs interfere with the focus on the page. I imagine that a purely client-side solution exists, and I'm hopeful that someone in the community can share.
A: If your calculations can be reproduced in JavaScript the easiest method would be using jQuery to get all the items like this:
$("#myGridView input[type='text']").each(function(){
this.change(function(){
updateTotal(this.value);
});
});
Or if your calculations are way too complex to be done in JavaScript (or time restraints prevent it) then an AJAX call to a web service is the best way. Lets say we've got our webservice like this:
[WebMethod, ScriptMethod]
public int UpdateTotal(int currTotal, int changedValue){
// do stuff, then return
}
You'll need some JavaScript to invoke the webservice, you can do it either with jQuery or MS AJAX. I'll show a combo of both, just for fun:
$("#myGridView input[type='text']").each(function(){
this.change(function(){
Sys.Net.WebServiceProxy.invoke(
"/Helpers.asmx",
"UpdateTotal",
false,
{ currTotal: $get('totalField').innerHTML, changedValue: this.value },
showNewTotal
);
});
});
function showNewTotal(res){
$get('totalField').innerHTML = res;
}
Check out this link for full info on the Sys.Net.WebServiceProxy.invoke method: http://www.asp.net/AJAX/Documentation/Live/ClientReference/Sys.Net/WebServiceProxyClass/WebServiceProxyInvokeMethod.aspx
A: One solution is to build some javascript in you RowDataBound method to constantly update those totals when the textboxes change.
So during the RowDataBound, start building a javascript string in memory that will add up the textboxes you need added. What's nice in RowDataBound is you can get the Client Side id's of these textboxes by calling TextBox.ClientId.
Add this javascript to the page, then also add an onkeyup event to each textbox you require to call this script.
So something like (this is a row bound event from a gridview)
private string _jscript;
protected void gridview_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Get your textbox
Textbox tb = e.Row.FindControl("tbAddUp");
//Add the event that you're going to call to this textbox's attributes
tb.Attributes.Add("onkeyup", "MyAddUpJavaScriptMethod();");
//Build the javascript for the MyAddUpJavaScriptMethod
jscript += "document.getElementById('" + tb.ClientId + '").value + ";
}
}
Then once you've built that whole script, use your Page.ClientScript class to add a method to you page which will be called by your onkeyup in your textboxes "MyAddUpJavaScriptMethod"
Hope that makes sense and helps
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147364",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How does this C++ function use memoization? #include <vector>
std::vector<long int> as;
long int a(size_t n){
if(n==1) return 1;
if(n==2) return -2;
if(as.size()<n+1)
as.resize(n+1);
if(as[n]<=0)
{
as[n]=-4*a(n-1)-4*a(n-2);
}
return mod(as[n], 65535);
}
The above code sample using memoization to calculate a recursive formula based on some input n. I know that this uses memoization, because I have written a purely recursive function that uses the same formula, but this one much, much faster for much larger values of n. I've never used vectors before, but I've done some research and I understand the concept of them. I understand that memoization is supposed to store each calculated value, so that instead of performing the same calculations over again, it can simply retrieve ones that have already been calculated.
My question is: how is this memoization, and how does it work? I can't seem to see in the code at which point it checks to see if a value for n already exists. Also, I don't understand the purpose of the if(as[n]<=0). This formula can yield positive and negative values, so I'm not sure what this check is looking for.
Thank you, I think I'm close to understanding how this works, it's actually a bit more simple than I was thinking it was.
I do not think the values in the sequence can ever be 0, so this should work for me, as I think n has to start at 1.
However, if zero was a viable number in my sequence, what is another way I could solve it? For example, what if five could never appear? Would I just need to fill my vector with fives?
Edit: Wow, I got a lot of other responses while checking code and typing this one. Thanks for the help everyone, I think I understand it now.
A: if (as[n] <= 0) is the check. If valid values can be negative like you say, then you need a different sentinel to check against. Can valid values ever be zero? If not, then just make the test if (as[n] == 0). This makes your code easier to write, because by default vectors of ints are filled with zeroes.
A: The code appears to be incorrectly checking is (as[n] <= 0), and recalculates the negative values of the function(which appear to be approximately every other value). This makes the work scale linearly with n instead of 2^n with the recursive solution, so it runs a lot faster.
Still, a better check would be to test if (as[n] == 0), which appears to run 3x faster on my system. Even if the function can return 0, a 0 value just means it will take slightly longer to compute (although if 0 is a frequent return value, you might want to consider a separate vector that flags whether the value has been computed or not instead of using a single vector to store the function's value and whether it has been computed)
A: If the formula can yield both positive and negative values then this function has a serious bug. The check if(as[n]<=0) is supposed to be checking if it had already cached this value of computation. But if the formula can be negative this function recalculates this cached value alot...
What it really probably wanted was a vector<pair<bool, unsigned> >, where the bool says if the value has been calculated or not.
A: The code, as posted, only memoizes about 40% of the time (precisely when the remembered value is positive). As Chris Jester-Young pointed out, a correct implementation would instead check if(as[n]==0). Alternatively, one can change the memoization code itself to read as[n]=mod(-4*a(n-1)-4*a(n-2),65535);
(Even the ==0 check would spend effort when the memoized value was 0. Luckily, in your case, this never happens!)
A: There's a bug in this code. It will continue to recalculate the values of as[n] for as[n] <= 0. It will memoize the values of a that turn out to be positive. It works a lot faster than code without the memoization because there are enough positive values of as[] so that the recursion is terminated quickly. You could improve this by using a value of greater than 65535 as a sentinal. The new values of the vector are initialized to zero when the vector expands.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147372",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Database under source control again! We use MS SQL Server and C#. Our database is under sourse control and I will tell you some details of our implementation. We had implemented two operations:
*
*Export database to plain-text files. Database schema files:
tables.sql
relationships.sql
views.sql
...
and table contents files:
Data/table1.txt
Data/table2.txt
...
It is easy to review database changes using source control logs because all these files has plain-text format.
Imlementation is based on classes from namespace Microsoft.SqlServer.Management.Smo.
*Import database from this plain-text files. Implementation is strightforward - just execute sql statements from *.sql files, and then execute a bunch of inserts.
So we have two bat-files: create-test-databse.bat and export-test-database.bat. When a developer needs a new test database he just executes the bat-file and waits for a minute.
Every functional test, which needs a database creates a new database, uses it, and then kills it. But I should say that it is not very fast operation. :(
So what instruments do YOU use to put your database under source control?
I mean how do you implement operations "create test database" and "export test database" for example?
A: I think you are asking two questions here. The first is how to get your database under source control. Your solution is interesting, and I've also used Visual Studio Team Edition for Database Professionals (here's a tutorial I wrote on TDD of stored procedures using it)
The second is how to you set up your database for integration tests. Setting up and tearing down the entire database seems like it might be a bit overkill. There are several solutions out there. I've used DBFit. Roy Osherove published a tool called XtUnit a while back that I haven't played with. And, of course, you could always setup your tests to do a transaction start in the SetUp, and a Rollback during teardown.
A: We use Visual Studio for Database Professionals. Don't leave home without it.
A: I use VSTS for DB Pros. You point it at your SQL server and it analyzes your database and creates the individual files for you. You can even have it generate test data for you. The next release will include support for third party providers (think Oracle, MySQL, DB2).
The really great feature in here is the validation. We found that parts of our database were totally broken (they were vestigial, not used by the code anymore). It basically makes it possible to deploy your database on demand.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147376",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Options for refactoring bits of code away from native C++? So, one commonly heard comment when talking about performance is that you write your code with whatever language gets the job done fastest. If performance in specific areas is a problem, then rewrite those bits in C/C++.
But, what if you're starting with a native C++ app? What options do you have if you want to write the easy bits, or refactor the old bits, in a language like Python, Ruby, C#, or whatever? Keep in mind that transferring data between the native and other sides is a must. Being able to simply call a function written in an "easier" language, while passing C++ classes as data, would be beautiful.
We've got a crusty Win32 app that would benefit greatly if we could crank out new code, or refactor old code, in C# or something. Very little of it requires the complexity of C++, and dealing with the little fiddly bits is dragging down the programming process.
A: As Aaron Fischer suggests, try recompiling your C++ application with the /clr option turned on and then start leveraging the .Net platform.
CLI/C++ is pretty easy to pick up if you know C# and C++ already and it provides the bridge between the .Net world and native C++.
If your current C++ code can't compile cleanly with /clr turned on then I'd suggest trying to build your application as a static lib (without /clr enabled) and then have your main() be in a CLI/C++ project that calls your legacy app entry point. That way you can at least start leveraging .Net for new functionality.
For examples of "legacy" C/C++ apps that have been "ported" to .Net CLI/C++ check out the .Net ports of Quake 2 and Quake 3: Arena.
A: If you want to work between C++ and Python, than Boost Python is what you're looking for. You can write C Python bindings by hand for Cython, but that limits in many ways how you're going to write your code. This is the easiest way, as seen in some snippets from this tutorial:
A simple function that performs a hello world:
char const* greet()
{
return "hello, world";
}
The Boost python code needed to expose it to python:
#include <boost/python.hpp>
BOOST_PYTHON_MODULE(hello_ext)
{
using namespace boost::python;
def("greet", greet);
}
How to use this code from python:
>>> import hello_ext
>>> print hello.greet()
hello, world
Going in the opposite direction is bit tougher, since python doesn't compile to native code. You have to embed the python interpreter into your C++ application, but the work necessary to do that is documented here. This is an example of calling the python interpreter and extracting the result (the python interpreter defines the object class for use in C++):
object result = eval("5 ** 2");
int five_squared = extract<int>(result);
A: Well, it really depends on the language. Python interfacing, for instance, is most easily done with Boost Python, and many other languages will require you to interface them as you would with C, using their C library and declaring your callbacks to be extern "C" (unfortunate that you can't use the C++ class definitions in other languages usually).
But I would also ask what you intend to use it for as C++ is a complex language, but once you get familiar with it, it is very powerful and not very much harder to code than other languages. The only really good exception I could think of is if you plan on using a powerful library that exists only in one language and there isn't a decent C++ alternative (graphics libraries are probably the best example of this because you have to be very familiar with them to use them effectively).
It's also worth pointing out that if you interface C++ code to another language, you lose out on the inter-platform compatibility granted by that language.
A: You can change the common Language run time support in your c++ project to /clr. From this point you can use any .net functionality right in your c++ code. This includes creating winforms in your project as well. You can also add a c# library that handles ui and other functionality.
A: In the .NET world you always have the option of crreating a COM/ActiveX interop layer for your C#/VB.NET assembly.
You can then use the normal COM API from your C++ application to create an instance of this COM server that actually wraps your .NET assembly.
Good thing about this is that simple parameters such as int, bool, string, float etc are mapped to their COM equivalent for you. However to my knowledge it is not possible to easily pass full .NET objects (instances of classes you create).
Also be aware that COM interop calls are relatively slow. You should not be calling a COM interop method continually from your C++ code in a tight loop.
COM/ActiveX have traditionally relied on the Windows Registry, not ideal as it is a big dependency. However it is also possible to to use Registration-Free COM interop to avoid this dependency.
This article covers the steps required to register a .NET assembly for COM interop.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147378",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Using boost::random as the RNG for std::random_shuffle I have a program that uses the mt19937 random number generator from boost::random. I need to do a random_shuffle and want the random numbers generated for this to be from this shared state so that they can be deterministic with respect to the mersenne twister's previously generated numbers.
I tried something like this:
void foo(std::vector<unsigned> &vec, boost::mt19937 &state)
{
struct bar {
boost::mt19937 &_state;
unsigned operator()(unsigned i) {
boost::uniform_int<> rng(0, i - 1);
return rng(_state);
}
bar(boost::mt19937 &state) : _state(state) {}
} rand(state);
std::random_shuffle(vec.begin(), vec.end(), rand);
}
But i get a template error calling random_shuffle with rand. However this works:
unsigned bar(unsigned i)
{
boost::mt19937 no_state;
boost::uniform_int<> rng(0, i - 1);
return rng(no_state);
}
void foo(std::vector<unsigned> &vec, boost::mt19937 &state)
{
std::random_shuffle(vec.begin(), vec.end(), bar);
}
Probably because it is an actual function call. But obviously this doesn't keep the state from the original mersenne twister. What gives? Is there any way to do what I'm trying to do without global variables?
A: I'm using tr1 instead of boost::random here, but should not matter much.
The following is a bit tricky, but it works.
#include <algorithm>
#include <tr1/random>
std::tr1::mt19937 engine;
std::tr1::uniform_int<> unigen;
std::tr1::variate_generator<std::tr1::mt19937,
std::tr1::uniform_int<> >gen(engine, unigen);
std::random_shuffle(vec.begin(), vec.end(), gen);
A: In the comments, Robert Gould asked for a working version for posterity:
#include <algorithm>
#include <functional>
#include <vector>
#include <boost/random.hpp>
struct bar : std::unary_function<unsigned, unsigned> {
boost::mt19937 &_state;
unsigned operator()(unsigned i) {
boost::uniform_int<> rng(0, i - 1);
return rng(_state);
}
bar(boost::mt19937 &state) : _state(state) {}
};
void foo(std::vector<unsigned> &vec, boost::mt19937 &state)
{
bar rand(state);
std::random_shuffle(vec.begin(), vec.end(), rand);
}
A: In C++03, you cannot instantiate a template based on a function-local type. If you move the rand class out of the function, it should work fine (disclaimer: not tested, there could be other sinister bugs).
This requirement has been relaxed in C++0x, but I don't know whether the change has been implemented in GCC's C++0x mode yet, and I would be highly surprised to find it present in any other compiler.
A: I thought it was worth pointing out that this is now pretty straightforward in C++11 using only the standard library:
#include <random>
#include <algorithm>
std::random_device rd;
std::mt19937 randEng(rd());
std::shuffle(vec.begin(), vec.end(), randEng);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147391",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: Performance challenge: NAL Unit Wrapping From what I've seen in the past, StackOverflow seems to like programming challenges, such as the fast char to string exercise problem which got dozens of responses. This is an optimization challenge: take a very simple function and see if you can come up with a smarter way of doing it.
I've had a function that I've wanted to further optimize for quite some time but I always find that my optimizations have some hole that result in incorrect output--some rare special case in which they fail. But, given the function, I've always figured one should be able to do better than this.
The function takes an input datastream (effectively random bits, from an entropy perspective) and wraps it into a NAL unit. This involves placing escape codes: any byte sequence of 00 00 00, 00 00 01, 00 00 02, or 00 00 03 gets replaced with 00 00 03 XX, where XX is that last byte of the original sequence. As one can guess, these only get placed about 1 in every 4 million bytes of input, given the odds against such a sequence--so this is a challenge where one is searching an enormous amount of data and doing almost nothing to it except in very rare cases. However, because "doing something" involves inserting bytes, it makes things a bit trickier. The current unoptimized code is the following C:
src and dst are pointers to arrays of bytes, and end is the pointer to the end of the input data.
int i_count = 0;
while( src < end )
{
if( i_count == 2 && *src <= 0x03 )
{
*dst++ = 0x03;
i_count = 0;
}
if( *src == 0 )
i_count++;
else
i_count = 0;
*dst++ = *src++;
}
Common input sizes to this function range from roughly between 1000 and 1000000 bytes of data.
Initial ideas of mine include a function which (somehow) quickly searches the input for situations where an escape code is needed, to avoid more complex logic in the vast majority of inputs where escape codes don't need to be placed.
A: Hmm...how about something like this?
#define likely(x) __builtin_expect((x),1)
#define unlikely(x) __builtin_expect((x),0)
while( likely(src < end) )
{
//Copy non-zero run
int runlen = strlen( src );
if( unlikely(src+runlen >= end) )
{
memcpy( dest, src, end-src );
dest += end-src;
src = end;
break;
}
memcpy( dest, src, runlen );
src += runlen;
dest += runlen;
//Deal with 0 byte
if( unlikely(src[1]==0 && src[2]<=3 && src<=end-3) )
{
*dest++ = 0;
*dest++ = 0;
*dest++ = 3;
*dest++ = *src++;
}
else
{
*dest++ = 0;
src++;
}
}
There's some duplication of effort between strcpy and memcpy it'd be nice to get rid of though.
A: Applying the obvious optimisations to your code:
#define unlikely(x) __builtin_expect((x),0)
while( src < end )
{
const char s = *src++;
if( unlikely(i_count==2 && s<=0x03) )
{
*dst++ = 0x03;
i_count = 0;
}
if( unlikely(s==0) )
i_count++;
else
i_count = 0;
*dst++ = s;
}
A: Mike F, thanks a lot for the "unlikely" suggestion: the following is about 10% faster than the original:
#define unlikely(x) __builtin_expect((x),0)
while( src < end )
{
if( unlikely(i_count == 2) && unlikely(*src <= 0x03) )
{
*dst++ = 0x03;
i_count = 0;
}
if( unlikely(*src == 0) )
i_count++;
else
i_count = 0;
*dst++ = *src++;
}
And, even better, the following is 50% faster than the original (!!!) I still can't figure out why the likely() in the loop condition helps at all... must be gcc being weird again.
#define unlikely(x) __builtin_expect((x),0)
#define likely(x) __builtin_expect((x),1)
while( likely(src < end) )
{
if( unlikely(i_count == 2) && unlikely(*src <= 0x03) )
{
*dst++ = 0x03;
i_count = 0;
}
if( unlikely(*src == 0) )
i_count++;
else
i_count = 0;
*dst++ = *src++;
}
However, I was hoping for more than just optimizing the current naive approach; I suspect there must be a better way to do it than merely handling every byte individually.
A: while (src < end-2)
{
if ((src[0] == 0) && (src[1] == 0) && (src[2] <= 3))
{
dst[0] = 0;
dst[1] = 0;
dst[2] = 3;
dst[3] = src[2];
src += 3;
dst += 4;
}
else
*dst++ = *src++;
}
while (src < end)
*dst++ = *src++;
A: Faster version of my previous answer:
while (src < end-2)
{
if (src[0] == 0)
{
if (src[1] == 0)
{
if (src[2] <= 3)
{
dst[0] = 0;
dst[1] = 0;
dst[2] = 3;
dst[3] = src[2];
src += 3;
dst += 4;
}
else
{
dst[0] = 0;
dst[1] = 0;
dst[2] = src[2];
src += 3;
dst += 3;
}
}
else
{
dst[0] = 0;
dst[1] = src[1];
src += 2;
dst += 2;
}
}
else
*dst++ = *src++;
}
while (src < end)
*dst++ = *src++;
A: A test like this is insanely dependent on your compiler and processor/memory setup. On my system, my improved version is the exact same speed as Mike F's strlen/memcpy version.
A: It seems to me that as long as you're copying byte-by-byte you'll be falling foul of word alignment issues when accessing memory, and these will be slowing you down.
So, I'd suggest the following (sorry for the pseudo code, my C/C++ is largely forgotten):
*
*Search to find the next insertion point
[The Boyer-Moore search algorithm would be a good bet, as it's sublinear (doesn't need to examine every byte)]
*Block copy the unchanged block
[My understanding is that GCC and other good C++ compilers can turn the memcpy() call directly into the correct processor instruction, giving near optimal performance]
*Insert the altered code
*Repeat until done
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147408",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Copy collection items to another collection in .NET In .NET (VB), how can I take all of the items in one collection, and add them to a second collection (without losing pre-existing items in the second collection)? I'm looking for something a little more efficient than this:
For Each item As Host In hostCollection1
hostCollection2.Add(item)
Next
My collections are generic collections, inherited from the base class -- Collection(Of )
A: I know you're asking for VB, but in C# you can just use the constructor of the collection to initialize it with any IEnumerable. For example:
List<string> list1 = new List<string>();
list1.Add("Hello");
List<string> list2 = new List<string>(list1);
Perhaps the same kind of thing exists in VB.
A: You can use AddRange: hostCollection2.AddRange(hostCollection1).
A: Don't forget that you will be getting a reference and not a copy if you initialize your List2 to List1. You will still have one set of strings unless you do a deep clone.
A: I always use the List<T>.AddRange(otherList<T>) function. Again, if this is a list of objects, they will be references the same thing.
You have not specified what sort of collection though, AddRange doesn't exist in CollectionBase inherited objects
A: This is available when one use an IList. But AddRange method is not available in Collection. I thought of casting Collection to List, but it is not possible.
A: List.CopyTo(T[]); maybe?
http://msdn.microsoft.com/en-us/library/t69dktcd.aspx
A: Ben's solution does exist for VB.Net:
Dim collection As IEnumerable(Of T)
Dim instance As New List(collection)
Here is the linked documentation.
However, one thing I would be concerned with is whether or not it does a shallow copy or a deep copy.
A: Unless you want both collections to modify the same set of objects, then each object is going to have to be copied to the Heap. Maybe you can describe your scenario of how this is impacting your performance and we can find a good solution.
A: Array.Copy may solve your problem.
A: Not sure for this one
Why not just do this
Dim newlines = _singSongs.ToList
That .tolist means it creates a whole new list
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147416",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
} |
Q: What is the best way to set-up authentication in a tomcat webapp? I have a self built JSP webapp and at the moment I'm using tomcats built in admin pannel to manage user accounts (that are stored in tomcats config xml files) but this is limited because i can not create new accounts from within the web-app (eg. I can not have a sign up website) and need to manually create the accounts.
What is the most straight forward way of implementing accounts in a tomcat environment?
dennis
A: Set up a database realm in Tomcat, either a simple JDBC realm or a DataSource realm that will allow for connection pooling. Then adding users is a very simple CRUD web application, possibly combined with some confirmation emails.
A: If you are on Windows (not specified in the question) and want to use a windows logon to authenticate you might want to check out JCIFS. JCIFS allows you to obtain the user name of an authenticated windows logon in Java. It is easy to install and relatively foolproof.
Not for every situation but in windows only environments it can get you up and running quickly.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147420",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Difflib.SequenceMatcher isjunk optional parameter query: how to ignore whitespaces, tabs, empty lines? I am trying to use Difflib.SequenceMatcher to compute the similarities between two files. These two files are almost identical except that one contains some extra whitespaces, empty lines and other doesn't. I am trying to use
s=difflib.SequenceMatcher(isjunk,text1,text2)
ratio =s.ratio()
for this purpose.
So, the question is how to write the lambda expression for this isjunk method so the SequenceMatcher method will discount all the whitespaces, empty lines etc. I tried to use the parameter lambda x: x==" ", but the result isn't as great. For two closely similar text, the ratio is very low. This is highly counter intuitive.
For testing purpose, here are the two strings that you can use on testing:
What Motivates jwovu to do your Job
Well? OK, this is an entry trying to
win $100 worth of software development
books despite the fact that I don‘t
read
programming books. In order to win the
prize you have to write an entry and
what motivatesfggmum to do your job
well. Hence this post. First
motivation
money. I know, this doesn‘t sound like
a great inspiration to many, and
saying that money is one of the
motivation factors might just blow my
chances away.
As if money is a taboo in programming
world. I know there are people who
can‘t be motivated by money. Mme, on
the other hand, am living in a real
world,
with house mortgage to pay, myself to
feed and bills to cover. So I can‘t
really exclude money from my
consideration. If I can get a large
sum of money for
doing a good job, then definitely
boost my morale. I won‘t care whether
I am using an old workstation, or
forced to share rooms or cubicle with
other
people, or have to put up with an
annoying boss, or whatever. The fact
that at the end of the day I will walk
off with a large pile of money itself
is enough
for me to overcome all the obstacles,
put up with all the hard feelings and
hurt egos, tolerate a slow computer
and even endure
And here's another string
What Motivates You to do your Job
Well? OK, this is an entry trying to
win $100 worth of software development
books, despite the fact that I don't
read programming books. In order to
win the prize you have to write an
entry and describes what motivates you
to do your job well. Hence this post.
First motivation, money. I know, this
doesn't sound like a great inspiration
to many, and saying that money is one
of the motivation factors might just
blow my chances away. As if money is a
taboo in programming world. I know
there are people who can't be
motivated by money. Kudos to them. Me,
on the other hand, am living in a real
world, with house mortgage to pay,
myself to feed and bills to cover. So
I can't really exclude money from my
consideration.
If I can get a large sum of money for
doing a good job, then thatwill
definitely boost my morale. I won't
care whether I am using an old
workstation, or forced to share rooms
or cubicle with other people, or have
to put up with an annoying boss, or
whatever. The fact that at the end of
the day I will walk off with a large
pile of money itself is enough for me
to overcome all the obstacles, put up
with all the hard feelings and hurt
egos, tolerate a slow computer and
even endure
I ran the above command, and set the isjunk to lambda x:x==" ", the ratio is only 0.36.
A: If you match all whitespaces the similarity is better:
difflib.SequenceMatcher(lambda x: x in " \t\n", doc1, doc2).ratio()
However, difflib is not ideal to such a problem because these are two nearly identical documents, but typos and such produce differences for difflib where a human wouldn't see many.
Try reading up on tf-idf, Bayesian probability, Vector space Models and w-shingling
I have written a an implementation of tf-idf applying it to a vector space and using the dot product as a distance measure to classify documents.
A: Using your sample strings:
>>> s=difflib.SequenceMatcher(lambda x: x == '\n', s1, s2)
>>> s.ratio()
0.94669848846459825
Interestingly if ' ' is also included as junk:
>>> s=difflib.SequenceMatcher(lambda x: x in ' \n', s1, s2)
>>> s.ratio()
0.7653142402545744
Looks like the new lines are having a much greater affect than the spaces.
A: Given the texts above, the test is indeed as suggested:
difflib.SequenceMatcher(lambda x: x in " \t\n", doc1, doc2).ratio()
However, to speed up things a little, you can take advantage of CPython's method-wrappers:
difflib.SequenceMatcher(" \t\n".__contains__, doc1, doc2).ratio()
This avoids many python function calls.
A: I haven't used Difflib.SequenceMatcher, but have you considered pre-processing the files to remove all blank lines and whitespace (perhaps via regular expressions) and then doing the compare?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147437",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Writing Color Calibration Data to a TIFF or PNG file My custom homebrew photography processing software, running on 64 bit Linux/GNU, writes out PNG and TIFF files. These are to be sent to a quality printing shop to be made into fine art. Working with interior designers - it's important to get the colors just right!
The print shops usually have no trouble with TIFF and PNGs made from commercial software such as Photoshop. Even though i have the TIFF 6.0 specs, PNG specs, and other info in hand, it is not clear how to include color calibration data or implement color management system on linux. My files are often rejected as faulty, without sufficient error reports to make fixes.
This has been a nasty problem for a while for many. Even my contacts at the Hollywood postproduction studios are struggling with this issue. One studio even wanted to hire me to take care of their color calibration, thinking i was the expert - but no, i am just as blind and lost as everyone!
Does anyone know of good code examples, detailed technical information, or have any other enlightenment? Or time to switch to pure Apple?
A: Take a look at LittleCMS
http://www.littlecms.com/
This page has the code for applying it to TIFF
http://www.littlecms.com/newutils.htm
The basic thing you need to know is that Color profile data is something you need to store in the meta-data of the file itself.
A: There is a consultant called Charles Poynton who specialises in this area. I work for one of the post production studios you mention (albeit in london not hollywood), and have seen him speak on the subject a couple of times. His website contains a lot of the material he presents and you might find something of use there. He also has a book called Digital Video and HDTV Algorithms and Interfaces which is not as heavy as the title might suggest! While these resources might not answer your question directly, it might provide a spring board to other solutions.
More specifically, which libraries are you using to write the png and tif files - you mention they are homebrew, but how custom are they exactly? Postprocessing the images in an image manipulation program (such as ImageMagick or dcraw) might allow you to inject this information into the header more successfully.
Sorry, I don't have any specific answers, but maybe something that will point you a bit further in the right direction...
A: As a GNU/Linux user, you’ll want to consider DispcalGUI – http://dispcalgui.hoech.net/ – a GNOME-based GUI that centralizes color management, ICC profile management, and (crucially for your case) device calibration. It can talk to well-known pro- and mid-level hardware, e.g, i1, X-Rite, Spyder, etc.
But before you get into that – you say you are generating your files to spec; are you validating your output using a test suite specific to the format in question? If not, here are three to get you started:
*
*imagetestsuite supports the well-known formats: https://code.google.com/p/imagetestsuite/w/list?can=1&q=
*The Luminous* test suite is a JIRA plugin, if that’s your thing: https://marketplace.atlassian.com/plugins/com.luminouslead.plugin.jira.testsuite.LuminousTestSuite
*FLOSS Decoder implementations often have one you can use, i.e. OpenJPEG – https://code.google.com/p/openjpeg/wiki/TestSuiteDocumentation
But even barring all of those, it seems like your problem is with embedded ICC data – which is two specs in one. First, there’s the host image-file format, and they all handle embedding differently (meaning the ICC data will likely look totally different when embedded in a TIFF than, say, a JPEG or WebP file). Second, there is the ICC spec itself. It is documented here: http://color.org/v4spec.xalter – and you may also want to look at the source for the aforementioned dispcalGUI, which includes a very legible and hackable ICC profile class in Python: http://sourceforge.net/p/dispcalgui/code/HEAD/tree/trunk/dispcalGUI/ICCProfile.py
Full disclosure: I have contributed to that very ICC profile class, to which I just linked in that last ¶
That’s the basics (many of which you have no doubt covered)... beyond that, if you post more information about what exactly is going wrong, I’d be interested to look it over. Good luck with it either way.
* NB. This project is unrelated to the long-standing photography website, “the Luminous Landscape”
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147449",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: What are valid characters for creating a multipart form boundary? In an HTML form post what are valid characters for creating a multipart boundary?
A: According to RFC 2046, section 5.1.1:
boundary := 0*69<bchars> bcharsnospace
bchars := bcharsnospace / " "
bcharsnospace := DIGIT / ALPHA / "'" / "(" / ")" /
"+" / "_" / "," / "-" / "." /
"/" / ":" / "=" / "?"
So it can be between 1 and 70 characters long, consisting of alphanumeric, and the punctuation you see in the list. Spaces are allowed except at the end.
A: There are no rules as of the content of the boundary but as it must not occur in any of the parts of your message content is usually a randomly generated sequence of numbers, letters or combination of both in order to guarantee uniqueness and differentiate from any possible dictionary words. So as you start your message each data type section is separated by “–” followed by the boundary sequence and the content type + encoding. After the last section “–” followed by the boundary followed by “–” is used to delimit the end of the message. The way multipart content works is by specifying a boundary in the “Content-type:” header of your email. The boundary is used to separate the different content types and looks something like this:
Content-type: multipart/mixed; boundary="fU3W4Vzr4G3D54f3"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147451",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: Why is using a wild card with a Java import statement bad? It is much more convenient and cleaner to use a single statement like
import java.awt.*;
than to import a bunch of individual classes
import java.awt.Panel;
import java.awt.Graphics;
import java.awt.Canvas;
...
What is wrong with using a wildcard in the import statement?
A: It's not bad to use a wild card with a Java import statement.
In Clean Code, Robert C. Martin actually recommends using them to avoid long import lists.
Here is the recommendation:
J1: Avoid Long Import Lists by Using
Wildcards
If you use two or more classes from a
package, then import the whole package
with
import package.*;
Long lists of imports are daunting to
the reader. We don’t want to clutter
up the tops of our modules with 80
lines of imports. Rather we want the
imports to be a concise statement
about which packages we collaborate
with.
Specific imports are hard
dependencies, whereas wildcard imports
are not. If you specifically import a
class, then that class must exist. But
if you import a package with a
wildcard, no particular classes need
to exist. The import statement simply
adds the package to the search path
when hunting for names. So no true
dependency is created by such imports,
and they therefore serve to keep our
modules less coupled.
There are times when the long list of
specific imports can be useful. For
example, if you are dealing with
legacy code and you want to find out
what classes you need to build mocks
and stubs for, you can walk down the
list of specific imports to find out
the true qualified names of all those
classes and then put the appropriate
stubs in place. However, this use for
specific imports is very rare.
Furthermore, most modern IDEs will
allow you to convert the wildcarded
imports to a list of specific imports
with a single command. So even in the
legacy case it’s better to import
wildcards.
Wildcard imports can sometimes cause
name conflicts and ambiguities. Two
classes with the same name, but in
different packages, will need to be
specifically imported, or at least
specifically qualified when used. This
can be a nuisance but is rare enough
that using wildcard imports is still
generally better than specific
imports.
A: In DDD book
In whatever development technology the implementation will be based on, look for ways of minimizing the
work of refactoring MODULES . In Java, there is no escape from importing into individual classes, but you
can at least import entire packages at a time, reflecting the intention that packages are highly cohesive units
while simultaneously reducing the effort of changing package names.
And if it clutters local namespace its not your fault - blame the size of the package.
A: The only problem with it is that it clutters your local namespace. For example, let's say that you're writing a Swing app, and so need java.awt.Event, and are also interfacing with the company's calendaring system, which has com.mycompany.calendar.Event. If you import both using the wildcard method, one of these three things happens:
*
*You have an outright naming conflict between java.awt.Event and com.mycompany.calendar.Event, and so you can't even compile.
*You actually manage only to import one (only one of your two imports does .*), but it's the wrong one, and you struggle to figure out why your code is claiming the type is wrong.
*When you compile your code, there is no com.mycompany.calendar.Event, but when they later add one, your previously valid code suddenly stops compiling.
The advantage of explicitly listing all imports is that I can tell at a glance which class you meant to use, which simply makes reading the code much easier. If you're just doing a quick one-off thing, there's nothing explicitly wrong, but future maintainers will thank you for your clarity otherwise.
A: Here are the few things that I found regarding this topic.
*
*During compilation, the compiler tries to find classes that are used in the code from the .* import and the corresponding byte code will be generated by selecting the used classes from .* import. So the byte code of using .* import or .class names import will be same and the runtime performance will also be the same because of the same byte code.
*In each compilation, the compiler has to scan all the classes of .* package to match the classes that are actually used in the code. So, code with .* import takes more time during the compilation process as compared to using .class name imports.
*Using .* import helps to make code more cleaner
*Using .* import can create ambiguity when we use two classes of the same name from two different packages. Eg, Date is available in both packages.
import java.util.*;
import java.sql.*;
public class DateDemo {
private Date utilDate;
private Date sqlDate;
}
A: Performance: No impact on performance as byte code is same.
though it will lead to some compile overheads.
Compilation: on my personal machine, Compiling a blank class without importing anything takes 100 ms but same class when import java.* takes 170 ms.
A: The most important one is that importing java.awt.* can make your program incompatible with a future Java version:
Suppose that you have a class named "ABC", you're using JDK 8 and you import java.util.*. Now, suppose that Java 9 comes out, and it has a new class in package java.util that by coincidence also happens to be called "ABC". Your program now will not compile on Java 9, because the compiler doesn't know if with the name "ABC" you mean your own class or the new class in java.awt.
You won't have that problem when you import only those classes explicitly from java.awt that you actually use.
Resources:
Java Imports
A: It clutters your namespace, requiring you to fully specify any classnames that are ambiguous. The most common occurence of this is with:
import java.util.*;
import java.awt.*;
...
List blah; // Ambiguous, needs to be qualified.
It also helps make your dependencies concrete, as all of your dependencies are listed at the top of the file.
A: *
*It helps to identify classname conflicts: two classes in different packages that have the same name. This can be masked with the * import.
*It makes dependencies explicit, so that anyone who has to read your code later knows what you meant to import and what you didn't mean to import.
*It can make some compilation faster because the compiler doesn't have to search the whole package to identify depdencies, though this is usually not a huge deal with modern compilers.
*The inconvenient aspects of explicit imports are minimized with modern IDEs. Most IDEs allow you to collapse the import section so it's not in the way, automatically populate imports when needed, and automatically identify unused imports to help clean them up.
Most places I've worked that use any significant amount of Java make explicit imports part of the coding standard. I sometimes still use * for quick prototyping and then expand the import lists (some IDEs will do this for you as well) when productizing the code.
A: Here's a vote for star imports. An import statement is intended to import a package, not a class. It is much cleaner to import entire packages; the issues identified here (e.g. java.sql.Date vs java.util.Date) are easily remedied by other means, not really addressed by specific imports and certainly do not justify insanely pedantic imports on all classes. There is nothing more disconcerting than opening a source file and having to page through 100 import statements.
Doing specific imports makes refactoring more difficult; if you remove/rename a class, you need to remove all of its specific imports. If you switch an implementation to a different class in the same package, you have to go fix the imports. While these extra steps can be automated, they are really productivity hits for no real gain.
If Eclipse didn't do specific class imports by default, everyone would still be doing star imports. I'm sorry, but there's really no rational justification for doing specific imports.
Here's how to deal with class conflicts:
import java.sql.*;
import java.util.*;
import java.sql.Date;
A: Please see my article Import on Demand is Evil
In short, the biggest problem is that your code can break when a class is added to a package you import. For example:
import java.awt.*;
import java.util.*;
// ...
List list;
In Java 1.1, this was fine; List was found in java.awt and there was no conflict.
Now suppose you check in your perfectly working code, and a year later someone else brings it out to edit it, and is using Java 1.2.
Java 1.2 added an interface named List to java.util. BOOM! Conflict. The perfectly working code no longer works.
This is an EVIL language feature. There is NO reason that code should stop compiling just because a type is added to a package...
In addition, it makes it difficult for a reader to determine which "Foo" you're using.
A: Among all the valid points made on both sides I haven't found my main reason to avoid the wildcard: I like to be able to read the code and know directly what every class is, or if it's definition isn't in the language or the file, where to find it. If more than one package is imported with * I have to go search every one of them to find a class I don't recognize. Readability is supreme, and I agree code should not require an IDE for reading it.
A: For the record:
When you add an import, you are also indicating your dependencies.
You could see quickly what are the dependencies of files (excluding classes of the same namespace).
A: I prefer specific imports, because it allows me to see all the external references used in the file without looking at the whole file. (Yes, I know it won't necessarily show fully qualified references. But I avoid them whenever possible.)
A: In a previous project I found that changing from *-imports to specific imports reduced compilation time by half (from about 10 minutes to about 5 minutes). The *-import makes the compiler search each of the packages listed for a class matching the one you used. While this time can be small, it adds up for large projects.
A side affect of the *-import was that developers would copy and paste common import lines rather than think about what they needed.
A: *
*There is no runtime impact, as compiler automatically replaces the * with concrete class names. If you decompile the .class file, you would never see import ...*.
*C# always uses * (implicitly) as you can only using package name. You can never specify the class name at all. Java introduces the feature after c#. (Java is so tricky in many aspects but it's beyond this topic).
*In Intellij Idea when you do "organize imports", it automatically replaces multiple imports of the same package with *. This is a mandantory feature as you can not turn it off (though you can increase the threshold).
*The case listed by the accepted reply is not valid. Without * you still got the same issue. You need specify the pakcage name in your code no matter you use * or not.
A: Forget about cluttered namespaces... And consider the poor soul who has to read and understand your code on GitHub, in vi, Notepad++, or some other non-IDE text editor.
That person has to painstakingly look up every token that comes from one of the wildcards against all the classes and references in each wildcarded scope... just to figure out what in the heck is going on.
If you're writing code for the compiler only - and you know what you're doing - I'm sure there's no problem with wildcards.
But if other people - including future you - want to quickly make sense of a particular code file on one reading, then explicit references help a lot.
A:
Why is using a wild card with a Java import statement bad?
If you're using an IDE (which you should be doing), and there are more code owners than just you, using wildcard imports is bad because it:
*
*conceals information from the rest of the team
*provides only false benefits (things which are better-solved using IDE functionality than with wildcard imports) to you as an individual
Most of the "use wildcards" proponents have a focus on the individual: I don't want to maintain the list, I don't want see the clutter, etc. Here are several of the common examples:
*
*maintenance is harder – when you want to introduce a new class into your source code, you have to manually add the import statement
*refactoring is more difficult – if code is moved around, then import statements have to be updated
*reduce clutter, tidy up file contents – goal here is something along the lines of "removing distractions"
These arguments were more convincing before IDEs did all of that automatically. If you're using a plain text editor instead of an IDE, then these arguments have some merit. But if you're using a plain text editor, you are already subjecting yourself to a number of other much more significant inefficiencies, and managing import statements is just one among many things that you should stop doing by hand. IDEs offer automatic management of imports, powerful refactoring tools, and folding (hiding) of any parts of the code you don't want to see.
For the "avoid wildcards" proponents, there are many examples, but I'll point out only one:
*
*clarity – specifically, when someone new enters the codebase. They will arrive with questions, and continue to discover new questions as they explore the code. For this new code contributor, wildcard import statements do not answer any questions, and at worst can produce confusion, misunderstanding, new questions. In contrast, with explicit imports (and using an IDE) the worst case is neutral: no new info provided; at best, it not only reduces ambiguity but it can also provide answers.
At the end of the day, it helps the entire team to reduce (albeit in a small way) code complexity, to reduce confusion, to add clarity.
A: Importing all the classes in a package is considered a blind approach. A major reason for this is that it clutters the class namespace and could lead to conflicts between classes in different packages with the same name.
Specifically populating the necessary classes avoids that problem and clearly shows which versions were wanted. This is good for code maintainability.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147454",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "558"
} |
Q: GetCallbackEventReference doesn't work synchronously I have an ASP.NET 3.5 WebForm that leverages the frameworks Page.ClientScript.GetCallbackEventReference() method and I'd like some of the calls to be synchronous.
Now, the documentation says that the 5th parameter (see below) controls this. Specifically, when you pass 'false' it's supposed to be a non-asynchronous call. However, regardless if it's true or false, it still processes the call asynchronously.
Page.ClientScript.GetCallbackEventReference(this, "arg", "ReceiveServerData", "context",false);
Is there a work-around for this or perhaps I'm doing something wrong?
A: ASPX Page
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="How-to-use-GetCallbackEventReference.aspx.vb" Inherits="How_to_use_Callback" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>How to use GetCallbackEventReference</title>
<script type="text/javascript">
function GetNumber() {
UseCallback();
}
function GetRandomNumberFromServer(txtGetNumber, context) {
document.forms[0].txtGetNumber.value = txtGetNumber
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input id="Button1" type="button" value="Get Random Number" onclick="GetNumber()" /><br /><br />
<asp:TextBox ID="txtGetNumber" runat="server"></asp:TextBox> </div>
</form>
</body>
</html>
Code Behind
Partial Class How_to_use_Callback
Inherits System.Web.UI.Page
Implements System.Web.UI.ICallbackEventHandler
Dim CallbackResult As String = Nothing
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim cbReference As String = Page.ClientScript.GetCallbackEventReference(Me, "arg", "GetRandomNumberFromServer", "context")
Dim cbScript As String = "function UseCallback(arg,context)" & "{" & cbReference & " ; " & "}"
Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "UseCallback", cbScript, True)
End Sub
Public Function GetCallbackResult() As String Implements System.Web.UI.ICallbackEventHandler.GetCallbackResult
Return CallbackResult
End Function
Public Sub RaiseCallbackEvent(ByVal eventArgument As String) Implements System.Web.UI.ICallbackEventHandler.RaiseCallbackEvent
CallbackResult = Rnd().ToString()
End Sub
End Class
A: For any other poor souls still using the MS AJAX library I found the following post:
https://social.msdn.microsoft.com/Forums/vstudio/en-US/f4134c2e-ca04-423a-9da3-c613713a7b52/synchronous-callbacks-with-the-net-20-framework?forum=netfxjscript
The last comment from an MS source says:
This is actually by design. In order not to block the UI of the browser, this parameter doesn't actually do the request synchronously but makes sure the requests are queued and only one is going on at any given time. The effect is pretty much the same, except that the end-user can still use the browser UI while the request is going on and he won't have to kill the process if the server fails to respond or the network connection falls.
The MSDN page confirms this:
When sending data synchronously in a callback scenario, synchronous callbacks return immediately and do not block the browser. No two synchronous callbacks callback can execute at the same time in the browser. If a second synchronous callback is fired while one is currently pending, the second synchronous callback cancels the first and only the second callback will return.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147458",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Proper build reports in TFS with multiple products under a project Underneath one "Project" in TFS we have multiple products. This is because for us, a project is a business unit and they each can have many applications that we develop for them. Each one has its own folder in source control(under the TFS project) and each one has its own TeamBuild set up. The issue I have is that whenever a build runs, the report generated for it contains a listing of all the changesets that were associated to the TFS Project; even though many of them were for a different product and the code referenced actually wasn't compiled or built during that build.
Does anyone know how to get TFS to only include changesets in its report that are associated to the actual VisualStudio projects that are being built in TeamBuild?
A: The best solution would to to modify the Workspace Mapping for the Team Build Definition to include the Solution Root path instead of the Team Project Root.
In TFS2008,
*
*Right click the Team Build Definition and choose 'Edit Build Definition'
*Select the 'Workspace' tab
*Remove the existing mapping: $/TeamProjectName
*Add a new mapping to the solution root, for example: $/TeamProject/Main/Solution1/
In TFS2005,
*
*Open Source Control Explorer
*Browse to $/TeamProject/TeamBuildTypes/BuildName/WorkspaceMappings.xml
*Get Latest of the file and check it out for edit
*Remove the existing mapping: $/TeamProjectName
*Add a new mapping to the solution root, for example: $/TeamProject/Main/Solution1/
This workspace mapping defines the scope for changesets to be included in the build.
See:
*
*http://blogs.msdn.com/buckh/archive/2007/08/14/tfs-2008-a-basic-guide-to-team-build-2008.aspx
*http://msdn.microsoft.com/en-us/library/ms181718.aspx
*http://msdn.microsoft.com/en-us/library/ms181286.aspx
Grant
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147459",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Can you recommend a .cvsignore file for a Visual C#.NET solution? I've developed a Visual C#.NET 2008 Express Edition solution containing three projects. I am cleaning it up to commit it into a CVS repository.
There are several files that are created during the build process that are not necessary to be placed in the repository since they will be regenerated automatically.
The question: Can anyone suggest a list of patterns to be placed into a .cvsignore file so that these generated files and folders are ignored?
A: Typically these are the only things that you have to commit:
*
*.sln files
*.cs files
*.csproj files
*.config files
*External DLLs and corresponding XML/config files that you are referencing
*other non-generated files that your application uses
All the rest are to be ignored, including:
*
*.suo files
*.csproj.user files
*/bin folder and contents
*/obj folder and contents
*practically everything else
A: Thanks! This is what I have created:
bin
obj
*.cache
*.suo
*.csproj.user
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147460",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: When memory is allocated for a program? I need to know when the memory will be allocated for a particular program. How can i view where the memory is allocated.
A: You'll need to be more specific with the OS, and perhaps language if it's interpreted or run time compiled (ie, PHP, JAVA, .NET, etc).
However, in general:
*
*Static and global variables are allocated when the program is loaded into memory.
*Local variables are allocated on the stack (sometimes heap, depending on compiler) when the function or block is run that instantiates them.
*At other points in the program memory is allocated when objects are created, and released when they are destroyed (explicitly or through garbage collection)
*The program may also explicitly allocate memory through malloc or similar memory allocation calls to the OS.
It should be noted that even if memory has been allocated with the OS, it may not yet actually be assigned - the OS waits until the memory is used before it gets a page for it. A memory profiler will help you learn where and when this occurs for a given process.
Where the memory is allocated is a much larger question. There are several points of view to consider:
*
*The program's point of view (usually a flat virtual memory area that the program can run around in without colliding with other programs - about 4GB on a 32 bit machine)
*The OS's point of view, with pages of memory swapped in an out as needed so the programs can pretend they have a nice, flat, unsegmented memory area to play in
*The CPU's point of view where the memory is contiguous
*The memory controller's point of view where it may have two 512 sticks and a 1GB stick with an empty slot inbetween
Which perspective are you curious about? Are you writing code that runs within the program of interest, shares memory with it, runs on the same OS, runs on the same CPU, or hooking a logic analyzer up to the memory bus?
-Adam
A: I'll take a stab here and recommend dotTrace, the best profiler I've used. It'll tell you memory usage and a lot more.
A: Install Process Explorer, locate your application/process in the list, right click, Properties, Performance tab.
A: Just as a cautionary story, even if you don't allocate much yourself, the libraries you use might be doing lots of allocations, so you need something that ties into the kernel or framework. as Ben Hoffstein says dotTrace would probably be a good solution for .Net application (something that I only realized after looking at the question's tags)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147462",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Why should the interface for a Java class be preferred? PMD would report a violation for:
ArrayList<Object> list = new ArrayList<Object>();
The violation was "Avoid using implementation types like 'ArrayList'; use the interface instead".
The following line would correct the violation:
List<Object> list = new ArrayList<Object>();
Why should the latter with List be used instead of ArrayList?
A: Using interfaces over concrete types is the key for good encapsulation and for loose coupling your code.
It's even a good idea to follow this practice when writing your own APIs. If you do, you'll find later that it's easier to add unit tests to your code (using Mocking techniques), and to change the underlying implementation if needed in the future.
Here's a good article on the subject.
Hope it helps!
A: ArrayList and LinkedList are two implementations of a List, which is an ordered collection of items. Logic-wise it doesn't matter if you use an ArrayList or a LinkedList, so you shouldn't constrain the type to be that.
This contrasts with say, Collection and List, which are different things (List implies sorting, Collection does not).
A: This is preferred because you decouple your code from the implementation of the list. Using the interface lets you easily change the implementation, ArrayList in this case, to another list implementation without changing any of the rest of the code as long as it only uses methods defined in List.
A:
Why should the latter with List be used instead of ArrayList?
It's a good practice : Program to interface rather than implementation
By replacing ArrayList with List, you can change List implementation in future as below depending on your business use case.
List<Object> list = new LinkedList<Object>();
/* Doubly-linked list implementation of the List and Deque interfaces.
Implements all optional list operations, and permits all elements (including null).*/
OR
List<Object> list = new CopyOnWriteArrayList<Object>();
/* A thread-safe variant of ArrayList in which all mutative operations
(add, set, and so on) are implemented by making a fresh copy of the underlying array.*/
OR
List<Object> list = new Stack<Object>();
/* The Stack class represents a last-in-first-out (LIFO) stack of objects.*/
OR
some other List specific implementation.
List interface defines contract and specific implementation of List can be changed. In this way, interface and implementation are loosely coupled.
Related SE question:
What does it mean to "program to an interface"?
A: In general I agree that decoupling interface from implementation is a good thing and will make your code easier to maintain.
There are, however, exceptions that you must consider. Accessing objects through interfaces adds an additional layer of indirection that will make your code slower.
For interest I ran an experiment that generated ten billion sequential accesses to a 1 million length ArrayList. On my 2.4Ghz MacBook, accessing the ArrayList through a List interface took 2.10 seconds on average, when declaring it of type ArrayList it took on average 1.67 seconds.
If you are working with large lists, deep inside an inner loop or frequently called function, then this is something to consider.
A: In general for your line of code it does not make sense to bother with interfaces. But, if we are talking about APIs there is a really good reason. I got small class
class Counter {
static int sizeOf(List<?> items) {
return items.size();
}
}
In this case is usage of interface required. Because I want to count size of every possible implementation including my own custom. class MyList extends AbstractList<String>....
A: Properties of your classes/interfaces should be exposed through interfaces because it gives your classes a contract of behavior to use, regardless of the implementation.
However...
In local variable declarations, it makes little sense to do this:
public void someMethod() {
List theList = new ArrayList();
//do stuff with the list
}
If its a local variable, just use the type. It is still implicitly upcastable to its appropriate interface, and your methods should hopefully accept the interface types for its arguments, but for local variables, it makes total sense to use the implementation type as a container, just in case you do need the implementation-specific functionality.
A: Even for local variables, using the interface over the concrete class helps. You may end up calling a method that is outside the interface and then it is difficult to change the implementation of the List if necessary.
Also, it is best to use the least specific class or interface in a declaration. If element order does not matter, use a Collection instead of a List. That gives your code the maximum flexibility.
A: Interface is exposed to the end user. One class can implement multiple interface. User who have expose to specific interface have access to some specific behavior which are defined in that particular interface.
One interface also have multiple implementation. Based on the scenario system will work with different scenario (Implementation of the interface).
let me know if you need more explanation.
A: The interface often has better representation in the debugger view than the concrete class.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147468",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "80"
} |
Q: XPath query searching for an element with specific text Given the following XML structure
<html>
<body>
<div>
<span>Test: Text2</span>
</div>
<div>
<span>Test: Text3</span>
</div>
<div>
<span>Test: Text5</span>
</div>
</body>
</html>
What is the best XPath query to locate any span with text that starts with Test?
A: Valid option is also:
//span[contains(.,'Test')]
A: //span[starts-with(.,'Test')]
References:
http://www.w3.org/TR/xpath/#function-starts-with
https://developer.mozilla.org/en-US/docs/Web/XPath/Functions/starts-with
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147486",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
} |
Q: How to convert a byte into a string in vb.net? I have the function below ENCRYPT.
Public Function Encrypt(ByVal plainText As String) As Byte()
Dim key() As Byte = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24}
Dim iv() As Byte = {65, 110, 68, 26, 69, 178, 200, 219}
' Declare a UTF8Encoding object so we may use the GetByte
' method to transform the plainText into a Byte array.
Dim utf8encoder As UTF8Encoding = New UTF8Encoding()
Dim inputInBytes() As Byte = utf8encoder.GetBytes(plainText)
' Create a new TripleDES service provider
Dim tdesProvider As TripleDESCryptoServiceProvider = New TripleDESCryptoServiceProvider()
' The ICryptTransform interface uses the TripleDES
' crypt provider along with encryption key and init vector
' information
Dim cryptoTransform As ICryptoTransform = tdesProvider.CreateEncryptor(Me.key, Me.iv)
' All cryptographic functions need a stream to output the
' encrypted information. Here we declare a memory stream
' for this purpose.
Dim encryptedStream As MemoryStream = New MemoryStream()
Dim cryptStream As CryptoStream = New CryptoStream(encryptedStream, cryptoTransform, CryptoStreamMode.Write)
' Write the encrypted information to the stream. Flush the information
' when done to ensure everything is out of the buffer.
cryptStream.Write(inputInBytes, 0, inputInBytes.Length)
cryptStream.FlushFinalBlock()
encryptedStream.Position = 0
' Read the stream back into a Byte array and return it to the calling
' method.
Dim result(encryptedStream.Length - 1) As Byte
encryptedStream.Read(result, 0, encryptedStream.Length)
cryptStream.Close()
Return result
End Function
How do i see the byte value of the text?
A: You can use Encoding class.
To convert array of bytes to a string you can use Encoding.GetString method
There is a special version for UTF8: UTF8Encoding.GetString
A: Not 100% sure what you are asking, if you want to display your encrypted byte array as a string, then I would say, don't do that as your string won't be "string" data it will be encryted bytes and won't be displayable (generally)
if you are asking how can I see the byte values as a string...i.e. 129,45,24,67 etc then (assuming .net 3.5)
string.Join(",", byteArray.Select(b => b.ToString()).ToArray());
And if you are asking about converting back your de-crypted byte array, then you need to use the same encoding class that you used to create the original byte array, in your case the UTF8 encoding class.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147491",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is it possible to include one CSS file in another? Is it possible to include one CSS file in another?
A: Yes, use @import
detailed info easily googled for, a good one at http://webdesign.about.com/od/beginningcss/f/css_import_link.htm
A: yes it is possible using @import and providing the path of css file
e.g.
@import url("mycssfile.css");
or
@import "mycssfile.css";
A: @import("/path-to-your-styles.css");
That is the best way to include a css stylesheet within a css stylesheet using css.
A: The "@import" rule could calls in multiple styles files. These files are called by the browser or User Agent when needed e.g. HTML tags call the CSS.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="EN" dir="ltr">
<head>
<title>Using @import</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<style type="text/css">
@import url("main.css");
</style>
</head>
<body>
</body>
</html>
CSS File "main.css" Contains The Following Syntax:
@import url("fineprint.css") print;
@import url("bluish.css") projection, tv;
@import 'custom.css';
@import url("chrome://communicator/skin/");
@import "common.css" screen, projection;
@import url('landscape.css') screen and (orientation:landscape);
To insert in style element use createTexNode don't use innerHTML but:
<script>
var style = document.createElement('style');
style.setAttribute("type", "text/css");
var textNode = document.createTextNode("
@import 'fineprint.css' print;
@import 'bluish.css' projection, tv;
@import 'custom.css';
@import 'chrome://communicator/skin/';
@import 'common.css' screen, projection;
@import 'landscape.css' screen and (orientation:landscape);
");
style.appendChild(textNode);
</script>
A: The @import url("base.css"); works fine but bear in mind that every @import statement is a new request to the server. This might not be a problem for you, but when optimal performance is required you should avoid the @import.
A: The CSS @import rule does just that. E.g.,
@import url('/css/common.css');
@import url('/css/colors.css');
A: Import bootstrap with altervista and wordpress
I use this to import bootstrap.css in altervista with wordpress
@import url("https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css");
and it works fine, as it would delete the html link rel code if I put it into a page
A: @import url('style.css');
As opposed to the best answer, it is not recommended to aggregate all CSS files into one chunk when using HTTP/2.0
A: Yes.
@import "your.css";
The rule is documented here.
A: Yes. Importing CSS file into another CSS file is possible.
It must be the first rule in the style sheet using the @import rule.
@import "mystyle.css";
@import url("mystyle.css");
The only caveat is that older web browsers will not support it. In fact, this is one of the CSS 'hack' to hide CSS styles from older browsers.
Refer to this list for browser support.
A: In some cases it is possible using @import "file.css", and most modern browsers should support this, older browsers such as NN4, will go slightly nuts.
Note: the import statement must precede all other declarations in the file, and test it on all your target browsers before using it in production.
A: Yes:
@import url("base.css");
Note:
*
*The @import rule must precede all other rules (except @charset).
*Additional @import statements require additional server requests. As an alternative, concatenate all CSS into one file to avoid multiple HTTP requests. For example, copy the contents of base.css and special.css into base-special.css and reference only base-special.css.
A: I have created main.css file and included all css files in it.
We can include only one main.css file
@import url('style.css');
@import url('platforms.css');
A: Yes You can import easily one css to another (any where in website)
You have to use like:
@import url("url_path");
A: sing the CSS @import Rule
here
@import url('/css/header.css') screen;
@import url('/css/content.css') screen;
@import url('/css/sidebar.css') screen;
@import url('/css/print.css') print;
A: For whatever reason, @import didn't work for me, but it's not really necessary is it?
Here's what I did instead, within the html:
<link rel="stylesheet" media="print" href="myap-print.css">
<link rel="stylesheet" media="print" href="myap-screen.css">
<link rel="stylesheet" media="screen" href="myap-screen.css">
Notice that media="print" has 2 stylesheets: myap-print.css and myap-screen.css. It's the same effect as including myap-screen.css within myap-print.css.
A: I stumbled upon this and I just wanted to say PLEASE DON'T USE @IMPORT IN CSS!!!! The import statement is sent to the client and the client does another request. If you want to divide your CSS between various files use Less. In Less the import statement happens on the server and the output is cached and does not create a performance penalty by forcing the client to make another connection. Sass is also an option another not one I have explored. Frankly, if you are not using Less or Sass then you should start. http://willseitz-code.blogspot.com/2013/01/using-less-to-manage-css-files.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147500",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "858"
} |
Q: Flex HTTPService does not include Content-Length header? I am trying to get a Flex application to communicate with a custom python webserver I have developed.
I am noticing that I cannot read the postdata received because Flex does not seem to include the Content-Length in the HTTP headers. (My webserver work when posted to from plain HTML)
Is this a known problem? any ideas how to set the content-length header?
Here is the current headers being sent:
Host: localhost:7070
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0
.3
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
A: It should, so long as you set your HTTPService's method property to POST. If you omit it, it will default to GET, and the parameters will be sent as part of the query string, not as POST data.
I set up this scenario using this Flex code:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application layout="absolute"
xmlns:mx="http://www.adobe.com/2006/mxml"
creationComplete="init()">
<mx:HTTPService id="service"
url="http://localhost:8000/"
method="POST"
resultFormat="text"
result="response.htmlText=ResultEvent(event).result.toString()"/>
<mx:Text id="response" width="100%" height="100%"/>
<mx:Script>
<![CDATA[
import mx.rpc.events.ResultEvent;
private function init() : void {
service.send({
foo: "Fred",
bar: "Barney"
});
}
]]>
</mx:Script>
</mx:Application>
And this python server code:
#!/usr/bin/env python
import SimpleHTTPServer, BaseHTTPServer, string
class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def do_POST(self):
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write("<html><body>")
self.wfile.write("<b>METHOD:</b> " + self.command)
# Write out Headers
header_keys = self.headers.dict.keys()
for key in header_keys:
self.wfile.write("<br><b>" + key + "</b>: ")
self.wfile.write(self.headers.dict[key])
# Write out any POST data
if self.headers.dict.has_key("content-length"):
content_length = string.atoi(self.headers.dict["content-length"])
raw_post_data = self.rfile.read(content_length)
self.wfile.write("<br><b>Post Data:</b> " + raw_post_data)
self.wfile.write("</body></html>")
def do_GET(self):
self.do_POST()
try:
BaseHTTPServer.test(MyHandler, BaseHTTPServer.HTTPServer)
except KeyboardInterrupt:
print 'Exiting...'
And got this result:
METHOD: POST
content-length: 19
accept-language: en-us,en;q=0.5
accept-encoding: gzip,deflate
connection: keep-alive
keep-alive: 300
accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
user-agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1
accept-charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
host: 10.0.7.61:8000
content-type: application/x-www-form-urlencoded
Post Data: bar=Barney&foo=Fred
So it should work.
A: I don't believe this is a known problem.
Are you sure no Content-Length is being sent? You've posted the request side of the HTTP interaction, coming from your browser; there is never a Content-Length header on that side of the protocol.
A: As Bill D says, you almost certainly are not doing a POST, as we do those all the time, fielding them with our server code and it most certainly includes the Content-Length.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147505",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How does one do the equivalent of "import * from module" with Python's __import__ function? Given a string with a module name, how do you import everything in the module as if you had called:
from module import *
i.e. given string S="module", how does one get the equivalent of the following:
__import__(S, fromlist="*")
This doesn't seem to perform as expected (as it doesn't import anything).
A: Here's my solution for dynamic naming of local settings files for Django. Note the addition below of a check to not include attributes containing '__' from the imported file. The __name__ global was being overwritten with the module name of the local settings file, which caused setup_environ(), used in manage.py, to have problems.
try:
import socket
HOSTNAME = socket.gethostname().replace('.','_')
# See http://docs.python.org/library/functions.html#__import__
m = __import__(name="settings_%s" % HOSTNAME, globals=globals(), locals=locals(), fromlist="*")
try:
attrlist = m.__all__
except AttributeError:
attrlist = dir(m)
for attr in [a for a in attrlist if '__' not in a]:
globals()[attr] = getattr(m, attr)
except ImportError, e:
sys.stderr.write('Unable to read settings_%s.py\n' % HOSTNAME)
sys.exit(1)
A: Please reconsider. The only thing worse than import * is magic import *.
If you really want to:
m = __import__ (S)
try:
attrlist = m.__all__
except AttributeError:
attrlist = dir (m)
for attr in attrlist:
globals()[attr] = getattr (m, attr)
A: The underlying problem is that I am developing some Django, but on more than one host (with colleagues), all with different settings. I was hoping to do something like this in the project/settings.py file:
from platform import node
settings_files = { 'BMH.lan': 'settings_bmh.py", ... }
__import__( settings_files[ node() ] )
It seemed a simple solution (thus elegant), but I would agree that it has a smell to it and the simplicity goes out the loop when you have to use logic like what John Millikin posted (thanks). Here's essentially the solution I went with:
from platform import node
from settings_global import *
n = node()
if n == 'BMH.lan':
from settings_bmh import *
# add your own, here...
else:
raise Exception("No host settings for '%s'. See settings.py." % node())
Which works fine for our purposes.
A: It appears that you can also use dict.update() on module's dictionaries in your case:
config = [__import__(name) for name in names_list]
options = {}
for conf in config:
options.update(conf.__dict__)
Update: I think there's a short "functional" version of it:
options = reduce(dict.update, map(__import__, names_list))
A: I didn't find a good way to do it so I took a simpler but ugly way from http://www.djangosnippets.org/snippets/600/
try:
import socket
hostname = socket.gethostname().replace('.','_')
exec "from host_settings.%s import *" % hostname
except ImportError, e:
raise e
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147507",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "22"
} |
Q: Least common multiple for 3 or more numbers How do you calculate the least common multiple of multiple numbers?
So far I've only been able to calculate it between two numbers. But have no idea how to expand it to calculate 3 or more numbers.
So far this is how I did it
LCM = num1 * num2 / gcd ( num1 , num2 )
With gcd is the function to calculate the greatest common divisor for the numbers. Using euclidean algorithm
But I can't figure out how to calculate it for 3 or more numbers.
A: I just figured this out in Haskell:
lcm' :: Integral a => a -> a -> a
lcm' a b = a`div`(gcd a b) * b
lcm :: Integral a => [a] -> a
lcm (n:ns) = foldr lcm' n ns
I even took the time to write my own gcd function, only to find it in Prelude! Lots of learning for me today :D
A: Some Python code that doesn't require a function for gcd:
from sys import argv
def lcm(x,y):
tmp=x
while (tmp%y)!=0:
tmp+=x
return tmp
def lcmm(*args):
return reduce(lcm,args)
args=map(int,argv[1:])
print lcmm(*args)
Here's what it looks like in the terminal:
$ python lcm.py 10 15 17
510
A: Here is a Python one-liner (not counting imports) to return the LCM of the integers from 1 to 20 inclusive:
Python 3.5+ imports:
from functools import reduce
from math import gcd
Python 2.7 imports:
from fractions import gcd
Common logic:
lcm = reduce(lambda x,y: x*y // gcd(x, y), range(1, 21))
Note that in both Python 2 and Python 3, operator precedence rules dictate that the * and // operators have the same precedence, and so they apply from left to right. As such, x*y // z means (x*y) // z and not x * (y//z). The two typically produce different results. This wouldn't have mattered as much for float division but it does for floor division.
A: Here it is in Swift.
// Euclid's algorithm for finding the greatest common divisor
func gcd(_ a: Int, _ b: Int) -> Int {
let r = a % b
if r != 0 {
return gcd(b, r)
} else {
return b
}
}
// Returns the least common multiple of two numbers.
func lcm(_ m: Int, _ n: Int) -> Int {
return m / gcd(m, n) * n
}
// Returns the least common multiple of multiple numbers.
func lcmm(_ numbers: [Int]) -> Int {
return numbers.reduce(1) { lcm($0, $1) }
}
A: Here is a C# port of Virgil Disgr4ce's implemenation:
public class MathUtils
{
/// <summary>
/// Calculates the least common multiple of 2+ numbers.
/// </summary>
/// <remarks>
/// Uses recursion based on lcm(a,b,c) = lcm(a,lcm(b,c)).
/// Ported from http://stackoverflow.com/a/2641293/420175.
/// </remarks>
public static Int64 LCM(IList<Int64> numbers)
{
if (numbers.Count < 2)
throw new ArgumentException("you must pass two or more numbers");
return LCM(numbers, 0);
}
public static Int64 LCM(params Int64[] numbers)
{
return LCM((IList<Int64>)numbers);
}
private static Int64 LCM(IList<Int64> numbers, int i)
{
// Recursively iterate through pairs of arguments
// i.e. lcm(args[0], lcm(args[1], lcm(args[2], args[3])))
if (i + 2 == numbers.Count)
{
return LCM(numbers[i], numbers[i+1]);
}
else
{
return LCM(numbers[i], LCM(numbers, i+1));
}
}
public static Int64 LCM(Int64 a, Int64 b)
{
return (a * b / GCD(a, b));
}
/// <summary>
/// Finds the greatest common denominator for 2 numbers.
/// </summary>
/// <remarks>
/// Also from http://stackoverflow.com/a/2641293/420175.
/// </remarks>
public static Int64 GCD(Int64 a, Int64 b)
{
// Euclidean algorithm
Int64 t;
while (b != 0)
{
t = b;
b = a % b;
a = t;
}
return a;
}
}'
A: And the Scala version:
def gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b)
def gcd(nums: Iterable[Int]): Int = nums.reduce(gcd)
def lcm(a: Int, b: Int): Int = if (a == 0 || b == 0) 0 else a * b / gcd(a, b)
def lcm(nums: Iterable[Int]): Int = nums.reduce(lcm)
A: Function to find lcm of any list of numbers:
def function(l):
s = 1
for i in l:
s = lcm(i, s)
return s
A: Here's an ECMA-style implementation:
function gcd(a, b){
// Euclidean algorithm
while (b != 0){
var temp = b;
b = a % b;
a = temp;
}
return a;
}
function lcm(a, b){
return (a * b / gcd(a, b));
}
function lcmm(args){
// Recursively iterate through pairs of arguments
// i.e. lcm(args[0], lcm(args[1], lcm(args[2], args[3])))
if(args.length == 2){
return lcm(args[0], args[1]);
} else {
var arg0 = args[0];
args.shift();
return lcm(arg0, lcmm(args));
}
}
A: You can compute the LCM of more than two numbers by iteratively computing the LCM of two numbers, i.e.
lcm(a,b,c) = lcm(a,lcm(b,c))
A: Using LINQ you could write:
static int LCM(int[] numbers)
{
return numbers.Aggregate(LCM);
}
static int LCM(int a, int b)
{
return a * b / GCD(a, b);
}
Should add using System.Linq; and don't forget to handle the exceptions ...
A: I would go with this one (C#):
static long LCM(long[] numbers)
{
return numbers.Aggregate(lcm);
}
static long lcm(long a, long b)
{
return Math.Abs(a * b) / GCD(a, b);
}
static long GCD(long a, long b)
{
return b == 0 ? a : GCD(b, a % b);
}
Just some clarifications, because at first glance it doesn't seams so clear what this code is doing:
Aggregate is a Linq Extension method, so you cant forget to add using System.Linq to your references.
Aggregate gets an accumulating function so we can make use of the property lcm(a,b,c) = lcm(a,lcm(b,c)) over an IEnumerable. More on Aggregate
GCD calculation makes use of the Euclidean algorithm.
lcm calculation uses Abs(a*b)/gcd(a,b) , refer to Reduction by the greatest common divisor.
Hope this helps,
A: In Python (modified primes.py):
def gcd(a, b):
"""Return greatest common divisor using Euclid's Algorithm."""
while b:
a, b = b, a % b
return a
def lcm(a, b):
"""Return lowest common multiple."""
return a * b // gcd(a, b)
def lcmm(*args):
"""Return lcm of args."""
return reduce(lcm, args)
Usage:
>>> lcmm(100, 23, 98)
112700
>>> lcmm(*range(1, 20))
232792560
reduce() works something like that:
>>> f = lambda a,b: "f(%s,%s)" % (a,b)
>>> print reduce(f, "abcd")
f(f(f(a,b),c),d)
A: you can do it another way -
Let there be n numbers.Take a pair of consecutive numbers and save its lcm in another array. Doing this at first iteration program does n/2 iterations.Then next pick up pair starting from 0 like (0,1) , (2,3) and so on.Compute their LCM and store in another array. Do this until you are left with one array.
(it is not possible to find lcm if n is odd)
A: ES6 style
function gcd(...numbers) {
return numbers.reduce((a, b) => b === 0 ? a : gcd(b, a % b));
}
function lcm(...numbers) {
return numbers.reduce((a, b) => Math.abs(a * b) / gcd(a, b));
}
A: In R, we can use the functions mGCD(x) and mLCM(x) from the package numbers, to compute the greatest common divisor and least common multiple for all numbers in the integer vector x together:
library(numbers)
mGCD(c(4, 8, 12, 16, 20))
[1] 4
mLCM(c(8,9,21))
[1] 504
# Sequences
mLCM(1:20)
[1] 232792560
A: Just for fun, a shell (almost any shell) implementation:
#!/bin/sh
gcd() { # Calculate $1 % $2 until $2 becomes zero.
until [ "$2" -eq 0 ]; do set -- "$2" "$(($1%$2))"; done
echo "$1"
}
lcm() { echo "$(( $1 / $(gcd "$1" "$2") * $2 ))"; }
while [ $# -gt 1 ]; do
t="$(lcm "$1" "$2")"
shift 2
set -- "$t" "$@"
done
echo "$1"
try it with:
$ ./script 2 3 4 5 6
to get
60
The biggest input and result should be less than (2^63)-1 or the shell math will wrap.
A: i was looking for gcd and lcm of array elements and found a good solution in the following link.
https://www.hackerrank.com/challenges/between-two-sets/forum
which includes following code. The algorithm for gcd uses The Euclidean Algorithm explained well in the link below.
https://www.khanacademy.org/computing/computer-science/cryptography/modarithmetic/a/the-euclidean-algorithm
private static int gcd(int a, int b) {
while (b > 0) {
int temp = b;
b = a % b; // % is remainder
a = temp;
}
return a;
}
private static int gcd(int[] input) {
int result = input[0];
for (int i = 1; i < input.length; i++) {
result = gcd(result, input[i]);
}
return result;
}
private static int lcm(int a, int b) {
return a * (b / gcd(a, b));
}
private static int lcm(int[] input) {
int result = input[0];
for (int i = 1; i < input.length; i++) {
result = lcm(result, input[i]);
}
return result;
}
A: Here is the PHP implementation:
// https://stackoverflow.com/q/12412782/1066234
function math_gcd($a,$b)
{
$a = abs($a);
$b = abs($b);
if($a < $b)
{
list($b,$a) = array($a,$b);
}
if($b == 0)
{
return $a;
}
$r = $a % $b;
while($r > 0)
{
$a = $b;
$b = $r;
$r = $a % $b;
}
return $b;
}
function math_lcm($a, $b)
{
return ($a * $b / math_gcd($a, $b));
}
// https://stackoverflow.com/a/2641293/1066234
function math_lcmm($args)
{
// Recursively iterate through pairs of arguments
// i.e. lcm(args[0], lcm(args[1], lcm(args[2], args[3])))
if(count($args) == 2)
{
return math_lcm($args[0], $args[1]);
}
else
{
$arg0 = $args[0];
array_shift($args);
return math_lcm($arg0, math_lcmm($args));
}
}
// fraction bonus
function math_fraction_simplify($num, $den)
{
$g = math_gcd($num, $den);
return array($num/$g, $den/$g);
}
var_dump( math_lcmm( array(4, 7) ) ); // 28
var_dump( math_lcmm( array(5, 25) ) ); // 25
var_dump( math_lcmm( array(3, 4, 12, 36) ) ); // 36
var_dump( math_lcmm( array(3, 4, 7, 12, 36) ) ); // 252
Credits go to @T3db0t with his answer above (ECMA-style code).
A: GCD needs a little correction for negative numbers:
def gcd(x,y):
while y:
if y<0:
x,y=-x,-y
x,y=y,x % y
return x
def gcdl(*list):
return reduce(gcd, *list)
def lcm(x,y):
return x*y / gcd(x,y)
def lcml(*list):
return reduce(lcm, *list)
A: How about this?
from operator import mul as MULTIPLY
def factors(n):
f = {} # a dict is necessary to create 'factor : exponent' pairs
divisor = 2
while n > 1:
while (divisor <= n):
if n % divisor == 0:
n /= divisor
f[divisor] = f.get(divisor, 0) + 1
else:
divisor += 1
return f
def mcm(numbers):
#numbers is a list of numbers so not restricted to two items
high_factors = {}
for n in numbers:
fn = factors(n)
for (key, value) in fn.iteritems():
if high_factors.get(key, 0) < value: # if fact not in dict or < val
high_factors[key] = value
return reduce (MULTIPLY, ((k ** v) for k, v in high_factors.items()))
A: clc;
data = [1 2 3 4 5]
LCM=1;
for i=1:1:length(data)
LCM = lcm(LCM,data(i))
end
A: We have working implementation of Least Common Multiple on Calculla which works for any number of inputs also displaying the steps.
What we do is:
0: Assume we got inputs[] array, filled with integers. So, for example:
inputsArray = [6, 15, 25, ...]
lcm = 1
1: Find minimal prime factor for each input.
Minimal means for 6 it's 2, for 25 it's 5, for 34 it's 17
minFactorsArray = []
2: Find lowest from minFactors:
minFactor = MIN(minFactorsArray)
3: lcm *= minFactor
4: Iterate minFactorsArray and if the factor for given input equals minFactor, then divide the input by it:
for (inIdx in minFactorsArray)
if minFactorsArray[inIdx] == minFactor
inputsArray[inIdx] \= minFactor
5: repeat steps 1-4 until there is nothing to factorize anymore.
So, until inputsArray contains only 1-s.
And that's it - you got your lcm.
A: LCM is both associative and commutative.
LCM(a,b,c)=LCM(LCM(a,b),c)=LCM(a,LCM(b,c))
here is sample code in C:
int main()
{
int a[20],i,n,result=1; // assumption: count can't exceed 20
printf("Enter number of numbers to calculate LCM(less than 20):");
scanf("%d",&n);
printf("Enter %d numbers to calculate their LCM :",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n;i++)
result=lcm(result,a[i]);
printf("LCM of given numbers = %d\n",result);
return 0;
}
int lcm(int a,int b)
{
int gcd=gcd_two_numbers(a,b);
return (a*b)/gcd;
}
int gcd_two_numbers(int a,int b)
{
int temp;
if(a>b)
{
temp=a;
a=b;
b=temp;
}
if(b%a==0)
return a;
else
return gcd_two_numbers(b%a,a);
}
A: Method compLCM takes a vector and returns LCM. All the numbers are within vector in_numbers.
int mathOps::compLCM(std::vector<int> &in_numbers)
{
int tmpNumbers = in_numbers.size();
int tmpMax = *max_element(in_numbers.begin(), in_numbers.end());
bool tmpNotDividable = false;
while (true)
{
for (int i = 0; i < tmpNumbers && tmpNotDividable == false; i++)
{
if (tmpMax % in_numbers[i] != 0 )
tmpNotDividable = true;
}
if (tmpNotDividable == false)
return tmpMax;
else
tmpMax++;
}
}
A: For anyone looking for quick working code, try this:
I wrote a function lcm_n(args, num) which computes and returns the lcm of all the numbers in the array args. The second parameternum is the count of numbers in the array.
Put all those numbers in an array args and then call the function like lcm_n(args,num);
This function returns the lcm of all those numbers.
Here is the implementation of the function lcm_n(args, num):
int lcm_n(int args[], int num) //lcm of more than 2 numbers
{
int i, temp[num-1];
if(num==2)
{
return lcm(args[0], args[1]);
}
else
{
for(i=0;i<num-1;i++)
{
temp[i] = args[i];
}
temp[num-2] = lcm(args[num-2], args[num-1]);
return lcm_n(temp,num-1);
}
}
This function needs below two functions to work. So, just add them along with it.
int lcm(int a, int b) //lcm of 2 numbers
{
return (a*b)/gcd(a,b);
}
int gcd(int a, int b) //gcd of 2 numbers
{
int numerator, denominator, remainder;
//Euclid's algorithm for computing GCD of two numbers
if(a > b)
{
numerator = a;
denominator = b;
}
else
{
numerator = b;
denominator = a;
}
remainder = numerator % denominator;
while(remainder != 0)
{
numerator = denominator;
denominator = remainder;
remainder = numerator % denominator;
}
return denominator;
}
A: int gcd(int a, int b) {
if (b == 0) return a;
return gcd(b, a%b);
}
int lcm(int[] a, int n) {
int res = 1, i;
for (i = 0; i < n; i++) {
res = res*a[i]/gcd(res, a[i]);
}
return res;
}
A: In python:
def lcm(*args):
"""Calculates lcm of args"""
biggest = max(args) #find the largest of numbers
rest = [n for n in args if n != biggest] #the list of the numbers without the largest
factor = 1 #to multiply with the biggest as long as the result is not divisble by all of the numbers in the rest
while True:
#check if biggest is divisble by all in the rest:
ans = False in [(biggest * factor) % n == 0 for n in rest]
#if so the clm is found break the loop and return it, otherwise increment factor by 1 and try again
if not ans:
break
factor += 1
biggest *= factor
return "lcm of {0} is {1}".format(args, biggest)
>>> lcm(100,23,98)
'lcm of (100, 23, 98) is 112700'
>>> lcm(*range(1, 20))
'lcm of (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19) is 232792560'
A: This is what I used --
def greater(n):
a=num[0]
for i in range(0,len(n),1):
if(a<n[i]):
a=n[i]
return a
r=input('enter limit')
num=[]
for x in range (0,r,1):
a=input('enter number ')
num.append(a)
a= greater(num)
i=0
while True:
while (a%num[i]==0):
i=i+1
if(i==len(num)):
break
if i==len(num):
print 'L.C.M = ',a
break
else:
a=a+1
i=0
A: for python 3:
from functools import reduce
gcd = lambda a,b: a if b==0 else gcd(b, a%b)
def lcm(lst):
return reduce(lambda x,y: x*y//gcd(x, y), lst)
A: In Ruby, it's as simple as:
> [2, 3, 4, 6].reduce(:lcm)
=> 12
> [16, 32, 96].reduce(:gcd)
=> 16
(tested on Ruby 2.2.10 and 2.6.3.)
A: Python 3.9 math module's gcd and lcm support over a list of numbers.
import math
lst = [1,2,3,4,5,6,7,8,9]
print(math.lcm(*lst))
print(math.gcd(*lst))
A: If there's no time-constraint, this is fairly simple and straight-forward:
def lcm(a,b,c):
for i in range(max(a,b,c), (a*b*c)+1, max(a,b,c)):
if i%a == 0 and i%b == 0 and i%c == 0:
return i
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147515",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "174"
} |
Q: How do I force a DIV block to extend to the bottom of a page even if it has no content? In the markup shown below, I'm trying to get the content div to stretch all the way to the bottom of the page but it's only stretching if there's content to display. The reason I want to do this is so the vertical border still appears down the page even if there isn't any content to display.
Here is my DEMO:
body {
font-family: Trebuchet MS, Verdana, MS Sans Serif;
font-size:0.9em;
margin:0;
padding:0;
}
div#header {
width: 100%;
height: 100px;
}
#header a {
background-position: 100px 30px;
background: transparent url(site-style-images/sitelogo.jpg) no-repeat fixed 100px 30px;
height: 80px;
display: block;
}
#header, #menuwrapper {
background-repeat: repeat;
background-image: url(site-style-images/darkblue_background_color.jpg);
}
#menu #menuwrapper {
height:25px;
}
div#menuwrapper {
width:100%
}
#menu, #content {
width:1024px;
margin: 0 auto;
}
div#menu {
height: 25px;
background-color:#50657a;
}
<form id="form1">
<div id="header">
<a title="Home" href="index.html" />
</div>
<div id="menuwrapper">
<div id="menu">
</div>
</div>
<div id="content">
</div>
</form>
A: you can kinda hack it with the min-height declaration
<div style="min-height: 100%">stuff</div>
A: I'll try to answer the question directly in the title, rather than being hell-bent on sticking a footer to the bottom of the page.
Make div extend to the bottom of the page if there's not enough content to fill the available vertical browser viewport:
Demo at (drag the frame handle to see effect) : http://jsfiddle.net/NN7ky
(upside: clean, simple. downside: requires flexbox - http://caniuse.com/flexbox)
HTML:
<body>
<div class=div1>
div1<br>
div1<br>
div1<br>
</div>
<div class=div2>
div2<br>
div2<br>
div2<br>
</div>
</body>
CSS:
* { padding: 0; margin: 0; }
html, body {
height: 100%;
display: flex;
flex-direction: column;
}
body > * {
flex-shrink: 0;
}
.div1 { background-color: yellow; }
.div2 {
background-color: orange;
flex-grow: 1;
}
ta-da - or i'm just too sleepy
A: You can use the "vh" length unit for the min-height property of the element itself and its parents. It's supported since IE9:
<body class="full-height">
<form id="form1">
<div id="header">
<a title="Home" href="index.html" />
</div>
<div id="menuwrapper">
<div id="menu">
</div>
</div>
<div id="content" class="full-height">
</div>
</body>
CSS:
.full-height {
min-height: 100vh;
box-sizing: border-box;
}
A: While it isn't as elegant as pure CSS, a small bit of javascript can help accomplish this:
<html>
<head>
<style type='text/css'>
div {
border: 1px solid #000000;
}
</style>
<script type='text/javascript'>
function expandToWindow(element) {
var margin = 10;
if (element.style.height < window.innerHeight) {
element.style.height = window.innerHeight - (2 * margin)
}
}
</script>
</head>
<body onload='expandToWindow(document.getElementById("content"));'>
<div id='content'>Hello World</div>
</body>
</html>
A: The min-height property is not supported by all browsers. If you need your #content to extend it's height on longer pages the height property will cut it short.
It's a bit of a hack but you could add an empty div with a width of 1px and height of e.g. 1000px inside your #content div. That will force the content to be at least 1000px high and still allow longer content to extend the height when needed
A: Try Ryan Fait's "Sticky Footer" solution,
http://ryanfait.com/sticky-footer/
http://ryanfait.com/resources/footer-stick-to-bottom-of-page/
Works across IE, Firefox, Chrome, Safari and supposedly Opera too, but haven't tested that. It's a great solution. Very easy and reliable to implement.
A: Try:
html, body {
height: 102%;
}
.wrapper {
position: relative;
height: 100%;
width: 100%;
}
.div {
position: absolute;
top: 0;
bottom: 0;
width: 1000px;
min-height: 100%;
}
Haven't tested it yet...
A: Sticky footer with fixed height:
HTML scheme:
<body>
<div id="wrap">
</div>
<div id="footer">
</div>
</body>
CSS:
html, body {
height: 100%;
}
#wrap {
min-height: 100%;
height: auto !important;
height: 100%;
margin: 0 auto -60px;
}
#footer {
height: 60px;
}
A: Try http://mystrd.at/modern-clean-css-sticky-footer/
The link above is down, but this link https://stackoverflow.com/a/18066619/1944643 is ok. :D
Demo:
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<meta name="author" content="http://mystrd.at">
<meta name="robots" content="noindex, nofollow">
<title>James Dean CSS Sticky Footer</title>
<style type="text/css">
html {
position: relative;
min-height: 100%;
}
body {
margin: 0 0 100px;
/* bottom = footer height */
padding: 25px;
}
footer {
background-color: orange;
position: absolute;
left: 0;
bottom: 0;
height: 100px;
width: 100%;
overflow: hidden;
}
</style>
</head>
<body>
<article>
<!-- or <div class="container">, etc. -->
<h1>James Dean CSS Sticky Footer</h1>
<p>Blah blah blah blah</p>
<p>More blah blah blah</p>
</article>
<footer>
<h1>Footer Content</h1>
</footer>
</body>
</html>
A: Try playing around with the following css rule:
#content {
min-height: 600px;
height: auto !important;
height: 600px;
}
Change the height to suit your page. height is mentioned twice for cross browser compatibility.
A: Your problem is not that the div is not at 100% height, but that the container around it is not.This will help in the browser I suspect you are using:
html,body { height:100%; }
You may need to adjust padding and margins as well, but this will get you 90% of the way there.If you need to make it work with all browsers you will have to mess around with it a bit.
This site has some excellent examples:
http://www.brunildo.org/test/html_body_0.html
http://www.brunildo.org/test/html_body_11b.html
http://www.brunildo.org/test/index.html
I also recommend going to http://quirksmode.org/
A: I think the issue would be fixed just making the html fill 100% also,
might be body fills the 100% of the html but html doesn't fill 100% of the screen.
Try with:
html, body {
height: 100%;
}
A: Also you might like this: http://matthewjamestaylor.com/blog/ultimate-2-column-left-menu-pixels.htm
It isn't quite what you asked for, but it might also suit your needs.
A: I dont have the code, but I know I did this once using a combination of height:1000px and margin-bottom: -1000px; Try that.
A: Depending on how your layout works, you might get away with setting the background on the <html> element, which is always at least the height of the viewport.
A: It is not possible to accomplish this using only stylesheets (CSS). Some browsers will not accept
height: 100%;
as a higher value than the viewpoint of the browser window.
Javascript is the easiest cross browser solution, though as mentioned, not a clean or beautiful one.
A: I know this is not the best method, but I couldnt figure it out without messing my header, menu, etc positions. So.... I used a table for those two colums. It was a QUICK fix. No JS needed ;)
A: #content {
height: calc(100% - the amount of pixels the content div is away from the top);
}
So if your div is 200px from the top, the code you need would be
#content {
height: calc(100% - 200px);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147528",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "219"
} |
Q: Real HLSL IDE/debugger Are there any IDE's for developing HLSL code? The three key features I want are:
1) syntax highlighting
2) auto-complete
3) interaction debugging
Visual Studio doesn't do any of these things, and it doesn't seem that RenderMonkey or FX Composer do either.
Is there some IDE that I'm not aware of, or does one of these three IDE's actually support these features and I'm too clueless to figure out how to use them properly?
A: Have you actually tried ATI's RenderMoney or NVidia's FX Composer?
Both actually provide syntax highlighting. Futher more, NVidia's Cg toolkits actually allows you to enable syntaxhightling in Visual Studio with some custom setting.
As for auto-completion, I don't think it's much needed as compare to our normal programming. It's because you won't be writing a very long code for your shader programming. Shader is quite critical in that it is run on every frame generated, and every instruction require 1 to a few clock cycle to execute, thus there's always a physical limit to how long you can afford to write.
Interactive debugging is currently the limitation of GPU hardware. To actually do that, the GPU has to be emulated with our CPU, which is quite impossible considering that the REF (software rendering) device can never cop up with even obsolete GPU, what more to say about emulating shader.
A: New answer to old question,
For debugging: NVidias Shader Debugger and it recently became free.
A: Another new answer to an old question (actually 2 answers):
*
*NShader is a Visual Studio plugin that provides syntax highlighting for HLSL / GLSL / CG. No intellisense or debugging though.
*IntelliShade, mentioned already, is no longer available at the original site, but it has been mirrored here.
A: In the MSDev environment you can define key words and also specify 'hlsl' and 'fx' to be recognized and known files and get MSDev highlight the keywords you want.
As for the editing tools - you can use the FX composer by NVidia or RenderMonkey by ATI. If you need to debug and profile you can use their tools as well and give Pix a spin.
A: Take a look at Shazzam. It doesn't feature interactive debugging, but it's pretty easy to edit and refresh.
A: Now with Visual Studio 11 there is a "real hlsl ide and debugger". It was detailed at Game Debugging in Visual Studio 11 and is available at Visual Studio 11 Beta.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147530",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Best place to save user information for Windows XP and Vista applications I need to save a user's login information in encrypted form for this application I'm building, but I'm not sure of the best place to save the file. I don't want to save it into the program application folder as I want it per user.
So what is the best folder (or way) to save it into?
Edit: Using C++.
A: Seems like C:\Documents and Settings\%username%\Local Settings\Application Data may be the appropriate place according to Wikipedia. The article says this location is used for "User-specific and computer-specific application settings".
Edit: Cruizer pointed out in the comments (I'd reply there but I can't comment yet) that in Vista it is C:\Users\%username% and that it shouldn't be hard-coded. Thanks.
A: Use the Data Protection API (DPAPI) - a part of the CryptoAPI in XP and Vista. Here's a good overview of DPAPI - http://msdn.microsoft.com/en-us/library/ms995355.aspx
A: Yeah, local application path looks like a winner.
I found this article in MSDN to get it in C++: http://msdn.microsoft.com/en-us/library/bb762494.aspx
Example:
char localAppPath[MAX_PATH];
SHGetFolderPath(NULL, CSIDL_LOCAL_APPDATA, NULL, SHGFP_TYPE_CURRENT, localAppPath);
A: are you using .NET? how about IsolatedStorage? That way you wouldn't have to worry about the directory location, it'll just be there...
A: User information should always go in some sub directory in %HOMEDRIVE%%HOMEPATH% (Which maps to the users home directory). No exceptions.
A good place for application specific settings per user is a sub directory inside %APPDATA%. This maps to: "%HOMEDRIVE%%HOMEPATH%\Application Data" on XP and to: " %HOMEDRIVE%%HOMEPATH%\AppData\Roaming" on Vista.
A: If you are using .NET to get special folders you can use
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
or
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
for the non-roaming version.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147533",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: ASP.NET and unverifiable components I am working on an ASP.NET application. I need to use some third party component (do not have the source code) that is unverifiable (I think it is written in managed c++).
I am wondering if this can cause problems for the customers.
The ASP.NET application can be installed on the customers servers or potentially on some hosted server.
What are the problems that I/customers may get into?
A: You have to test these yourself. Potentially the problems that can crop up are:
*
*Improper registering of COM DLLs -- you have to test your application installer to make sure this doesn't happen
*Registry complications - some third party components set registry entries that can only be entered using their own installer, rendering it impossible for you to properly install the component yourself. In that case you have to bootstrap their installer to yours.
*Unknown dependencies -- if your third party components have dependencies to other components that are not obvious
*Unknown requirements -- if your third party component has specific hardware requirements, they might fail.
*Unclear environment requirements -- some third party components can run on Windows Server 2000 or 2003, but not on 2008, or vice-versa
All of these can be mitigated by testing your final application installer on vanilla (plain-Windows) servers which represent a good sample of your targeted server OSs: Windows Server 2000, 2003, 2008. You should also test your application against freshly-installed instances of IIS 5, 6, and 7.
Consequently, if you wish to target Mono, you have to make further tests on various Linux distros.
A: First of all you have to ensure that you're using the same .NET Framework version as your customer. Also note the dependencies/requirements of that third party component; if those are not present in your customer's machines then it won't work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147536",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is Silverlight the 'same' as jQuery? Could Silverlight be used for the same things as jQuery, or are they intended for different things?
For example, vb.net could be used for the same stuff as C# while C# is intended for different things than what JavaScript is. Is Silverlight and jQuery like vb.net and C#, or more like C# and JavaScript?
A: It's more like the difference between C# and JavaScript. Silverlight and jQuery at the high level are intended for similar things - rich user interaction in a web browser. However, Silverlight can do some more interesting things by using the .NET framework, and allows you to muck around with with WPF so you can add 3D rendering, advanced printing, playing back movies, DRM (ugh), and more things that jQuery just can't do yet. That said, I have no doubt that JavaScript and JS frameworks like jQuery will eventually catch up to most of the things Silverlight can do.
Another thing to mention is that Silverlight requires users to download and install a browser plugin, while jQuery works with any modern JavaScript-enabled browser. I think Silverlight is more comparable to Adobe Flash than to jQuery.
A: Interesting riddle. No, Silverlight and jQuery are two different things entirely. If you want analogies, Silverlight is more akin to Adobe Flash. jQuery is a Javascript library akin to Prototype, Dojo, etc.
A: It's not the 'same' thing.
It's more like C# and Javascript.
jQuery is a javascript framework that helps with writing javascript
but Silverlight is an interactive media technology of its own... which is... IMO... totally different.
A: Saying that Silverlight is "just like Flash" doesn't answer the question.
Ok, how about, can (Flash|Silverlight) produce the same results javascript?
More to the point, with today's browsers, is there any visual effect which cannot be rendered in Javascript as easily as (Flash|Silverlight)?
Are there speed and performance benefits in using (Flash|Silverlight) for things like drop down menus and animation versus javascript?
Are there difficulties in using (Flash|Silverlight) when it comes to tailoring highly data rich sites that make it easier to use code rather than designer type interface?
A: Silverlight can be used to create rich interactive media, and is more akin to Flash than anything else. jQuery is a javascript library.
A: Silverlight comes closer to being like Flash, than JScript.
Both Flash & Silverlight are browser plug-ins that can be used to create rich interfaces. Both use proprietary technology & formats.
A: Think of Silverlight as "Flash.NET" -- a way to write a .NET app that runs within its own box within the browser.
A: Expanding on what been said, you may as well try comparing assembler with photoshop. On the reasoning both can be used to generate files.
They really are totally different technologies.
Javascript relies soley on the underlying page structure and DOM augmentation to yield results, Silverlight is like Flash, and tends more towards being just a "window" in the page with its own canvas etc.
Trying to compare silverlight with jQuery however, which is a library for javascript, its just nonsensical.
They're so incomparable, I'm having difficulty finding 2 other things that are equally incomparable. You may as well ask, "which is better, a house, or a slice of cheese".
A: This morning a post went up on Scott Guthrie's blog indicating that Microsoft will be shipping the standard jQuery library with Visual Studio from now on, and defining intellisense for it. That's exciting news for the future of jQuery and Silverlight, not as competing technologies but as complimentary ones!
A: You can use them for the same tasks. You could make interactive web applications in jQuery or flash. There are advantages to each, it depends on if you need flash/silverlight or not. If you can achieve your goal without resorting to flash then you should use just JS. Some people might see it the other way around and feel that javascript is a resort and flash/silverlight is the primary method of creating interactive content. Personally, I hear that silverlight takes much longer for development than flash/flex and also has a much smaller userbase (understandably). With both flash and flex, you will get those people who haven't downloaded flash yet. With javascript you will get people who have odd browsers that have trouble running it. It just depends on what your needs are.
A: jQuery is for manipulating the HTML DOM and carry out complex tasks (like finding controls, animating, etc.) in a easier way..... jQuery is completely different from Silverlight. Silverlight is a client side UI language similar to Java Applets, Adobe Flex, etc.
If you are looking for a similar tool (like jQuery) for Silverlight, try XamlQuery. You can manipulate the Silverlight DOM using XamlQuery and carry out most of the tasks that can be carried out using jQuery. But remember, jQuery is for JavaScript but XamlQuery is for Silverlight.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147551",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: Error logging in C# I am making my switch from coding in C++ to C#. I need to replace my C++ error logging/reporting macro system with something similar in C#.
In my C++ source I can write
LOGERR("Some error");
or
LOGERR("Error with inputs %s and %d", stringvar, intvar);
The macro & supporting library code then passes the (possibly varargs) formatted message into a database along with the source file, source line, user name, and time. The same data is also stuffed into a data structure for later reporting to the user.
Does anybody have C# code snippets or pointers to examples that do this basic error reporting/logging?
Edit: At the time I asked this question I was really new to .NET and was unaware of System.Diagnostics.Trace. System.Diagnostics.Trace was what I needed at that time. Since then I have used log4net on projects where the logging requirements were larger and more complex. Just edit that 500 line XML configuration file and log4net will do everything you will ever need :)
A: Lots of log4net advocates here so I'm sure this will be ignored, but I'll add my own preference:
System.Diagnostics.Trace
This includes listeners that listen for your Trace() methods, and then write to a log file/output window/event log, ones in the framework that are included are DefaultTraceListener, TextWriterTraceListener and the EventLogTraceListener. It allows you to specify levels (Warning,Error,Info) and categories.
Trace class on MSDN
Writing to the Event Log in a Web Application
UdpTraceListener - write log4net compatible XML messages to a log viewer such as log2console
A: Even though I personally hate it, log4net seems to be the de facto standard for C# logging. Sample usage:
log4net.ILog log = log4net.LogManager.GetLogger(typeof(Program));
log.Error(“Some error”);
log.ErrorFormat("Error with inputs {0} and {1}", stringvar, intvar);
A: As I said in another thread, we've been using The Object Guy's Logging Framework in multiple production apps for several years. It's super easy to use and extend.
A: I would highly recommend looking at log4Net. This post covers the majority of what you need to get started.
A: Log4Net is a rather comprehensive logging framework that will allow you to log to different levels (Debug, Error, Fatal) and output these log statements to may different places (rolling file, web service, windows errors)
I am able to easily log anywhere by creating an instance of the logger
private static readonly ILog _log = LogManager.GetLogger(typeof([Class Name]));
and then logging the error.
_log.Error("Error messsage", ex);
A: Serilog is late to the party here, but brings some interesting options to the table. It looks much like classical text-based loggers to use:
Log.Information("Hello, {0}", username);
But, unlike earlier frameworks, it only renders the message and arguments into a string when writing text, e.g. to a file or the console.
The idea is that if you're using a 'NoSQL'-style data store for logs, you can record events like:
{
Timestamp: "2014-02-....",
Message: "Hello, nblumhardt",
Properties:
{
"0": "nblumhardt"
}
}
The .NET format string syntax is extended so you can write the above example as:
Log.Information("Hello, {Name}", username);
In this case the property will be called Name (rather than 0), making querying and correlation easier.
There are already a few good options for storage. MongoDB and Azure Table Storage seem to be quite popular for DIY. I originally built Serilog (though it is a community project) and I'm now working on a product called Seq, which provides storage and querying of these kinds of structured log events.
A: You can use built in .NET logging. Look into TraceSource and TraceListeners, they can be configured in the .config file.
A: Another good logging library is NLog, which can log to a lot of different places, such as files, databases, event logger etc.
A: I use The Object Guy's Logging Framework--as do most people who try it. This guy has some interesting comments about it.
A: Enterprise Library is a solid alternative to log4net and it offers a bunch of other capabilities as well (caching, exception handling, validation, etc...). I use it on just about every project I build.
Highly recommended.
A: Ditto for log4net. I'm adding my two bits because for actual use, it makes sense to look at some open source implementations to see real world code samples with some handy additions. For log4net, I'd suggest off the top of my head looking at subtext. Particularly take a look at the application start and assemblyinfo bits.
A: Further to the couple of comments realting to the use of the System.Diagnostics methods for logging, I would also like to point out that the DebugView tool is very neat for checking debug output when needed - unless you require it, there is no need for the apps to produce a log file, you just launch DebugView as and when needed.
A: The built in tracing in System.Diagnostics is fine in the .NET Framework and I use it on many applications. However, one of the primary reasons I still use log4net is that the built in .NET Framework tracing lacks many of the useful full featured appenders that log4net already supplies built in.
For instance there really isn't a good rolling file trace listener defined in the .NET Framework other than the one in a VB.NET dll which really is not all that full featured.
Depending on your development environment I would recommend using log4net unless 3rd party tools are not available, then I'd say use the System.Diagnostics tracing classes. If you really need a better appender/tracelistener you can always implement it yourself.
For instance many of our customers require that we do not use open source libraries when installed on their corporate machines, so in that case the .NET Framework tracing classes are a perfect fit.
Additionally - http://www.postsharp.org/ is an AOP library I'm looking into that may also assist in logging as demonstrated here on code project:http://www.codeproject.com/KB/dotnet/log4postsharp-intro.aspx.
A: ExceptionLess is one of the easiest nuget package available to use for logging. Its an open source project. It automatically takes care of unhandled exception, and options for manually logs are available. You can log to online or self host on local server.
A: Log4Net, as others have said, is fairly common and similar to Log4j which will help you if you ever do any Java.
You also have the option of using the Logging Application Block http://www.codeproject.com/KB/architecture/GetStartedLoggingBlock.aspx
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147557",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "75"
} |
Q: Proxy for command line utilities in Win XP How do I get command line utilities like ping to use the default proxy in Windows XP.
proxycfg -u sets the proxy to the default (IE) proxy alright, but it doesn't seem to be working.
Update: I am behind a proxy and would like a way to check if a site is up or not hence trying to use ping! Also would like a way to telnet (without using Putty) to a specific site and port to check connectivity.
A: A proxy is usually used for web (HTTP) traffic, ping uses ICMP, which is a completely separate protocol. What, exactly are you trying to do?
A: So, standard ping doesn't go via an HTTP proxy, as everyone's already mentioned. What you probably want is to tunnel your TCP connections (e.g., HTTP, telnet, ssh) via your HTTP proxy using the CONNECT method. For instance, using netcat (telnet will also work, but netcat's better) you'll do the following:
$ nc yourproxy 3128
CONNECT yourtelnetserver:23 HTTP/1.0
then press enter twice.
There are also tools that can do this for you. Keep in mind that some HTTP proxies are configured to allow CONNECT connections only to certain destinations, for example, to port 443 ony (for TLS/SSL/HTTPS).
A: Ping doesn't use TCP - it uses ICMP, so using a proxy doesn't really make sense.
Do you have another command line utility in mind?
A: Your best bet will probably be a command line browser for Windows.
You can try out lynx, which is nearly a full browser, or you can go something simpler and use wget. I would recommend wget myself.
Both programs have some way of configuring a proxy, and the documentation should be the same for both Linux and Windows versions.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147558",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How was Adobe Acrobat 9 made? Can anyone tell how Adobe Acrobat 9 was made? I like the look and feel of the GUI and I'm curious how it was made. Specifically, what programming language was used to make it?
A: All of Adobe's major products are written in C++. Although they're mostly written using proprietary toolkits, Adobe has actually open-sourced some of their common low-level libraries. You can read more about them, and download them yourself, at Adobe's Software and Technology Lab (STLab). One of their libraries, Adam and Eve, I find especially interesting and generally useful.
A: I believe it was programmed in C++ using the Evil framework.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147565",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Will the below code cause memory leak in c++ class someclass {};
class base
{
int a;
int *pint;
someclass objsomeclass;
someclass* psomeclass;
public:
base()
{
objsomeclass = someclass();
psomeclass = new someclass();
pint = new int();
throw "constructor failed";
a = 43;
}
}
int main()
{
base temp();
}
In the above code, the constructor throws. Which objects will be leaked, and how can the memory leaks be avoided?
int main()
{
base *temp = new base();
}
How about in the above code? How can the memory leaks be avoided after the constructor throws?
A: Both new's will be leaked.
Assign the address of the heap created objects to named smart pointers so that it will be deleted inside the smart pointers destructor that get call when the exception is thrown - (RAII).
class base {
int a;
boost::shared_ptr<int> pint;
someclass objsomeclass;
boost::shared_ptr<someclass> psomeclass;
base() :
objsomeclass( someclass() ),
boost::shared_ptr<someclass> psomeclass( new someclass() ),
boost::shared_ptr<int> pint( new int() )
{
throw "constructor failed";
a = 43;
}
};
Now psomeclass & pint destructors will be called when the stack unwind when the exception is thrown in the constructor, and those destructors will deallocate the allocated memory.
int main(){
base *temp = new base();
}
For ordinary memory allocation using (non-plcaement) new, memory allocated by the operator new is freed automatically if the constructor throws an exception. In terms of why bother freeing individual members (in response to comments to Mike B's answer), the automatic freeing only applies when an exception is thrown in a constructor of an object being new'ly allocated, not in other cases. Also, the memory that is freed is those allocated for the object members, not any memory you might have allocated say inside the constructor. i.e. It would free the memory for the member variables a, pint, objsomeclass, and psomeclass, but not the memory allocated from new someclass() and new int().
A: Yes it will leak memory. When the constructor throws, no destructor will be called (in this case you don't show a destructor that frees the dynamically allocated objects, but lets assume you had one).
This is a major reason to use smart pointers - since the smart poitners are full fledged objects, they will get destructors called during the exception's stack unwind and have the opportunity to free the memory.
If you use something like Boost's scoped_ptr<> template, your class could look more like:
class base{
int a;
scoped_ptr<int> pint;
someclass objsomeclass;
scoped_ptr<someclass> psomeclass;
base() :
pint( new int),
objsomeclass( someclass()),
psomeclass( new someclass())
{
throw "constructor failed";
a = 43;
}
}
And you would have no memory leaks (and the default dtor would also clean up the dynamic memory allocations).
To sum up (and hopefully this also answers the question about the
base* temp = new base();
statement):
When an exception is thrown inside a constructor there are several things that you should take note of in terms of properly handling resource allocations that may have occured in the aborted construction of the object:
*
*the destructor for the object being constructed will not be called.
*destructors for member objects contained in that object's class will be called
*the memory for the object that was being constructed will be freed.
This means that if your object owns resources, you have 2 methods available to clean up those resources that might have already been acquired when the constructor throws:
*
*catch the exception, release the resources, then rethrow. This can be difficult to get correct and can become a maintenance problem.
*use objects to manage the resource lifetimes (RAII) and use those objects as the members. When the constructor for your object throws an exception, the member objects will have desctructors called and will have an opportunity to free the resource whose lifetimes they are responsible for.
A: I believe that the top answer is wrong and would still leak memory.
The destructor for the class members will not be called if the constructor throws an exception (because it never completed its initialization, and perhaps some members have never reached their constructor calls).
Their destructors are only called during the class's destructor call. That only makes sense.
This simple program demonstrates it.
#include <stdio.h>
class A
{
int x;
public:
A(int x) : x(x) { printf("A constructor [%d]\n", x); }
~A() { printf("A destructor [%d]\n", x); }
};
class B
{
A a1;
A a2;
public:
B()
: a1(3),
a2(5)
{
printf("B constructor\n");
throw "failed";
}
~B() { printf("B destructor\n"); }
};
int main()
{
B b;
return 0;
}
With the following output (using g++ 4.5.2):
A constructor [3]
A constructor [5]
B constructor
terminate called after throwing an instance of 'char const*'
Aborted
If your constructor fails partway then it is your responsibility to deal with it. Worse, the exception may be thrown from your base class' constructor!
The way to deal with these cases is by employing a "function try block" (but even then you must carefully code the destruction of your partially initialized object).
The correct approach to your problem would then be something like this:
#include <stdio.h>
class A
{
int x;
public:
A(int x) : x(x) { printf("A constructor [%d]\n", x); }
~A() { printf("A destructor [%d]\n", x); }
};
class B
{
A * a1;
A * a2;
public:
B()
try // <--- Notice this change
: a1(NULL),
a2(NULL)
{
printf("B constructor\n");
a1 = new A(3);
throw "fail";
a2 = new A(5);
}
catch ( ... ) { // <--- Notice this change
printf("B Cleanup\n");
delete a2; // It's ok if it's NULL.
delete a1; // It's ok if it's NULL.
}
~B() { printf("B destructor\n"); }
};
int main()
{
B b;
return 0;
}
If you run it you will get the expected output where only the allocated objects are destroyed and freed.
B constructor
A constructor [3]
B Cleanup
A destructor [3]
terminate called after throwing an instance of 'char const*'
Aborted
You can still work it out with smart shared pointers if you want to, with additional copying. Writing a constructor similar to this:
class C
{
std::shared_ptr<someclass> a1;
std::shared_ptr<someclass> a2;
public:
C()
{
std::shared_ptr<someclass> new_a1(new someclass());
std::shared_ptr<someclass> new_a2(new someclass());
// You will reach here only if both allocations succeeded. Exception will free them both since they were allocated as automatic variables on the stack.
a1 = new_a1;
a2 = new_a2;
}
}
Good luck,
Tzvi.
A: Yes, that code will leak memory. Blocks of memory allocated using "new" are not freed when an exception is raised. This is part of the motivation behind RAII.
To avoid the memory leak, try something like this:
psomeclass = NULL;
pint = NULL;
/* So on for any pointers you allocate */
try {
objsomeclass = someclass();
psomeclass = new someclass();
pint = new int();
throw "constructor failed";
a = 43;
}
catch (...)
{
delete psomeclass;
delete pint;
throw;
}
A: If you throw in a constructor, you should clean up everything that came before the call to throw. If you are using inheritance or throwing in a destructor, you really shouldn't be. The behaviour is odd (don't have my standard handy, but it might be undefined?).
A: you need to delete psomeclass... Its not necessary to clean up the integer...
RWendi
A: Everything you "new" needs to be deleted, or you'll cause a memory leak. So these two lines:
psomeclass = new someclass();
pint = new int();
Will cause memory leaks, because you need to do:
delete pint;
delete psomeclass;
In a finally block to avoid them being leaked.
Also, this line:
base temp = base();
Is unnecessary. You just need to do:
base temp;
Adding the "= base()" is unnecessary.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147572",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "20"
} |
Q: Determining if the window is in help mode Developing a .NET WinForms application: how can I check if the window is in Help mode (i.e. after clicking the "?" button in the title bar)?
The problem I have is that my System.Windows.Forms.ToolStripItem objects do not have a HelpRequested event (because they do not inherit from Control) so in the Click event handler, I am trying to determine if the window is currently in help mode so I can popup a ToolTip programmatically.
Any help is always appreciated! Thanks
A: I believe that the Form.HelpButtonClicked event is what you want, since it's in your namespace.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147583",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Regexp matching of list of quotes strings - unquoted in Javascript, the following:
var test = '"the quick" "brown fox" "jumps over" "the lazy dog"';
var result = test.match(/".*?"/g);
alert(result);
yields "the quick","brown fox","jumps over","the lazy dog"
I want each matched element to be unquoted: the quick,brown fox,jumps over,the lazy dog
what regexp will do this?
A: This seems to work:
var test = '"the quick" "brown fox" "jumps over" "the lazy dog"';
var result = test.match(/[^"]+(?=(" ")|"$)/g);
alert(result);
Note: This doesn't match empty elements (i.e. ""). Also, it won't work in browsers that don't support JavaScript 1.5 (lookaheads are a 1.5 feature).
See http://www.javascriptkit.com/javatutors/redev2.shtml for more info.
A: It is not one regexp, but two simpler regexps.
var test = '"the quick" "brown fox" "jumps over" "the lazy dog"';
var result = test.match(/".*?"/g);
// ["the quick","brown fox","jumps over","the lazy dog"]
result.map(function(el) { return el.replace(/^"|"$/g, ""); });
// [the quick,brown fox,jumps over,the lazy dog]
A: grapefrukt's answer works also. I would up using a variation of David's
match(/[^"]+(?=("\s*")|"$)/g)
as it properly deals with arbitrary amounts of white space and tabs tween the strings, which is what I needed.
A: You can use the Javascript replace() method to strip them out.
var test = '"the quick" "brown fox" "jumps over" "the lazy dog"';
var result = test.replace(/"/, '');
Is there more to it than just getting rid of the double-quotes?
A: This is what I would use in actionscript3:
var test:String = '"the quick" "brown fox" "jumps over" "the lazy dog"';
var result:Array = test.match(/(?<=^"| ").*?(?=" |"$)/g);
for each(var str:String in result){
trace(str);
}
A:
For matching content between pairs of simple quotes and double quotes taking care of escaped ones.
As search engine first drove me here, I really would like to orient people looking to check quotes pairs to the more generic question: https://stackoverflow.com/a/41867753/2012407.
The regex will get the full content between well formed pairs of quotes like '"What\'s up?"' for instance that are not in a code comment like // Comment. or /* Comment. */.
A: Here's one way:
var test = '"the quick" "brown fox" "jumps over" "the lazy dog"';
var result = test.replace(/"(.*?)"/g, "$1");
alert(result);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147626",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Django VMware appliance Does anyone know of a Django 1.0 + postgresql + apache + mod_python VMware appliance? A "vanilla" Django 1.0 appliance where postgresql can be installed manually would also do.
A: Configure and build your appliance at Elastic Server On-Demand.
A: Another option I've had moderate success with
TurnKey Linux Django Appliance
A: In addition to the other appliances suggested, you may want to take a look at our BitNami Django Stack VMWare Appliance.
It is completely free and we keep it up to date, often within hours of each new Django release. In particular, it includes mod_wsgi since mod_python has not been updated for a while. One other thing that you may want to checkout is the Django Amazon Cloud Image. Together with the Amazon Free Tier you can have your own hosted Django for free (with some limitations in terms of bandwith, etc).
A: It might be a little too heavy for your requirements, but all of those items (and a whole lot more) are included in the Python Web Developer Appliance.
A: Poulsenj is right the Elastic Server On-Demand (Django Elastic Server Site) is a great place to configure and download a free custom Django VMware image in minutes.
The Elastic Server platform lets you assemble custom servers by choosing components from a library of popular software stacks. Once assembled, these custom application stacks can be configured to a variety of virtualization and cloud-ready formats, downloaded and deployed in real-time.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147627",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Best way to detect when a user leaves a web page? What is the best way to detect if a user leaves a web page?
The onunload JavaScript event doesn't work every time (the HTTP request takes longer than the time required to terminate the browser).
Creating one will probably be blocked by current browsers.
A: In the case you need to do some asynchronous code (like sending a message to the server that the user is not focused on your page right now), the event beforeunload will not give time to the async code to run. In the case of async I found that the visibilitychange and mouseleave events are the best options. These events fire when the user change tab, or hiding the browser, or taking the courser out of the window scope.
document.addEventListener('mouseleave', e=>{
//do some async code
})
document.addEventListener('visibilitychange', e=>{
if (document.visibilityState === 'visible') {
//report that user is in focus
} else {
//report that user is out of focus
}
})
A: Thanks to Service Workers, it is possible to implement a solution similar to Adam's purely on the client-side, granted the browser supports it. Just circumvent heartbeat requests:
// The delay should be longer than the heartbeat by a significant enough amount that there won't be false positives
const liveTimeoutDelay = 10000
let liveTimeout = null
global.self.addEventListener('fetch', event => {
clearTimeout(liveTimeout)
liveTimeout = setTimeout(() => {
console.log('User left page')
// handle page leave
}, liveTimeoutDelay)
// Forward any events except for hearbeat events
if (event.request.url.endsWith('/heartbeat')) {
event.respondWith(
new global.Response('Still here')
)
}
})
A: I know this question has been answered, but in case you only want something to trigger when the actual BROWSER is closed, and not just when a pageload occurs, you can use this code:
window.onbeforeunload = function (e) {
if ((window.event.clientY < 0)) {
//window.localStorage.clear();
//alert("Y coords: " + window.event.clientY)
}
};
In my example, I am clearing local storage and alerting the user with the mouses y coords, only when the browser is closed, this will be ignored on all page loads from within the program.
A: Mozilla Developer Network has a nice description and example of onbeforeunload.
If you want to warn the user before leaving the page if your page is dirty (i.e. if user has entered some data):
window.addEventListener('beforeunload', function(e) {
var myPageIsDirty = ...; //you implement this logic...
if(myPageIsDirty) {
//following two lines will cause the browser to ask the user if they
//want to leave. The text of this dialog is controlled by the browser.
e.preventDefault(); //per the standard
e.returnValue = ''; //required for Chrome
}
//else: user is allowed to leave without a warning dialog
});
A: One (slightly hacky) way to do it is replace and links that lead away from your site with an AJAX call to the server-side, indicating the user is leaving, then use that same javascript block to take the user to the external site they've requested.
Of course this won't work if the user simply closes the browser window or types in a new URL.
To get around that, you'd potentially need to use Javascript's setTimeout() on the page, making an AJAX call every few seconds (depending on how quickly you want to know if the user has left).
A: Try the onbeforeunload event: It is fired just before the page is unloaded. It also allows you to ask back if the user really wants to leave. See the demo onbeforeunload Demo.
Alternatively, you can send out an Ajax request when he leaves.
A: Here's an alternative solution - since in most browsers the navigation controls (the nav bar, tabs, etc.) are located above the page content area, you can detect the mouse pointer leaving the page via the top and display a "before you leave" dialog. It's completely unobtrusive and it allows you to interact with the user before they actually perform the action to leave.
$(document).bind("mouseleave", function(e) {
if (e.pageY - $(window).scrollTop() <= 1) {
$('#BeforeYouLeaveDiv').show();
}
});
The downside is that of course it's a guess that the user actually intends to leave, but in the vast majority of cases it's correct.
A: What you can do, is open up a WebSocket connection when the page loads, optionally send data through the WebSocket identifying the current user, and check when that connection is closed on the server.
A: Page Visibility API
✅ The Page Visibility API provides events which can be watch to know when a document becomes visible or hidden.
✅ When the user minimizes the window or switches to another tab, API triggers a visibilitychange event.
✅ We can perform the actions based on the visibilityState
function onVisibilityChange() {
if (document.visibilityState === 'visible') {
console.log("user is focused on the page")
} else {
console.log("user left the page")
}
}
document.addEventListener('visibilitychange', onVisibilityChange);
A: For What its worth, this is what I did and maybe it can help others even though the article is old.
PHP:
session_start();
$_SESSION['ipaddress'] = $_SERVER['REMOTE_ADDR'];
if(isset($_SESSION['userID'])){
if(!strpos($_SESSION['activeID'], '-')){
$_SESSION['activeID'] = $_SESSION['userID'].'-'.$_SESSION['activeID'];
}
}elseif(!isset($_SESSION['activeID'])){
$_SESSION['activeID'] = time();
}
JS
window.setInterval(function(){
var userid = '<?php echo $_SESSION['activeID']; ?>';
var ipaddress = '<?php echo $_SESSION['ipaddress']; ?>';
var action = 'data';
$.ajax({
url:'activeUser.php',
method:'POST',
data:{action:action,userid:userid,ipaddress:ipaddress},
success:function(response){
//alert(response);
}
});
}, 5000);
Ajax call to activeUser.php
if(isset($_POST['action'])){
if(isset($_POST['userid'])){
$stamp = time();
$activeid = $_POST['userid'];
$ip = $_POST['ipaddress'];
$query = "SELECT stamp FROM activeusers WHERE activeid = '".$activeid."' LIMIT 1";
$results = RUNSIMPLEDB($query);
if($results->num_rows > 0){
$query = "UPDATE activeusers SET stamp = '$stamp' WHERE activeid = '".$activeid."' AND ip = '$ip' LIMIT 1";
RUNSIMPLEDB($query);
}else{
$query = "INSERT INTO activeusers (activeid,stamp,ip)
VALUES ('".$activeid."','$stamp','$ip')";
RUNSIMPLEDB($query);
}
}
}
Database:
CREATE TABLE `activeusers` (
`id` int(11) NOT NULL,
`activeid` varchar(20) NOT NULL,
`stamp` int(11) NOT NULL,
`ip` text
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
Basically every 5 seconds the js will post to a php file that will track the user and the users ip address. Active users are simply a database record that have an update to the database time stamp within 5 seconds. Old users stop updating to the database. The ip address is used just to ensure that a user is unique so 2 people on the site at the same time don't register as 1 user.
Probably not the most efficient solution but it does the job.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147636",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "227"
} |
Q: Window short cuts for XFCE4 This is not a programming question per se, but this is certainly about something which would help increasing my programming productivity.
In KDE, one can assign short-cuts to particular windows. This eliminates alt-tabbing completely and, is very very convenient when multiple apps(browser, console, emacs etc) are open.
My question is - can window short cuts be assigned in XFCE4 ? And if yes, how ? I very recently switched to XFCE from KDE4 and would appreciate any help regarding this.
TIA.
A: I'm using xdotool.
For example command below moves Firefox to foreground:
xdotool search --onlyvisible --name 'Mozilla Firefox' windowraise
You can update your keyboard settings with needed parameters (Applications Menu -> Settings -> Settings Manager -> Keyboard):
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147642",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Solution for overloaded operator constraint in .NET generics What would I do if I want to have a generic method that only accepts types that have overloaded an operator, for instance the subtraction operator. I tried using an interface as a constraint but interfaces can't have operator overloading.
What is the best way to achieve this?
A: There is no immediate answer; operators are static, and cannot be expressed in constraints - and the existing primatives don't implement any specific interface (contrast to IComparable[<T>] which can be used to emulate greater-than / less-than).
However; if you just want it to work, then in .NET 3.5 there are some options...
I have put together a library here that allows efficient and simple access to operators with generics - such as:
T result = Operator.Add(first, second); // implicit <T>; here
It can be downloaded as part of MiscUtil
Additionally, in C# 4.0, this becomes possible via dynamic:
static T Add<T>(T x, T y) {
dynamic dx = x, dy = y;
return dx + dy;
}
I also had (at one point) a .NET 2.0 version, but that is less tested. The other option is to create an interface such as
interface ICalc<T>
{
T Add(T,T)()
T Subtract(T,T)()
}
etc, but then you need to pass an ICalc<T>; through all the methods, which gets messy.
A: I found that IL can actually handle this quite well. Ex.
ldarg.0
ldarg.1
add
ret
Compiled in a generic method, the code will run fine as long as a primitive type is specified. It may be possible to extend this to call operator functions on non-primitive types.
See here.
A: You can solve this problem by using a delegate instead of an interface constraint.
public class Example
{
public static T Add<T>(T left, T right, Func<T, T, T> addFunc) =>
addFunc(left, right);
}
Define a method that takes a delegate as a parameter, and use it follows.
var result = Example.Add(10, 20, (x, y) => x + y);
A: There is a piece of code stolen from the internats that I use a lot for this. It looks for or builds using IL basic arithmetic operators. It is all done within an Operation<T> generic class, and all you have to do is assign the required operation into a delegate. Like add = Operation<double>.Add.
It is used like this:
public struct MyPoint
{
public readonly double x, y;
public MyPoint(double x, double y) { this.x=x; this.y=y; }
// User types must have defined operators
public static MyPoint operator+(MyPoint a, MyPoint b)
{
return new MyPoint(a.x+b.x, a.y+b.y);
}
}
class Program
{
// Sample generic method using Operation<T>
public static T DoubleIt<T>(T a)
{
Func<T, T, T> add=Operation<T>.Add;
return add(a, a);
}
// Example of using generic math
static void Main(string[] args)
{
var x=DoubleIt(1); //add integers, x=2
var y=DoubleIt(Math.PI); //add doubles, y=6.2831853071795862
MyPoint P=new MyPoint(x, y);
var Q=DoubleIt(P); //add user types, Q=(4.0,12.566370614359172)
var s=DoubleIt("ABC"); //concatenate strings, s="ABCABC"
}
}
Operation<T> Source code courtesy of paste bin: http://pastebin.com/nuqdeY8z
with attribution below:
/* Copyright (C) 2007 The Trustees of Indiana University
*
* Use, modification and distribution is subject to the Boost Software
* License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
*
* Authors: Douglas Gregor
* Andrew Lumsdaine
*
* Url: http://www.osl.iu.edu/research/mpi.net/svn/
*
* This file provides the "Operations" class, which contains common
* reduction operations such as addition and multiplication for any
* type.
*
* This code was heavily influenced by Keith Farmer's
* Operator Overloading with Generics
* at http://www.codeproject.com/csharp/genericoperators.asp
*
* All MPI related code removed by ja72.
*/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147646",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "39"
} |
Q: CakePHP hasAndBelogsToMany using save() vs. saveAll() I am using a very intrinsic database with a CakePHP application and so far my multi-models views and controllers are working fine. I have a singular table (Entity) that have it's id on several other tables as the Foreign Key entity_id
Some tables are one to one relations (Like a Company is one Entity) and some are one to many (Entity can have several Addresses) and so on.
I won't/can't change the database model, so this is the structure.
I have been using saveAll() to save data on those tables with input names like:
Entity.type='x' (hidden inside the view)
Company.name
Address.0.street
Address.0.city
Address.1.street
Address.1.city
... and so on ...
and my save all is doing all the hard job, BEGIN TRANSACTION, all INSERTs and a final COMMIT ...
But now I've created a EntityCategory that is a n to n relation and created the full HABTM relation inside the model.
It works when I save() it but just the HABTM relation, and it saves everthing when I use saveAll() (just as before) except for the HABTM relation.
Am I missing something ? How I make this work correctly ? I am using the following code today:
if (!empty($this->data)) {
$this->Entity->saveAll($this->data);
$this->Entity->save($this->data);
}
The saveAll() saves all data in several tables, saves the id in Entity->id and the save() saves the HABTM relations, but I am not sure if it is correct or if it can bring me problems if I change some structure/model.
Is this the best way to use it? Is there a correct way to save that relations inside CakePHP ? What your experience/knowledge can tell me ?
A: This is fixed if you download the nightly.
Be careful though, something else might break.
A: The problem with saveAll() and HABTM associations is a known CakePHP issue, and has not been resolved as of 1.2 RC2.
As fas as best pratices for saving related model data goes, according to the CakePHP cookbook:
"When working with associated models, it is important to realize that saving model data should always be done by the corresponding CakePHP model. If you are saving a new Post and its associated Comments, then you would use both Post and Comment models during the save operation."
However, using saveAll() and save() should work, and IMHO is a more flexible/generic solution.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147649",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Debug Pylons application through Eclipse I have Eclipse setup with PyDev and love being able to debug my scripts/apps. I've just started playing around with Pylons and was wondering if there is a way to start up the paster server through Eclipse so I can debug my webapp?
A: If you'd rather not include your Python installation in your project's workspace to get paster, you can create a pure-Python driver like:
#!/usr/bin/env python
from paste.script.serve import ServeCommand
ServeCommand("serve").run(["development.ini"])
...and run/debug that in Eclipse.
Note: this is running without the --reload option, so you don't get hot deploys (i.e., you'll need to reload server to see changes). Alternatively, you can add the --reload option to get hot deploys, but then Pydev won't stop at your breakpoints. Can't have your cake and eat it too...
ServeCommand("serve").run(["--reload", "development.ini"])
A: yanjost has it right, just wanted to add that you need to make sure you do not use the --reload option, this will prevent the debugger from properly attaching itself and cause your breakpoints not to work. Just a little thing I ran in to.
A: I was able to get --reload working by changing the 'Working directory' in the arguments tab to not use default (i.e. select 'Other'->File System->'Root of your Pylons' app where development.ini is stored.
A: Create a new launch configuration (Python Run)
Main tab
Use paster-script.py as main module (you can find it in the Scripts sub-directory in your python installation directory)
Don't forget to add the root folder of your application in the PYTHONPATH zone
Arguments
Set the base directory to the root folder also.
As Program Arguments use "serve development.ini" (or whatever you use to debug your app")
Common Tab
Check allocate console and launch in background
A: On linux that will probably be /usr/bin/paster or /usr/local/bin/paster for paste script, and for arguments i have: serve ${workspace_loc}${project_path}/development.ini
A: I also got this working (finally). I used buildout instead of virtualenv to install pylons (instructions at: http://wiki.pylonshq.com/display/pylonscommunity/Howto+install+Pylons+with+buildout), so the instructions above needed to be changed a little as far as the paths go.
-for "Main Module", I use:
${workspace_loc:myeclipseprojectname/bin/paster}
(adding --reload made breakpoints not work for me, and I tested this a couple times)
-for "Program Arguments", I use:
serve ${workspace_loc:myeclipseprojectname/mypylonsprojectname/development.ini}
-for "Working Directory, Other:", I use:
${workspace_loc:myeclipseprojectname/mypylonsprojectname}
-as mentioned above, in "Common Tab", "Check allocate console and launch in background"
-and remember to set a breakpoint before trying.
A: This doesn't really answer question about how to do it in eclipse. But I've been debugging paster server with winpdb, which is quite nice graphical python debugger (you can install it with easy_install winpdb).
Just start your server e.g.:
winpdb /usr/local/bin/paster serve development.ini
And click run button.
As wayne said, it's necessary to not use --reload option. At least I wasn't able to find how to attach to actual webapp even, when selecting to which forked process debugger should enter (entering different processes can be controlled with "fork parent" and "fork child" debugger commands).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147650",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: How to make RightToLeftLayout work for controls inside GroupBoxes and Panels? According to MSDN
form.RightToLeftLayout = True;
form.RightToLeft = ifWeWantRTL() ? RightToLeft.True : RightToLeft.False;
is enough to mirrow the form content for RTL languages.
But controls placement gets mirrowed only for controls immediately on the form,
those inside a GroupBox or a Panel are not mirrowed, unless I put them on a TableLayoutPanel or a FlowLayoutPanel fisrt.
This is a lot of manual work to place a TableLayoutPanel inside each GroupBox,
and especially to rearrange the controls (one control per table cell, padding, margin, etc)
Is there an easier way to make mirrowing work for all controls?
Or at least, how can I bypass the rearranging step, for it is quite a task with our number of forms?
Edit: RightToLeft property for each control on the form by default is inherited,
so Panels and GroupBoxes always have the needed RightToLeft setting.
Nevertheless, I tryed to reassign it for them both programmatically and from designer, it did not help.
A: It does seen that you have quite a nasty problem on your hands. Have played with it for a while and come up with the following:
Making use of a little recursion you can run though all the controls and do the manaul RTL conversion for those controls trapped in Pannels and GroupBoxes.
This is a quick little mock of code that I slapped together. I would suggest you put this in your BaseForm (heres hoping you have one of these) and call on base form load.
private void SetRTL (bool setRTL)
{
ApplyRTL(setRTL, this);
}
private void ApplyRTL(bool yes, Control startControl)
{
if ((startControl is Panel ) || (startControl is GroupBox))
{
foreach (Control control in startControl.Controls)
{
control.Location = CalculateRTL(control.Location, startControl.Size, control.Size);
}
}
foreach (Control control in startControl.Controls)
ApplyRTL(yes, control);
}
private Point CalculateRTL (Point currentPoint, Size parentSize, Size currentSize)
{
return new Point(parentSize.Width - currentSize.Width - currentPoint.X, currentPoint.Y);
}
A: i dont remember where i first saw this tip on overriding CreateParams, but here you are ;)
fastest, and easiest way is to Inherit from the Panel, GroupBox or Usercontrol
and override the CreateParams Property
protected override CreateParams CreateParams
{
get
{
return Control_RTF(base.CreateParams, base.RightToLeft);
}
}
private CreateParams Control_RTF(CreateParams CP, RightToLeft rightToLeft)
{
if (rightToLeft == System.Windows.Forms.RightToLeft.Yes)
CP.ExStyle = ((CP.ExStyle | 0x400000) | 0x100000);
return CP;
}
A: According to the article
Visual Studio 2005: Developing Arabic Windows Forms applications
I am left with just two alternatives
*
*continue adding TableLayoutPanels here and there
*reposition child controls on RTL change myself
It is a real pity that it has to be that way.
A: If you have a class derived from Control that contains child controls (like a ContainerControl), you can add the following code to force all child controls to mirror when the parent form's RightToLeftLayout is set to true and when your control's RightToLeft is set to RightToLeft.Yes.
protected override CreateParams CreateParams
{
get
{
CreateParams createParams = base.CreateParams;
Form parent = this.FindForm();
bool parentRightToLeftLayout = parent != null ? parent.RightToLeftLayout : false;
if ((this.RightToLeft == RightToLeft.Yes) && parentRightToLeftLayout)
{
createParams.ExStyle |= 0x500000; // WS_EX_LAYOUTRTL | WS_EX_NOINHERITLAYOUT
createParams.ExStyle &= ~0x7000; // WS_EX_RIGHT | WS_EX_RTLREADING | WS_EX_LEFTSCROLLBAR
}
return createParams;
}
}
protected override void OnRightToLeftChanged(EventArgs e)
{
base.OnRightToLeftChanged(e);
RecreateHandle();
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147657",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Get list of databases from SQL Server How can I get the list of available databases on a SQL Server instance? I'm planning to make a list of them in a combo box in VB.NET.
A: in light of the ambiguity as to the number of non-user databases, you should probably add:
WHERE name NOT IN ('master', 'tempdb', 'model', 'msdb');
and add the names of the reporting services databases
A: SELECT [name]
FROM master.dbo.sysdatabases
WHERE dbid > 4 and [name] <> 'ReportServer' and [name] <> 'ReportServerTempDB'
This will work for both condition, Whether reporting is enabled or not
A: Execute:
SELECT name FROM master.sys.databases
This the preferred approach now, rather than dbo.sysdatabases, which has been deprecated for some time.
Execute this query:
SELECT name FROM master.dbo.sysdatabases
or if you prefer
EXEC sp_databases
A: To exclude system databases:
SELECT [name]
FROM master.dbo.sysdatabases
WHERE dbid > 6
Edited : 2:36 PM 2/5/2013
Updated with accurate database_id, It should be greater than 4, to skip listing
system databases which are having database id between 1 and 4.
SELECT *
FROM sys.databases d
WHERE d.database_id > 4
A: I use the following SQL Server Management Objects code to get a list of databases that aren't system databases and aren't snapshots.
using Microsoft.SqlServer.Management.Smo;
public static string[] GetDatabaseNames( string serverName )
{
var server = new Server( serverName );
return ( from Database database in server.Databases
where !database.IsSystemObject && !database.IsDatabaseSnapshot
select database.Name
).ToArray();
}
A: If you want to omit system databases and ReportServer tables (if installed)
select DATABASE_NAME = db_name(s_mf.database_id)
from sys.master_files s_mf
where
s_mf.state = 0 -- ONLINE
and has_dbaccess(db_name(s_mf.database_id)) = 1
and db_name(s_mf.database_id) NOT IN ('master', 'tempdb', 'model', 'msdb')
and db_name(s_mf.database_id) not like 'ReportServer%'
group by s_mf.database_id
order by 1;
This works on SQL Server 2008/2012/2014. Most of query comes from "sp_databases" system stored procedure. I only removed unneeded column and added where conditions.
A: SELECT [name]
FROM master.dbo.sysdatabases
WHERE dbid > 4
Works on our SQL Server 2008
A: Use the query below to get all the databases:
select * from sys.databases
If you need only the user-defined databases;
select * from sys.databases WHERE name NOT IN ('master', 'tempdb', 'model', 'msdb');
Some of the system database names are (resource,distribution,reportservice,reportservicetempdb) just insert it into the query if you have the above db's in your machine as default.
A: Since you are using .NET you can use the SQL Server Management Objects
Dim server As New Microsoft.SqlServer.Management.Smo.Server("localhost")
For Each db As Database In server.Databases
Console.WriteLine(db.Name)
Next
A: Not sure if this will omit the Report server databases since I am not running one, but from what I have seen, I can omit system user owned databases with this SQL:
SELECT db.[name] as dbname
FROM [master].[sys].[databases] db
LEFT OUTER JOIN [master].[sys].[sysusers] su on su.sid = db.owner_sid
WHERE su.sid is null
order by db.[name]
A: In SQL Server 7, dbid 1 thru 4 are the system dbs.
A: perhaps I'm a dodo!
show databases; worked for me.
A: If you are looking for a command to list databases in MYSQL, then just use the below command. After login to sql server,
show databases;
A: To exclude system databases :
SELECT name FROM master.dbo.sysdatabases where sid <>0x01
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147659",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "459"
} |
Q: Is there a decent open-source gaming console I've got a young nephew who aspires to grow up to be a game programmer and i'd like to introduce him to the world of open-source as well as get him a sweet gift.
Anything like that out there?
A: There are a number of Open Source platforms out their for game development, if you go to here there are a large number of game engines and development platforms. For a beginner with little programming experience I would suggest a game engine like Game Maker or RPG Maker, which are drag and drop game engines. Both of these are free open source game engines. The other problem with these two game engines is that they are limited to 2D games only, even though Game Maker allows you to make and FPS that is like Doom style graphics.
For a more intermediate or beginning programmer I would honestly suggest Torque, which has both a 2D and 3D game engine. This engine is licensed as open source, but you still have to pay for the compiled version from their site. I have had much success with Torque in the past, especially Torque Game Builder (2D Game Engine). It is very simple to pickup and begin making good looking/functional games. In fact, a number of XBOX live games have been built using Torque game engines, like Marble Blast.
Another open source game engine I have heard good things about, but have not had a chance to try, is Multiverse. Multiverse is actually aimed at MMOG creation. The nice thing about Multiverse is that it provides for the creation of a 3D game environment, but also allows for the integration of Flash content into the game world.
For a more advanced programmer I would suggest looking into the SDL, OpenGL, and OpenAL. These are not game engines but graphics and sound libraries for game programmers. These are completely open source and are free to use. Most game technologies will have some implementation of one or all of these libraries in their software.
Even though XNA is not open source, it is also a good place to start for more advanced programmers. Not only does it allow for the creation of XBOX games, but you can also develop for the PC and Zune also.
Another thing you may want to suggest to your nephew is to modify existing games he owns. Most PC games and many console games allow for game modification of some form or another (level design, rescripting, etc). Some of the more popular game engines that I have seen mods for are the Source Engine and Unreal Engine. There are a number of tutorials at MODDB and 3DBuzz (which also has great tutorials on other aspects of game programming and design).
In addition to what I have listed, I have also heard good things about Ogre3D and Havok (a physics engine used in many many games). He can also go to such sites as IGDA, Gamasutra, GameDev,Game Career Guie, 3D Buzz for additional information on game development.
Hope this information helps.
A: I saw a question earlier about programming on a Nintendo DS. That sounds like it might be what you're looking for.
Also, I recently read about the BUG which looks like a really cool platform for building any number of handheld devices.
A: You might be interested in the XGameStation. It's a hardware console designed to teach programming a game console. It was created by Andre LaMothe who has written several books on game programming.
A: http://devmaster.net/devdb/engines/sylphis-3d#general-overview looks pretty nice, c/c++ oriented, GPL license, and Free.
A: Well, this is a tricky question because we don't know the level your nephew is at, nevermind the fact that it's difficult to produce a very nice showy game without a lot more work than a beginner might put forth.
X Game Station
Nevertheless, André LaMothe's X Game Station is meant to be exactly the system you're asking for - a beginner's guide and system on how to develop complex programs with interactive elements and gameplay on resource limited hardware. Which is pretty much what a game designer is called on to do.
GP32
The GP32 was also meant to fill this gap, but with a much more powerful processor. The successor was never released, and the company went bankrupt shortly after, but you may still be able to find one on ebay or within the communities that developed around the original machine.
Google Android
You might also consider looking toward the Google Android platform. Cell phone gaming is now and will be one of the biggest platforms in the future. The android isn't set up perfectly for gaming, but it's a good first approximation, isn't horribly expensive and includes a robust development toolset for a high-end mobile processor. Several big name game development companies have already pledged support for this platform, so it will also look good on a resume.
But a cheap computer and a VGA graphics book is surprisingly fun as a kid...
-Adam
A: Well programming on the NintendoDS is possible, however you'll be breaking and stretching quite a few laws there.
However, I should say that I learned most of what I did about hardware doing stuff just like that while I was back in school. I learned a LOT from doing that sort of stuff ;)
But I wouldn't recommend it to youngsters or newcomers because you'll be totally out of support (lots of frustration), might break your game console, and unless you already know about programming the learning curve is WAY to high.
Might I recommend starting out with flash or PC games before console programming?
Edit: When I mean breaking/stretching laws, I don't mean writing code for your hardware, that's up to you. But it is illegal to buy pirate memory cards and card writers (that infringe on patent laws). Also funding hardware piracy will unlikely be something to proud of.
Edit:@Mike F did you read my post? I said, I HAVE done this while I was a student, and I learned a lot. But it's still piracy, and yes I did my fair share of piracy when I was a poor student, but it's not something I'd want to teach someone just getting into programming. Would you?
Besides there are plenty of perfectly great ways to learn game programming without needing to hack stuff like RPGMaker, XNA, etc...
@Mike F: Once more just for the sake of it NDS flash-roms are produced through patent piracy(/infringement), not software piracy, as in it is illegal to produce such hardware because it goes against patent laws. And the companies that make such flash rom hardware are piracy companies that traffic their goods in the grey market, Its as simple as that. I'm not talking about "software piracy" at all here. Thats why I mentioned twice already that anyone is free to run whatever software on their hardware, be homebrew or whatever.
A: well, this is not completely open source (the editor isn't, the engine is), but I recommend RPG Maker VX (if he likes role playing games):
http://tkool.jp/products/rpgvx/eng/index.html
I have used this (and the earlier versions) for some time. It is nice because there is a great editor and event system which can teach basic programming concepts without writing any code. Once your nephew wants to write some real code, there is an entire API (RGSS2) written in ruby that they he is free to manipulate and extend. This API makes up most of the game engine, hiding only low level implementation stuff.
There are other programs out there like GameMaker, but RPG Maker is the most user friendly, while still providing a way to get at the more advanced stuff.
EDIT: I forgot to mention one of the best parts; there is a large and active community around RPG Maker. There are many forums completely dedicated to the program where people will be happy to help on even the most basic tasks, not to mention the great resources that are avilable.
A: I'd third the Nintendo DS recommendation - grab a R4 "homebrew" cartridge and you're pretty much set.
Another idea is one of the independent handhelds - something like the GP32, though there's certainly newer devices on the market.
A: I believe this is somewhat like Basketball, start from close to the basket and work your way out and you'll be hitting 3's with practice.
In my opinion, game programming is 3pt, without learning to shoot the basketball properly, you will probably cheat and start slinging it or just chucking the ball at the backboard hoping it's going to go in.
If you have a youngster without the ability to shoot a mid-range basket properly, do you think he will be able to motivate himself to keep trying, rather then trying something closer to the goal and working himself outside when he is confident?
If your nephew is serious about learning programming, get him a python book or vb.net/c# book. Maybe he will become more interested in application development because of these languages (it was the case with me, I'm 14). :)
Edit: This is assuming he doesn't have much programming experience.
A: Ars Technica just came out w/ an article about open-source gaming consoles. They are hand-helds, so I don't know if that's an issue but they seem to be pretty nice, with lots of features to tinker with.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147661",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Why does regasm.exe register my c# assembly with the wrong GUID? I've got a c# assembly which I'm invoking via COM from a Delphi (win32 native) application.
This works on all the machines I've tested it on, except one.
The problem is that the Delphi application gets "Class not registered" when trying to create the COM object.
Now, when I look in the registry under HKEY_CLASSES_ROOT\DelphiToCSharp\CLSID, the GUID listed there is not the same as the assembly Guid in AssemblyInfo.cs. It should be the same - it IS the same on all the other computers where it's installed.
I have tried regasm /unregister delphitocsharp.dll, and that removes the registry key. Then if I do regasm delphitocsharp.dll, the registry key returns, but the GUID is the same as before (ie. wrong), and Delphi still gets "Class not registered".
DelphiToCSharp.dll on the working machine is identical (verified with md5) to the version on the non-working machine.
All I can think of is that an old version of the dll was registered before, and there still exists some remnant of that file which is making regasm confused.
How can I fix or at least further diagnose this issue?
A: The GUID in AssemblyInfo becomes the "Type-Library" GUID and usually is not what you'd be looking for. I'm going to assume you're trying to access a class, and you need to define a Guid attribute and ComVisible for the class. For example:
[Guid("00001111-2222-3333-4444-555566667777"), ComVisible(true)]
public class MyCOMRegisteredClass
If you don't, then the class either a) won't be registered, or b) if you've defined COMVisible(true) at the assembly level, will be assigned a guid that .NET bakes up for you.
A: Maybe you have an old version of the assembly somewhere? Maybe in the GAC? Regasm is probably picking that up and using it.
A: Most probably you have a copy of the same (old version) dll somewhere on your system, search disk for copies of the same file and remove (backup) them manually before registering the new copy.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147669",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: Get list of available servers in SQL server group How can I extract the list of available SQL servers in an SQL server group? I'm planning to put that list in a combo box in VB.NET.
A: The only way I knew to do it was using the command line:
osql -L
But I found the below article which seems to solve your specific goal filling a combobox:
http://www.sqldbatips.com/showarticle.asp?ID=45
A: If you didn't want to be tied to SQL SMO, which is what Ben's article uses, you can do something like this to discover all SQL servers on your network:
Private Sub cmbServer_DropDown(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmbServer.DropDown
Dim oTable As Data.DataTable
Dim lstServers As List(Of String)
Try
If cmbServer.Items.Count = 0 Then
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor
oTable = System.Data.Sql.SqlDataSourceEnumerator.Instance.GetDataSources
For Each oRow As DataRow In oTable.Rows
If oRow("InstanceName").ToString = "" Then
cmbServer.Items.Add(oRow("ServerName"))
Else
cmbServer.Items.Add(oRow("ServerName").ToString & "\" & oRow("InstanceName").ToString)
End If
Next oRow
End If
Catch ex As Exception
ErrHandler("frmLogin", "cmbServer_DropDown", ex.Source, ex.Message, Ex.InnerException)
Finally
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default
If oTable IsNot Nothing Then
oTable.Dispose()
End If
End Try
End Sub
The SqlDataSourceEnumerator class is nice because it gives you SQL server discovery right out of the 2.0 framework.
A: In C# I've used calls to odbc32.dll
For example:
[DllImport("odbc32.dll", CharSet = CharSet.Ansi)]
private static extern short SQLBrowseConnect(
IntPtr hconn, StringBuilder inString,
short inStringLength, StringBuilder outString, short outStringLength, out short
outLengthNeeded);
Documentation for that function is on MSDN
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147670",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: What's the best way to deploy a JRuby on Rails application to Tomcat? I'm looking at ways to deploy a Ruby on Rails app (running on JRuby) to a Tomcat instance for testing.
The tomcat instance is running on a Solaris server that I can SSH to. I've looked at using Capistrano, but there doesn't seem to be a lot out there about using it to deploy to Tomcat, or even about running it under JRuby, and I keep hitting bugs in Capistrano due to the Windows/JRuby environment my PC is running (yeah, it's corporate - not my choice, but I've got to live with it).
I'm using warble to build the .war file, and the app deploys and runs fine once I manually copy it up and deploy it. I'm wanting something easier and more automated to actually get it there.
Anyone done this before? Documentation on the web seems pretty thin.
A: I don't have much experience on this, so I don't know if I can give you the BEST way, but if Capistrano doesn't work, and you can't have a separate MRI install just to run it, you have just a few alternatives left:
Try running plain Rake and write your own deployment target:
http://www.gra2.com/article.php/deploy-ruby-on-rails-applications-rake
Or use Ant or Maven.
Or if it just ONE server you have to deploy to, you could just hack together two Ruby scripts - one that listens on the server for shutdown/startup requests, and one local that you run to: Send shutdown, scp over the file, send startup.
By the way, have you submitted any integration bugs you find with Capistrano to the JRuby team? I'm sure they'd be happy to have any contribution.
:)
A: Might be worth looking at 'Vlad the deployer' it adds remote_task to Rake allowing you to run tasks on a remote server. Personally however I prefer to have a standard Rake task on the server, ssh in and run that task - which would then do an svn checkout, make the WAR file, whatever...
A: I would probably use Ant for this. After all, it's just another WAR file, right? I don't know which version of Tomcat you're using but version 4.1x comes with an Ant task for deploying to Tomcat.
A: I am running a Rails project using JRuby and deploying to a Tomcat server. I have chosen to deploy with Capistrano because it automates just about everything. I had to make a few minor modifications to Capistrano's deployment lifecycle in order to get it to run on Tomcat:
Step 1: I created a warble task to be run on the server after Capistrano updates the code:
desc "Run the warble command to deploy the site"
namespace(:deploy) do
task :warble do
run ". ~/.profile;cd #{release_path};warble"
end
end
And hooked it into Capistrano lifecycle using:
after 'deploy:update_code', 'deploy:warble'
My Tomcat server has a symlink pointing to the #{release_path}/tmp/war directory created by warble. If you don't like this, you can easily modify the warble task to move the war file into the Tomcat directory instead.
Step 2: I overrode the deploy:start and deploy:stop tasks so that they kick off the Tomcat server instead of a Mongrel server:
desc "Starts the Tomcat Server"
namespace(:deploy) do
task :start do
sudo "#{tomcat_home}/bin/startup.sh"
end
end
desc "Shutdown the Tomcat Server"
namespace(:deploy) do
task :stop do
sudo "#{tomcat_home}/bin/shutdown.sh"
end
end
I run Capistrano tasks using MRI rather than the JRuby interpreter.
A: There's a few Capistrano recipes for deploying to Tomcat -- I built one into a gem called capistrano-tomcat. It takes a WAR you've built (probably with Warbler) and deploys and starts a Tomcat instance on a remote server.
The source is up on Github: http://github.com/rhunter/capistrano-tomcat
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147671",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Page working in FF, not in IE, where to start I have a page which is largely created by DOM script, which generates a table of images (normal img elements) from several webcams (helping out a friend with a pet boarding and my HTML/DOM is a bit rusty).
It works fine in FF3 or Chrome, but not in IE7, In fact, the whole table is not visible in IE (but the body background-color is applied).
Looking at the page in IE, there are no script errors, the CSS appears to be applied OK, and the DOM appears to show all the cells and rows in the table, which are all generated.
Using the IE Developer Toolbar, running the Image report even shows the images (even though they don't appear in the table and there is no evidence of the table in the page as rendered - even the text in the cells isn't rendered)
In looking at the img elements and using the trace style feature, at one time, I saw that the img elements all had display : none, and it said inline style, but there's nothing in my code or stylesheet which does this. That problem appears to have gone away as I started to add explicit entries for every table element in my stylesheet.
Where to start?
body { background-color : gray ; color : white ; margin : 0 ; font-family : Verdana, "lucida console", arial, sans-serif ; }
#CameraPreviewParent { text-align : center ; width : 100% ; }
#CameraTable { text-align : center ; width : 100% ; }
#CameraLiveParent { text-align : center ; margin : 50px ; }
#CameraLiveHeading { color : white ; }
td.CameraCell { text-align : center ; }
img.CameraImage { border : none ; }
a:link, a:visited, a:active, a:hover { text-decoration : none ; color : inherit ; }
table#CameraTable { color : white ; background-color : gray ; }
td.CameraCell { color : white ; background-color : gray ; }
Removing the stylesheet completely has no effect.
Here's the code of the page after generation (I apologize for the formatting from the DOM toolbar - I've tried to put in some linefeeds to make it easier to read):
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML Strict//EN"><META http-equiv="Content-Type" content="text/html; charset=windows-1252">
<HTML>
<HEAD>
<TITLE></TITLE>
<SCRIPT src="cameras.js" type="text/javascript"> </SCRIPT>
<SCRIPT type="text/javascript">
function CallOnLoad() {
document.title = PreviewPageTitle ; BuildPreview(document.getElementById("CameraPreviewParent")) ;
}
</SCRIPT>
</HEAD>
<BODY>
<!-- Any HTML can go here to modify page content/layout -->
<DIV id="CameraPreviewParent">
<TABLE id="CameraTable" class="CameraTable">
<TR id="CameraRow0" class="CameraRow">
<TD id="CameraCell0" class="CameraCell"><A id="CameraNameLink0" href="http://192.168.4.3:801" class="CameraNameLink">Luxury Suite 1 (1)</A><BR /><A id="CameraLink0" href="camlive.html?camIndex=0" class="CameraLink"><IMG id="CameraImage0" title="Click For Live Video from Luxury Suite 1 (1)" height="0" alt="Click For Live Video from Luxury Suite 1 (1)" src="http://192.168.4.3:801/IMAGE.JPG" width="0" class="CameraImage" /></A></TD>
<TD id="CameraCell1" class="CameraCell"><A id="CameraNameLink1" href="http://192.168.4.3:802" class="CameraNameLink">Luxury Suite 2 (2)</A><BR /><A id="CameraLink1" href="camlive.html?camIndex=1" class="CameraLink"><IMG id="CameraImage1" title="Click For Live Video from Luxury Suite 2 (2)" height="0" alt="Click For Live Video from Luxury Suite 2 (2)" src="http://192.168.4.3:802/IMAGE.JPG" width="0" class="CameraImage" /></A></TD>
</TR>
</TABLE>
</DIV><!-- This element is used to hold the preview -->
<!-- Any HTML can go here to modify page content/layout -->
</BODY>
</HTML>
Apparently the DOM code which inserts with width and height of the images is not working right in IE:
var PhotoWidth = 320 ;
var PhotoHeight = 240 ;
var image = document.createElement("img") ;
image.setAttribute("id", "CameraImage" + camIndex) ;
image.setAttribute("class", "CameraImage") ;
image.setAttribute("src", thisCam.ImageURL()) ;
image.setAttribute("width", PhotoWidth) ;
image.setAttribute("height", PhotoHeight) ;
image.setAttribute("alt", thisCam.PreviewAction()) ;
image.setAttribute("title", thisCam.PreviewAction()) ;
link.appendChild(image) ;
The response about the require TBODY element when dynamically building tables appears to be the entire problem - this appears to even set the image width and height to 0 in the DOM!
A: One gotcha I found is that in IE, if you dynamically create tables using document.createElement(), you need table(tbody(tr(tds))). Without a tbody, the table will not show.
A: The gotcha that always gets me is IE's mishandling of the <script> tag when it's used like <script src="..." /> instead of an opening and then a closing </script> tag. I seem to run into that a lot because I tend to use XSLT to generate HTML output.
The first step, though, would be to post somewhere an example of a page that doesn't display properly. It doesn't have to contain any real data, just enough to show the problem. Nobody is going to be able to guess what the problem is without a working example.
A: Have you started by resetting the CSS to a common base? Have a look at CSS Reset or YUI Reset CSS. (But without an example page to look at, we're going to be guessing what the actual problem is.)
A: Explorer Exposed! on positioniseverything.net lists bugs found only in IE.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147684",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Calculating the size of Array::pack format string How do you calculate the length of the string that would be returned by Array::pack? Is there something like Python's calcsize?
A: array.pack("").count I would say. Not really the fastest method, but it works.
A: By making an interpreter complying to the specifications found in Array::pack.
Or, reusing the existing implementation to count the number of characters instead of appending them to a string.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147693",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How can I assign a datasource to a generic list collection? I have a generic list, i.e. List<myclass>. Here myclass contains two string properties.
How can I assign a datasource to the list collection?
A: Start with a simple class:
// create a dummy class
public class MyClass
{
private string name;
public MyClass(string name)
{
ItemName = name;
}
public string ItemName
{
get { return name; }
set { name = value; }
}
}
Create a binding list and add some classes to the list:
// create a binding list
BindingList<MyClass> my_list = new BindingList<MyClass>();
// add some clssses to the list
my_list.Add(new MyClass("Item #1"));
my_list.Add(new MyClass("Item #2"));
Bind the list to the listbox datasource indicating which class property is to be used in the listbox display:
// make the list the datasource for a listbox
listBox1.DataSource = my_list;
// this is the property of the class displayed in the listbox
listBox1.DisplayMember = "ItemName";
A: You can wrap your list into a binding list:
System.ComponentModel.BindingList<myClass> bindingList = new System.ComponentModel.BindingList<myClass>(originalList);
Goran
A: Mirmal, I guess English is not your first language, this question is not very clear. I think that what you are asking is given a list of your class how do you then bind that list to something (a listbox or combobox etc)
Here is a simple code snippet of how to do this...
private void button2_Click(object sender, EventArgs e)
{
List<MyClass> list = new List<MyClass>();
list.Add(new MyClass() { FirstName = "Tim", Lastname = "Jarvis"});
list.Add(new MyClass() { FirstName = "John", Lastname = "Doe" });
listBox1.DataSource = list;
listBox1.DisplayMember = "FirstName"; // or override MyClass's ToString() method.
}
I hope this has answered your question.
A: You can't. That's because a List is no IBindableComponent. A Windows Forms is: See MSDN Control Class.
A: You do not assign a datasource to a List<> object. You can use a List<> as a datasource for a user interface control though.
If you want to make you could derive from List<> and implement IBindableComponent which would allow you to provide mechanisms for databinding to a list. This is almost certaintly not the best way to go about achieving what you want to do though.
Edit: If you have a control and want to retrieve the datasource and you know it's a List<> object you can just do:
List<MyClass> lst = listBox1.DataSource as List<MyClass>;
A: You got it the other way around. Databound objects like grids and the like could set generic lists as their data source.
You have to either manually populate your list or use a technology that populates it for you (e.g., LINQ to SQL, NHibernate)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147703",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Change the resolution of image in iPhone? I wanted to change the resolution of a image,this image I am getting from remote location.The image I am getting is too large to fit in iPhone screen is their any way to change that resolution?
A: If you're using a UIImageView then UIView's contentMode is what you need, you should probably set it to UIViewContentModeScaleAspectFit (or the equivalent in Interface Builder).
A: Assuming you are using some kind of "View" to display the image (rather than custom drawing) you might see if there is some kind of property which would allow you to set the "Mode" of the view to allow various scaling methods.
A: If you render it, it should scale anyway (see UIImage::drawInRect) However, CGContextDrawImage will scale draw an image into a new context, which you can then use to render to the screen.
A: If you're looking to actually resize a UIImage to smaller dimensions, this blog post might help.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147706",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Connection timed out when doing deployment of ear file I getting the following error:
Deploying application in domain failed; Error loading deployment descriptors for jrules-teamserver-SUNAS82 -- Connection timed out ; requested operation cannot be completed Error loading deployment descriptors for jrules-teamserver-SUNAS82 -- Connection timed out
When deploying a ear file.
What could be the possible cause Connection timed out and how to resolve the issue?
A: there is a possibility that the your deployment tool was NOT able to connect to the appserver at all. It was trying to get a network connection and that connection was not established : after TIMING OUT , it gave the error
Can you find out which appserver it is trying to connect to >?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147708",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I manipulate bits in Python? In C I could, for example, zero out bit #10 in a 32 bit unsigned value like so:
unsigned long value = 0xdeadbeef;
value &= ~(1<<10);
How do I do that in Python ?
A: Bitwise operations on Python ints work much like in C. The &, | and ^ operators in Python work just like in C. The ~ operator works as for a signed integer in C; that is, ~x computes -x-1.
You have to be somewhat careful with left shifts, since Python integers aren't fixed-width. Use bit masks to obtain the low order bits. For example, to do the equivalent of shift of a 32-bit integer do (x << 5) & 0xffffffff.
A: Python has C style bit manipulation operators, so your example is literally the same in Python except without type keywords.
value = 0xdeadbeef
value &= ~(1 << 10)
A: You should also check out BitArray, which is a nice interface for dealing with sequences of bits.
A: Omit the 'unsigned long', and the semi-colons are not needed either:
value = 0xDEADBEEF
value &= ~(1<<10)
print value
"0x%08X" % value
A: Have you tried copying and pasting your code into the Python REPL to see what will happen?
>>> value = 0xdeadbeef
>>> value &= ~(1<<10)
>>> hex (value)
'0xdeadbaef'
A: If you're going to do a lot of bit manipulation ( and you care much more about readability rather than performance for your application ) then you may want to create an integer wrapper to enable slicing like in Verilog or VHDL:
import math
class BitVector:
def __init__(self,val):
self._val = val
def __setslice__(self,highIndx,lowIndx,newVal):
assert math.ceil(math.log(newVal)/math.log(2)) <= (highIndx-lowIndx+1)
# clear out bit slice
clean_mask = (2**(highIndx+1)-1)^(2**(lowIndx)-1)
self._val = self._val ^ (self._val & clean_mask)
# set new value
self._val = self._val | (newVal<<lowIndx)
def __getslice__(self,highIndx,lowIndx):
return (self._val>>lowIndx)&(2L**(highIndx-lowIndx+1)-1)
b = BitVector(0)
b[3:0] = 0xD
b[7:4] = 0xE
b[11:8] = 0xA
b[15:12] = 0xD
for i in xrange(0,16,4):
print '%X'%b[i+3:i]
Outputs:
D
E
A
D
A: a = int('00001111', 2)
b = int('11110000', 2)
bin(a & b)[2:].zfill(8)
bin(a | b)[2:].zfill(8)
bin(a << 2)[2:].zfill(8)
bin(a >> 2)[2:].zfill(8)
bin(a ^ b)[2:].zfill(8)
int(bin(a | b)[2:].zfill(8), 2)
A: value = 0xdeadbeef
value &= ~(1<<10)
A: Some common bit operations that might serve as example:
def get_bit(value, n):
return ((value >> n & 1) != 0)
def set_bit(value, n):
return value | (1 << n)
def clear_bit(value, n):
return value & ~(1 << n)
Usage e.g.
>>> get_bit(5, 2)
True
>>> get_bit(5, 1)
False
>>> set_bit(5, 1)
7
>>> clear_bit(5, 2)
1
>>> clear_bit(7, 2)
3
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147713",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "42"
} |
Q: Good HTML Templates for form based Web Applications I would like to refer HTML templates designed/developed especially for form based Web Applications.
I have been searching them but am not able to find out which I find better.
Regards,
Jatan
A: Much of the choice in this sort of thing is going to be defined by your choice of server tech / platform, e.g. .NET has in built widgets you can use, as do many web application frameworks.
The django admin layouts are extremely well designed, you could download Django and check it out.
Similar forms are also implemented for Rails by the Streamlined framwork, not to mention the inbuilt scaffolding generators.
Tthe YUI framework has a bunch of different widgets with a consistent style, as does the ExtJS framework, and are server technology agnostic. These can be dynamically created using json as the data source, rather than html/xml
You could also use a CSS framework such as BlueprintCSS, and combine it with the suggested HTML, and add effects + interactions with jQuery, and build that on top of your html.
Modifying an existing layout is not too hard, for a simple CRUD application you probably just need a large area for forms and lists/tables and a menu.
If you need anything more particular than that, its probably time to invest in a design, or learn to do it yourself.
The simplest possible layout is going to be a header with a menu inside (& maybe a heading), and a content area for your forms.
<style type="text/css" media="screen">
div#page { width:900px; margin:0; auto; }
</style>
<body>
<div id="page">
<div id="header">
<!-- Menu Goes Here! -->
</div>
<div id="content">
<!-- Put some Forms n stuff here -->
</div>
</div>
</body>
A: Here are a few catalogs of template designs:
*
*Open Design Community
*Open Web Design
*Open Source Web Design
A: I create one, maybe you will find it useful => web application admin template
A: I personally like ThemeForest. They have a large selection and includes the raw markup and css scripts so you can make your forms app look like the template in no time.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147714",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Delphi #IF(DEBUG) equivalent? Is there a Delphi equivalent of the C# #if(DEBUG) compiler directive?
A: DebugHook is set if an application is running under the IDE debugger. Not the same as a compiler directive but still pretty useful. For example:
ReportMemoryLeaksOnShutdown := DebugHook <> 0; // show memory leaks when debugging
A: Apart from what lassevk said, you can also use a few other methods of compiler-evaluation (since Delphi 6, I believe) :
{$IF NOT DECLARED(SOME_SYMBOL)}
// Mind you : The NOT above is optional
{$ELSE}
{$IFEND}
To check if the compiler has this feature, use :
{$IFDEF CONDITIONALEXPRESSIONS}
There are several uses for this.
For example, you could check the version of the RTL; From the Delphi help :
You can use RTLVersion in $IF
expressions to test the runtime
library version level independently
of the compiler version level.
Example: {$IF RTLVersion >= 16.2} ...
{$IFEND}
Also, the compiler version itself can be checked, again from the code:
CompilerVersion is assigned a value by
the compiler when the system unit is
compiled. It indicates the revision
level of the compiler features /
language syntax, which may advance
independently of the RTLVersion.
CompilerVersion can be tested in $IF
expressions and should be used
instead of testing for the VERxxx
conditional define. Always test for
greater than or less than a known
revision level. It's a bad idea to
test for a specific revision level.
Another thing I do regularly, is define a symbol when it's not defined yet (nice for forward-compatiblity), like this :
{$IF NOT DECLARED(UTF8String)}
type
UTF8String = type AnsiString;
{$IFEND}
Hope this helps!
A: Use this:
{$IFDEF DEBUG}
...
{$ENDIF}
A: These control directives are available:
{$IFDEF}
{$ELSE}
{$ENDIF}
{$IFNDEF} //if *not* defined
and they can be used as shown here:
procedure TfrmMain.Button1Click(Sender: TObject);
begin
{$IFDEF MY_CONDITIONAL}
ShowMessage('my conditional IS defined!');
{$ELSE}
ShowMessage('my conditional is NOT defined!');
{$ENDIF}
{$IFNDEF MY_CONDITIONAL}
ShowMessage('My conditional is explicitly NOT defined');
{$ENDIF}
end;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147719",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "23"
} |
Q: Saving a SecureString One of the feature requests I've got for the program I'm working on is to be able to save the list of credentials users enter in, so they can be shared around. The specific use case that inspired this request was using our program on a large corporate network, made up of fairly good LANs connected by a flaky WAN. The idea was that, instead of having our program beat against the WAN when it's down, they'd send a 'configuration' file containing the closely-guarded admin credentials, run it in each LAN and zip up the results and e-mail it back.
Yeah.
My initial instinct is to scoff at this request - saving passwords? really? and surely the network division of the company would prefer you to try and sell whatever WAN products they have - but it turns out one of the classes I use the credentials for can take a SecureString, and, well, it's always good to look out for ways you can save people some effort. That got me to wondering:
Is it possible to save an encrypted SecureString, so that I can save the sensitive data to a file and open it up someplace else?
What are your thoughts, Stack Overflow?
A: There is no save support in SecureString, it's intended as a mechanism to protect a in-memory managed string and is only used for interfacing with unmanaged APIs. If a password was stored in a System.String instance, security would be less due to the nature of System.String. The existence of garbage collection and interning would keep the password in memory longer than necessary. Also due to the plethora of great debugging tools for .NET, it would be significantly easier to access the string through reflection or another .NET API even without the longer lifetime.
If you're going to save a password on the disk your security is pretty far compromised. If someone has physical access to the machine, or administrator level remote access, then the best you can do is make it more difficult, but never impossible. Use an encryption API, store it in a secure location, configure access rights.
All that aside, Merus, I'd suggest you try to improve the overall system because for a use-case like you're describing (assuming I understand it) you'd be better served to store a hash than the actual password.
A: You might want to look at comparing password hash.
You would have a salt made of username and probably some other constant, followed by the string. Then, you would pass that to a hashing algorithm, like SHA1*.
For instance,
using System.Security.Cryptography;
public byte[] GetPasswordHash(string username, string password, string salt)
{
// get salted byte[] buffer, containing username, password and some (constant) salt
byte[] buffer;
using (MemoryStream stream = new MemoryStream())
using (StreamWriter writer = new StreamWriter(stream))
{
writer.Write(salt);
writer.Write(username);
writer.Write(password);
writer.Flush();
buffer = stream.ToArray();
}
// create a hash
SHA1 sha1 = SHA1.Create();
return sha1.ComputeHash(buffer);
}
Then, you would compare the result for GetPasswordHash(username, expectedPassword, salt) to GetPasswordHash(username, givenPassword, salt).
If you implement your own user list with usernames and passwords, you might consider only saving the hash (GetPasswordHash(username, givenPassword, salt)) and comparing against the saved hash.
A: If you mean saving the SecureString's encrypted bytes then this will not work - the key for the SecureString is tied to the user and process. Read in those bytes in a different process or for a different user, and there's no way to decrypt the string.
A: This would defeat the point of a SecureString, which is guaranteed to reside in memory. So if you are saving it to file, you might as well save it as a normal string, since it is no longer "secure".
A: You might want to take a look at the IsolatedStorageFileStream class. It specifies ways to write and store file data which can be accessed only by your assembly.
I don't think you can use SecureString on it though.
A: The SecureString is not serializable so you cannot just save it with some of the delivered serializers (binary, XML, etc.)
you also cannot just access e.g. a "Password" property from a securestring object as there is no such thing.
you have to use Marshalling and a little bit of plumbing to do this.
if you want to store user credentials somewhere I suggest encrypting them on your own as this eases later development. after evaluating the SecureString approach, we decided to implement something by ourselves, but these are just my 2 cents.
A: As stated here, SecureString is not the best way to use in this scenario.
If I had the need to share the users credentials I would probably share the username and the hashed + salted password, so you would be safe and only share the representation of a password, not it's contents.
The simply way to this is for example use the BCryt Library (where there's a .NET representation of it) and simply host the username and password representation in a table ready to be shared
This is how you would use it:
StringBuilder sb = new StringBuilder();
// run ADO.NET / Entity Framework / etc and query your DB with something like:
"SELECT user_id, username, password FROM [TblUsers];"
// loop through the results
sb.AppendFormat(
"INSERT INTO [TblSharedUsers] SELECT '{0}','{1}','{2}'",
dr["id"], dr["username"],
BCrypt.HashPassword(dr["password"], BCrypt.GenerateSalt(12));
);
// then run sb.ToSTring() agains your db
on the client end, you can create a new AuthenticationProvider (so it will be easy to change when the network is not available using IoC and DI) that reads from the TblSharedUsers and check the user password like
string userPassword = Request["password"];
"SELECT id, password FROM [TblSharedUsers] WHERE username = @usr;"
if( BCrypt.CheckPassword(userPassword, dr["password"]) )
// User can log in
else
// Credentials are invalid
I hope this helps someone with the same problem.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147726",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Character reading from file in Python In a text file, there is a string "I don't like this".
However, when I read it into a string, it becomes "I don\xe2\x80\x98t like this". I understand that \u2018 is the unicode representation of "'". I use
f1 = open (file1, "r")
text = f1.read()
command to do the reading.
Now, is it possible to read the string in such a way that when it is read into the string, it is "I don't like this", instead of "I don\xe2\x80\x98t like this like this"?
Second edit: I have seen some people use mapping to solve this problem, but really, is there no built-in conversion that does this kind of ANSI to unicode ( and vice versa) conversion?
A: But it really is "I don\u2018t like this" and not "I don't like this". The character u'\u2018' is a completely different character than "'" (and, visually, should correspond more to '`').
If you're trying to convert encoded unicode into plain ASCII, you could perhaps keep a mapping of unicode punctuation that you would like to translate into ASCII.
punctuation = {
u'\u2018': "'",
u'\u2019': "'",
}
for src, dest in punctuation.iteritems():
text = text.replace(src, dest)
There are an awful lot of punctuation characters in unicode, however, but I suppose you can count on only a few of them actually being used by whatever application is creating the documents you're reading.
A: There is a possibility that somehow you have a non-unicode string with unicode escape characters, e.g.:
>>> print repr(text)
'I don\\u2018t like this'
This actually happened to me once before. You can use a unicode_escape codec to decode the string to unicode and then encode it to any format you want:
>>> uni = text.decode('unicode_escape')
>>> print type(uni)
<type 'unicode'>
>>> print uni.encode('utf-8')
I don‘t like this
A: Leaving aside the fact that your text file is broken (U+2018 is a left quotation mark, not an apostrophe): iconv can be used to transliterate unicode characters to ascii.
You'll have to google for "iconvcodec", since the module seems not to be supported anymore and I can't find a canonical home page for it.
>>> import iconvcodec
>>> from locale import setlocale, LC_ALL
>>> setlocale(LC_ALL, '')
>>> u'\u2018'.encode('ascii//translit')
"'"
Alternatively you can use the iconv command line utility to clean up your file:
$ xxd foo
0000000: e280 980a ....
$ iconv -t 'ascii//translit' foo | xxd
0000000: 270a '.
A: Ref: http://docs.python.org/howto/unicode
Reading Unicode from a file is therefore simple:
import codecs
with codecs.open('unicode.rst', encoding='utf-8') as f:
for line in f:
print repr(line)
It's also possible to open files in update mode, allowing both reading and writing:
with codecs.open('test', encoding='utf-8', mode='w+') as f:
f.write(u'\u4500 blah blah blah\n')
f.seek(0)
print repr(f.readline()[:1])
EDIT: I'm assuming that your intended goal is just to be able to read the file properly into a string in Python. If you're trying to convert to an ASCII string from Unicode, then there's really no direct way to do so, since the Unicode characters won't necessarily exist in ASCII.
If you're trying to convert to an ASCII string, try one of the following:
*
*Replace the specific unicode chars with ASCII equivalents, if you are only looking to handle a few special cases such as this particular example
*Use the unicodedata module's normalize() and the string.encode() method to convert as best you can to the next closest ASCII equivalent (Ref https://web.archive.org/web/20090228203858/http://techxplorer.com/2006/07/18/converting-unicode-to-ascii-using-python):
>>> teststr
u'I don\xe2\x80\x98t like this'
>>> unicodedata.normalize('NFKD', teststr).encode('ascii', 'ignore')
'I donat like this'
A: It is also possible to read an encoded text file using the python 3 read method:
f = open (file.txt, 'r', encoding='utf-8')
text = f.read()
f.close()
With this variation, there is no need to import any additional libraries
A: There are a few points to consider.
A \u2018 character may appear only as a fragment of representation of a unicode string in Python, e.g. if you write:
>>> text = u'‘'
>>> print repr(text)
u'\u2018'
Now if you simply want to print the unicode string prettily, just use unicode's encode method:
>>> text = u'I don\u2018t like this'
>>> print text.encode('utf-8')
I don‘t like this
To make sure that every line from any file would be read as unicode, you'd better use the codecs.open function instead of just open, which allows you to specify file's encoding:
>>> import codecs
>>> f1 = codecs.open(file1, "r", "utf-8")
>>> text = f1.read()
>>> print type(text)
<type 'unicode'>
>>> print text.encode('utf-8')
I don‘t like this
A: Actually, U+2018 is the Unicode representation of the special character ‘ . If you want, you can convert instances of that character to U+0027 with this code:
text = text.replace (u"\u2018", "'")
In addition, what are you using to write the file? f1.read() should return a string that looks like this:
'I don\xe2\x80\x98t like this'
If it's returning this string, the file is being written incorrectly:
'I don\u2018t like this'
A: This is Pythons way do show you unicode encoded strings. But i think you should be able to print the string on the screen or write it into a new file without any problems.
>>> test = u"I don\u2018t like this"
>>> test
u'I don\u2018t like this'
>>> print test
I don‘t like this
A: Not sure about the (errors="ignore") option but it seems to work for files with strange Unicode characters.
with open(fName, "rb") as fData:
lines = fData.read().splitlines()
lines = [line.decode("utf-8", errors="ignore") for line in lines]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147741",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "117"
} |
Q: Return "correct" error code, or protect privacy? OK, probably best to give an example here of what I mean.
Imagine a web based forum system, where the user authentication is done by some external method, which the system is aware of.
Now, say for example, a user enters the URL for a thread that they do not have access to. For this should I return a 403 (Forbidden), letting the user know that they should try another authentication method, or a 404, not letting them know that there is something there to access.
Assuming I return a 403, should I also return a 403 when they access a URL for a topic that doesn't exist yet?
Edit: the example above was more of an example that something IRL.
Another Example, say I expose something like
/adminnotes/user
if there are Administrator notes about the user. Now, returning a 403 would let the user know that there is something there being said about them. A 404 would say nothing.
But, if I were to return a 403 - I could return it for adminnotes/* - which would resolve that issue.
Edit 2: Another example. Soft deleted Questions here return a 404. Yet, with the right authentication and access, you can still see them (I'd presume)
A: Above everything else, comply with HTTP spec. Returning 403 in place of 404 is not a good thing. Returning 404 in place of 403 probably is ok (or not a big blunder), but I would just let the software tell the truth. If user only knows the ID of a topic, it's not much anyway. And he could try timing attacks to determine whether this topic exists.
A: I would go for a 307 redirect to NoSuchPageOrNoPermissions.html where you nicely tell the user they either mistyped the url or don't have permissions.
This will not break compliance and not send out the incorrect message.
If you are very paranoid you could put in a random wait before returning the redirect so time analysis would be harder.
As for all the people here asking why protect directories try these examples
1. User Name
Imagine we are an ISP we give each user a webpage at www.isp.example/home/USERNAME and email address of USERNAME@isp.example. If an attacker does a dictionary attack sending requests to www.isp.example/home/[Random] and can tell if that is a valid user name we now can generate a list of valid email address to sell to bad people.
2. What Folder
Bob is running for office he has an account with the poster and uses his site to store personal information. But he has secured it by making it private folder his public pages are at:
www.example.com/Bob and his secret folder is www.example.com/Bob/IceCream he has marked this as private so any one requesting gets 403. however www.example.com/Bob/Cake returns a 404 as Bobs secret is icecream not cake.
Alice the reporter does a dictionary attack on Bobs site trying
*
*www.example.com/Bob/Cake - 404
*www.example.com/Bob/Donuts - 404
*www.example.com/Bob/Lollies - 404
*www.example.com/Bob/IceCream - 403
Now Alice knows Bobs secrets and can discredit him as an ice cream eater.
A: I think you should send 307 (Temporary Redirect) for requests for "/adminnotes/user" to redirect unprivileged clients to "/adminnotes/". So the client makes a request for "/adminnotes/", therefore you can send back 403, because it is forbidden.
This way your application stays HTTP compliant, and unprivileged users won't learn much about protected data.
A: What "privacy" is protected by hiding from users the existence of a particular thread?
I'd say that returning either 403 or 404 on a thread they cannot access is OK. Returning 403 on a thread that does not exist is a bad idea.
A: No website in the world does what you are suggesting, so by this example we see that it is probably best to follow the standard and return 404 when the resource does not exist and 403 when it is forbidden.
A: I don't see why you worry about privacy issue from the URL. In the case of stackoverflow, you can put any text after the QuestionID number. For example, Return "correct" error code, or protect privacy? still comes back to this question.
A: Don't forget that a 404 can also technically be revealing information. For example, you could tell who didn't have adminnotes. Depending on the circumstances, this could be just as bad as indicating that the resource did exist.
In my opinion, errors should not lie. If you give a 404, it should always be the case that the resource does not exist.
If you're dealing with sensitive information, then you can always say that the user doesn't have permission for the resource. This doesn't necessarily require that the resource exists. A client may not have permission to even know if the resource exists. Therefore you would need to provide a permission denied error for any combination of /adminnotes/.
That said, the official spec seems to disagree, here's what the official rfc says about the errors at http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html:
10.4.4 403 Forbidden
The server understood the request, but is refusing to fulfill it. Authorization will not help and the request SHOULD NOT be repeated. If the request method was not HEAD and the server wishes to make public why the request has not been fulfilled, it SHOULD describe the reason for the refusal in the entity. If the server does not wish to make this information available to the client, the status code 404 (Not Found) can be used instead.
10.4.5 404 Not Found
The server has not found anything matching the Request-URI. No indication is given of whether the condition is temporary or permanent. The 410 (Gone) status code SHOULD be used if the server knows, through some internally configurable mechanism, that an old resource is permanently unavailable and has no forwarding address. This status code is commonly used when the server does not wish to reveal exactly why the request has been refused, or when no other response is applicable.
I'm no expert, but I think it's crappy to give a "not found", when a resource may exist. I'd prefer a "forbidden", without a guarantee that the resource exists, implying that you would need to authenticate somehow in order to find out.
A: Lets say you did return a "page not found" error when you detect that the user does not have the correct access rights. A malicious person with the intent of hacking will soon figure out that you would return this in place of the access denied.
But the real users who mistype a url or use a wrong login etc would be confused and it would take no end of explanations and release notes to explain your position to the customers, TAC etc. In exchange for what ?
The intention is good, but i'm afraid this policy you propose might not work out the way you wanted it to.
A: My suggestion is to:
*
*If Not Exists_Thread then return 404
*If Not User_Can_Access_to_this_Thread then return 403
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147747",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: In Django is there a way to display choices as checkboxes? In the admin interface and newforms there is the brilliant helper of being able to define choices. You can use code like this:
APPROVAL_CHOICES = (
('yes', 'Yes'),
('no', 'No'),
('cancelled', 'Cancelled'),
)
client_approved = models.CharField(choices=APPROVAL_CHOICES)
to create a drop down box in your form and force the user to choose one of those options.
I'm just wondering if there is a way to define a set of choices where multiple can be chosen using checkboxes? (Would also be nice to be able to say that the user can select a maximum number of them.) It seems like it's a feature that is probably implemented, it's just I can't seem to find it in the documentation.
A: In terms of the forms library, you would use the MultipleChoiceField field with a CheckboxSelectMultiple widget to do that. You could validate the number of choices which were made by writing a validation method for the field:
class MyForm(forms.Form):
my_field = forms.MultipleChoiceField(choices=SOME_CHOICES, widget=forms.CheckboxSelectMultiple())
def clean_my_field(self):
if len(self.cleaned_data['my_field']) > 3:
raise forms.ValidationError('Select no more than 3.')
return self.cleaned_data['my_field']
To get this in the admin application, you'd need to customise a ModelForm and override the form used in the appropriate ModelAdmin.
A: @JonnyBuchanan gave the right answer.
But if you need this in the django admin for many models, and you're (like me) too lazy to customize a ModelForm and ovverride the right methods inside the ModelAdmin class, you can use this approach:
http://www.abidibo.net/blog/2013/04/10/convert-select-multiple-widget-checkboxes-django-admin-form/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147752",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "52"
} |
Q: How to be successful in web user interface testing? We are setting up a Selenium test campaign on a big web application.
The first thing we've done was to build a framework which initialize SQL data in database before the test, launch the test, archive results and then clear data.
We've integrate that in a Maven 2 process, run every day by TeamCity on a dedicated database.
We've set up several Selenium tests now but It's not as used as planned.
Reasons are that tests are sometimes broken for other reasons than regressions (data may have changed, stored procedure may have been recompiled and so on).
I would like to know if there are big success in user interface testing and if so, reasons to that. Commons errors may also interest me.
A: If you want reliable unit tests, you need to have the same input. Starting state of the database is the input. So, you need to have the same starting database each time. Of course, if you wish to do testing with different input, you need to create another unit test (as results will obviously not be the same).
When I do stuff like this, I always use the same database as a starting point. Of course, some of the tests might fail without modifying the database is correct way, so some other subsequent tests might fail as well even though they wouldn't otherwise. If your unit-test tool allows, you should define dependencies between tests to make sure that those tests will not be run at all when the 'parent' one fails.
A: Testability helps a lot. The biggest win for testability in web apps is if all of the HTML elements you need to interact with on the page have unique and consistent attributes. If the attributes you are using to identify the HTML elements (Selenium uses xpath) are not consistent/reliable from build-to-build, or session-to-session, your test scripts will fail. Also, these attributes must be unique, so that the automation tool (in this case Selenium) can reliably find the object on the web page.
A: I use http-unit which has the added benefit of working before any styling has been added to the page.
http://httpunit.sourceforge.net/
You can attach the tests to run in the integration test phase for maven2.
From the site
Written in Java, HttpUnit emulates the
relevant portions of browser behavior,
including form submission, JavaScript,
basic http authentication, cookies and
automatic page redirection, and allows
Java test code to examine returned
pages either as text, an XML DOM, or
containers of forms, tables, and
links.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147767",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: MS VC++ 6 class wizard Ok, I'm developing an application that has been in pretty much continous development over the last 16 years, from C in DOS, through various flavours of C++ and now is largely based around C++ with MFC and StingRay GUIs and various other SDKs.
While I use VS 2005 for the release builds, I still use MSVC 6 for much of the GUI building, simply because ClassWizard is so much quicker in this environment than the weak equivalent tools that followed. Note that I am using ClassWizard to automatically generate code for my own user defined types (see Custom DDXs) and I like to add a lot of member variables and methods in one go. Creating them one at a time as per later versions of Visual Studio for me is a big backward step. At the same time, working with multiple IDEs is also a pain.
My question is in two parts;
*
*Is there any way of getting ClassWizard to work is VS 2005 or VS 2008?
*Is there any drop in replacement, or alternative IDE, that provides similar levels of productivty for old C++ hacks such as myself?
A: A follow up to those who are interested. ClassWizard may be re-introduced in VS2010, from Tarek Madkour [VC++ Team]
'We are considering adding the Class
Wizard back to VS10. We hope this will
make DDX/DDV function creation more
keyboard-centric just like it was in
VC6. There are some schedule
challenges that we will need to
overcome to get the feature done, but
I am optimistic that you will see it
when we ship VS10.'
Click here for the full discussion
Edit: The release notes for VS2010 confirm that MFC Class Wizard is back. So contrary to popular belief, the guys at MS do listen to their users.
Visual Studio 2010 provides a C++ IDE
experience that includes the return of
the MFC Class Wizard, the ability to
view large source files through Source
Outline, integrated quick searching to
find information without the confusion
of the current “Find In Files” method
and an easily extensible IDE model
through the new Managed Extensibility
Framework (MEF).
A: Agree with Shane, the CW alternative in vs2008 is shockingly poor; it makes you wonder if anybody at Microsoft still uses MFC. I’ve started bumping my estimates up just because of the generally poor afx/mfc integration. It’s just not finished and what is there is pretty buggy. Sure you can put the code in by hand, nobody is claiming its hard but seriously, its grunt code, its 2010, you just shouldn’t be writing this stuff by hand anymore.
A: I will suggest avoid code generation at all and use your favorite editor to manually create new code. If i understand correctly your are expert in this area and i sure you know that manually created code will be much cleaner and simpler then the generated one.
In additional the code generator is a nightmare for code reviews, it change zillions of places that should not be changed at all and it's really hard to concentrate to the meaningful changes.
IMHO.
A: I would also suggest you put the neccessary DDX/DDV (as well as message handling) macros (and member variables) manually into your classes. At first it seems a bit difficult to find out how and where exactly one is supposed to write the entries, but after a short while it's rather easy. I started doing that after porting a VC6 project over to VS2005, and for exactly the same reason you gave: there is no suitable replacement for ClassWizard. However, after two years I can say that I don't miss it at all anymore.
A: You can write click on controls on form and add variable or event handler. It is not as good as VC6 but still. I do not see any point in writing the DDX manually.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147777",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: MPI for multicore? With the recent buzz on multicore programming is anyone exploring the possibilities of using MPI ?
A: I've used MPI extensively on large clusters with multi-core nodes. I'm not sure if it's the right thing for a single multi-core box, but if you anticipate that your code may one day scale larger than a single chip, you might consider implementing it in MPI. Right now, nothing scales larger than MPI. I'm not sure where the posters who mention unacceptable overheads are coming from, but I've tried to give an overview of the relevant tradeoffs below. Read on for more.
MPI is the de-facto standard for large-scale scientific computation and it's in wide use on multicore machines already. It is very fast. Take a look at the most recent Top 500 list. The top machines on that list have, in some cases, hundreds of thousands of processors, with multi-socket dual- and quad-core nodes. Many of these machines have very fast custom networks (Torus, Mesh, Tree, etc) and optimized MPI implementations that are aware of the hardware.
If you want to use MPI with a single-chip multi-core machine, it will work fine. In fact, recent versions of Mac OS X come with OpenMPI pre-installed, and you can download an install OpenMPI pretty painlessly on an ordinary multi-core Linux machine. OpenMPI is in use at Los Alamos on most of their systems. Livermore uses mvapich on their Linux clusters. What you should keep in mind before diving in is that MPI was designed for solving large-scale scientific problems on distributed-memory systems. The multi-core boxes you are dealing with probably have shared memory.
OpenMPI and other implementations use shared memory for local message passing by default, so you don't have to worry about network overhead when you're passing messages to local processes. It's pretty transparent, and I'm not sure where other posters are getting their concerns about high overhead. The caveat is that MPI is not the easiest thing you could use to get parallelism on a single multi-core box. In MPI, all the message passing is explicit. It has been called the "assembly language" of parallel programming for this reason. Explicit communication between processes isn't easy if you're not an experienced HPC person, and there are other paradigms more suited for shared memory (UPC, OpenMP, and nice languages like Erlang to name a few) that you might try first.
My advice is to go with MPI if you anticipate writing a parallel application that may need more than a single machine to solve. You'll be able to test and run fine with a regular multi-core box, and migrating to a cluster will be pretty painless once you get it working there. If you are writing an application that will only ever need a single machine, try something else. There are easier ways to exploit that kind of parallelism.
Finally, if you are feeling really adventurous, try MPI in conjunction with threads, OpenMP, or some other local shared-memory paradigm. You can use MPI for the distributed message passing and something else for on-node parallelism. This is where big machines are going; future machines with hundreds of thousands of processors or more are expected to have MPI implementations that scale to all nodes but not all cores, and HPC people will be forced to build hybrid applications. This isn't for the faint of heart, and there's a lot of work to be done before there's an accepted paradigm in this space.
A: No, in my opinion it is unsuitable for most processing you would do on a multicore system. The overhead is too high, the objects you pass around must be deeply cloned, and passing large objects graphs around to then run a very small computation is very inefficient. It is really meant for sharing data between separate processes, most often running in separate memory spaces, and most often running long computations.
A multicore processor is a shared memory machine, so there are much more efficient ways to do parallel processing, that do not involve copying objects and where most of the threads run for a very small time. For example, think of a multithreaded Quicksort. The overhead of allocating memory and copying the data to a thread before it can be partioned will be much slower with MPI and an unlimited number of processors than Quicksort running on a single processor.
As an example, in Java, I would use a BlockingQueue (a shared memory construct), to pass object references between threads, with very little overhead.
Not that it does not have its place, see for example the Google search cluster that uses message passing. But it's probably not the problem you are trying to solve.
A: MPI is not inefficient. You need to break the problem down into chunks and pass the chunks around and reorganize when the result is finished per chunk. No one in the right mind would pass around the whole object via MPI when only a portion of the problem is being worked on per thread. Its not the inefficiency of the interface or design pattern thats the inefficiency of the programmers knowledge of how to break up a problem.
When you use a locking mechanism the overhead on the mutex does not scale well. this is due to the fact that the underlining runqueue does not know when you are going to lock the thread next. You will perform more kernel level thrashing using mutex's than a message passing design pattern.
A: I would have to agree with tgamblin. You'll probably have to roll your sleeves up and really dig into the code to use MPI, explicitly handling the organization of the message-passing yourself. If this is the sort of thing you like or don't mind doing, I would expect that MPI would work just as well on multicore machines as it would on a distributed cluster.
Speaking from personal experience... I coded up some C code in graduate school to do some large scale modeling of electrophysiologic models on a cluster where each node was itself a multicore machine. Therefore, there were a couple of different parallel methods I thought of to tackle the problem.
1) I could use MPI alone, treating every processor as it's own "node" even though some of them are grouped together on the same machine.
2) I could use MPI to handle data moving between multicore nodes, and then use threading (POSIX threads) within each multicore machine, where processors share memory.
For the specific mathematical problem I was working on, I tested two formulations first on a single multicore machine: one using MPI and one using POSIX threads. As it turned out, the MPI implementation was much more efficient, giving a speed-up of close to 2 for a dual-core machine as opposed to 1.3-1.4 for the threaded implementation. For the MPI code, I was able to organize operations so that processors were rarely idle, staying busy while messages were passed between them and masking much of the delay from transferring data. With the threaded code, I ended up with a lot of mutex bottlenecks that forced threads to often sit and wait while other threads completed their computations. Keeping the computational load balanced between threads didn't seem to help this fact.
This may have been specific to just the models I was working on, and the effectiveness of threading vs. MPI would likely vary greatly for other types of parallel problems. Nevertheless, I would disagree that MPI has an unwieldy overhead.
A: MPI has a very large amount of overhead, primarily to handle inter-process communication and heterogeneous systems. I've used it in cases where a small amount of data is being passed around, and where the ratio of computation to data is large.
This is not the typical usage scenario for most consumer or business tasks, and in any case, as a previous reply mentioned, on a shared memory architecture like a multicore machine, there are vastly faster ways to handle it, such as memory pointers.
If you had some sort of problem with the properties describe above, and you want to be able to spread the job around to other machines, which must be on the same highspeed network as yourself, then maybe MPI could make sense. I have a hard time imagining such a scenario though.
A: I personally have taken up Erlang( and i like to so far). The messages based approach seem to fit most of the problem and i think that is going to be one of the key item for multi core programming. I never knew about the overhead of MPI and thanks for pointing it out
A: You have to decide if you want low level threading or high level threading. If you want low level then use pThread. You have to be careful that you don't introduce race conditions and make threading performance work against you.
I have used some OSS packages for (C and C++) that are scalable and optimize the task scheduling. TBB (threading building blocks) and Cilk Plus are good and easy to code and get applications of the ground. I also believe they are flexible enough integrate other thread technologies into it at a later point if needed (OpenMP etc.)
www.threadingbuildingblocks.org
www.cilkplus.org
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147784",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "25"
} |
Q: Is there a SAPI module for PHP 5 for supporting the thttpd web server? Is there a SAPI module for PHP 5 for supporting the thttpd web server?
Oddly, the one included on PHP 5.2.6 source is for PHP 4.x.
Thanks,
Kenneth
A: The thttpd SAPI that ships with PHP 5 works. Ignore the README where it says "PHP 4".
However, understand that PHP for thttpd is single-threaded. All other requests will stall while PHP is executing. This is might be acceptable for a low traffic site or embedded application. If not, I recommend trying nginx, another lightweight web server that runs PHP in a separate process via FastCGI.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147798",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Best way to parse float? What is the best way to parse a float in CSharp?
I know about TryParse, but what I'm particularly wondering about is dots, commas etc.
I'm having problems with my website. On my dev server, the ',' is for decimals, the '.' for separator. On the prod server though, it is the other way round.
How can I best capture this?
A: If you want persist values ( numbers, date, time, etc... ) for internal purpose. Everytime use "InvariantCulture" for formating & parsing values. "InvariantCulture" is same on every computer, every OS with any user's culture/language/etc...
string strFloat = (15.789f).ToString(System.Globalization.CultureInfo.InvariantInfo);
float numFloat = float.Parse(System.Globalization.CultureInfo.InvariantInfo, strFloat);
string strNow = DateTime.Now.ToString(System.Globalization.CultureInfo.InvariantInfo);
DateTime now = DateTime.Parse(System.Globalization.CultureInfo.InvariantInfo, strNow);
A: I agree with leppie's reply; to put that in terms of code:
string s = "123,456.789";
float f = float.Parse(s, CultureInfo.InvariantCulture);
A: You could always use the overload of Parse which includes the culture to use?
For instance:
double number = Double.Parse("42,22", new CultureInfo("nl-NL").NumberFormat); // dutch number formatting
If you have control over all your data, you should use "CultureInfo.InvariantCulture" in all of your code.
A: Use a neutral culture (or one you know) when parsing with Try/Parse.
A: Depends where the input is coming from.
If your input comes from the user, you should use the CultureInfo the user/page is using (Thread.CurrentThread.CurrentUICulture).
You can get and indication of the culture of the user, by looking at the HttpRequest.UserLanguages property. (Not correct 100%, but I've found it a very good first guess) With that information, you can set the Thread.CurrentThread.CurrentUICulture at the start of the page.
If your input comes from an internal source, you can use the InvariantCulture to parse the string.
The Parse method is somewhat easier to use, if your input is from a controlled source. That is, you have already validated the string. Parse throws a (slow) exception if its fails.
If the input is uncontrolled, (from the user, or other Internet source) the TryParse looks better to me.
A: Pass in a CultureInfo or NumberFormatInfo that represents the culture you want to parse the float as; this controls what characters are used for decimals, group separators, etc.
For example to ensure that the '.' character was treated as the decimal indicator you could pass in CultureInfo.InvariantCulture (this one is typically very useful in server applications where you tend to want things to be the same irrespective of the environment's culture).
A: Try to avoid float.Parse, use TryParse instead as it performs a lot better but does the same job.
this also applies to double, DateTime, etc...
(some types also offer TryParseExact which also performs even better!)
A: The source is an input from a website. I can't rely on it being valid. So I went with TryParse as mentioned before.
But I can't figure out how to give the currentCulture to it.
Also, this would give me the culture of the server it's currently running on, but since it's the world wide web, the user can be from anywhere...
A: you can know current Cuklture of your server with a simple statement:
System.Globalization.CultureInfo culture = System.Globalization.CultureInfo.CurrentCulture;
Note that there id a CurrentUICulture property, but UICulture is used from ResourceMeanager form multilanguages applications. for number formatting, you must considere CurrentCulture.
I hope this will help you
A: One approach is to force localization to use dot instead of comma separator - this way your code will work identically on all windows machines independently from selected language and settings.
This approach is applicable to small gained applications, like test applications, console applications and so on. For application, which was localization in use this is not so useful, but depends on requirements of application.
var CurrentCultureInfo = new CultureInfo("en", false);
CurrentCultureInfo.NumberFormat.NumberDecimalSeparator = ".";
CurrentCultureInfo.NumberFormat.CurrencyDecimalSeparator = ".";
Thread.CurrentThread.CurrentUICulture = CurrentCultureInfo;
Thread.CurrentThread.CurrentCulture = CurrentCultureInfo;
CultureInfo.DefaultThreadCurrentCulture = CurrentCultureInfo;
This code forces to use dot ('.') instead of comma, needs to be placed at application startup.
A: Since you don't know the web user's culture, you can do some guesswork. TryParse with a culture that uses , for separators and . for decimal, AND TryParse with a culture that uses . for separators and , for decimal. If they both succeed but yield different answers then you'll have to ask the user which they intended. Otherwise you can proceed normally, given your two equal results or one usable result or no usable result.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147801",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "47"
} |
Q: Why does Swing in my Java Applet flicker on fast mouse over? I made a Java Applet with some Standard GUI Components on it. I used the MigLayout Manager.
If I move the mouse slowly over the various GUI Components everything appears to be fine, but if I move the mouse fast, it flickers.
What could make that nasty ugly redraw?
(Core 2 Duo 6300, 2GB Ram, Windows XP)
A: One thought would be to check your code (and/or the MigLayout code) for unnecessary repaint() operations.
Custom UIs and layouts can cause weird problems sometimes...
A: you could use double buffering in java applet to improve screen refreshing speed. ask more if details needed..
A: I found the bugger:
I used a custom ClosableTabbedPaint Class.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147802",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Preserving signatures of decorated functions Suppose I have written a decorator that does something very generic. For example, it might convert all arguments to a specific type, perform logging, implement memoization, etc.
Here is an example:
def args_as_ints(f):
def g(*args, **kwargs):
args = [int(x) for x in args]
kwargs = dict((k, int(v)) for k, v in kwargs.items())
return f(*args, **kwargs)
return g
@args_as_ints
def funny_function(x, y, z=3):
"""Computes x*y + 2*z"""
return x*y + 2*z
>>> funny_function("3", 4.0, z="5")
22
Everything well so far. There is one problem, however. The decorated function does not retain the documentation of the original function:
>>> help(funny_function)
Help on function g in module __main__:
g(*args, **kwargs)
Fortunately, there is a workaround:
def args_as_ints(f):
def g(*args, **kwargs):
args = [int(x) for x in args]
kwargs = dict((k, int(v)) for k, v in kwargs.items())
return f(*args, **kwargs)
g.__name__ = f.__name__
g.__doc__ = f.__doc__
return g
@args_as_ints
def funny_function(x, y, z=3):
"""Computes x*y + 2*z"""
return x*y + 2*z
This time, the function name and documentation are correct:
>>> help(funny_function)
Help on function funny_function in module __main__:
funny_function(*args, **kwargs)
Computes x*y + 2*z
But there is still a problem: the function signature is wrong. The information "*args, **kwargs" is next to useless.
What to do? I can think of two simple but flawed workarounds:
1 -- Include the correct signature in the docstring:
def funny_function(x, y, z=3):
"""funny_function(x, y, z=3) -- computes x*y + 2*z"""
return x*y + 2*z
This is bad because of the duplication. The signature will still not be shown properly in automatically generated documentation. It's easy to update the function and forget about changing the docstring, or to make a typo. [And yes, I'm aware of the fact that the docstring already duplicates the function body. Please ignore this; funny_function is just a random example.]
2 -- Not use a decorator, or use a special-purpose decorator for every specific signature:
def funny_functions_decorator(f):
def g(x, y, z=3):
return f(int(x), int(y), z=int(z))
g.__name__ = f.__name__
g.__doc__ = f.__doc__
return g
This works fine for a set of functions that have identical signature, but it's useless in general. As I said in the beginning, I want to be able to use decorators entirely generically.
I'm looking for a solution that is fully general, and automatic.
So the question is: is there a way to edit the decorated function signature after it has been created?
Otherwise, can I write a decorator that extracts the function signature and uses that information instead of "*kwargs, **kwargs" when constructing the decorated function? How do I extract that information? How should I construct the decorated function -- with exec?
Any other approaches?
A: *
*Install decorator module:
$ pip install decorator
*Adapt definition of args_as_ints():
import decorator
@decorator.decorator
def args_as_ints(f, *args, **kwargs):
args = [int(x) for x in args]
kwargs = dict((k, int(v)) for k, v in kwargs.items())
return f(*args, **kwargs)
@args_as_ints
def funny_function(x, y, z=3):
"""Computes x*y + 2*z"""
return x*y + 2*z
print funny_function("3", 4.0, z="5")
# 22
help(funny_function)
# Help on function funny_function in module __main__:
#
# funny_function(x, y, z=3)
# Computes x*y + 2*z
Python 3.4+
functools.wraps() from stdlib preserves signatures since Python 3.4:
import functools
def args_as_ints(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
args = [int(x) for x in args]
kwargs = dict((k, int(v)) for k, v in kwargs.items())
return func(*args, **kwargs)
return wrapper
@args_as_ints
def funny_function(x, y, z=3):
"""Computes x*y + 2*z"""
return x*y + 2*z
print(funny_function("3", 4.0, z="5"))
# 22
help(funny_function)
# Help on function funny_function in module __main__:
#
# funny_function(x, y, z=3)
# Computes x*y + 2*z
functools.wraps() is available at least since Python 2.5 but it does not preserve the signature there:
help(funny_function)
# Help on function funny_function in module __main__:
#
# funny_function(*args, **kwargs)
# Computes x*y + 2*z
Notice: *args, **kwargs instead of x, y, z=3.
A: There is a decorator module with decorator decorator you can use:
@decorator
def args_as_ints(f, *args, **kwargs):
args = [int(x) for x in args]
kwargs = dict((k, int(v)) for k, v in kwargs.items())
return f(*args, **kwargs)
Then the signature and help of the method is preserved:
>>> help(funny_function)
Help on function funny_function in module __main__:
funny_function(x, y, z=3)
Computes x*y + 2*z
EDIT: J. F. Sebastian pointed out that I didn't modify args_as_ints function -- it is fixed now.
A: Take a look at the decorator module - specifically the decorator decorator, which solves this problem.
A: Second option:
*
*Install wrapt module:
$ easy_install wrapt
wrapt have a bonus, preserve class signature.
import wrapt
import inspect
@wrapt.decorator
def args_as_ints(wrapped, instance, args, kwargs):
if instance is None:
if inspect.isclass(wrapped):
# Decorator was applied to a class.
return wrapped(*args, **kwargs)
else:
# Decorator was applied to a function or staticmethod.
return wrapped(*args, **kwargs)
else:
if inspect.isclass(instance):
# Decorator was applied to a classmethod.
return wrapped(*args, **kwargs)
else:
# Decorator was applied to an instancemethod.
return wrapped(*args, **kwargs)
@args_as_ints
def funny_function(x, y, z=3):
"""Computes x*y + 2*z"""
return x * y + 2 * z
>>> funny_function(3, 4, z=5))
# 22
>>> help(funny_function)
Help on function funny_function in module __main__:
funny_function(x, y, z=3)
Computes x*y + 2*z
A: As commented above in jfs's answer ; if you're concerned with signature in terms of appearance (help, and inspect.signature), then using functools.wraps is perfectly fine.
If you're concerned with signature in terms of behavior (in particular TypeError in case of arguments mismatch), functools.wraps does not preserve it. You should rather use decorator for that, or my generalization of its core engine, named makefun.
from makefun import wraps
def args_as_ints(func):
@wraps(func)
def wrapper(*args, **kwargs):
print("wrapper executes")
args = [int(x) for x in args]
kwargs = dict((k, int(v)) for k, v in kwargs.items())
return func(*args, **kwargs)
return wrapper
@args_as_ints
def funny_function(x, y, z=3):
"""Computes x*y + 2*z"""
return x*y + 2*z
print(funny_function("3", 4.0, z="5"))
# wrapper executes
# 22
help(funny_function)
# Help on function funny_function in module __main__:
#
# funny_function(x, y, z=3)
# Computes x*y + 2*z
funny_function(0)
# observe: no "wrapper executes" is printed! (with functools it would)
# TypeError: funny_function() takes at least 2 arguments (1 given)
See also this post about functools.wraps.
A: This is solved with Python's standard library functools and specifically functools.wraps function, which is designed to "update a wrapper function to look like the wrapped function". It's behaviour depends on Python version, however, as shown below. Applied to the example from the question, the code would look like:
from functools import wraps
def args_as_ints(f):
@wraps(f)
def g(*args, **kwargs):
args = [int(x) for x in args]
kwargs = dict((k, int(v)) for k, v in kwargs.items())
return f(*args, **kwargs)
return g
@args_as_ints
def funny_function(x, y, z=3):
"""Computes x*y + 2*z"""
return x*y + 2*z
When executed in Python 3, this would produce the following:
>>> funny_function("3", 4.0, z="5")
22
>>> help(funny_function)
Help on function funny_function in module __main__:
funny_function(x, y, z=3)
Computes x*y + 2*z
Its only drawback is that in Python 2 however, it doesn't update function's argument list. When executed in Python 2, it will produce:
>>> help(funny_function)
Help on function funny_function in module __main__:
funny_function(*args, **kwargs)
Computes x*y + 2*z
A: from inspect import signature
def args_as_ints(f):
def g(*args, **kwargs):
args = [int(x) for x in args]
kwargs = dict((k, int(v)) for k, v in kwargs.items())
return f(*args, **kwargs)
sig = signature(f)
g.__signature__ = sig
g.__doc__ = f.__doc__
g.__annotations__ = f.__annotations__
g.__name__ = f.__name__
return g
@args_as_ints
def funny_function(x, y, z=3):
"""Computes x*y + 2*z"""
return x*y + 2*z
>>> funny_function("3", 4.0, z="5")
22
I wanted to add that answer (since this shows up first in google). The inspect module is able to fetch the signature of a function, so that it can be preserved in decorators. But that's not all. If you want to modify the signature, you can do so like this :
from inspect import signature, Parameter, _ParameterKind
def foo(a: int, b: int) -> int:
return a + b
sig = signature(foo)
sig._parameters = dict(sig.parameters)
sig.parameters['c'] = Parameter(
'c', _ParameterKind.POSITIONAL_OR_KEYWORD,
annotation=int
)
foo.__signature__ = sig
>>> help(foo)
Help on function foo in module __main__:
foo(a: int, b: int, c: int) -> int
Why would you want to mutate a function's signature ?
It's mostly useful to have adequate documentation on your functions and methods. If you're using the *args, **kwargs syntax and then popping arguments from kwargs for other uses in your decorators, that keyword argument won't be properly documented, hence, modifying the signature of the function.
A: def args_as_ints(f):
def g(*args, **kwargs):
args = [int(x) for x in args]
kwargs = dict((k, int(v)) for k, v in kwargs.items())
return f(*args, **kwargs)
g.__name__ = f.__name__
g.__doc__ = f.__doc__
return g
this fixes name and documentation. to preserve the function signature, wrap is used exactly at same location as g.__name__ = f.__name__, g.__doc__ = f.__doc__.
the wraps itself a decorator. we pass the closure-the inner function to that decorator, and it is going to fix up the metadata. BUt if we only pass in the inner function to wraps, it is not gonna know where to copy the metadata from. It needs to know which function's metadata needs to be protected. It needs to know the original function.
def args_as_ints(f):
def g(*args, **kwargs):
args = [int(x) for x in args]
kwargs = dict((k, int(v)) for k, v in kwargs.items())
return f(*args, **kwargs)
g=wraps(f)(g)
return g
wraps(f) is going to return a function which will take g as its parameter. And that is going to return closure and will assigned to g and then we return it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147816",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "135"
} |
Q: Loading .sql files from within PHP I'm creating an installation script for an application that I'm developing and need to create databases dynamically from within PHP. I've got it to create the database but now I need to load in several .sql files. I had planned to open the file and mysql_query it a line at a time - until I looked at the schema files and realised they aren't just one query per line.
So, how do I load an sql file from within PHP (as phpMyAdmin does with its import command)?
A: Since I can't comment on answer, beware to use following solution:
$db = new PDO($dsn, $user, $password);
$sql = file_get_contents('file.sql');
$qr = $db->exec($sql);
There is a bug in PHP PDO https://bugs.php.net/bug.php?id=61613
db->exec('SELECT 1; invalidstatement; SELECT 2');
won't error out or return false (tested on PHP 5.5.14).
A: $db = new PDO($dsn, $user, $password);
$sql = file_get_contents('file.sql');
$qr = $db->exec($sql);
A: phpBB uses a few functions to parse their files. They are rather well-commented (what an exception!) so you can easily know what they do (I got this solution from http://www.frihost.com/forums/vt-8194.html). here is the solution an I've used it a lot:
<?php
ini_set('memory_limit', '5120M');
set_time_limit ( 0 );
/***************************************************************************
* sql_parse.php
* -------------------
* begin : Thu May 31, 2001
* copyright : (C) 2001 The phpBB Group
* email : support@phpbb.com
*
* $Id: sql_parse.php,v 1.8 2002/03/18 23:53:12 psotfx Exp $
*
****************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
/***************************************************************************
*
* These functions are mainly for use in the db_utilities under the admin
* however in order to make these functions available elsewhere, specifically
* in the installation phase of phpBB I have seperated out a couple of
* functions into this file. JLH
*
\***************************************************************************/
//
// remove_comments will strip the sql comment lines out of an uploaded sql file
// specifically for mssql and postgres type files in the install....
//
function remove_comments(&$output)
{
$lines = explode("\n", $output);
$output = "";
// try to keep mem. use down
$linecount = count($lines);
$in_comment = false;
for($i = 0; $i < $linecount; $i++)
{
if( preg_match("/^\/\*/", preg_quote($lines[$i])) )
{
$in_comment = true;
}
if( !$in_comment )
{
$output .= $lines[$i] . "\n";
}
if( preg_match("/\*\/$/", preg_quote($lines[$i])) )
{
$in_comment = false;
}
}
unset($lines);
return $output;
}
//
// remove_remarks will strip the sql comment lines out of an uploaded sql file
//
function remove_remarks($sql)
{
$lines = explode("\n", $sql);
// try to keep mem. use down
$sql = "";
$linecount = count($lines);
$output = "";
for ($i = 0; $i < $linecount; $i++)
{
if (($i != ($linecount - 1)) || (strlen($lines[$i]) > 0))
{
if (isset($lines[$i][0]) && $lines[$i][0] != "#")
{
$output .= $lines[$i] . "\n";
}
else
{
$output .= "\n";
}
// Trading a bit of speed for lower mem. use here.
$lines[$i] = "";
}
}
return $output;
}
//
// split_sql_file will split an uploaded sql file into single sql statements.
// Note: expects trim() to have already been run on $sql.
//
function split_sql_file($sql, $delimiter)
{
// Split up our string into "possible" SQL statements.
$tokens = explode($delimiter, $sql);
// try to save mem.
$sql = "";
$output = array();
// we don't actually care about the matches preg gives us.
$matches = array();
// this is faster than calling count($oktens) every time thru the loop.
$token_count = count($tokens);
for ($i = 0; $i < $token_count; $i++)
{
// Don't wanna add an empty string as the last thing in the array.
if (($i != ($token_count - 1)) || (strlen($tokens[$i] > 0)))
{
// This is the total number of single quotes in the token.
$total_quotes = preg_match_all("/'/", $tokens[$i], $matches);
// Counts single quotes that are preceded by an odd number of backslashes,
// which means they're escaped quotes.
$escaped_quotes = preg_match_all("/(?<!\\\\)(\\\\\\\\)*\\\\'/", $tokens[$i], $matches);
$unescaped_quotes = $total_quotes - $escaped_quotes;
// If the number of unescaped quotes is even, then the delimiter did NOT occur inside a string literal.
if (($unescaped_quotes % 2) == 0)
{
// It's a complete sql statement.
$output[] = $tokens[$i];
// save memory.
$tokens[$i] = "";
}
else
{
// incomplete sql statement. keep adding tokens until we have a complete one.
// $temp will hold what we have so far.
$temp = $tokens[$i] . $delimiter;
// save memory..
$tokens[$i] = "";
// Do we have a complete statement yet?
$complete_stmt = false;
for ($j = $i + 1; (!$complete_stmt && ($j < $token_count)); $j++)
{
// This is the total number of single quotes in the token.
$total_quotes = preg_match_all("/'/", $tokens[$j], $matches);
// Counts single quotes that are preceded by an odd number of backslashes,
// which means they're escaped quotes.
$escaped_quotes = preg_match_all("/(?<!\\\\)(\\\\\\\\)*\\\\'/", $tokens[$j], $matches);
$unescaped_quotes = $total_quotes - $escaped_quotes;
if (($unescaped_quotes % 2) == 1)
{
// odd number of unescaped quotes. In combination with the previous incomplete
// statement(s), we now have a complete statement. (2 odds always make an even)
$output[] = $temp . $tokens[$j];
// save memory.
$tokens[$j] = "";
$temp = "";
// exit the loop.
$complete_stmt = true;
// make sure the outer loop continues at the right point.
$i = $j;
}
else
{
// even number of unescaped quotes. We still don't have a complete statement.
// (1 odd and 1 even always make an odd)
$temp .= $tokens[$j] . $delimiter;
// save memory.
$tokens[$j] = "";
}
} // for..
} // else
}
}
return $output;
}
$dbms_schema = 'yourfile.sql';
$sql_query = @fread(@fopen($dbms_schema, 'r'), @filesize($dbms_schema)) or die('problem ');
$sql_query = remove_remarks($sql_query);
$sql_query = split_sql_file($sql_query, ';');
$host = 'localhost';
$user = 'user';
$pass = 'pass';
$db = 'database_name';
// mysql_* is deprecated, prefer using mysqli_* instead
// mysql_connect($host,$user,$pass) or die('error connection');
// mysql_select_db($db) or die('error database selection');
$connection = mysqli_connect($host,$user,$pass) or die('error connection');
mysqli_select_db($connection, $db) or die('error database selection');
$i=1;
foreach($sql_query as $sql){
echo $i++;
echo "<br />";
// mysql_* is deprecated, prefer using mysqli_* instead
// mysql_query($sql) or die('error in query');
mysqli_query($connection, $sql) or die('error in query');
}
A: I'm getting the feeling that everyone here who's answered this question doesn't know what it's like to be a web application developer who allows people to install the application on their own servers. Shared hosting, especially, doesn't allow you to use SQL like the "LOAD DATA" query mentioned previously. Most shared hosts also don't allow you to use shell_exec.
Now, to answer the OP, your best bet is to just build out a PHP file that contains your queries in a variable and can just run them. If you're determined to parse .sql files, you should look into phpMyAdmin and get some ideas for getting data out of .sql files that way. Look around at other web applications that have installers and you'll see that, rather than use .sql files for their queries, they just package them up in PHP files and just run each string through mysql_query or whatever it is that they need to do.
A: My suggestion would be to look at the sourcecode of PHPMyBackup. It's an automated PHP SQL loader. You will find that mysql_query only loads one query at a time, and projects like PHPMyAdmin and PHPMyBackup have already done the hard work for you of parsing the SQL the correct way. Please don't re-invent that wheel :P
A: mysql_query("LOAD DATA LOCAL INFILE '/path/to/file' INTO TABLE mytable");
A: An updated solution of Plahcinski solution. Alternatively you can use fopen and fread for bigger files:
$fp = file('database.sql', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$query = '';
foreach ($fp as $line) {
if ($line != '' && strpos($line, '--') === false) {
$query .= $line;
if (substr($query, -1) == ';') {
mysql_query($query);
$query = '';
}
}
}
A: Briefly, the way I have done this is:
*
*Read the file (a db dump eg $ mysqldump db > db.sql)
$sql = file_get_contents(db.sql);
*Import it using mysqli::multi_query
if ($mysqli->multi_query($sql)) {
$mysqli->close();
} else {
throw new Exception ($mysqli->error);
}
Watch out mysqli_query supports async queries. More here: http://php.net/manual/en/mysqli.multi-query.php and here https://stackoverflow.com/a/6652908/2002493
A: The simplest solution is to use shell_exec() to run the mysql client with the SQL script as input. This might run a little slower because it has to fork, but you can write the code in a couple of minutes and then get back to working on something useful. Writing a PHP script to run any SQL script could take you weeks.
Supporting SQL scripts is more complex than what people are describing here, unless you're certain that your script contains only a subset of the functionality of scripts. Below are some examples of things that may appear in an ordinary SQL script that make it complex to code a script to interpret it line by line.
-- Comment lines cannot be prepared as statements
-- This is a MySQL client tool builtin command.
-- It cannot be prepared or executed by server.
USE testdb;
-- This is a multi-line statement.
CREATE TABLE foo (
string VARCHAR(100)
);
-- This statement is not supported as a prepared statement.
LOAD DATA INFILE 'datafile.txt' INTO TABLE foo;
-- This statement is not terminated with a semicolon.
DELIMITER //
-- This multi-line statement contains a semicolon
-- but not as the statement terminator.
CREATE PROCEDURE simpleproc (OUT param1 INT)
BEGIN
SELECT COUNT(*) INTO param1 FROM foo;
END
//
If you only support a subset of SQL scripts, excluding some corner cases such as those above, it's relatively easy to write a PHP script that reads a file and executes the SQL statements within the file. But if you want to support any valid SQL script, that's much more complex.
See also my answers to these related questions:
*
*Running MySQL *.sql files in PHP
*is it possible to call a sql script from a stored procedure in another sql script?
*PHP: multiple SQL queries in one mysql_query statement
A: Are you sure that its not one query per line? Your text editor may be wrapping lines, but in reality each query may be on a single line.
At any rate, olle's method seems best. If you have reasons to run queries one at time, you should be able to read in your file line by line, then use the semicolon at the end of each query to delimit. You're much better off reading in a file line by line than trying to split an enormous string, as it will be much kinder to your server's memory. Example:
$query = '';
$handle = @fopen("/sqlfile.sql", "r");
if ($handle) {
while (!feof($handle)) {
$query.= fgets($handle, 4096);
if (substr(rtrim($query), -1) === ';') {
// ...run your query, then unset the string
$query = '';
}
}
fclose($handle);
}
Obviously, you'll need to consider transactions and the rest if you're running a whole lot of queries in a batch, but it's probably not a big deal for a new-install script.
A: I noticed that the PostgreSQL PDO driver does not allow you to run scripts separated by semicolons. In order to run a .sql file on any database using PDO it is necessary to split the statements in PHP code yourself. Here is a solution that seems to work quite well:
https://github.com/diontruter/migrate/blob/master/src/Diontruter/Migrate/SqlScriptParser.php
The referenced class has done the trick for me in a database independent way, please message me if there are any issues. Here is how you could use the script after adding it to your project:
$pdo = new PDO($connectionString, $userName, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$parser = new SqlScriptParser();
$sqlStatements = $parser->parse($fileName);
foreach ($sqlStatements as $statement) {
$distilled = $parser->removeComments($statement);
if (!empty($distilled)) {
$statement = $pdo->prepare($sql);
$affectedRows = $statement->execute();
}
}
A: Unless you plan to import huge .sql files, just read the entire file into memory, and run it as a query.
It's been a while since I've used PHP, so, pseudo code:
all_query = read_file("/my/file.sql")
con = mysql_connect("localhost")
con.mysql_select_db("mydb")
con.mysql_query(all_query)
con.close()
Unless the files are huge (say, over several megabytes), there's no reason to execute it line-at-a-time, or try and split it into multiple queries (by splitting using ;, which as I commented on cam8001's answer, will break if the query has semi-colons within strings)..
A: Works on Navicat dumps. Might need to dump the first /* */ comment navicat puts in.
$file_content = file('myfile.sql');
$query = "";
foreach($file_content as $sql_line){
if(trim($sql_line) != "" && strpos($sql_line, "--") === false){
$query .= $sql_line;
if (substr(rtrim($query), -1) == ';'){
echo $query;
$result = mysql_query($query)or die(mysql_error());
$query = "";
}
}
}
A: This The Best Code For restore sql by php can use 100% Goooood!
Thank A lot
$file_content = file('myfile.sql');
$query = "";
foreach($file_content as $sql_line){
if(trim($sql_line) != "" && strpos($sql_line, "--") === false){
$query .= $sql_line;
if (substr(rtrim($query), -1) == ';'){
echo $query;
$result = mysql_query($query)or die(mysql_error());
$query = "";
}
}
}
A: Try This:
// SQL File
$SQLFile = 'YourSQLFile.sql';
// Server Name
$hostname = 'localhost';
// User Name
$db_user = 'root';
// User Password
$db_password = '';
// DBName
$database_name = 'YourDBName';
// Connect MySQL
$link = mysql_connect($hostname, $db_user, $db_password);
if (!$link) {
die("MySQL Connection error");
}
// Select MySQL DB
mysql_select_db($database_name, $link) or die("Wrong MySQL Database");
// Function For Run Multiple Query From .SQL File
function MultiQuery($sqlfile, $sqldelimiter = ';') {
set_time_limit(0);
if (is_file($sqlfile) === true) {
$sqlfile = fopen($sqlfile, 'r');
if (is_resource($sqlfile) === true) {
$query = array();
echo "<table cellspacing='3' cellpadding='3' border='0'>";
while (feof($sqlfile) === false) {
$query[] = fgets($sqlfile);
if (preg_match('~' . preg_quote($sqldelimiter, '~') . '\s*$~iS', end($query)) === 1) {
$query = trim(implode('', $query));
if (mysql_query($query) === false) {
echo '<tr><td>ERROR:</td><td> ' . $query . '</td></tr>';
} else {
echo '<tr><td>SUCCESS:</td><td>' . $query . '</td></tr>';
}
while (ob_get_level() > 0) {
ob_end_flush();
}
flush();
}
if (is_string($query) === true) {
$query = array();
}
}
echo "</table>";
return fclose($sqlfile);
}
}
return false;
}
/* * * Use Function Like This: ** */
MultiQuery($SQLFile);
A: The easiest and fastest way to load & parse phpmyadmin dump or mysql dump file..
$ mysql -u username -p -h localhost dbname < dumpfile.sql
A: In my projects I've used next solution:
<?php
/**
* Import SQL from file
*
* @param string path to sql file
*/
function sqlImport($file)
{
$delimiter = ';';
$file = fopen($file, 'r');
$isFirstRow = true;
$isMultiLineComment = false;
$sql = '';
while (!feof($file)) {
$row = fgets($file);
// remove BOM for utf-8 encoded file
if ($isFirstRow) {
$row = preg_replace('/^\x{EF}\x{BB}\x{BF}/', '', $row);
$isFirstRow = false;
}
// 1. ignore empty string and comment row
if (trim($row) == '' || preg_match('/^\s*(#|--\s)/sUi', $row)) {
continue;
}
// 2. clear comments
$row = trim(clearSQL($row, $isMultiLineComment));
// 3. parse delimiter row
if (preg_match('/^DELIMITER\s+[^ ]+/sUi', $row)) {
$delimiter = preg_replace('/^DELIMITER\s+([^ ]+)$/sUi', '$1', $row);
continue;
}
// 4. separate sql queries by delimiter
$offset = 0;
while (strpos($row, $delimiter, $offset) !== false) {
$delimiterOffset = strpos($row, $delimiter, $offset);
if (isQuoted($delimiterOffset, $row)) {
$offset = $delimiterOffset + strlen($delimiter);
} else {
$sql = trim($sql . ' ' . trim(substr($row, 0, $delimiterOffset)));
query($sql);
$row = substr($row, $delimiterOffset + strlen($delimiter));
$offset = 0;
$sql = '';
}
}
$sql = trim($sql . ' ' . $row);
}
if (strlen($sql) > 0) {
query($row);
}
fclose($file);
}
/**
* Remove comments from sql
*
* @param string sql
* @param boolean is multicomment line
* @return string
*/
function clearSQL($sql, &$isMultiComment)
{
if ($isMultiComment) {
if (preg_match('#\*/#sUi', $sql)) {
$sql = preg_replace('#^.*\*/\s*#sUi', '', $sql);
$isMultiComment = false;
} else {
$sql = '';
}
if(trim($sql) == ''){
return $sql;
}
}
$offset = 0;
while (preg_match('{--\s|#|/\*[^!]}sUi', $sql, $matched, PREG_OFFSET_CAPTURE, $offset)) {
list($comment, $foundOn) = $matched[0];
if (isQuoted($foundOn, $sql)) {
$offset = $foundOn + strlen($comment);
} else {
if (substr($comment, 0, 2) == '/*') {
$closedOn = strpos($sql, '*/', $foundOn);
if ($closedOn !== false) {
$sql = substr($sql, 0, $foundOn) . substr($sql, $closedOn + 2);
} else {
$sql = substr($sql, 0, $foundOn);
$isMultiComment = true;
}
} else {
$sql = substr($sql, 0, $foundOn);
break;
}
}
}
return $sql;
}
/**
* Check if "offset" position is quoted
*
* @param int $offset
* @param string $text
* @return boolean
*/
function isQuoted($offset, $text)
{
if ($offset > strlen($text))
$offset = strlen($text);
$isQuoted = false;
for ($i = 0; $i < $offset; $i++) {
if ($text[$i] == "'")
$isQuoted = !$isQuoted;
if ($text[$i] == "\\" && $isQuoted)
$i++;
}
return $isQuoted;
}
function query($sql)
{
global $mysqli;
//echo '#<strong>SQL CODE TO RUN:</strong><br>' . htmlspecialchars($sql) . ';<br><br>';
if (!$query = $mysqli->query($sql)) {
throw new Exception("Cannot execute request to the database {$sql}: " . $mysqli->error);
}
}
set_time_limit(0);
$mysqli = new mysqli('localhost', 'root', '', 'test');
$mysqli->set_charset("utf8");
header('Content-Type: text/html;charset=utf-8');
sqlImport('import.sql');
echo "Peak MB: ", memory_get_peak_usage(true)/1024/1024;
On test sql file (41Mb) memory peak usage: 3.25Mb
A: mysqli can run multiple queries separated by a ;
you could read in the whole file and run it all at once using mysqli_multi_query()
But, I'll be the first to say that this isn't the most elegant solution.
A: None of the solutions I have seen here deal with needing to change the delimiter while creating a stored procedure on a server where I can't count on having access to LOAD DATA INFILE. I was hoping to find that someone had already solved this without having to scour the phpMyAdmin code to figure it out. Like others, I too was in the process of looking for someone else's GPL'ed way of doing it since I am writing GPL code myself.
A: Some PHP libraries can parse a SQL file made of multiple SQL statements, explode it properly (not using a simple ";" explode, naturally), and the execute them.
For instance, check Phing's PDOSQLExecTask
A: Just to restate the problem for everyone:
PHP's mysql_query, automatically end-delimits each SQL commands, and additionally is very vague about doing so in its manual. Everything beyond one command will yield an error.
On the other mysql_query is fine with a string containing SQL-style comments, \n, \r..
The limitation of mysql_query reveals itself in that the SQL parser reports the problem to be directly at the next command e.g.
You have an error in your SQL syntax; check the manual that corresponds to your
MySQL server version for the right syntax to use near 'INSERT INTO `outputdb:`
(`intid`, `entry_id`, `definition`) VALUES...
Here is a quick solution:
(assuming well formatted SQL;
$sqlCmds = preg_split("/[\n|\t]*;[\n|\t]*[\n|\r]$/", $sqlDump);
A: Many hosts will not allow you to create your own database through PHP, but you seem to have solved that.
Once the DB has been created, you can manipulate and populate it simply:
mysql_connect("localhost");
mysql_query("SOURCE file.sql");
A: Some guys (Plahcinski) suggested this code:
$file_content = file('myfile.sql');
$query = "";
foreach($file_content as $sql_line){
if(trim($sql_line) != "" && strpos($sql_line, "--") === false){
$query .= $sql_line;
if (substr(rtrim($query), -1) == ';'){
echo $query;
$result = mysql_query($query)or die(mysql_error());
$query = "";
}
}
}
but I would update it with the one which worked for me:
//selecting my database
$database = 'databaseTitleInFile';
$selectDatabase = mysql_select_db($database, $con);
if(! $selectDatabase )
{
die('Could not select the database: ' . mysql_error());
}
echo "The database " . $database . " selected successfully\n";
//reading the file
$file_path='..\yourPath\to\File';
if(!file_exists($file_path)){
echo "File Not Exists";
}
$file_content = file_get_contents($file_path);
$array = explode("\n", $file_content)
//making queries
$query = "";
foreach($array as $sql_line){
$sql_line=trim($sql_line);
if($sql_line != "" && substr($sql_line, 0, 2) === "--" && strpos($sql_line, "/*") === false){
$query .= $sql_line;
if (substr(rtrim($query), -1) == ';'){
$result = mysql_query($query)or die(mysql_error());
$query = "";
}
}
}
because it is more comprehensive. ;-)
A: This may be helpful -->
More or less what it does is to first take the string given to the function (the file_get_contents() value of your file.sql) and remove all the line breaks. Then it splits the data by the ";" character. Next it goes into a while loop, looking at each line of the array that is created. If the line contains the " ` " character, it will know it is a query and execture the myquery() function for the given line data.
Code:
function myquery($query) {
mysql_connect(dbhost, dbuser, dbpass);
mysql_select_db(dbname);
$result = mysql_query($query);
if (!mysql_errno() && @mysql_num_rows($result) > 0) {
}
else {
$result="not";
}
mysql_close();
return $result;
}
function mybatchquery ($str) {
$sql = str_replace("\n","",$str)
$sql = explode(";",$str);
$x=0;
while (isset($str[$x])) {
if (preg_match("/(\w|\W)+`(\w|\W)+) {
myquery($str[$x]);
}
$x++
}
return TRUE;
}
function myrows($result) {
$rows = @mysql_num_rows($result);
return $rows;
}
function myarray($result) {
$array = mysql_fetch_array($result);
return $array;
}
function myescape($query) {
$escape = mysql_escape_string($query);
return $escape;
}
$str = file_get_contents("foo.sql");
mybatchquery($str);
A: $sql = file_get_contents("sql.sql");
Seems to be the simplest answer
A: I use this all the time:
$sql = explode(";",file_get_contents('[your dump file].sql'));//
foreach($sql as $query)
mysql_query($query);
A: I hope the following code will solve your problem pretty well.
//Empty all tables' contents
$result_t = mysql_query("SHOW TABLES");
while($row = mysql_fetch_assoc($result_t))
{
mysql_query("TRUNCATE " . $row['Tables_in_' . $mysql_database]);
}
// Temporary variable, used to store current query
$templine = '';
// Read in entire file
$lines = file($filename);
// Loop through each line
foreach ($lines as $line)
{
// Skip it if it's a comment
if (substr($line, 0, 2) == '--' || $line == '')
continue;
// Add this line to the current segment
$templine .= $line;
// If it has a semicolon at the end, it's the end of the query
if (substr(trim($line), -1, 1) == ';')
{
// Perform the query
mysql_query($templine) or print('Error performing query \'<strong>' . $templine . '\': ' . mysql_error() . '<br /><br />');
// Reset temp variable to empty
$templine = '';
}
}
?>
A: this actually worked for me:
/* load sql-commands from a sql file */
function loadSQLFromFile($url)
{
// ini_set ( 'memory_limit', '512M' );
// set_time_limit ( 0 );
global $settings_database_name;
global $mysqli_object; global $worked; $worked = false;
$sql_query = "";
// read line by line
$lines = file($url);
$count = count($lines);
for($i = 0;$i<$count;$i++)
{
$line = $lines[$i];
$cmd3 = substr($line, 0, 3);
$cmd4 = substr($line, 0, 4);
$cmd6 = substr($line, 0, 6);
if($cmd3 == "USE")
{
// cut away USE ``;
$settings_database_name = substr($line, 5, -3);
}
else if($cmd4 == "DROP")
{
$mysqli_object->query($line); // execute this line
}
else if(($cmd6 == "INSERT") || ($cmd6 == "CREATE"))
{
// sum all lines up until ; is detected
$multiline = $line;
while(!strstr($line, ';'))
{
$i++;
$line = $lines[$i];
$multiline .= $line;
}
$multiline = str_replace("\n", "", $multiline); // remove newlines/linebreaks
$mysqli_object->query($multiline); // execute this line
}
}
return $worked;
}
?>
A: I have an environment where no mysql tool or phpmyadmin just my php application connecting to a mysql server on a different host but I need to run scripts exported by mysqldump or myadmin. To solve the problem I created a script multi_query as I mentioned here
It can process mysqldump output and phpmyadmin exports without mysql command line tool. I also made some logic to process multiple migration files based on timestamp stored in DB like Rails. I know it needs more error handling but currently does the work for me.
Check it out: https://github.com/kepes/php-migration
It's pure php and don't need any other tools. If you don't process user input with it only scripts made by developers or export tools you can use it safely.
A: This is from a project I am working on. Basically takes any text file and extracts the SQL statements while ignoring comments and gratuitous line breaks.
<?php
/*
ingestSql(string) : string
Read the contents of a SQL batch file, stripping away comments and
joining statements that are broken over multiple lines with the goal
of producing lines of sql statements that can be successfully executed
by PDO exec() or execute() functions.
For example:
-- My SQL Batch
CREATE TABLE foo(
bar VARCHAR(80),
baz INT NOT NULL);
Becomes:
CREATE TABLE foo(bar VARCHAR(80), baz INT NOT NULL);
*/
function ingestSql($sqlFilePath=__DIR__ . "/create-db.sql") {
$sqlFile = file($sqlFilePath);
$ingestedSql = "";
$statement = "";
foreach($sqlFile as $line) {
// Ignore anything between a double-dash and the end of the line.
$commentStart = strpos($line, "--");
if ($commentStart !== false) {
$line = substr($line, 0, $commentStart);
}
// Only process non-blank lines.
if (strlen($line)) {
// Remove any leading and trailing whitespace and append what's
// left of the line to the current statement.
$line = trim($line);
$statement .= $line;
// A semi-colon ends the current statement. Otherwise what was a
// newline becomes a single space;
if (substr($statement, -1) == ";") {
$ingestedSql .= $statement;
$statement = "\n";
}
else {
$statement .= " ";
}
}
}
return $ingestedSql;
}
?>
A: PHP Code
The code I found on this page worked for me. This code can load a specified SQL file and import it into a MySQL database. I tested this code with a WordPress database exported to SQL using phpMyAdmin and it worked fine.
(Scroll down to see the commented version)
<?php
$conn = new mysqli('localhost', 'root', '' , 'sql_auto_test_table');
$query = '';
$sqlScript = file('sqlFileName.sql');
foreach ($sqlScript as $line) {
$startWith = substr(trim($line), 0 ,2);
$endWith = substr(trim($line), -1 ,1);
if (empty($line) || $startWith == '--' || $startWith == '/*' || $startWith == '//') {
continue;
}
$query = $query . $line . "/*<br>*/";
if ($endWith == ';') {
mysqli_query($conn,$query) or die('<div>Problem in executing the SQL query <b>,<br><br>' . $query. '</b><br><br>'.$conn->error.'</div>');
$query= '';
}
}
echo '<div>SQL file imported successfully</div>';
?>
Potential Fixes
I had to add the following lines at the top of the .sql file to avoid a few DEFAULT VALUE errors in some DATE columns. Alternatively, you can try executing the following queries before executing your SQL file if you receive a similar error.
SET GLOBAL sql_mode = 'NO_ENGINE_SUBSTITUTION';
SET SESSION sql_mode = 'NO_ENGINE_SUBSTITUTION';
In addition, substitute the violent die() function with a better error-handling mechanism.
Explanation
In case you want, I added a few comment lines to explain the behavior.
<?php
$conn = new mysqli('localhost', 'root', '' , 'db_name');
$query = ''; //Set an empty query variable to hold the query
$sqlScript = file('mySqlFile.sql'); //Set the sql file location
//Read each line of the file
foreach ($sqlScript as $line) {
//Get the starting character and the ending character of each line
$startWith = substr(trim($line), 0 ,2);
$endWith = substr(trim($line), -1 ,1);
//Check for empty or comment lines. (If the line starts with --,/*,// or the line is empty, skip to the next line)
if (empty($line) || $startWith == '--' || $startWith == '/*' || $startWith == '//') {
continue;
}
//Add the line to the query. (Additional optional commented out <br> tag added to query for easy error identification)
$query = $query . $line . "/*<br>*/";
//If the line end with a ";" assume the last query has ended in this line
if ($endWith == ';') {
//Therefore, try to execute the query. Upon failure, display the last formed query with the SQL error message
mysqli_query($conn,$query) or die('<div>Problem in executing the SQL query <b>,<br><br>' . $query. '</b><br><br>'.$conn->error.'</div>');
//Reset the query variable and continue to loop the next lines
$query= '';
}
}
//If nothing went wrong, display a success message after looping through all the lines in the sql file
echo '<div>SQL file imported successfully</div>';
/*
If failed with an invalid DEFAULT value for a DATE column error, try adding the following lines to the top of your SQL file. Otherwise, execute these lines before executing your .sql file.
SET GLOBAL sql_mode = 'NO_ENGINE_SUBSTITUTION';
SET SESSION sql_mode = 'NO_ENGINE_SUBSTITUTION';
*/
?>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147821",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "77"
} |
Q: How to find whether a particular string has unicode characters (esp. Double Byte characters) To be more precise, I need to know whether (and if possible, how) I can find whether a given string has double byte characters or not. Basically, I need to open a pop-up to display a given text which can contain double byte characters, like Chinese or Japanese. In this case, we need to adjust the window size than it would be for English or ASCII.
Anyone has a clue?
A: Actually, all of the characters are Unicode, at least from the Javascript engine's perspective.
Unfortunately, the mere presence of characters in a particular Unicode range won't be enough to determine you need more space. There are a number of characters which take up roughly the same amount of space as other characters which have Unicode codepoints well above the ASCII range. Typographic quotes, characters with diacritics, certain punctuation symbols, and various currency symbols are outside of the low ASCII range and are allocated in quite disparate places on the Unicode basic multilingual plane.
Generally, projects that I've worked on elect to provide extra space for all languages, or sometimes use javascript to determine whether a window with auto-scrollbar css attributes actually has content with a height which would trigger a scrollbar or not.
If detecting the presence of, or count of, CJK characters will be adequate to determine you need a bit of extra space, you could construct a regex using the following ranges:
[\u3300-\u9fff\uf900-\ufaff], and use that to extract a count of the number of characters that match. (This is a little excessively coarse, and misses all the non-BMP cases, probably excludes some other relevant ranges, and most likely includes some irrelevant characters, but it's a starting point).
Again, you're only going to be able to manage a rough heuristic without something along the lines of a full text rendering engine, because what you really want is something like GDI's MeasureString (or any other text rendering engine's equivalent). It's been a while since I've done so, but I think the closest HTML/DOM equivalent is setting a width on a div and requesting the height (cut and paste reuse, so apologies if this contains errors):
o = document.getElementById("test");
document.defaultView.getComputedStyle(o,"").getPropertyValue("height"))
A: Here is benchmark test: http://jsben.ch/NKjKd
This is much faster:
function containsNonLatinCodepoints(s) {
return /[^\u0000-\u00ff]/.test(s);
}
than this:
function isDoubleByte(str) {
for (var i = 0, n = str.length; i < n; i++) {
if (str.charCodeAt( i ) > 255) { return true; }
}
return false;
}
A: I used mikesamuel answer on this one. However I noticed perhaps because of this form that there should only be one escape slash before the u, e.g. \u and not \\u to make this work correctly.
function containsNonLatinCodepoints(s) {
return /[^\u0000-\u00ff]/.test(s);
}
Works for me :)
A: JavaScript holds text internally as UCS-2, which can encode a fairly extensive subset of Unicode.
But that's not really germane to your question. One solution might be to loop through the string and examine the character codes at each position:
function isDoubleByte(str) {
for (var i = 0, n = str.length; i < n; i++) {
if (str.charCodeAt( i ) > 255) { return true; }
}
return false;
}
This might not be as fast as you would like.
A: I have benchmarked the two functions in the top answers and thought I would share the results. Here is the test code I used:
const text1 = `The Chinese Wikipedia was established along with 12 other Wikipedias in May 2001. 中文維基百科的副標題是「海納百川,有容乃大」,這是中国的清朝政治家林则徐(1785年-1850年)於1839年為`;
const regex = /[^\u0000-\u00ff]/; // Small performance gain from pre-compiling the regex
function containsNonLatinCodepoints(s) {
return regex.test(s);
}
function isDoubleByte(str) {
for (var i = 0, n = str.length; i < n; i++) {
if (str.charCodeAt( i ) > 255) { return true; }
}
return false;
}
function benchmark(fn, str) {
let startTime = new Date();
for (let i = 0; i < 10000000; i++) {
fn(str);
}
let endTime = new Date();
return endTime.getTime() - startTime.getTime();
}
console.info('isDoubleByte => ' + benchmark(isDoubleByte, text1));
console.info('containsNonLatinCodepoints => ' + benchmark(containsNonLatinCodepoints, text1));
When running this I got:
isDoubleByte => 2421
containsNonLatinCodepoints => 868
So for this particular string the regex solution is about 3 times faster.
However note that for a string where the first character is unicode, isDoubleByte() returns right away and so is much faster than the regex (which still has the overhead of the regular expression).
For instance for the string 中国, I got these results:
isDoubleByte => 51
containsNonLatinCodepoints => 288
To get the best of both world, it's probably better to combine both:
var regex = /[^\u0000-\u00ff]/; // Small performance gain from pre-compiling the regex
function containsDoubleByte(str) {
if (!str.length) return false;
if (str.charCodeAt(0) > 255) return true;
return regex.test(str);
}
In that case, if the first character is Chinese (which is likely if the whole text is Chinese), the function will be fast and return right away. If not, it will run the regex, which is still faster than checking each character individually.
A: Why not let the window resize itself based on the runtime height/width?
Run something like this in your pop-up:
window.resizeTo(document.body.clientWidth, document.body.clientHeight);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147824",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "37"
} |
Q: CouchDB modeling for multi-user I am already excited about document databases and especially about CouchDB's simplicity. But I have a hard time understanding if such databases are a viable option for multi user systems. Since those systems require some kind of relations between records which document databases do not provide.
Is it completely the wrong tool for such cases? Or some tagging and temporary views are the way to accomplish this? Or else...
UPDATE:
I understand the answers so far. But let me rephrase the question a bit. Lets say I have a load of semi-structured data which is normally a fit for CouchDB. I can tag them like "type=post" and "year=2008". My question is how far can I go with this type of tagging? Say can I create an array field with 10.000 names in it? Or is there a better way of doing this? It is a matter of understanding how to think in this document based sense.
A: There was a discussion on the mailing list awhile back that fits this question fairly well. The rule of thumb was to only store data in a document that is likely to change vs. grow. If the data is more likely to grow then you most likely want to store separate docs.
So in the case of a multi-user system one way of implementing ACL based permissions could be to create 'permission docs' that would be a mapping of user_id to doc_id with the appropriate permission indicated.
{
_id: "permission_doc_1",
type: "acl",
user: "John",
docid: "John's Account Info",
read: true,
write: true
}
And your views would be something along the lines of
function(doc)
{
emit([doc.user, doc.docid], {"read": doc.read, "write": doc.write});
}
And given a docid and userid, checking for permissions would be:
http://localhost:5984/db/_view/permissions/all?key=["John", "John's Account Info"]
Obviously, this would require having some intermediary between the client and couch to make sure permissions were enforced.
A: Multi-user systems do not require relational databases, though RDBMSs are a staple technology for data storage/retrieval for a vast number of (especially CRUD) applications.
If you want to read-up on document/object -oriented, distributed database solutions of yore, search on "Lotus Notes/Domino" (it's a mature technology/product in this area that's good background knowledge in how applications are designed in a document-based paradigm. Classically, it's really good at workflow type applications).
On CouchDB specifically, check out:
http://wiki.apache.org/couchdb/ (this shouldn't be a surprise)
http://seanoc.wordpress.com/2007/10/12/more-on-couchdb/ (easy reading description overview)
http://twit.tv/floss36 (Podcast interview all about CouchDB)
A: What @micahwittman says. Just a quick addition: Temp views should never be used in a production system, they are for development only. Permanent views can do everything temp views can do and are magnitudes faster.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147837",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Cognos 8 Javascript to select values in a multi select list box prompt I have a multi select list box value prompt in Cognos 8.3.
It contains values:
Adelaide North
Adelaide South
Adelaide East
Adelaide East
Sydney North
Sydney South
Sydney East
Sydney West
etc.
I want to able to add a button onto my prompt page that when clicked, selects predetermined options, such as Adelaide North, South East and West.
For example: An Adelaide button to select Adelaide North, Adelaide South, Adelaide East and Adelaide West, instead of making the user select the 4 choices in the multi-select list box.
Is there a way I can do this? I have named my list box cboFSA in the miscellaneous area of the properties.
Any help much appreciated.
A: I'm assuming this is a web-based Cognos interface? If so, this should do it for you:
If the name cboFSA is assigned as the ID attribute of the <select> use:
<select size="6" id="cboFSA" multiple="multiple">
<option>Adelaide North</option>
<option>Adelaide South</option>
<option>Adelaide East</option>
<option>Adelaide East</option>
<option>Sydney North</option>
<option>Sydney South</option>
<option>Sydney East</option>
<option>Sydney West</option>
</select>
<input type="button" value="Select all Adelaide" onclick="selectCity('adelaide', 'cboFSA');">
<input type="button" value="Select all Sydney" onclick="selectCity('sydney', 'cboFSA');">
<script type="text/javascript">
function selectCity(city, list) {
if ('string' === typeof city) {
city = city.toLowerCase();
if (document.getElementById) {
var sel = document.getElementById(list);
if (sel && (sel = sel.options)) {
for (var ii = 0, iiLen = sel.length; ii < iiLen; ++ii) {
sel[ii].selected = (sel[ii].text.toLowerCase().indexOf(city) !== -1);
}
}
}
}
}
</script>
If the name cboFSA is assigned as the NAME attribute of the <select> use:
<select size="6" name="cboFSA" multiple="multiple">
<option>Adelaide North</option>
<option>Adelaide South</option>
<option>Adelaide East</option>
<option>Adelaide East</option>
<option>Sydney North</option>
<option>Sydney South</option>
<option>Sydney East</option>
<option>Sydney West</option>
</select>
<input type="button" value="Select all Adelaide" onclick="selectCity('adelaide', 'cboFSA', this);">
<input type="button" value="Select all Sydney" onclick="selectCity('sydney', 'cboFSA', this);">
<script type="text/javascript">
function selectCity(city, list, btn) {
if ('string' === typeof city) {
city = city.toLowerCase();
var sel;
if (btn && btn.form && (sel = btn.form[list]) && (sel = sel.options)) {
for (var ii = 0, iiLen = sel.length; ii < iiLen; ++ii) {
sel[ii].selected = (sel[ii].text.toLowerCase().indexOf(city) !== -1);
}
}
}
}
</script>
You can use View > Source in your browser to figure out whether Cognos assigns the value you specify as the ID or NAME attribute.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147839",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What is the best "closable TabbedPane" Component in Java? After solving my flicker issue, I wonder if there is a better closable Tabbed Pane, then the one that pops up on top by googling for closabletappedpane?
(you recognize it by its processMouseEvents Method)
I especially need one, that never flickers :-)
Please post your experience, links with your own closable Tabbed Panes here.
A: There is a sample implementation of closable tabs using JTabbedPane in the JDK.
A: JideTabbedPane is pretty awesome and it's in the common layer (which is open source). It supports all sorts of sweet features to make Java apps not seem so crusty. We've had great success with it on my project.
A: I really recommend to follow tutorial mentioned above. It is simple to create such a tab and you have full control over its behavior.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147845",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Subcribe via RSS for log4j logs? Is it possible to subscribe to a url with log4j logs?
I understand that many applications do have daily error logs notification by email. But a problem with this approach is that the server that host the application may not provide smtp capability. Thus the RSS subscribe approach seens to be more flexibile.
Anyone know how is this being done ?
A: A log4j RSS appender has already been written. Have a look at http://code.google.com/p/rssappender/
A: A pretty simple solution would be to use log4j (or log4net in my case) to persist the logging information to some store (database or file). Then you can easily create a service that exposes that log as an RSS feed.
A: Simplest thing to do would be to write a custom Log4J appender (not hard, just subclass WriterAppender) which converts LoggingEvents into RSS format, and stores them in a disk file. Each time it gets a new event, load in the existing file, parse it, add the new RSS entry, and write it back. Then use a web server to server up the RSS.
It won't scale well, but then if you have large numbers of log events, then RSS itself is not a good choice.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147847",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: When using ANT, how can I define a task only if I have some specific java version? I have the problem that an specific step in Ant can only be executed when we have Java 1.5 installed in the build computer. The task definition uses uses a jar file that was compiled using 1.5, so running with a 1.4 virtual machine will throw an IncompatibleClassVersion exception.
I have to find a solution meanwhile to have this task working for this specific project that requires 1.4, but a question came to me. How can I avoid defining this task and executing this optional step if I don't have a specific java version?
I could use the "if" or "unless" tags on the target tag, but those only check if a property is set or not. I also would like to have a solution that doesn't require extra libraries, but I don't know if the build-in functionality in standard is enough to perform such a task.
A: The property to check in the buildfile is ${ant.java.version}.
You could use the <condition> element to make a task conditional when a property equals a certain value:
<condition property="legal-java">
<matches pattern="1.[56].*" string="${ant.java.version}"/>
</condition>
A: The Java version is exposed via the ant.java.version property. Use a condition to set a property and execute the task only if it is true.
<?xml version="1.0" encoding="UTF-8"?>
<project name="project" default="default">
<target name="default" depends="javaCheck" if="isJava6">
<echo message="Hello, World!" />
</target>
<target name="javaCheck">
<echo message="ant.java.version=${ant.java.version}" />
<condition property="isJava6">
<equals arg1="${ant.java.version}" arg2="1.6" />
</condition>
</target>
</project>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147850",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Customization of Hibernate sequence generation I have one hibernate sequence, that generates all sequence-numbers in my app. When I generate the schemas from hibernate (target Oracle10), it genererates:
create sequence hibernate_sequence;
I would like to change the configuration of the sequence. I have to use something like:
create sequence hibernate_sequence order nocache;
I don't like to change the generated scripts, everytime I create them. Where can I customize the sequence generated by hibernate?
A: You can create a custom sequence generator. See http://www.hibernate.org/296.html for details.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147859",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: What is your favourite Java Script WYSIWYG Editor component? I definitifely like the one at stackoverflow, because it's clean and simple. Also the live preview with code/syntax hilighting is really helpful (and motivating).
What is your favourite Javascript Editor Framework and why?
A: I like widgEditor because it's very simple and it only do the minimum. TinyMCE or FCKeditor are goods, but they are too big for what I need.
A: TinyMCE looks good with lots of useful features.
A: I just stumpeld over MarkItUp, which is JQuery based and adaptable for different kinds of markup.
Could be an option, if your markup isn't just HTML, but Template, Forum or "whatever style"
markup.
I found a List of Editors with their features.
A: Simple Text Editor is a good one (STE 1.0).
A: In my web-hacker days, I used Xinha quite a lot.
A: I like FCKeditor because of it's flexibility and it worked fine on all the browsers I've tested it on.
A: Really depends on your needs, here are your options: TinyMCE, NicEdit, FreeRichTextEditor, TinyEditor, openWYSIWYG, WYMeditor, jHtmlArea, uEditor, CLEditor, jQRTE, jQuery Simple WYSIWYG Editor, xinha, ckedit
A: I love tiny_mce
Goran
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147867",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How to convert generic dictionary to non-generic without enumerating? I want to convert an instance of generic IDictionary to non generic IDictionary. Can I do it without creating new instance of IDictionary? Is any framework support for this task?
I tried wrap generic IDictionary in class that implements nongenetic IDictionary however I discovered that I have to also somehow convert generic ICollection to nongeneric one so I go with Mark Gravell solution.
A: It all depends on the concrete implementation you are using.
For example, Dictionary<TKey,TValue> implements both the generic IDictionary<TKey,TValue> and the non-generic IDictionary - so if you have a Dictionary<TKey,TValue> you can use it as either without issue:
Dictionary<int, string> lookup = new Dictionary<int,string>();
IDictionary<int,string> typed = lookup;
IDictionary untyped = lookup;
However, this doesn't necessarily apply for all IDictionary<TKey,TValue> imlpementations, since it is not true that IDictionary<TKey,TValue> : IDictionary. If you are deep in the bowels of some generic code, you could test the current dictionary:
IDictionary<int,string> typed = ...
IDictionary untyped = typed as IDictionary;
if(untyped == null) {/* create by enumeration */}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147875",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Javascript exception stack trace In Firefox I can get the stack trace of an exception by using exception.stack.
Is there a way to get that in other browsers, too?
Edit: I actually want to save the stack trace automatically (if possible) and not debug it at the time (i.e. I know how to get the stack trace in a debugger).
A: Place this line where you want to print the stack trace:
console.log(new Error().stack);
Note: tested by me on Chrome 24 and Firefox 18
May be worth taking a look at this tool as well.
A: If you want the string stack trace, I'd go with insin's answer: stacktrace.js. If you want to access the pieces of a stacktrace (line numbers, file names, etc) stackinfo, which actually uses stacktrace.js under the hood.
A: Webkit now has functionality that provides stack traces:
Web Inspector: Understanding Stack Traces, posted by Yury Semikhatsky on Wednesday, April 20th, 2011 at 7:32 am (webkit.org)
From that post:
A: Not really, at least not easily.
In IE, you can debug the browser process with MS Script Debugger (which for some reason is an Office component) or Visual Studio, and then you can see the stack on breakpoints.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147891",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "101"
} |
Q: In SQL Server can I insert multiple nodes into XML from a table? I want to generate some XML in a stored procedure based on data in a table.
The following insert allows me to add many nodes but they have to be hard-coded or use variables (sql:variable):
SET @MyXml.modify('
insert
<myNode>
{sql:variable("@MyVariable")}
</myNode>
into (/root[1]) ')
So I could loop through each record in my table, put the values I need into variables and execute the above statement.
But is there a way I can do this by just combining with a select statement and avoiding the loop?
Edit I have used SELECT FOR XML to do similar stuff before but I always find it hard to read when working with a hierarchy of data from multiple tables. I was hoping there would be something using the modify where the XML generated is more explicit and more controllable.
A: Have you tried nesting FOR XML PATH scalar valued functions?
With the nesting technique, you can brake your SQL into very managable/readable elemental pieces
Disclaimer: the following, while adapted from a working example, has not itself been literally tested
Some reference links for the general audience
*
*http://msdn2.microsoft.com/en-us/library/ms178107(SQL.90).aspx
*http://msdn2.microsoft.com/en-us/library/ms189885(SQL.90).aspx
The simplest, lowest level nested node example
Consider the following invocation
DECLARE @NestedInput_SpecificDogNameId int
SET @NestedInput_SpecificDogNameId = 99
SELECT [dbo].[udfGetLowestLevelNestedNode_SpecificDogName]
(@NestedInput_SpecificDogNameId)
Let's say had udfGetLowestLevelNestedNode_SpecificDogName had been written without the FOR XML PATH clause, and for @NestedInput_SpecificDogName = 99 it returns the single rowset record:
@SpecificDogNameId DogName
99 Astro
But with the FOR XML PATH clause,
CREATE FUNCTION dbo.udfGetLowestLevelNestedNode_SpecificDogName
(
@NestedInput_SpecificDogNameId
)
RETURNS XML
AS
BEGIN
-- Declare the return variable here
DECLARE @ResultVar XML
-- Add the T-SQL statements to compute the return value here
SET @ResultVar =
(
SELECT
@SpecificDogNameId as "@SpecificDogNameId",
t.DogName
FROM tblDogs t
FOR XML PATH('Dog')
)
-- Return the result of the function
RETURN @ResultVar
END
the user-defined function produces the following XML (the @ signs causes the SpecificDogNameId field to be returned as an attribute)
<Dog SpecificDogNameId=99>Astro</Dog>
Nesting User-defined Functions of XML Type
User-defined functions such as the above udfGetLowestLevelNestedNode_SpecificDogName can be nested to provide a powerful method to produce complex XML.
For example, the function
CREATE FUNCTION [dbo].[udfGetDogCollectionNode]()
RETURNS XML
AS
BEGIN
-- Declare the return variable here
DECLARE @ResultVar XML
-- Add the T-SQL statements to compute the return value here
SET @ResultVar =
(
SELECT
[dbo].[udfGetLowestLevelNestedNode_SpecificDogName]
(t.SpecificDogNameId)
FROM tblDogs t
FOR XML PATH('DogCollection') ELEMENTS
)
-- Return the result of the function
RETURN @ResultVar
END
when invoked as
SELECT [dbo].[udfGetDogCollectionNode]()
might produce the complex XML node (given the appropriate underlying data)
<DogCollection>
<Dog SpecificDogNameId="88">Dino</Dog>
<Dog SpecificDogNameId="99">Astro</Dog>
</DogCollection>
From here, you could keep working upwards in the nested tree to build as complex an XML structure as you please
CREATE FUNCTION [dbo].[udfGetAnimalCollectionNode]()
RETURNS XML
AS
BEGIN
DECLARE @ResultVar XML
SET @ResultVar =
(
SELECT
dbo.udfGetDogCollectionNode(),
dbo.udfGetCatCollectionNode()
FOR XML PATH('AnimalCollection'), ELEMENTS XSINIL
)
RETURN @ResultVar
END
when invoked as
SELECT [dbo].[udfGetAnimalCollectionNode]()
the udf might produce the more complex XML node (given the appropriate underlying data)
<AnimalCollection>
<DogCollection>
<Dog SpecificDogNameId="88">Dino</Dog>
<Dog SpecificDogNameId="99">Astro</Dog>
</DogCollection>
<CatCollection>
<Cat SpecificCatNameId="11">Sylvester</Cat>
<Cat SpecificCatNameId="22">Tom</Cat>
<Cat SpecificCatNameId="33">Felix</Cat>
</CatCollection>
</AnimalCollection>
A: Use sql:column instead of sql:variable. You can find detailed info here: http://msdn.microsoft.com/en-us/library/ms191214.aspx
A: Can you tell a bit more about what exactly you are planning to do.
Is it simply generating XML data based on a content of the table
or adding some data from the table to an existing xml structure?
There are great series of articles on the subject on XML in SQLServer written by Jacob Sebastian, it starts with the basics of generating XML from the data in the table
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147897",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Linux configuration file libraries Are there any good configuration file reading libraries for C\C++ that can be used for applications written on the linux platform. I would like to have a simple configuration file for my application. At best i would like to steer clear of XML files that might potentially confuse users.
A: Another option is Boost.PropertyTree (doc). It allows to read/write XML, INI, JSON and Info files. And you get portability for free.
A: Boost program_options This allows you to read program options from config files, environment variables and the command line. It is portable and very easy to use.
A: I would recommend 'libconfig'.
A: You could try glib's key-value-file-parser
A: If you just want a simple config file, with a list of commands and/or variable settings, then it's very easy to write your own parser, so easy that it's probably not worth using a library. If you need something more complicated then the parser rapidly becomes more complicated and an existing library is worth using.
I've never tried using libconfig, but it looks like a good choice, and I like the format of the config files it uses.
You need to decide whether you want your program to be able to write config files. If it's a GUI program, you probably do. This will affect what libraries are suitable.
A: For a single app, you could consider libconfuse.
If you need to be able to handle a wide variety of config file formats (e.g. for a web portal for a system, which needs to read and write config files from many apps in many formats), there is Augeas.
A: The question is what file format did you have in mind? The attribute "simple" is a bit of an underspecification.
If you are looking for a library that can use "windows .ini formated" config files you may want to check out ACE http://www.cs.wustl.edu/~schmidt/ACE/ .
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147902",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "27"
} |
Q: Tabbed VS Tree for navigaion. Which is the preferred approach? I realize that in of TOAD books right, it justifies the reaons on why it uses tabbed pane is that tree view involves too much scrolling.
But for me i like tree view better. As it only shows you the top level.
I see TOAD user interface. i thought the tabbed panels was very confusing for me to switch around.
What are your opinions regarding this?
A: I think in general if you are designing the interface, I think it depends on the number of items you are trying to display.
in your TOAD example. (which i am assuming is Toad from www.quest.com) the tabs only serve to remove 1 level (the top level) from your tree.
The advantage the tree structure has is that you can 'drill down' from scheme to table to trigger, etc..
so it really depends on what you are trying to achieve, or the style you want to work with.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147906",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I databind a ColumnDefinition's Width or RowDefinition's Height? Under the View-Model-ViewModel pattern for WPF, I am trying to databind the Heights and Widths of various definitions for grid controls, so I can store the values the user sets them to after using a GridSplitter. However, the normal pattern doesn't seem to work for these particular properties.
Note: I'm posting this as a reference question that I'm posting as Google failed me and I had to work this out myself. My own answer to follow.
A: The easiest solution is to simply use string settings for these properties so that WPF will automatically support them using GridLengthConverter without any extra work.
A: Create a IValueConverter as follows:
public class GridLengthConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
double val = (double)value;
GridLength gridLength = new GridLength(val);
return gridLength;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
GridLength val = (GridLength)value;
return val.Value;
}
}
You can then utilize the converter in your Binding:
<UserControl.Resources>
<local:GridLengthConverter x:Key="gridLengthConverter" />
</UserControl.Resources>
...
<ColumnDefinition Width="{Binding Path=LeftPanelWidth,
Mode=TwoWay,
Converter={StaticResource gridLengthConverter}}" />
A: Another possibility, since you brought up converting between GridLength and int, is to create an IValueConverter and use it when binding to Width. IValueConverters also handle two-way binding because they have both ConvertTo() and ConvertBack() methods.
A: There were a number of gotchas I discovered:
*
*Although it may appear like a double in XAML, the actual value for a *Definition's Height or Width is a 'GridLength' struct.
*All the properties of GridLength are readonly, you have to create a new one each time you change it.
*Unlike every other property in WPF, Width and Height don't default their databinding mode to 'TwoWay', you have to manually set this.
Thusly, I used the following code:
private GridLength myHorizontalInputRegionSize = new GridLength(0, GridUnitType.Auto)
public GridLength HorizontalInputRegionSize
{
get
{
// If not yet set, get the starting value from the DataModel
if (myHorizontalInputRegionSize.IsAuto)
myHorizontalInputRegionSize = new GridLength(ConnectionTabDefaultUIOptions.HorizontalInputRegionSize, GridUnitType.Pixel);
return myHorizontalInputRegionSize;
}
set
{
myHorizontalInputRegionSize = value;
if (ConnectionTabDefaultUIOptions.HorizontalInputRegionSize != myHorizontalInputRegionSize.Value)
{
// Set the value in the DataModel
ConnectionTabDefaultUIOptions.HorizontalInputRegionSize = value.Value;
}
OnPropertyChanged("HorizontalInputRegionSize");
}
}
And the XAML:
<Grid.RowDefinitions>
<RowDefinition Height="*" MinHeight="100" />
<RowDefinition Height="Auto" />
<RowDefinition Height="{Binding Path=HorizontalInputRegionSize,Mode=TwoWay}" MinHeight="50" />
</Grid.RowDefinitions>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/147908",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "39"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.