text
stringlengths
8
267k
meta
dict
Q: Make Test.QuickCheck.Batch use a default type for testing list functions I am testing a function called extractions that operates over any list. extractions :: [a] -> [(a,[a])] extractions [] = [] extractions l = extract l [] where extract [] _ = [] extract (x:xs) prev = (x, prev++xs) : extract xs (x : prev) I want to test it, for example, with import Test.QuickCheck.Batch prop_len l = length l == length (extractions l) main = runTests "extractions" defOpt [run prop_len] But this won't compile; I have to supply a type either for run or prop_len, because QuickCheck can't generate [a], it has to generate something concrete. So I chose Int: main = runTests "extractions" defOpt [r prop_len] where r = run :: ([Int] -> Bool) -> TestOptions -> IO TestResult Is there any way to get QuickCheck to choose a for me instead of having it specified in the type of run? A: The quickcheck manual says "no": Properties must have monomorphic types. `Polymorphic' properties, such as the one above, must be restricted to a particular type to be used for testing. It is convenient to do so by stating the types of one or more arguments in a where types = (x1 :: t1, x2 :: t2, ...) clause...
{ "language": "en", "url": "https://stackoverflow.com/questions/64197", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How do I call MySQL stored procedures from Perl? How do I call MySQL stored procedures from Perl? Stored procedure functionality is fairly new to MySQL and the MySQL modules for Perl don't seem to have caught up yet. A: MySQL stored procedures that produce datasets need you to use Perl DBD::mysql 4.001 or later. (http://www.perlmonks.org/?node_id=609098) Below is a test program that will work in the newer version: mysql> delimiter // mysql> create procedure Foo(x int) -> begin -> select x*2; -> end -> // perl -e 'use DBI; DBI->connect("dbi:mysql:database=bonk", "root", "")->prepare("call Foo(?)")->execute(21)' But if you have too old a version of DBD::mysql, you get results like this: DBD::mysql::st execute failed: PROCEDURE bonk.Foo can't return a result set in the given context at -e line 1. You can install the newest DBD using CPAN. A: There's an example in the section on Multiple result sets in the DBD::mysql docs. A: #!/usr/bin/perl # Stored Proc - Multiple Values In, Multiple Out use strict; use Data::Dumper; use DBI; my $dbh = DBI->connect('DBI:mysql:RTPC;host=db.server.com', 'user','password',{ RaiseError => 1 }) || die "$!\n"; my $sth = $dbh->prepare('CALL storedProcedure(?,?,?,?,@a,@b);'); $sth->bind_param(1, 2); $sth->bind_param(2, 1003); $sth->bind_param(3, 5000); $sth->bind_param(4, 100); $sth->execute(); my $response = $sth->fetchrow_hashref(); print Dumper $response . "\n"; It took me a while to figure it out, but I was able to get what I needed with the above. if you need to get multiple return "lines" I'm guessing you just... while(my $response = $sth->fetchrow_hashref()) { print Dumper $response . "\n"; } I hope it helps. A: First of all you should be probably connect through the DBI library and then you should use bind variables. E.g. something like: #!/usr/bin/perl # use strict; use DBI qw(:sql_types); my $dbh = DBI->connect( $ConnStr, $User, $Password, {RaiseError => 1, AutoCommit => 0} ) || die "Database connection not made: $DBI::errstr"; my $sql = qq {CALL someProcedure(1);} } my $sth = $dbh->prepare($sql); eval { $sth->bind_param(1, $argument, SQL_VARCHAR); }; if ($@) { warn "Database error: $DBI::errstr\n"; $dbh->rollback(); #just die if rollback is failing } $dbh->commit(); Mind you i haven't tested this, you'll have to lookup the exact syntax on CPAN. A: Hi, similar to above but using SQL exec. I could not get the CALL command to work. You will need to fill in anything that is within square brackets and remove the square brackets. use DBI; #START: SET UP DATABASE AND CONNECT my $host = '*[server]*\\*[database]*'; my $database = '*[table]*'; my $user = '*[user]*'; my $auth = '*[password]*'; my $dsn = "dbi:ODBC:Driver={SQL Server};Server=$host;Database=$database"; my $dbh = DBI->connect($dsn, $user, $auth, { RaiseError => 1 }); #END : SET UP DATABASE AND CONNECT $sql = "exec *[stored procedure name]* *[param1]*,*[param2]*,*[param3]*;"; $sth = $dbh->prepare($sql); $sth->execute or die "SQL Error: $DBI::errstr\n";
{ "language": "en", "url": "https://stackoverflow.com/questions/64200", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How to add a constant column when replicating a database? I am using SQL Server 2000 and I have two databases that both replicate (transactional push subscription) to a single database. I need to know which database the records came from. So I want to add a fixed column specified in the publication to my table so I can tell which database the row originated from. How do I go about doing this? I would like to avoid altering the main databases mostly due to the fact there are many tables I would need to do this to. I was hoping for some built in feature of replication that would do this for me some where. Other than that I would go with the view idea. A: You could use a calculated column Use the following on the two databases: ALTER TABLE TableName ADD MyColumn AS 'Server1' Then just define the single "master" database to use a VARCHAR column (or whatever you want) that you fill using the calculated columns value. A: You can create a view, which adds the "constant" column, and use it as a replication source. A: So the solution for me was to set up the replication publications to allow transformations and create a DTS package for each site that appends the siteid into the tables to keep the ids unique as I can't use guids.
{ "language": "en", "url": "https://stackoverflow.com/questions/64202", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Can I filter the messages I receive from a message queue (MSMQ) by some property? (a.k.a. topic) I am creating a Windows Service in C# that processes messages from a queue. I want to give ops the flexibility of partitioning the service in production according to properties of the message. For example, they should be able to say that one instance processes web orders from Customer A, another batch orders from Customer A, a third web or batch orders from Customer B, and so on. My current solution is to assign separate queues to each customer\source combination. The process that puts orders into the queues has to make the right decision. My Windows Service can be configured to pull messages from one or more queues. It's messy, but it works. A: No, but you can PEEK into the queue and decide if you really want to consume the message. A: Use GetMessageEnumerator2() like this: MessageEnumerator en = q.GetMessageEnumerator2(); while (en.MoveNext()) { if (en.Current.Label == label) { string body = ((XmlDocument)en.Current.Body).OuterXml; en.RemoveCurrent(); return body; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/64204", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to force nolock hint for sql server logins Does anyone know of a way to force a nolock hint on all transactions issued by a certain user? I'd like to provide a login for a support team to query the production system, but I want to protect it by forcing a nolock on everything they do. I'm using SQL Server 2005. A: This is a painful and hacky way to do it, but it's what we're doing where I work. We're also using classic asp so we're using inline sql calls. we actually wrap the sql call in a function (here you can check for a specific user) and add "SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED" to the beginning of the call. I believe functionally this is the same as the no lock hint. Sorry I don't have a pure SQL answer, I'd be interested to hear if you find a good way to do this. A: You could configure your support staff's SQL Management Studio to set the default transaction isolation level to READ UNCOMMITTED (Tools->Options->Query Execution->SQL Server->Advanced). This is functionally the same as having NOLOCK hints on everything. The downsides are that you'd have to do this for each member of your support team, and they'd have the ability to change the configuration on their SQL Management Studio. A: OK, you need to clarify what you are trying to do here. If you are trying to reduce locking on the database and possibly provide your support users with data that may never really get committed in the database. While allowing them to write anything they want to the database, then nolock is the way to go. You will get the added bonus that your user will still be able to increase their isolation level using the SET TRANSACTION ISOLATION LEVEL command. If you are trying to restrict the damage they can cause when running stuff against the DB, look at implementing security, make sure they are only allowed read access to your tables and look at stripping all access to stored procs and functions. I Find NOLOCK is heavily misunderstood on stack overflow. A: You could create a limited user for the support team, and then either write stored procedures or views with the nolock-hint. Then only give access to those and not direct table select access. A: As Espo hinted at, I'm pretty sure there's no direct way to do what you're asking. As he said, you can sort-of accomplish it by limiting the user's access to only procs that have built-in NOLOCK coded in them. A: Unfortunately, restricting the users to SPs defeats the purpose of this. I was hoping there was some way I could allow them to query everything and thereby enhance their troubleshooting skills. Thanks for your help guys.
{ "language": "en", "url": "https://stackoverflow.com/questions/64208", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Detect changes in random ordered input (hash function?) I'm reading lines of text that can come in any order. The problem is that the output can actually be indentical to the previous output. How can I detect this, without sorting the output first? Is there some kind of hash function that can take identical input, but in any order, and still produce the same result? A: The easiest way would seem to be to hash each line on the way in, storing the hash and the original data, and then compare each new hash with your collection of existing hashes. If you get a positive, you could compare the actual data, to make sure it's not a false positive - though this would be extremely rare, you could go with a quicker hash algorithm, like MD5 or CRC (instead of something like SHA, which is slower but less likely to collide), just so it's quick, and then compare the actual data when you get a hit. A: So you have input like A B C D D E F G C B A D and you need to detect that the first and third lines are identical? A: If you want to find out if two files contain the same set of lines, but in a different order, you can use a regular hash function on each line individually, then combine them with a function where ordering doesn't matter, like addition. A: If the lines are fairly long, you could just keep a list of the hashes of each line -- sort those and compare with previous outputs. If you don't need a 100% fool-proof solution, you could store the hash of each line in a Bloom filter (look it up on Wikipedia) and compare the Bloom filters at the end of processing. This can give you false positives (i.e. you think you have the same output but it isn't really the same) but you can tweak the error rate by adjusting the size of the Bloom filter... A: If you add up the ASCII values of each character, you'd get the same result regardless of order. (This may be a bit too simplified, but perhaps it sparks an idea for you. See Programming Pearls, section 2.8, for an interesting back story.) A: Any of the hash-based methods may produce bad results because more than one string can produce the same hash. (It's not likely, but it's possible.) This is particularly true of the suggestion to add the hashes, since you would essentially be taking a particularly bad hash of the hash values. A hash method should only be attempted if it's not critical that you miss a change or spot a change where none exists. The most accurate way would be to keep a Map using the line strings as key and storing the count of each as the value. (If each string can only appear once, you don't need the count.) Compute this for the expected set of lines. Duplicate this collection to examine the incoming lines, reducing the count for each line as you see it. * *If you encounter a line with a zero count (or no map entry at all), you've seen a line you didn't expect. *If you end this with non-zero entries remaining in the Map, you didn't see something you expected. A: Well the problem specification is a bit limited. As I understand it you wish to see if several strings contain the same elements regardless of order. For example: A B C C B A are the same. The way to do this is to create a set of the values then compare the sets. To create a set do: HashSet set = new HashSet(); foreach (item : string) { set.add(item); } Then just compare the contents of the sets by running through one of the sets and comparing it w/others. The execution time will be O(N) instead of O(NlogN) for the sorting example.
{ "language": "en", "url": "https://stackoverflow.com/questions/64209", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is the most useful multi-purpose open-source library for java? Are there any open-source libraries that all programmers should know about? I'm thinking something general, a sort of extension to the standard java.util that contains basic functions that are useful for all kinds of application. A: The Spring framework is surprisingly general purpose. I started by just using it as a configuration management tool, but then realized how helpful dependency injection is when doing test-driven development. Then I slowly discovered many useful modules hidden in the corners of Spring. A: Apache's Jakarta Commons. A: The Google Collections API is pretty handy if you use lots of, well, Collections... A: It might be worth saying that the first thing to do is get to know the libraries in the newer versions of Java. A lot of ideas have worked their way back into java - java.util.concurrent, java.nio, and javax.xml A: Functional Java offers first-class function values, immutable lists/arrays, lazy/infinite streams, tuple types, either types, optional values (type-safe alternative to null). Works well in conjunction with Google Collections or the java.util collections. It also provides handy concurrency abstractions like parallel strategies, parallel list/array functors, actor concurrency, and composable light-weight processes. A: lambdaj is a thread safe library of static methods that provides an internal DSL to manipulate collections in a pseudo-functional and statically typed way without explicitly iterating on them. It eliminates the burden to write (often poorly readable) loops while iterating over collections. A: Here is a good start. http://java-sources.org/ A: Google Collections migrated to great Guava Libraries . It contains some common utilities, string matcher, splitter, joiner, IO utils etc. A: * *Apache Commons *Log4j *Google collections A: JXL for Excel workbook creation/edition. I work in a bank and the multipurpose report tool for diary work is Excel. Whatever appliction we do must import/export from/to Excel. The only fail it's that it has memory problems with large workbooks and formating it's a little obscure A: Take a look at jmate project. It contains really helpful methods for strings, collections and IO operations (for now). Look some examples here. A: Lately I was trying to find answer to this question. I made some data analysis for this, you can find results here and here.
{ "language": "en", "url": "https://stackoverflow.com/questions/64213", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Should rails models be concerned with other models for the sake of skinny controllers? I read everywhere that business logic belongs in the models and not in controller but where is the limit? I am toying with a personnal accounting application. Account Entry Operation When creating an operation it is only valid if the corresponding entries are created and linked to accounts so that the operation is balanced for exemple buy a 6-pack : o=Operation.new({:description=>"b33r", :user=>current_user, :date=>"2008/09/15"}) o.entries.build({:account_id=>1, :amount=>15}) o.valid? #=>false o.entries.build({:account_id=>2, :amount=>-15}) o.valid? #=>true Now the form shown to the user in the case of basic operations is simplified to hide away the entries details, the accounts are selected among 5 default by the kind of operation requested by the user (intialise account -> equity to accout, spend assets->expenses, earn revenues->assets, borrow liabilities->assets, pay debt assets->liabilities ...) I want the entries created from default values. I also want to be able to create more complex operations (more than 2 entries). For this second use case I will have a different form where the additional complexity is exposed.This second use case prevents me from including a debit and credit field on the Operation and getting rid of the Entry link. Which is the best form ? Using the above code in a SimpleOperationController as I do for the moment, or defining a new method on the Operation class so I can call Operation.new_simple_operation(params[:operation]) Isn't it breaking the separation of concerns to actually create and manipulate Entry objects from the Operation class ? I am not looking for advice on my twisted accounting principles :) edit -- It seems I didn't express myself too clearly. I am not so concerned about the validation. I am more concerned about where the creation logic code should go : assuming the operation on the controller is called spend, when using spend, the params hash would contain : amount, date, description. Debit and credit accounts would be derived from the action which is called, but then I have to create all the objects. Would it be better to have #error and transaction handling is left out for the sake of clarity def spend amount=params[:operation].delete(:amount)#remove non existent Operation attribute op=Operation.new(params[:operation]) #select accounts in some way ... #build entries op.entries.build(...) op.entries.build(...) op.save end or to create a method on Operation that would make the above look like def spend op=Operation.new_simple_operation(params) op.save end this definitely give a much thinner controller and a fatter model, but then the model will create and store instances of other models which is where my problem is. A: but then the model will create and store instances of other models which is where my problem is. What is wrong with this? If your 'business logic' states that an Operation must have a valid set of Entries, then surely there is nothing wrong for the Operation class to know about, and deal with your Entry objects. You'll only get problems if you take this too far, and have your models manipulating things they don't need to know about, like an EntryHtmlFormBuilder or whatever :-) A: Virtual Attributes (more info here and here) will help with this greatly. Passing the whole params back to the model keeps things simple in the controller. This will allow you to dynamically build your form and easily build the entries objects. class Operation has_many :entries def entry_attributes=(entry_attributes) entry_attributes.each do |entry| entries.build(entry) end end end class OperationController < ApplicationController def create @operation = Operation.new(params[:opertaion]) if @operation.save flash[:notice] = "Successfully saved operation." redirect_to operations_path else render :action => 'new' end end end The save will fail if everything isn't valid. Which brings us to validation. Because each Entry stands alone and you need to check all entries at "creation" you should probably override validate in Operation: class Operation # methods from above protected def validate total = 0 entries.each { |e| t += e.amount } errors.add("entries", "unbalanced transfers") unless total == 0 end end Now you will get an error message telling the user that the amounts are off and they should fix the problem. You can get really fancy here and add a lot of value by being specific about the problem, like tell them how much they are off. A: It's easier to think in terms of each entity validating itself, and entities which depend on one another delegating their state to the state of their associated entries. In your case, for instance: class Operation < ActiveRecord::Base has_many :entries validates_associated :entries end validates_associated will check whether each associated entity is valid (in this case, all entries should if the operation is to be valid). It is very tempting to try to validate entire hierarchies of models as a whole, but as you said, the place where that would be most easily done is the controller, which should act more as a router of requests and responses than in dealing with business logic. A: The way I look at it is that the controller should reflect the end-user view and translate requests into model operations and reponses while also doing formatting. In your case there are 2 kinds of operations that represent simple operations with a default account/entry, and more complex operations that have user selected entries and accounts. The forms should reflect the user view (2 forms with different fields), and there should be 2 actions in the controller to match. The controller however should have no logic relating to how the data is manipulated, only how to receive and respond. I would have class methods on the Operation class that take in the proper data from the forms and creates one or more object as needed, or place those class methods on a support class that is not an AR model, but has business logic that crosses model boundaries. The advantage of the separate utility class is that it keeps each model focused on one purpose, the down side is that the utility classes have no defined place to live. I put them in lib/ but Rails does not specify a place for model helpers as such. A: If you are concerned about embedding this logic into any particular model, why not put them into an observer class, that will keep the logic for your creation of the associated items separate from the classes being observed.
{ "language": "en", "url": "https://stackoverflow.com/questions/64214", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Fatal warnings on Windows While working between a Windows MySQL server and a Debian MySQL server, I noticed that warnings were fatal on Windows, but silently ignored on Debian. I'd like to make the warnings fatal on both servers while I'm doing development, but I wasn't able to find a setting that effected this behavior. Anyone have any ideas? A: I think what you're looking for is the sql_mode parameter in my.conf. STRICT_ALL_TABLES is the value. I guess it depends what you mean by "fatal". http://dev.mysql.com/doc/refman/5.0/en/server-sql-mode.html A: Look at enabling strict mode in the /etc/my.ini file.
{ "language": "en", "url": "https://stackoverflow.com/questions/64233", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: When to create a new app (with startapp) in Django? I've googled around for this, but I still have trouble relating to what Django defines as "apps". Should I create a new app for each piece of functionality in a site, even though it uses models from the main project? Do you guys have good rule of thumb of when to split off a new app, and when to keep functionality together with the "main project" or other apps? A: The two best answers to this question I've found around the web are: * *The Reusable Apps Talk (slides)(video) also mentioned in other answers. Bennett, the author and Django contributor, regularly publishes apps for others to use and has a strong viewpoint towards many small apps. *Doordash's Tips for Django at Scale which gives the opposite advice and says in their case they migrated to one single app after starting with many separate apps. They ran into problems with the migration dependency graph between apps. Both sources agree that you should create a separate app in the following situations: * *If you plan to reuse your app in another Django project (especially if you plan to publish it for others to reuse). *If the app has few or no dependencies between it and another app. Here you might be able to imagine an app running as its own microservice in the future. A: The rule I follow is it should be a new app if I want to reuse the functionality in a different project. If it needs deep understanding of the models in your project, it's probably more cohesive to stick it with the models. A: James Bennett has a wonderful set of slides on how to organize reusable apps in Django. A: The best answer to this question is given by Andrew Godwin (Django core developer): The main purpose of apps is, in my eyes, to provide logical separation of reusable components - specifically, a first-class namespace for models/admin/etc. - and to provide an easy way to turn things “on” or “off”. In some ways, it’s a relic of the time when Django was created - when Python packaging and modules were much less developed and you basically had to have your own solution to the problem. That said, it’s still a core part of Django’s mental model, and I think INSTALLED_APPS is still a cleaner, easier solution than Python’s replacement offering of entrypoints (which makes it quite hard to disable a package that is installed in an environment but which you don’t want to use). Is there anything specifically you think could be decoupled from the app concept today? Models and admin need it for autodiscovery and a unique namespace prefix, so that’s hard to undo, and I’m struggling to think of other features you need it for (in fact, if all you want is just a library, you can make it a normal Python one - no need for the app wrapping unless you’re shipping models, templates or admin code IIRC) A: I prefer to think of Django applications as reusable modules or components than as "applications". This helps me encapsulate and decouple certain features from one another, improving re-usability should I decide to share a particular "app" with the community at large, and maintainability. My general approach is to bucket up specific features or feature sets into "apps" as though I were going to release them publicly. The hard part here is figuring out how big each bucket is. A good trick I use is to imagine how my apps would be used if they were released publicly. This often encourages me to shrink the buckets and more clearly define its "purpose". A: Here is the updated presentation on 6 September 2008. DjangoCon 2008: Reusable Apps @7:53 Slide: Reusable_apps.pdf Taken from the slide Should this be its own application? * *Is it completely unrelated to the app’s focus? *Is it orthogonal to whatever else I’m doing? *Will I need similar functionality on other sites? If any of them is "Yes"? Then best to break it into a separate application. A: I tend to create new applications for each logically separate set of models. e.g.: * *User Profiles *Forum Posts *Blog posts A: An 'app' could be many different things, it all really comes down to taste. For example, let's say you are building a blog. Your app could be the entire blog, or you could have an 'admin' app, a 'site' app for all of the public views, an 'rss' app, a 'services' app so developers can interface with the blog in their own ways, etc. I personally would make the blog itself the app, and break out the functionality within it. The blog could then be reused rather easily in other websites. The nice thing about Django is that it will recognize any models.py file within any level of your directory tree as a file containing Django models. So breaking your functionality out into smaller 'sub apps' within an 'app' itself won't make anything more difficult.
{ "language": "en", "url": "https://stackoverflow.com/questions/64237", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "136" }
Q: Castle Windsor: How do you add a call to a factory facility not in xml? I know how to tell Castle Windsor to resolve a reference from a factory's method using XML, but can I do it programmatically via the Container.AddComponent() interface? If not is there any other way to do it from code? EDIT: There seems to be some confusion so let me clarify, I am looking for a way to do the following in code: <facilities> <facility id="factory.support" type="Castle.Facilities.FactorySupport.FactorySupportFacility, Castle.MicroKernel" /> </facilities> <components> <component id="CustomerRepositoryFactory" type="ConsoleApplication2.CustomerRepositoryFactory, ConsoleApplication2" /> <component id="CustomerRepository" service="ConsoleApplication2.ICustomerRepository, ConsoleApplication2" type="ConsoleApplication2.CustomerRepository, ConsoleApplication2" factoryId="CustomerRepositoryFactory" factoryCreate="Create" /> </components> (from this codebetter article on factory support in windsor and spring.net) A: Directly from the Unit Test FactorySupportTestCase (which are your friends): [Test] public void FactorySupport_UsingProxiedFactory_WorksFine() { container.AddFacility("factories", new FactorySupportFacility()); container.AddComponent("standard.interceptor", typeof(StandardInterceptor)); container.AddComponent("factory", typeof(CalulcatorFactory)); AddComponent("calculator", typeof(ICalcService), typeof(CalculatorService), "Create"); ICalcService service = (ICalcService) container["calculator"]; Assert.IsNotNull(service); } private void AddComponent(string key, Type service, Type type, string factoryMethod) { MutableConfiguration config = new MutableConfiguration(key); config.Attributes["factoryId"] = "factory"; config.Attributes["factoryCreate"] = factoryMethod; container.Kernel.ConfigurationStore.AddComponentConfiguration(key, config); container.Kernel.AddComponent(key, service, type); }
{ "language": "en", "url": "https://stackoverflow.com/questions/64238", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Encrypt/Decrypt across machines is a no-no I'm using an identical call to "CryptUnprotectData" (exposed from Crypt32.dll) between XP and Vista. Works fine in XP. I get the following exception when I run in Vista: "Decryption failed. Key not valid for use in specified state." As expected, the versions of crypt32.dll are different between XP and Vista (w/XP actually having the more recent, possibly as a result of SP3 or some other update). More specifically, I'm encrypting data, putting it in the registry, then reading and decrypting using "CryptUnprotectData". UAC is turned off. Anyone seen this one before? A: The CryptUnprotectData function documentation states that it usually only works when the user has the same logon credentials as the encrypter. This suggests to me that maybe the key is tied to the user's current token. Since you mention Vista, this makes me think UAC and restricted tokens. Can you show us some code? Can you give us more information about what you're doing with the data -- i.e. are you moving it between processes, or users, or computers? A: Nice. Hopefully this is my bone-head move of the week! ;-) This suggests to me that maybe the key is tied to the user's current token. That was it. Turns out I was using encrypted data from another machine (the XP one) and trying to decrypt on the Vista machine. As the MSDN documentation states: Usually, only a user with the same logon credentials as the encrypter can decrypt the data. In addition, the encryption and decryption must be done on the same computer. Once I re-encrypted the data on the Vista machine, decryption works as expected. Thanks.
{ "language": "en", "url": "https://stackoverflow.com/questions/64258", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to eliminate flicker in Windows.Forms custom control when scrolling? I want to create a custom control in C#. But every time I have to fully redraw my control, it flickers, even if I use double buffering (drawing to an Image first, and blitting that). How do I eliminate flicker when I have to fully redraw? A: I pulled this from a working C# program. Other posters have syntax errors and clearly copied from C++ instead of C# SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint, true); A: You could try putting the following in your constructor after the InitiliseComponent call. SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint, true); EDIT: If you're giving this a go, if you can, remove your own double buffering code and just have the control draw itself in response to the appropriate virtual methods being called. A: It may be good enough to just call SetStyle(ControlStyles::UserPaint | ControlStyles::AllDrawingInWmPaint, true); The flickering you are seeing most likely because Windows draws the background of the control first (via WM_ERASEBKGND), then asks your control to do whatever drawing you need to do (via WM_PAINT). By disabling the background paint and doing all painting in your OnPaint override can eliminate the problem in 99% of the cases without the need to use all the memory needed for double buffering. A: You say you've tried double buffering, but then you say drawing to an Image first and blitting that. Have you tried setting DoubleBuffered = true in the constructor rather than doing it yourself with an Image?
{ "language": "en", "url": "https://stackoverflow.com/questions/64272", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: How do you tell IIS 6 to set the .NET version to 2.0 (not 1.1) When New sites are created? We create new sites in IIS 6 (Windows Server 2003) using IIS Manager. When these sites are created in IIS 6, the ASP.NET version defaults to ASP.NET 1.1. We would like it to default to ASP.NET 2.0. The reason this is a problem for us is that when you take any site on the server and switch the ASP.NET version from ASP.NET 1.1 to ASP.NET 2.0, all web sites recycle. Is there a setting in the IIS metabase that controls this or a way to create a site via script that sets the ASP.Net version correctly so that we can avoid the IIS reset when setting up each site? A: Be warned, running aspnet_regiis -i will remap all of your IIS websites to 2.0. If you have existing 1.1 applications that you want to keep, run aspnet_regiis -ir instead. This will set 2.0 to be the default runtime for IIS, but it won't change the script mappings for existing sites. A: Find the directory for the version of .Net you want, for example; C:\Windows\Microsoft.NET\Framework\v2.0.50727 Get a cmd prompt there and then run aspnet_regiis -i. Further info @ http://weblogs.asp.net/owscott/archive/2006/05/30/ASPNet_5F00_regiis.exe-tool_2C00_-setting-the-default-version-without-forcing-an-upgrade-on-all-sites.aspx Ryan A: The following will set the default website to ASP.NET 2.0: C:\windows\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -sn W3SVC/ Child applications inherit the ASP.NET setting from the parent, so all children will have the new setting. Alternatively run as variation on this command after setting up the new application. Rob A: As already mentioned by another, I reference this post whenever I need to change the .NET settings for a site. As for your question, the following steps (summarized from the linked post) should achieve what you need: * *Run aspnet_regiis -lk from any .NET framework folder to list your current settings to help you determine which sites should remain using .NET 1.1. If you know there is a .NET 1.1 site, but it is not explicitly listed by this command, then it is inheriting from the root W3SVC/. *For all .NET 1.1 sites not explicitly listed by the previous command, you will need to force them to use .NET 1.1: * *Determine the Identifier ID of the site(s) which you want to force to use .NET 1.1. (Through the IIS 6 Manager, you can determine the Identifier of a site by clicking the "Web Sites" folder on the left side of the tool. On the right side, all your sites will be listed, and the Identifier column shows the ID.) *From the .NET 1.1 framework folder, run aspnet_regiis -sn W3SVC/<Identifier ID>/ROOT/ where <Identifier ID> is the ID of the site which you want to force to use .NET 1.1. *Finally, change the root W3SVC/ to use .NET 2.0 so that all newly created sites will inherit from the root and default to use .NET 2.0. To change the root, from the .NET 2.0 framework folder, run aspnet_regiis -sn W3SVC/. You can run aspnet_regiis -lk again to verify your settings. A: Simple answer: Open IIS Manager. In navigation pane, find the .NET2 web site and right click on it. Select "Properties". Then select "ASP.NET" tab. First dropdown on that screen gives you option to select a different version of .NET. Please be aware -- when I did this, all of the web sites on the web server stopped running. Microsoft support told me that .NET1 and .NET2 should not be run from same general area (default web sites) of the web server. Solution is to create an application pool on the web server for either .NET1 or .NET2 sites and then use that to isolate all sites running the "other" version of .NET. Instruction for creating an application pool can be found under "help" in IIS Manager. You can create just one application pool and put all sites with same .NET in the same pool or you can create an application pool for each application. Your choice.
{ "language": "en", "url": "https://stackoverflow.com/questions/64279", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: What's the best way to load highly re-used data in a .net web application Let's say I have a list of categories for navigation on a web app. Rather than selecting from the database for every user, should I add a function call in the application_onStart of the global.asax to fetch that data into an array or collection that is re-used over and over. If my data does not change at all - (Edit - very often), would this be the best way? A: Premature optimization is evil. That being a given, if you are having performance problems in your application and you have "static" information that you want to display to your users you can definitely load that data once into an array and store it in the Application Object. You want to be careful and balance memory usage with optimization. The problem you run into then is changing the database stored info and not having it update the cached version. You would probably want to have some kind of last changed date in the database that you store in the state along with the cached data. That way you can query for the greatest changed time and compare it. If it's newer than your cached date then you dump it and reload. A: You can store the list items in the Application object. You are right about the application_onStart(), simply call a method that will read your database and load the data to the Application object. In Global.asax public class Global : System.Web.HttpApplication { // The key to use in the rest of the web site to retrieve the list public const string ListItemKey = "MyListItemKey"; // a class to hold your actual values. This can be use with databinding public class NameValuePair { public string Name{get;set;} public string Value{get;set;} public NameValuePair(string Name, string Value) { this.Name = Name; this.Value = Value; } } protected void Application_Start(object sender, EventArgs e) { InitializeApplicationVariables(); } protected void InitializeApplicationVariables() { List<NameValuePair> listItems = new List<NameValuePair>(); // replace the following code with your data access code and fill in the collection listItems.Add( new NameValuePair("Item1", "1")); listItems.Add( new NameValuePair("Item2", "2")); listItems.Add( new NameValuePair("Item3", "3")); // load it in the application object Application[ListItemKey] = listItems; } } Now you can access your list in the rest of the project. For example, in default.aspx to load the values in a DropDownList: <asp:DropDownList runat="server" ID="ddList" DataTextField="Name" DataValueField="Value"></asp:DropDownList> And in the code-behind file: protected override void OnPreInit(EventArgs e) { ddList.DataSource = Application[Global.ListItemKey]; ddList.DataBind(); base.OnPreInit(e); } A: If it never changes, it probably doesn't need to be in the database. If there isn't much data, you might put it in the web.config, or as en Enum in your code. A: Fetching all may be expensive. Try lazy init, fetch only request data and then store it in the cache variable. A: In an application variable. Remember that an application variable can contain an object in .Net, so you can instantiate the object in the global.asax and then use it directly in the code. Since application variables are in-memory they are very quick (vs having to call a database) For example: // Create and load the profile object x_siteprofile thisprofile = new x_siteprofile(Server.MapPath(String.Concat(config.Path, "templates/"))); Application.Add("SiteProfileX", thisprofile); A: I would store the data in the Application Cache (Cache object). And I wouldn't preload it, I would load it the first time it is requested. What is nice about the Cache is that ASP.NET will manage it including giving you options for expiring the cache entry after file changes, a time period, etc. And since the items are kept in memory, the objects don't get serialized/deserialized so usage is very fast. Usage is straightforward. There are Get and Add methods on the Cache object to retrieve and add items to the cache respectively. A: I use a static collection as a private with a public static property that either loads or gets it from the database. Additionally you can add a static datetime that gets set when it gets loaded and if you call for it, past a certain amount of time, clear the static collection and requery it. A: Caching is the way to go. And if your into design patterns, take a look at the singleton. Overall however I'm not sure I'd be worried about it until you notice performance degradation.
{ "language": "en", "url": "https://stackoverflow.com/questions/64284", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can you cascade filter the attributes of more dimensions in a SSAS cube, viewed in Excel 2007 How can you cascade filter the attributes of more dimensions in a SSAS cube, viewed in Excel 2007. For example, if we have a cube Sales with the dimension Time and dimension Client, once the dimension Time is filtered to show only the sales from a particular date, if "Client.ClientName" is chosen as a filter in the filter area, how can the list of clients be filtered so that only the clients that have sales in the particular date, be shown. A: Take a look at www.clicksoft.ro The product named QuickCubeFiltrator is a wizard like addin for excel 2007 that does cascade filtering. Might be what you need. A: I have tried this before and haven't had much luck. Not sure you can really do it easily. You can try using named sets and calculated members but most of the time it depends on your data and hierarchies. You can also look at reporting services, and how it does it behind the scenes in MDX, but I don't know what good that will do you in Excel though. Like I said, this is a tough one.
{ "language": "en", "url": "https://stackoverflow.com/questions/64288", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: API for server-side 3D rendering I'm working on an application that needs to quickly render simple 3D scenes on the server, and then return them as a JPEG via HTTP. Basically, I want to be able to simply include a dynamic 3D scene in an HTML page, by doing something like: <img src="http://www.myserver.com/renderimage?scene=1&x=123&y=123&z=123"> My question is about what technologies to use to do the rendering. In a desktop application I would quite naturally use DirectX, but I'm afraid it might not be ideal for a server-side application that would be creating images for dozens or even hundreds of users in tandem. Does anyone have any experience with this? Is there a 3D API (preferably freely available) that would be ideal for this application? Is it better to write a software renderer from scratch? My main concerns about using DirectX or OpenGL, is whether it will function well in a virtualized server environment, and whether it makes sense with typical server hardware (over which I have little control). A: RealityServer by mental images is designed to do precisely what is described here. More details are available on the product page (including a downloadable Developer Edition). RealityServer docs A: Id say your best bet is have a Direct3D/OpenGL app running on the server (without stopping). THen making the server page send a request to the rendering app, and have the rendering app snend a jpg/png/whatever back. * *If Direct3D/OpenGL is to slow to render the scene in hardware, then any software solution will be worse *By keep the rendering app running, you are avoiding the overhead of creating/destroying textures, backbuffers, vertex buffers, etc. You could potentialy render a simply scene 100's of times a second. However many servers do not have graphics cards. Direct3D is largly useless in software (there is an emulated device from Ms, but its only good for testing effects), never tried OpenGL in software. A: You could wrap Pov-ray (here using POSIX and the Windows build). PHP example: <?php chdir("/tmp"); @unlink("demo.png"); system("~janus/.wine/drive_c/POV-Ray-v3.7-RC6/bin/pvengine-sse2.exe /render demo.pov /exit"); header("Content-type: image/png"); fpassthru($f = fopen("demo.png","r")); fclose($f); ?> demo.pov available here. You could use a templating language like Jinja2 to insert your own camera coordinates. A: Server side rendering only makes sense if the scene consists of a huge number of objects such that the download of the data set to the client for client rendering would be far too slow and the rendering is not expected to be in realtime. Client side rendering isn't too difficult if you use something like jogl coupled with progressive scene download (i.e. download foreground objects and render, then incrementally download objects based on distance from view point and re-render). If you really want to do server side rendering, you may want to separate the web server part and the rendering part onto two computers with each configured optimally for their task (renderer has OpenGL card, minimal HD and just enough RAM, server has lots of fast disks, lots of ram, backups and no OpenGL). I very much doubt you will be able to do hardware rendering on a virtualised server since the server probably doesn't have a GPU. A: Not so much an API but rather a renderer; Povray? There also seem to exist a http interface... A: Yafaray (http://www.yafaray.org/) might be a good first choice to consider for general 3D rendering. It's reasonably fast and the results look great. It can be used within other software, e.g. the Blender 3D modeler. The license is LPGL. If the server-side software happens to be written in Python, and the desired 3D scene is a visualization of scientific data, look into MayaVi2 http://mayavi.sourceforge.net/, or if not, go for a browse at http://www.vrplumber.com/py3d.py Those who suggest the widely popular POV-Ray need to realize it's not a library or any kind of entity that offers an API. The server-side process would need to write a text scene file, execute a new process to run POV-Ray with the right options, and take the resulting image file. If that's easy to set up for a particular application, and if you've more expertise with POV-Ray than with other renderers, well go for it! A: You could also look at Java3D (https://java3d.dev.java.net/), which would be an elegant solution if your server architecture was Java-based already. I'd also recommend trying to get away with a software-only rendering solution if you can - trying to wrangle a whole lot of server processes that are all making concurrent demands on the 3D rendering hardware sounds like a lot of work. A: Check out wgpu.net. I think it's very helpful.
{ "language": "en", "url": "https://stackoverflow.com/questions/64291", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Does emacs have something like vi's "set number"? Does emacs have something like vi's “set number”, so that each line starts with its line number? A: Take a look at this article. It explains various ways to add line numbers to emacs: http://www.emacswiki.org/cgi-bin/wiki/LineNumbers A: Try adding linum.el to your emacs dir / .emacs file.
{ "language": "en", "url": "https://stackoverflow.com/questions/64293", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Convert WAV to WMA using .NET What is the best solution for converting WAV files to WMA (and vice versa) in C#? I have actually implemented this once already using the Windows Media Encoder SDK, but having to distribute Windows Media Encoder with my application is cumbersome to say the least. The Windows Media Format SDK has large sections of the API marked as deprecated. It looks like there might be some DirectX Media Objects (DMOs) I could use from the Windows SDK, but there would be an awful lot of interop to write. I am wondering if there perhaps is a good managed wrapper for an unmanaged library that can perform the conversions. It would need a license that allows it to be distributed as part of a closed source commercial application. A: I haven't tried it personally (so not sure if it's the 'best' solution), but http://www.codeproject.com/KB/audio-video/WmaCompressor.aspx looks like it should meet your requirements... A: You can take a look at the BASS library. It has add-ons, such as BASSWMA and BASSEnc for doing encoding/decoding. All its API's are accessible from .NET using the BASS.Net wrapper. Both BASS and BASS.Net could be licensed for commercial use, with a reasonable fee (€100 each). A: If you're comfortable writing a bit of C++/CLI then you don't need much code to create a wrapper around DirectShow to do this. This can then be called directly from a C# assembly with no need to mess about with interop. Doing it with DirectShow is much easier than using WMF directly because you don't have to do any file parsing or I/O - it's all done for you. For reference, I have code in a commercial app that can encode/decode WMA to/from WAV files in less than 100 lines of C++, all wrapped up in a friendly .Net class. Judicious use of smart pointers helps if you go down this route... A: First of all, look at this: http://windowsmedianet.sourceforge.net/ Then, search for IWMWritter - and various ways of initializing it. You will supply raw PCM data, and it will write out wma file. Tag my answer please for more info on this. A: You might look at www.mitov.com. There are some libraries there that may help. You'll need to buy a copy to ship in a commercial product, I believe, but I think it's a reasonable price.
{ "language": "en", "url": "https://stackoverflow.com/questions/64303", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: How do you vertically center a custom image in a * element across browsers? The design for the website I am working on calls for a custom image on lists instead of a bullet. Using the image is fine, but I have been having difficulties ensuring that it is centered against the text of the list item across all browsers. Does anyone know of a standard solution for this? A: If you are referring to using a custom image bullet for your list this is the code you'll want to use, it will be vertically centered. I'm assuming here that the bullet image is 12px by 12px. ul li { background: transparent url(/link/to/custom/bullet.gif) no-repeat 0 50%; padding-left: 18px; } The only problem with this is that sometimes on long multi-line list items it looks odd. In that case it might be best to assign the background position to a slight indent from the top and the left (i.e. no-repeat 0 7px). cheers, Bruce A: Have you tried adding the following code in your CSS file? li { background-image: URL('custom.png'); background-repeat: no-repeat; background-position: center; } A: set a specific line-height on the li element and a vertica align on the image.. worked for me li { height: 150px; line-height: 150px; } li img { vertical-align: middle; } and the HTML code <li><img src="myimage.jpg" /></li> if you want adapt the image to a custon size, preserving the ratio li img { max-width: 150px; max-height: 150px; width: auto; height: auto; }
{ "language": "en", "url": "https://stackoverflow.com/questions/64311", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Copying databases to remote locations Our EPOS system copies data by compressing the database into a zip file, and manually copying to each till, using shared directories. Each branched is liked to the main location, using VPN which can be problematic, but is required for the file sharing to work correctly. Since our database system currently does not support replication, is there another solution for copying data or should we migrate our software to another database? A: Replication is the "right" way to go, so if migrating to another database is an option (is it really?), that's the best route. You might consider a utility that queries all the tables for raw data (in CSV?), sending that to files. Then at least you don't have to take the database down to do the backup.
{ "language": "en", "url": "https://stackoverflow.com/questions/64314", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Refactoring dissassembled code You write a function and, looking at the resulting assembly, you see it can be improved. You would like to keep the function you wrote, for readability, but you would like to substitute your own assembly for the compiler's. Is there any way to establish a relationship between your high-livel language function and the new assembly? A: If you are looking at the assembly, then its fair to assume that you have a good understanding about how code gets compiled down. If you have this knowledge, then its sometimes possible to 'reverse enginer' the changes back up into the original language but its often better not to bother. The optimisations that you make are likely to be very small in comparison to the time and effort required in first making these changes. I would suggest that you leave this kind of work to the compiler and go have a cup of tea. If the changes are significant, and the performance is critical, (as say in the embedded world) then you might want to mix the normal code with the assemblar in some fashion, however, on most computers and chips the performance is usually sufficient to avoid this headache. If you really need more performance, then optimise the code not the assembly. A: None, I suppose. You've rejected the compiler's work in favor of your own. You might as well throw out the function you wrote in the compiled language, because now all you have is your assembler in that platform. I would highly advise against engaging in this kind of optimization because unless you're sure, via profiling and analysis, that you truly are making a difference. A: It depends on the language you wrote your function in. Some languages like C are very low-level, translating each function call or statement to specific assembly statements. If you did use C, you can replace your function with inline assembly to improve performance. Other high-level languages may convert each statement into macro routines or other more complex calls on the assembly side. Certain optimizations (like tail recursion, loop unrolling, etc) can be implemented easily on the source side, but others (like making more efficient use of the register file) may be impossible (again, depending on the language and the compiler you're using). A: Its tough to say there is any relationship between modified assembly and the source which generated the unmodified version. It will certainly confuse debugging tools: register contents will no longer match the source variables they were supposed to correspond to. There are a number of places in packet processing code where I've examined the generated assembly and gone back to change the original source code in order to improve the result. Re-arranging source can reduce the number of branches, __attribute__ and compiler arguments can align branch points and functions to reduce I$ misses. In desperate cases a little inline assembly can be used, so that the binary can still be compiled from source. A: Something you could try is to separate your original function into its own file, and provide a make rule to build the assembler from there. Then update the assembler file with your improved version, and provide a make rule to build an object file from the assembler file. Then change your link rules to include that object file. If you only ever change the assembler file, that will keep on being used. If you ever change the original higher-level language file, the assembler file will be rebuilt and the object file built from the new (unimproved) version. This gives you a relationship between the two; you probably want to add a warning comment at the top of the higher-level language file to warn about the behaviour. Using some form of VCS will give you the ability to recover the improved assembler file if you make a mistake here. A: If you're writing a native compiled app in Visual C++, there are two methods: * *Use the __asm { } block and write your assembler in there. *Write your functions in MASM assembler, assemble to .obj, and link it as an static library. In your C/C++ code, declare the function with an extern "C" declaration. Other C/C++ compilers have similar approaches. A: In this situation, you generally have two options: optimize the code or rewrite the compiler. I can't see where breaking the link between source and op is ever going to be the correct solution.
{ "language": "en", "url": "https://stackoverflow.com/questions/64321", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Disadvantages of Test Driven Development? What do I lose by adopting test driven design? List only negatives; do not list benefits written in a negative form. A: Well, and this stretching, you need to debug your tests. Also, there is a certain cost in time for writing the tests, though most people agree that it's an up-front investment that pays off over the lifetime of the application in both time saved debugging and in stability. The biggest problem I've personally had with it, though, is getting up the discipline to actually write the tests. In a team, especially an established team, it can be hard to convince them that the time spent is worthwhile. A: The downside to TDD is that it is usually tightly associated with 'Agile' methodology, which places no importance on documentation of a system, rather the understanding behind why a test 'should' return one specific value rather than any other resides only in the developer's head. As soon as the developer leaves or forgets the reason that the test returns one specific value and not some other, you're screwed. TDD is fine IF it is adequately documented and surrounded by human-readable (ie. pointy-haired manager) documentation that can be referred to in 5 years when the world changes and your app needs to as well. When I speak of documentation, this isn't a blurb in code, this is official writing that exists external to the application, such as use cases and background information that can be referred to by managers, lawyers and the poor sap who has to update your code in 2011. A: I've encountered several situations where TDD makes me crazy. To name some: * *Test case maintainability: If you're in a big enterprise, many chances are that you don't have to write the test cases yourself or at least most of them are written by someone else when you enter the company. An application's features changes from time to time and if you don't have a system in place, such as HP Quality Center, to track them, you'll turn crazy in no time. This also means that it'll take new team members a fair amount of time to grab what's going on with the test cases. In turn, this can be translated into more money needed. *Test automation complexity: If you automate some or all of the test cases into machine-runnable test scripts, you will have to make sure these test scripts are in sync with their corresponding manual test cases and in line with the application changes. Also, you'll spend time to debug the codes that help you catch bugs. In my opinion, most of these bugs come from the testing team's failure to reflect the application changes in the automation test script. Changes in business logic, GUI and other internal stuff can make your scripts stop running or running unreliably. Sometimes the changes are very subtle and difficult to detect. Once all of my scripts report failure because they based their calculation on information from table 1 while table 1 was now table 2 (because someone swapped the name of the table objects in the application code). A: If your tests are not very thorough you might fall into a false sense of "everything works" just because you tests pass. Theoretically if your tests pass, the code is working; but if we could write code perfectly the first time we wouldn't need tests. The moral here is to make sure to do a sanity check on your own before calling something complete, don't just rely on the tests. On that note, if your sanity check finds something that is not tested, make sure to go back and write a test for it. A: When you get to the point where you have a large number of tests, changing the system might require re-writing some or all of your tests, depending on which ones got invalidated by the changes. This could turn a relatively quick modification into a very time-consuming one. Also, you might start making design decisions based more on TDD than on actually good design prinicipals. Whereas you may have had a very simple, easy solution that is impossible to test the way TDD demands, you now have a much more complex system that is actually more prone to mistakes. A: The biggest problem are the people who don't know how to write proper unit tests. They write tests that depend on each other (and they work great running with Ant, but then all of sudden fail when I run them from Eclipse, just because they run in different order). They write tests that don't test anything in particular - they just debug the code, check the result, and change it into test, calling it "test1". They widen the scope of classes and methods, just because it will be easier to write unit tests for them. The code of unit tests is terrible, with all the classical programming problems (heavy coupling, methods that are 500 lines long, hard-coded values, code duplication) and is a hell to maintain. For some strange reason people treat unit tests as something inferior to the "real" code, and they don't care about their quality at all. :-( A: You lose the ability to say you are "done" before testing all your code. You lose the capability to write hundreds or thousands of lines of code before running it. You lose the opportunity to learn through debugging. You lose the flexibility to ship code that you aren't sure of. You lose the freedom to tightly couple your modules. You lose option to skip writing low level design documentation. You lose the stability that comes with code that everyone is afraid to change. A: I think the biggest problem for me is the HUGE loss of time it takes "getting in to it". I am still very much at the beginning of my journey with TDD (See my blog for updates my testing adventures if you are interested) and I have literally spent hours getting started. It takes a long time to get your brain into "testing mode" and writing "testable code" is a skill in itself. TBH, I respectfully disagree with Jason Cohen's comments on making private methods public, that's not what it is about. I have made no more public methods in my new way of working than before. It does, however involve architectural changes and allowing for you to "hot plug" modules of code to make everything else easier to test. You should not be making the internals of your code more accessible to do this. Otherwise we are back to square one with everything being public, where is the encapsulation in that? So, (IMO) in a nutshell: * *The amount of time taken to think (i.e. actually grok'ing testing). *The new knowledge required of knowing how to write testable code. *Understanding the architectural changes required to make code testable. *Increasing your skill of "TDD-Coder" while trying to improve all the other skills required for our glorious programming craft :) *Organising your code base to include test code without screwing your production code. PS: If you would like links to positives, I have asked and answered several questions on it, check out my profile. A: In the few years that I've been practicing Test Driven Development, I'd have to say the biggest downsides are: Selling it to management TDD is best done in pairs. For one, it's tough to resist the urge to just write the implementation when you KNOW how to write an if/else statement. But a pair will keep you on task because you keep him on task. Sadly, many companies/managers don't think that this is a good use of resources. Why pay for two people to write one feature, when I have two features that need to be done at the same time? Selling it to other developers Some people just don't have the patience for writing unit tests. Some are very proud of their work. Or, some just like seeing convoluted methods/functions bleed off the end of the screen. TDD isn't for everyone, but I really wish it were. It would make maintaining stuff so much easier for those poor souls who inherit code. Maintaining the test code along with your production code Ideally, your tests will only break when you make a bad code decision. That is, you thought the system worked one way, and it turns out it didn't. By breaking a test, or a (small) set of tests, this is actually good news. You know exactly how your new code will affect the system. However, if your tests are poorly written, tightly coupled or, worse yet, generated (cough VS Test), then maintaining your tests can become a choir quickly. And, after enough tests start to cause more work that the perceived value they are creating, then the tests will be the first thing to be deleted when schedules become compressed (eg. it gets to crunch time) Writing tests so that you cover everything (100% code coverage) Ideally, again, if you adhere to the methodology, your code will be 100% tested by default. Typically, thought, I end up with code coverage upwards of 90%. This usually happens when I have some template style architecture, and the base is tested, and I try to cut corners and not test the template customizations. Also, I have found that when I encounter a new barrier I hadn't previously encountered, I have a learning curve in testing it. I will admit to writing some lines of code the old skool way, but I really like to have that 100%. (I guess I was an over achiever in school, er skool). However, with that I'd say that the benefits of TDD far outweigh the negatives for the simple idea that if you can achieve a good set of tests that cover your application but aren't so fragile that one change breaks them all, you will be able to keep adding new features on day 300 of your project as you did on day 1. This doesn't happen with all those who try TDD thinking it's a magic bullet to all their bug-ridden code, and so they think it can't work, period. Personally I have found that with TDD, I write simpler code, I spend less time debating if a particular code solution will work or not, and that I have no fear to change any line of code that doesn't meet the criteria set forth by the team. TDD is a tough discipline to master, and I've been at it for a few years, and I still learn new testing techniques all the time. It is a huge time investment up front, but, over the long term, your sustainability will be much greater than if you had no automated unit tests. Now, if only my bosses could figure this out. A: You lose a lot of time spent writing tests. Of course, this might be saved by the end of the project by catching bugs faster. A: Refocusing on difficult, unforeseen requirements is the constant bane of the programmer. Test-driven development forces you to focus on the already-known, mundane requirements, and limits your development to what has already been imagined. Think about it, you are likely to end up designing to specific test cases, so you won't get creative and start thinking "it would be cool if the user could do X, Y, and Z". Therefore, when that user starts getting all excited about potential cool requirements X, Y, and Z, your design may be too rigidly focused on already specified test cases, and it will be difficult to adjust. This, of course, is a double edged sword. If you spend all your time designing for every conceivable, imaginable, X, Y, and Z that a user could ever want, you will inevitably never complete anything. If you do complete something, it will be impossible for anyone (including yourself) to have any idea what you're doing in your code/design. A: On your first TDD project there are two big losses, time and personal freedom You lose time because: * *Creating a comprehensive, refactored, maintainable suite of unit and acceptance tests adds major time to the first iteration of the project. This may be time saved in the long run but equally it can be time you don't have to spare. *You need to choose and become expert in a core set of tools. A unit testing tool needs to be supplemented by some kind of mocking framework and both need to become part of your automated build system. You also want to pick and generate appropriate metrics. You lose personal freedom because: * *TDD is a very disciplined way of writing code that tends to rub raw against those at the top and bottom of the skills scale. Always writing production code in a certain way and subjecting your work to continual peer review may freak out your worst and best developers and even lead to loss of headcount. *Most Agile methods that embed TDD require that you talk to the client continually about what you propose to accomplish (in this story/day/whatever) and what the trade offs are. Once again this isn't everyone's cup of tea, both on the developers side of the fence and the clients. Hope this helps A: If you want to do "real" TDD (read: test first with the red, green, refactor steps) then you also have to start using mocks/stubs, when you want to test integration points. When you start using mocks, after a while, you will want to start using Dependency Injection (DI) and a Inversion of Control (IoC) container. To do that you need to use interfaces for everything (which have a lot of pitfalls themselves). At the end of the day, you have to write a lot more code, than if you just do it the "plain old way". Instead of just a customer class, you also need to write an interface, a mock class, some IoC configuration and a few tests. And remember that the test code should also be maintained and cared for. Tests should be as readable as everything else and it takes time to write good code. Many developers don't quite understand how to do all these "the right way". But because everybody tells them that TDD is the only true way to develop software, they just try the best they can. It is much harder than one might think. Often projects done with TDD end up with a lot of code that nobody really understands. The unit tests often test the wrong thing, the wrong way. And nobody agrees how a good test should look like, not even the so called gurus. All those tests make it a lot harder to "change" (opposite to refactoring) the behavior of your system and simple changes just becomes too hard and time consuming. If you read the TDD literature, there are always some very good examples, but often in real life applications, you must have a user interface and a database. This is where TDD gets really hard, and most sources don't offer good answers. And if they do, it always involves more abstractions: mock objects, programming to an interface, MVC/MVP patterns etc., which again require a lot of knowledge, and... you have to write even more code. So be careful... if you don't have an enthusiastic team and at least one experienced developer who knows how to write good tests and also knows a few things about good architecture, you really have to think twice before going down the TDD road. A: You will lose large classes with multiple responsibilities. You will also likely lose large methods with multiple responsibilities. You may lose some ability to refactor, but you will also lose some of the need to refactor. Jason Cohen said something like: TDD requires a certain organization for your code. This might be architecturally wrong; for example, since private methods cannot be called outside a class, you have to make methods non-private to make them testable. I say this indicates a missed abstraction -- if the private code really needs to be tested, it should probably be in a separate class. Dave Mann A: The biggest downside is that if you really want to do TDD properly you will have to fail a lot before you succeed. Given how many software companies work (dollar per KLOC) you will eventually get fired. Even if your code is faster, cleaner, easier to maintain, and has less bugs. If you are working in a company that pays you by the KLOCs (or requirements implemented -- even if not tested) stay away from TDD (or code reviews, or pair programming, or Continuous Integration, etc. etc. etc.). A: TDD requires you to plan out how your classes will operate before you write code to pass those tests. This is both a plus and a minus. I find it hard to write tests in a "vacuum" --before any code has been written. In my experience I tend to trip over my tests whenever I inevitably think of something while writing my classes that I forgot while writing my initial tests. Then it's time to not only refactor my classes, but ALSO my tests. Repeat this three or four times and it can get frustrating. I prefer to write a draft of my classes first then write (and maintain) a battery of unit tests. After I have a draft, TDD works fine for me. For example, if a bug is reported, I will write a test to exploit that bug and then fix the code so the test passes. A: Prototyping can be very difficult with TDD - when you're not sure what road you're going to take to a solution, writing the tests up-front can be difficult (other than very broad ones). This can be a pain. Honestly I don't think that for "core development" for the vast majority of projects there's any real downside, though; it's talked down a lot more than it should be, usually by people who believe their code is good enough that they don't need tests (it never is) and people who just plain can't be bothered to write them. A: Several downsides (and I'm not claiming there are no benefits - especially when writing the foundation of a project - it'd save a lot of time at the end): * *Big time investment. For the simple case you lose about 20% of the actual implementation, but for complicated cases you lose much more. *Additional Complexity. For complex cases your test cases are harder to calculate, I'd suggest in cases like that to try and use automatic reference code that will run in parallel in the debug version / test run, instead of the unit test of simplest cases. *Design Impacts. Sometimes the design is not clear at the start and evolves as you go along - this will force you to redo your test which will generate a big time lose. I would suggest postponing unit tests in this case until you have some grasp of the design in mind. *Continuous Tweaking. For data structures and black box algorithms unit tests would be perfect, but for algorithms that tend to be changed, tweaked or fine tuned, this can cause a big time investment that one might claim is not justified. So use it when you think it actually fits the system and don't force the design to fit to TDD. A: I second the answer about initial development time. You also lose the ability to confortably work without the safety of tests. I've also been described as a TDD nutbar, so you could lose a few friends ;) A: It's percieved as slower. Long term that's not true in terms of the grief it will save you down the road, but you'll end up writing more code so arguably you're spending time on "testing not coding". It's a flawed argument, but you did ask! A: It can be hard and time consuming writing tests for "random" data like XML-feeds and databases (not that hard). I've spent some time lately working with weather data feeds. It's quite confusing writing tests for that, at least as i don't have too much experience with TDD. A: You have to write applications in a different way: one which makes them testable. You'd be surprised how difficult this is at first. Some people find the concept of thinking about what they're going to write before they write it too hard. Concepts such as mocking can be difficult for some too. TDD in legacy apps can be very difficult if they weren't designed for testing. TDD around frameworks that are not TDD friendly can also be a struggle. TDD is a skill so junior devs may struggle at first (mainly because they haven't been taught to work this way). Overall though the cons become solved as people become skilled and you end up abstracting away the 'smelly' code and have a more stable system. A: * *unit test are more code to write, thus a higher upfront cost of development *it is more code to maintain *additional learning required A: Good answers all. I would add a few ways to avoid the dark side of TDD: * *I've written apps to do their own randomized self-test. The problem with writing specific tests is even if you write lots of them they only cover the cases you think of. Random-test generators find problems you didn't think of. *The whole concept of lots of unit tests implies that you have components that can get into invalid states, like complex data structures. If you stay away from complex data structures there's a lot less to test. *To the extent your application allows it, be shy of design that relies on the proper ordering of notifications, events and side-effects. Those can easily get dropped or scrambled so they need a lot of testing. A: Let me add that if you apply BDD principles to a TDD project, you can alleviate a few of the major drawbacks listed here (confusion, misunderstandings, etc.). If you're not familiar with BDD, you should read Dan North's introduction. He came up the concept in answer to some of the issues that arose from applying TDD at the workplace. Dan's intro to BDD can be found here. I only make this suggestion because BDD addresses some of these negatives and acts as a gap-stop. You'll want to consider this when collecting your feedback. A: It takes some time to get into it and some time to start doing it in a project but... I always regret not doing a Test Driven approach when I find silly bugs that an automated test could have found very fast. In addition, TDD improves code quality. A: You have to make sure your tests are always up to date, the moment you start ignoring red lights is the moment the tests become meaningless. You also have to make sure the tests are comprehensive, or the moment a big bug appears, the stuffy management type you finally convinced to let you spend time writing more code will complain. A: The person who taught my team agile development didn't believe in planning, you only wrote as much for the tiniest requirement. His motto was refactor, refactor, refactor. I came to understand that refactor meant 'not planning ahead'. A: Development time increases : Every method needs testing, and if you have a large application with dependencies you need to prepare and clean your data for tests. A: You lose the ability to make incremental changes (code refactorings) and still feel warm and fuzzy that the code does what it is supposed to. You lose practically free and painless motivation to structure your code with minimal explicit dependencies. IOW, you'll be able to embed lots of dependencies without noticing. Were you to use TDD the dependencies would show up as pain/smell when writing the tests. A: TDD requires a certain organization for your code. This might be inefficient or difficult to read. Or even architecturally wrong; for example, since private methods cannot be called outside a class, you have to make methods non-private to make them testable, which is just wrong. When code changes, you have to change the tests as well. With refactoring this can be a lot of extra work.
{ "language": "en", "url": "https://stackoverflow.com/questions/64333", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "201" }
Q: using load() to load page that also uses jQuery I'm trying to load a page that is basically an edit form inside a dialog (ui.dialog). I can load this page fine from an external (I'm using asp.net) page. The problem is that inside of my "popup" form, I need to $(function() {my function here}); syntax to do some stuff when the page loads, along with registering some .fn extensions for some dynamic dropdowns using ajax calls. I have created my <script type="text/javascript" src="jquery.js"> but I don't think these are being included, and also my $(function) is not being called. Is this possible to do or do I need to find another way of accomplishing what I need to do? A: If you really need to load that form via AJAX you could to do all the Javascript stuff in $.ajax callback itself. So, you load the popup form like this: $.ajax({ //... success: function(text) { // insert text into container // the code from $(function() {}); } }); A: The script isn't getting run because the document's ready event has already been fired. Remove your code from within the $() A: Use the livequery plugin. It allows you to bind events to elements that might be loaded later: http://brandonaaron.net/docs/livequery/
{ "language": "en", "url": "https://stackoverflow.com/questions/64351", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to copy text from Emacs to another application on Linux When I cut (kill) text in Emacs 22.1.1 (in its own window on X, in KDE, on Kubuntu), I can't paste (yank) it in any other application. A: I assume by emacs you are meaning Emacs under X (ie not inside a terminal window). There are two ways: * *(Applies to unix OS's only) Highlight the desired text with your mouse (this copies it to the X clipboard) and then middle click to paste. *Highlight the desired text and then "M-x clipboard-kill-ring-save" (note you can bind this to an easier key). Then just "Edit->Paste" in your favorite app. Clipboard operations available: * *clipboard-kill-ring-save -- copy selection from Emacs to clipboard *clipboard-kill-region -- cut selection from Emacs to clipboard *clipboard-yank -- paste from clipboard to Emacs A: There is an EmacsWiki article that explains some issues with copy & pasting under X and how to configure it to work. A: This works with M-w on Mac OSX. Just add to your .emacs file. (defun copy-from-osx () (shell-command-to-string "pbpaste")) (defun paste-to-osx (text &optional push) (let ((process-connection-type nil)) (let ((proc (start-process "pbcopy" "*Messages*" "pbcopy"))) (process-send-string proc text) (process-send-eof proc)))) (setq interprogram-cut-function 'paste-to-osx) (setq interprogram-paste-function 'copy-from-osx) Source https://gist.github.com/the-kenny/267162 A: I use the following, based on the other answers here, to make C-x C-w and C-x C-y be copy and paste on both Mac and Linux (if someone knows the version for Windows feel free to add it). Note that on Linux you will have to install xsel and xclip with your package manager. ;; Commands to interact with the clipboard (defun osx-copy (beg end) (interactive "r") (call-process-region beg end "pbcopy")) (defun osx-paste () (interactive) (if (region-active-p) (delete-region (region-beginning) (region-end)) nil) (call-process "pbpaste" nil t nil)) (defun linux-copy (beg end) (interactive "r") (call-process-region beg end "xclip" nil nil nil "-selection" "c")) (defun linux-paste () (interactive) (if (region-active-p) (delete-region (region-beginning) (region-end)) nil) (call-process "xsel" nil t nil "-b")) (cond ((string-equal system-type "darwin") ; Mac OS X (define-key global-map (kbd "C-x C-w") 'osx-copy) (define-key global-map (kbd "C-x C-y") 'osx-paste)) ((string-equal system-type "gnu/linux") ; linux (define-key global-map (kbd "C-x C-w") 'linux-copy) (define-key global-map (kbd "C-x C-y") 'linux-paste))) A: Let's be careful with our definitions here * *An Emacs copy is the command kill-ring-save (usually bound to M-w). *A system copy is what you typically get from pressing C-c (or choosing "Edit->Copy" in a application window). *An X copy is "physically" highlighting text with the mouse cursor. *An Emacs paste is the command yank (usually bound to C-y). *A system paste is what you typically get from pressing C-v (or choosing "Edit-Paste" in an application window). *An X paste is pressing the "center mouse button" (simulated by pressing the left and right mouse buttons together). In my case (on GNOME): * *Both Emacs and system copy usually work with X paste. *X copy usually works with Emacs paste. *To make system copy work with Emacs paste and Emacs copy work with system paste, you need to add (setq x-select-enable-clipboard t) to your .emacs. Or try META-X set-variable RET x-select-enable-clipboard RET t I think this is pretty standard modern Unix behavior. It's also important to note (though you say you're using Emacs in a separate window) that when Emacs is running in a console, it is completely divorced from the system and X clipboards: cut and paste in that case is mediated by the terminal. For example, "Edit->Paste" in your terminal window should act exactly as if you typed the text from the clipboard into the Emacs buffer. A: The difficulty with copy and paste in Emacs is that you want it to work independently from the internal kill/yank, and you want it to work both in terminal and the gui. There are existing robust solutions for either terminal or gui, but not both. After installing xsel (e.g. sudo apt-get install xsel), here is what I do for copy and paste to combine them: (defun copy-to-clipboard () (interactive) (if (display-graphic-p) (progn (message "Yanked region to x-clipboard!") (call-interactively 'clipboard-kill-ring-save) ) (if (region-active-p) (progn (shell-command-on-region (region-beginning) (region-end) "xsel -i -b") (message "Yanked region to clipboard!") (deactivate-mark)) (message "No region active; can't yank to clipboard!"))) ) (defun paste-from-clipboard () (interactive) (if (display-graphic-p) (progn (clipboard-yank) (message "graphics active") ) (insert (shell-command-to-string "xsel -o -b")) ) ) (global-set-key [f8] 'copy-to-clipboard) (global-set-key [f9] 'paste-from-clipboard) A: I stick this in my .emacs: (setq x-select-enable-clipboard t) (setq interprogram-paste-function 'x-cut-buffer-or-selection-value) I subsequently have basically no problems cutting and pasting back and forth from anything in Emacs to any other X11 or Gnome application. Bonus: to get these things to happen in Emacs without having to reload your whole .emacs, do C-x C-e with the cursor just after the close paren of each of those expressions in the .emacs buffer. Good luck! A: Insert the following into your .emacs file: (setq x-select-enable-clipboard t) A: The code below, inspired by @RussellStewart's answer above, adds support for x-PRIMARY and x-SECONDARY, replaces region-active-p with use-region-p to cover the case of an empty region, does not return silently if xsel has not been installed (returns an error message), and includes a "cut" function (emacs C-y, windows C-x). (defun my-copy-to-xclipboard(arg) (interactive "P") (cond ((not (use-region-p)) (message "Nothing to yank to X-clipboard")) ((and (not (display-graphic-p)) (/= 0 (shell-command-on-region (region-beginning) (region-end) "xsel -i -b"))) (error "Is program `xsel' installed?")) (t (when (display-graphic-p) (call-interactively 'clipboard-kill-ring-save)) (message "Yanked region to X-clipboard") (when arg (kill-region (region-beginning) (region-end))) (deactivate-mark)))) (defun my-cut-to-xclipboard() (interactive) (my-copy-to-xclipboard t)) (defun my-paste-from-xclipboard() "Uses shell command `xsel -o' to paste from x-clipboard. With one prefix arg, pastes from X-PRIMARY, and with two prefix args, pastes from X-SECONDARY." (interactive) (if (display-graphic-p) (clipboard-yank) (let* ((opt (prefix-numeric-value current-prefix-arg)) (opt (cond ((= 1 opt) "b") ((= 4 opt) "p") ((= 16 opt) "s")))) (insert (shell-command-to-string (concat "xsel -o -" opt)))))) (global-set-key (kbd "C-c C-w") 'my-cut-to-xclipboard) (global-set-key (kbd "C-c M-w") 'my-copy-to-xclipboard) (global-set-key (kbd "C-c C-y") 'my-paste-from-xclipboard) A: Hmm, what platform and what version of emacs are you using? With GNU Emacs 22.1.1 on Windows Vista, it works fine for me. If, by any chance, you are doing this from windows to linux through a RealVNC viewer, make sure you are running "vncconfig -iconic" on the linux box first..... A: I always use quick paste -- drag selection in emacs, hit the middle mouse button in target window. (From the reference to kate, I take it you're on linux or similar and probably using emacs in X one way or another.) A: You might want to specify what platform you are using. Is it on linux, unix, macosx, windows, ms-dos? I believe that for windows it should work. For MacOSX it will get added to the x-windows clipboard, which isn't the same thing as the macosx clipboard. For Linux, it depends on your flavour of window manager, but I believe that x-windows handles it in a nice way on most of them. So, please specify. A: What I do is to use a good terminal tool (PuTTY on Windows, Konsole or Terminal on Linux) that has copy facilities built-in. In PuTTY, you highlight the text you want with the mouse and then paste it elsewhere. Right-clicking in a PuTTY window pastes the contents of the Windows copy/paste buffer. In Konsole or Terminal on Linux, you highlight what you want then press Shift+Ctrl+C for copy and Shift+Ctrl+V for paste. In the win32 compile of emacs, yanking text does put it on the copy/paste buffer .. most of the time. On Mac OS X, the Apple-key chortcuts work fine, because Terminal traps them. There is no direct way of doing it on the commandline because the shell does not maintain a copy/paste buffer for each application. bash does maintain a copy/paste buffer for itself, and, by default, emacs ^k/^y shortcuts work.
{ "language": "en", "url": "https://stackoverflow.com/questions/64360", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "126" }
Q: How can I access App Engine through a Corporate proxy? I have corporate proxy that supports https but not HTTP CONNECT (even after authentication). It just gives 403 Forbidden in response anything but HTTP or HTTPS URLS. It uses HTTP authenication, not NTLM. It is well documented the urllib2 does not work with https thru a proxy. App Engine trys to connect to a https URL using urllib2 to update the app. On *nix, urllib2 expects proxies to set using env variables. export http_proxy="http://mycorporateproxy:8080" export https_proxy="https://mycorporateproxy:8080" This is sited as a work around: http://code.activestate.com/recipes/456195/. Also see http://code.google.com/p/googleappengine/issues/detail?id=126. None of these fixes have worked for me. They seem to rely on the proxy server supporting HTTP CONNECT. Does anyone have any other work arounds? I sure I am not the only one behind a restrictive corporate proxy. A: Do you mean it uses http basic-auth before allowing proxying, and does it then allow 'connect'. Then you should be able to tunnel over it using http-tunnel or proxytunnel
{ "language": "en", "url": "https://stackoverflow.com/questions/64362", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Jabber Openfire server v3.6.0a+ - how do I use Hybrid authentication? I'm setting up a Jabber server for my website. I've already got some user accounts in place in the openfire database, and working IMs between them. I'm now looking to add (some) of the users from my main database (members table, with login, password[plain text]) and allowed_to_IM[0 or 1] fields) to allow them to communicate between themselves. The Hybrid authentication is a new feature in v3.6.0a however, and there's little documentation in what configuration is required in the openfire.xml file for the database connectivity (to a second database), and what else may go in the properties (which have also taken much of the config's info away of the XML file). My question is: Does anyone have a complete example that checks multiple databases? All the examples I'm seen seem to be just fragments. A: I have it using ldap and mysql and if it helps you my setting from openfire.xml are: <connectionProvider> <className>org.jivesoftware.database.DefaultConnectionProvider</className> </connectionProvider> <database> <defaultProvider> <driver>com.mysql.jdbc.Driver</driver> <serverURL>jdbc:mysql://127.0.0.1:3306/openfire</serverURL> <username>username</username> <password>pass</password> <minConnections>5</minConnections> <maxConnections>15</maxConnections> <connectionTimeout>1.0</connectionTimeout> </defaultProvider> </database> <ldap> ldapsetting removed </ldap> <hybridAuthProvider> <primaryProvider> <className>org.jivesoftware.openfire.auth.DefaultAuthProvider</className> </primaryProvider> <secondaryProvider> <className>org.jivesoftware.openfire.ldap.LdapAuthProvider</className> </secondaryProvider> </hybridAuthProvider> <provider> <auth> <className>org.jivesoftware.openfire.auth.HybridAuthProvider</className> </auth> <vcard> <className>org.jivesoftware.openfire.auth.DefaultAuthProvider</className> </vcard> <user> <className>org.jivesoftware.openfire.ldap.LdapUserProvider</className> </user> <auth> <className>org.jivesoftware.openfire.ldap.LdapAuthProvider</className> </auth> <group> <className>org.jivesoftware.openfire.ldap.LdapGroupProvider</className> </group> </provider>
{ "language": "en", "url": "https://stackoverflow.com/questions/64364", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using Apache mod_rewrite to remove sub-directories from URL I'm managing an instance of Wordpress where the URLs are in the following format: http://www.example.com/example-category/blog-post-permalink/ The blog author did an inconsistent job of adding categories to posts, so while some of them had legitimate categories in their URLS, at least half are "uncategorised". I can easily change Wordpress to render the URL without the category name (e.g., http://www.example.com/blog-post-permalink/), but I'd like to create a mod_rewrite rule to automatically redirect any requests for the previous format to the new, cleaner one. How can I use a mod_rewrite recipe to handle this, taking into account that I want to honor requests for the real WordPress directories that are in my webroot? A: Something as simple as: RewriteRule ^/[^/]+/([^/]+)/?$ /$2 [R] Perhaps would do it? That simple redirects /foo/bar/ to /bar.
{ "language": "en", "url": "https://stackoverflow.com/questions/64380", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How can I perform an action n-many times in TextMate ( both Emacs and Vim can do it easily! )? Emacs: C-U (79) # » a pretty 79 character length divider VIM: 79-i-# » see above Textmate: ???? Or is it just assumed that we'll make a Ruby call or have a snippet somewhere? A: I would create a bundle command to do this. You can take editor selection as input to your script, then replace it with the result of execution. This command, for example, will take a selected number and print the character '#' that number of times. python -c "print '#' * $TM_SELECTED_TEXT" Of course this example doesn't allow you to specify the character, but it gives you an idea of what's possible. A: By taking the python -c "print '#' * $TM_SELECTED_TEXT" a step further, you can duplicate the examples you gave in the question. Just make a snippet, called divider or something, set the tab trigger field to something appropriate '--' for example, then enter something like: `python -c "print '_' * $TM_COLUMNS"` Then when you type --⇥ (dash dash tab), you should get a divider of the correct width. True, you've lost some of the terseness that you get from vim, but this is far easier to reuse, and you only have to type it once. You can also use whatever language you like. A: Inspired by the other answers. Make a snippet with the following: `python -c "print ':'.join('$TM_SELECTED_TEXT'.split(':')[:-1]) * int('$TM_SELECTED_TEXT'.split(':')[-1])"` and optionally assign a key sequence to it, e.g. CTRL-SHIFT-R If you type -x:4, select it, and call the snippet (by it's shortcut for example), you'll get "-x-x-x-x". You can also use ::4 to obtain "::::". The string you repeat is enclosed in single quotes, so to repeat ', you have to use \'.
{ "language": "en", "url": "https://stackoverflow.com/questions/64387", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Visual Studio Extensibility: Adding existing folders to a project I'm trying to use Visual Studio 2008's extensibility to write an addin that will create a project folder with various messages in it after parsing an interface. I'm having trouble at the step of creating/adding the folder, however. I've tried using ProjectItem folder = item.ProjectItem.Collection.AddFolder(newDirectoryName, string.Empty); (item is my target file next to which I'm creating a folder with the same name but "Messages" appended to it) but it chokes when a folder already exists (no big surprise). I tried deleting it if it already exists, such as: DirectoryInfo dirInfo = new DirectoryInfo(newDirectoryParent + newDirectoryName); if (dirInfo.Exists) { dirInfo.Delete(true); } ProjectItem folder = item.ProjectItem.Collection.AddFolder(newDirectoryName, string.Empty); I can SEE that the folder gets deleted when in debug, but it still seems to think the folder is still there and dies on a folder already exists exception. Any ideas??? Thanks. AK .... Perhaps the answer would lie in programmatically refreshing the project after the delete? How might this be done? A: ProjectItem pi = null; var dir = Path.Combine( project.Properties.Item("LocalPath").Value.ToString(), SubdirectoryName); if (Directory.Exists(dir)) pi = target.ProjectItems.AddFromDirectory(dir); else pi = target.ProjectItems.AddFolder(dir); ProjectItems.AddFromDirectory will add the directory and everything underneath the directory to the project. A: Yup, that was it... DirectoryInfo dirInfo = new DirectoryInfo(newDirectoryParent + newDirectoryName); if (dirInfo.Exists) { dirInfo.Delete(true); item.DTE.ExecuteCommand("View.Refresh", string.Empty); } ProjectItem folder = item.ProjectItem.Collection.AddFolder(newDirectoryName, string.Empty); If there's a more elegant way of doing this, it would be much appreciated... Thanks. A: This is my approach: //Getting the current project private DTE2 _applicationObject; System.Array projs = (System.Array)_applicationObject.ActiveSolutionProjects; Project proy=(Project)projs.GetValue(0); //Getting the path string path=proy.FullName.Substring(0,proy.FullName.LastIndexOf('\\')); //Valitating if the path exists bool existsDirectory= Directory.Exists(path + "\\Directory"); //Deleting and creating the Directory if (existeClasses) Directory.Delete(path + "\\Directory", true); Directory.CreateDirectory(path + "\\Directory"); //Including in the project proy.ProjectItems.AddFromDirectory(path + "\\Directory"); A: I am developing an extension for Visual Studio 2019 and had a similar issue. The question asked in the following page helped me out: https://social.msdn.microsoft.com/Forums/en-US/f4a4f73b-3e13-40bf-99df-9c1bba8fe44e/include-existing-folder-path-as-project-item?forum=vsx If the folder does not physically exist, you can use AddFolder(folderName). But if the folder is not included in the project while existing physically, you need to provide the full system path to the folder. (AddFolder(fullPath)) A: here's an idea i thought of because i've been using NAnt for so long and thought it might work. Open the .csproj file in a text editor and add the directory as such: <ItemGroup> <compile include="\path\rootFolderToInclude\**\*.cs" /> </ItemGroup> if an "ItemGroup" already esists, that's fine. Just add it into an existing one. Visual studio won't really know how to edit this entry, but it will scan the whole directory. edit to whatever you'd like.
{ "language": "en", "url": "https://stackoverflow.com/questions/64388", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Game programming in Java? I am looking into game programming in Java to see if it is feasible. When googling for it I find several old references to Java2D, Project Darkstar (Sun's MMO-server) and some books on Java game programming. But alot of the information seems to be several years old. So the question I am asking, is anyone creating any games in Java SE 1.5 or above? If so, what frameworks are used and are there any best practices or libraries available? A: http://www.javagaming.org/ is a good source for up-to-date information. Another framework not mentioned yet is Xith3D A: I haven't directly done any game programming but some scene-demo coding and have found that JOGL is really a quite nice framework to work with. It's Java OpenGL so it has a rich 3D functionality and i do believe there are some open source graphic engines done for it aswell. A: Also check Pulp core - deals with the most common problems facing Java gaming. A: Despite the odd name ( pretty sure he's talking about the soft drink...), this site has loads of resources and examples games both 2D and 3D. Coke and Code A: As an update, a couple of the JMonkeyEngine guys have forked that project to create Ardor3d, a new version of which was recently released, so its still under active development. Project Darkstar is also still actively developed. Indeed DarkMMO an opensource example Darkstar game is being currently refactored to use the latest version of both Darkstar and Ardor3d. A: GTGE (www.goldenstudios.or.id) is an excellent 2D Java Game Library, with tutorials and an extensive API. It has gone open-source in its latest version, and the source can be downloaded, browsed, etc. at gtge.googlecode.com. A: As mentioned by all others in this topic, there are plenty of excellent libraries/engines available for building games in Java. Game programming in Java is definitely feasible. Keep in mind though that, as with any other language, getting real-time performance will always take some effort. I wrote a small article about my experiences with using Java for our 3D breakout game 'Caromble!'. It is mainly about the steps we had to take to get our game running smoothly. http://www.caromble.com/2013/05/java-game-programming/ A: there is the excellent open source 3d engine called jMonkey (http://www.jmonkeyengine.com) which is being used for a few commercial projects as well as hobby developers... there is also at a lower level the lwjgl library which jmonkeyengine is built on which is a set of apis to wrap opengl as well as provide other game specific libs... A: I've made a list of a bunch of tutorials that should be of help A: I like to code games a bit in my free time. I use a library called slick2d which makes programming the back-end a lot easier. For example, you can copy/paste the example 'main' class file from the Slick2d Wiki and you have your game loop as well as the Update() and Render() methods all ready to go. Slick 2d is based on LWGJL and uses it to load images and do other cool things with OpenGL. There is also a bunch of helpful topics at: http://www.java-gaming.org/
{ "language": "en", "url": "https://stackoverflow.com/questions/64392", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "18" }
Q: What is the best way to store big files in Plone 3? I want to serve a lot of big files in a Plone site. By big files I mean around 5MB (music) and a lot of them. I've already do it straight to the ZODB, not a good idea. I'm running Plone 3.1.1 and Zope 2.10.6. A: Zodb blob support is the best, most integrated way to deal with large files. Big files are stored transparently on the filesytem instead of in the zodb object database. "Transparently" in this case means that you won't notice it in your actual programming work after initial configuration. The blob functionality has been backported to current (halfway 2008) zope versions and can be used in plone 3. Use plone.app.blob in your project for this: http://plone.org/products/plone.app.blob. A: Yeah, you shouldn't use anything else than the ZODB BLOB support at this point. It works fine with the 3.x series of releases. More information in ticket #6805 — Alexander Limi, Plone co-founder A: Clarifying, to the best of my knowledge: * *from various candidate technologies in a PLIP (Plone Immprovement Proposal), plone.app.blob is the lead contender with widespread support -- for exceptional use cases, we sometimes find something other than BLOBs recommended *4.0 is currently the most likely milestone for plone.app.blob to become a product within Plone core *in the meantime plone.app.blob is a recommended add-on product for current 3.x versions of Plone -- for use cases that suggest BLOB-like technologies. A: As you may already know, the long-term solution for this is supposed to be the ZODB BLOB support. Ticket 6805 is probably the most authorative source on this. Unfortunately, the milestone is set to 4.0, and running it in production on an older release is perhaps not a good solution. There has, historically, existed a lot of Plone products for storing files externally, keeping only metadata in the ZODB. I have tried several of them, and from my experience, there is not a single one that works well with current Plone/Zope releases. Don't trust me on this, though, I have not tried any products of this type the last year or so. Personally, I would go for a solution that is as simple as possible and doesn't involve Plone more than neccesary. Storing the music files on disk, serving them directly from apache/whatever web server you use, keeping only metadata in Plone - in a product you write yourself, will give you a robust solution with good performance. That is, your product should produce links to a path on your web server where the music files are available. If you require authorization for download of the music files and assuming that you run lighthttpd or apache in front of your Zope, looking at a solution based on X-sendfile is probably the best option. With X-sendfile, you keep the files on disk, and add a header (X-sendfile) to the response when a music file should be sent to the client browser. The web server will pick this header up and send the file to the client, without Plone being involved. Some pointers: * *http://tn123.ath.cx/mod_xsendfile/ (The apache module) *http://john.guen.in/past/2007/4/17/send_files_faster_with_xsendfile/ (Ruby example) A: I have plone.app.blob installed on some low-traffic sites and installable (ready to roll, if you like) for my busier production sites in the same instance. There's the 4.0 milestone but I'll certainly review (and probably click the install button for plone.app.blob on my production sites) around 3.4 time. A couple of references: http://n2.nabble.com/PLIPs-I%27d-love-to-see-for-Plone-3.3-tp1123218p1130015.html http://dev.plone.org/plone/ticket/8629#comment:2 highlight … 3.4, when we'll probably have blob filestorage specification support added to plone.recipe.zeoserver and zope2instance. That will give us a standard location for whatever owner/permission fixups the installers need to make. In context: I'm playing roughly with plone.app.blob and a very mixed bag of other add-on products with versions 3.1.7 and 3.2a1 of Plone based on standard and experimental installers. In these environments, without me treating things with kid gloves, Plone sies behave remarkably well and when (as expected) experiments lead to oddities, the support from the community is paced and proper.
{ "language": "en", "url": "https://stackoverflow.com/questions/64397", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How do I get rid of "Cannot resolve property key" in fmt:message tags in JSPs in Intellij This one has been bugging me for a while now. Is there a way I can stop Intellj IDEA from reporting missing keys in tags? My messages are not stored in property files so the issue does not apply in my case. I'm using IntelliJ IDEA 7.0.4 A: I reported this as an issue to JetBrains and according to their issue report this is fixed in "Diana 8858". AFICT that means this will be fixed in IDEA 8.0. A: IMHO you can disable every hint or error marker in IDEA. Please tell us the version of IDEA that you use.
{ "language": "en", "url": "https://stackoverflow.com/questions/64408", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I write an iPhone app entirely in JavaScript without making it just a web app? I don't want to take the time to learn Obj-C. I've spent 7+ years doing web application programming. Shouldn't there be a way to use the WebView and just write the whole app in javascript, pulling the files right from the resources of the project? A: I found the answer after searching around. Here's what I have done: * *Create a new project in XCode. I think I used the view-based app. *Drag a WebView object onto your interface and resize. *Inside of your WebViewController.m (or similarly named file, depending on the name of your view), in the viewDidLoad method: NSString *filePath = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"]; NSData *htmlData = [NSData dataWithContentsOfFile:filePath]; if (htmlData) { NSBundle *bundle = [NSBundle mainBundle]; NSString *path = [bundle bundlePath]; NSString *fullPath = [NSBundle pathForResource:@"index" ofType:@"html" inDirectory:path]; [webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:fullPath]]]; } *Now any files you have added as resources to the project are available for use in your web app. I've got an index.html file including javascript and css and image files with no problems. The only limitation I've found so far is that I can't create new folders so all the files clutter up the resources folder. *Trick: make sure you've added the file as a resource in XCode or the file won't be available. I've been adding an empty file in XCode, then dragging my file on top in the finder. That's been working for me. Note: I realize that Obj-C must not be that hard to learn. But since I already have this app existing in JS and I know it works in Safari this is a much faster dev cycle for me. Some day I'm sure I'll have to break down and learn Obj-C. A few other resources I found helpful: Calling Obj-C from javascript: calling objective-c from javascript Calling javascript from Obj-C: iphone app development for web hackers Reading files from application bundle: uiwebview A: For those doing this on iPhone 2.1 (maybe 2.0), you do NOT need to create any special services for local data storage. MobileSafari appears to support the HTML5/WHATWG SQL database API. This is the same API supported by recent versions of desktop Safari and Firefox. If you're using a toolkit like Dojo or ExtJS that offers a storage abstraction, your code should work on just about any modern browser, including MobileSafari. To test, open http://robertsanders.name/dev/stackoverflow/html5.html on your iPhone. If you open that page then look on the filesystem of a Jailbroken iPhone, you should see a database somewhere in /private/var/mobile/Library/WebKit/Databases/. There's even a directory of web-opened DBs there. root# sqlite3 /private/var/mobile/Library/WebKit/Databases/Databases.db SQLite version 3.5.9 Enter ".help" for instructions sqlite> .databases seq name file 0 main /private/var/mobile/Library/WebKit/Databases/Databases.db sqlite> .tables Databases Origins sqlite> select * from Databases; 1|http_robertsanders.name_0|NoteTest|Database|API example|20000|0000000000000001.db sqlite> select * from Origins; http_robertsanders.name_0|5242880 A: You can create an application without knowing any obj-C. The QuickConnectiPhone framework allows you to do this. Check out http://tetontech.wordpress.com for how to use it as well as other ways of doing what you have asked. A: Check out PhoneGap at http://www.phonegap.com they claim it allows you to embed JavaScript, HTML and CSS into a native iPhone app. A: You should have the native wrapper written in Objective C. This wrapper could contain really few lines of code (like, 10) necessary to create a WebView and navigate it to the given address in the internet (where your application resides). But in this case your application should be a full-featured web application (I mean, use not only the JavaScript, but also some HTML for markup). A: I ran into this same problem. I already have a game written entirely in Javascript. I would love to make an iPhone friendly version, but Obj-C is an overkill. What I ended up doing was using the WebView to point to a special url of the iphone app. After thinking about it, I suppose I could just move those files to the app directory and run them locally. A: There not way to do this with the current apple API's. Your closest bet is to write a simple native iPhone app that embeds the webkit browser. That will let you browse your xhtml/js application locally. If you want to store data, you'll need to take it a step further and include a light weight http server that servers up your app and provides calls to store and retrieve data. Probably not an ideal solution for you, but possibly less work than a full Obj-C app. As a side note, Obj-C is fairly easy to learn. There are tons of examples in the SDK. The community is strong and will answer well put questions without hesitation. A: I have been using phonegap for a while and it seems to have the best results for me. I will post my experience in a week or so with a link to my app as well. A: Titanium Mobile is also an option - it allows you to write JavaScript that gets translated into Objective-C. A: At least 2 others mentioned phonegap, but I thought I'd post this too and mention that Apple has approved the phonegap framework. So, now you won't get your app rejected by Apple just because you're using phonegap. Blog post about phonegap and Apple - http://blogs.nitobi.com/jesse/2009/11/20/phonegapp-store-approval/ Phone Gap Home
{ "language": "en", "url": "https://stackoverflow.com/questions/64420", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "85" }
Q: Best Python supported server/client protocol? I'm looking for a good server/client protocol supported in Python for making data requests/file transfers between one server and many clients. Security is also an issue - so secure login would be a plus. I've been looking into XML-RPC, but it looks to be a pretty old (and possibly unused these days?) protocol. A: If you are looking to do file transfers, XMLRPC is likely a bad choice. It will require that you encode all of your data as XML (and load it into memory). "Data requests" and "file transfers" sounds a lot like plain old HTTP to me, but your statement of the problem doesn't make your requirements clear. What kind of information needs to be encoded in the request? Would a URL like "http://yourserver.example.com/service/request?color=yellow&flavor=banana" be good enough? There are lots of HTTP clients and servers in Python, none of which are especially great, but all of which I'm sure will get the job done for basic file transfers. You can do security the "normal" web way, which is to use HTTPS and passwords, which will probably be sufficient. If you want two-way communication then HTTP falls down, and a protocol like Twisted's perspective broker (PB) or asynchronous messaging protocol (AMP) might suit you better. These protocols are certainly well-supported by Twisted. A: ProtocolBuffers was released by Google as a way of serializing data in a very compact efficient way. They have support for C++, Java and Python. I haven't used it yet, but looking at the source, there seem to be RPC clients and servers for each language. I personally have used XML-RPC on several projects, and it always did exactly what I was hoping for. I was usually going between C++, Java and Python. I use libxmlrpc in Python often because it's easy to memorize and type interactively, but it is actually much slower than the alternative pyxmlrpc. PyAMF is mostly for RPC with Flash clients, but it's a compact RPC format worth looking at too. When you have Python on both ends, I don't believe anything beats Pyro (Python Remote Objects.) Pyro even has a "name server" that lets services announce their availability to a network. Clients use the name server to find the services it needs no matter where they're active at a particular moment. This gives you free redundancy, and the ability to move services from one machine to another without any downtime. For security, I'd tunnel over SSH, or use TLS or SSL at the connection level. Of course, all these options are essentially the same, they just have various difficulties of setup. A: Pyro (Python Remote Objects) is fairly clever if all your server/clients are going to be in Python. I use XMPP alot though since I'm communicating with hosts that are not always Python. XMPP lends itself to being extended fairly easily too. There is an excellent XMPP library for python called PyXMPP which is reasonably up to date and has no dependancy on Twisted. A: I suggest you look at 1. XMLRPC 2. JSONRPC 3. SOAP 4. REST/ATOM XMLRPC is a valid choice. Don't worry it is too old. That is not a problem. It is so simple that little needed changing since original specification. The pro is that in every programming langauge I know there is a library for a client to be written in. Certainly for python. I made it work with mod_python and had no problem at all. The big problem with it is its verbosity. For simple values there is a lot of XML overhead. You can gzip it of cause, but then you loose some debugging ability with the tools like Fiddler. My personal preference is JSONRPC. It has all of the XMLRPC advantages and it is very compact. Further, Javascript clients can "eval" it so no parsing is necessary. Most of them are built for version 1.0 of the standard. I have seen diverse attempts to improve on it, called 1.1 1.2 and 2.0 but they are not built one on top of another and, to my knowledge, are not widely supported yet. 2.0 looks the best, but I would still stick with 1.0 for now (October 2008) Third candidate would be REST/ATOM. REST is a principle, and ATOM is how you convey bulk of data when it needs to for POST, PUT requests and GET responses. For a very nice implementation of it, look at GData, Google's API. Real real nice. SOAP is old, and lots lots of libraries / langauges support it. IT is heeavy and complicated, but if your primary clients are .NET or Java, it might be worth the bother. Visual Studio would import your WSDL file and create a wrapper and to C# programmer it would look like local assembly indeed. The nice thing about all this, is that if you architect your solution right, existing libraries for Python would allow you support more then one with almost no overhead. XMLRPC and JSONRPC are especially good match. Regarding authentication. XMLRPC and JSONRPC don't bother defining one. It is independent thing from the serialization. So you can implement Basic Authentication, Digest Authentication or your own with any of those. I have seen couple of examples of client side Digest Authentication for python, but am yet to see the server based one. If you use Apache, you might not need one, using mod_auth_digest Apache module instead. This depens on the nature of your application Transport security. It is obvously SSL (HTTPS). I can't currently remember how XMLRPC deals with, but with JSONRPC implementation that I have it is trivial - you merely change http to https in your URLs to JSONRPC and it shall be going over SSL enabled transport. A: HTTP seems to suit your requirements and is very well supported in Python. Twisted is good for serious asynchronous network programming in Python, but it has a steep learning curve, so it might be worth using something simpler unless you know your system will need to handle a lot of concurrency. To start, I would suggest using urllib for the client and a WSGI service behind Apache for the server. Apache can be set up to deal with HTTPS fairly simply. A: SSH can be a good choice for file transfer and remote control, especially if you are concerned with secure login. Most Linux and Solaris servers will already run an SSH service for administration, so if your Python program use ssh then you don't need to open up any additional ports or services on remote machines. OpenSSH is the standard and portable SSH client and server, and can be used via subprocesses from Python. If you want more flexibility Twisted includes Twisted Conch which is a SSH client and server implementation which provides flexible programmable control of an SSH stack, on both Linux and Windows. I use both in production. A: I'd use http and start with understanding what the Python library offers. Then I'd move onto the more industrial strength Twisted library. A: There is no need to use HTTP (indeed, HTTP is not good for RPC in general in some respects), and no need to use a standards-based protocol if you're talking about a python client talking to a python server. Use a Python-specific RPC library such as Pyro, or what Twisted provides (Twisted.spread). A: XMLRPC is very simple to get started with, and at my previous job, we used it extensively for intra-node communication in a distributed system. As long as you keep track of the fact that the None value can't be easily transferred, it's dead easy to work with, and included in Python's standard library. Run it over https and add a username/password parameter to all calls, and you'll have simple security in place. Not sure about how easy it is to verify server certificate in Python, though. However, if you are transferring large amounts of data, the coding into XML might become a bottleneck, so using a REST-inspired architecture over https may be as good as xmlrpclib. A: Facebook's thrift project may be a good answer. It uses a light-weight protocol to pass object around and allows you to use any language you wish. It may fall-down on security though as I believe there is none. A: In the RPC field, Json-RPC will bring a big performance improvement over xml-rpc: http://json-rpc.org/wiki/python-json-rpc
{ "language": "en", "url": "https://stackoverflow.com/questions/64426", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: How do I programmatically sanitize ColdFusion cfquery parameters? I have inherited a large legacy ColdFusion app. There are hundreds of <cfquery>some sql here #variable#</cfquery> statements that need to be parameterized along the lines of: <cfquery> some sql here <cfqueryparam value="#variable#"/> </cfquery> How can I go about adding parameterization programmatically? I have thought about writing some regular expression or sed/awk'y sort of solution, but it seems like somebody somewhere has tackled such a problem. Bonus points awarded for inferring the sql type automatically. A: There is a script referenced here: http://www.webapper.net/index.cfm/2008/7/22/ColdFusion-SQL-Injection that will do the majority of the heavy lifting for you. All you have to do is check the queries and make sure the syntax will parse properly. There is no excuse for not using CFQueryParam, apart from it being much more secure, it is a performance boost and the best way to handle quoted values in character based column types. A: Keep in mind that you may not be able to solve everything with <cfqueryparam>. I've seen a number of examples where the order by field name is being passed in the query string, which is a slightly trickier problem to solve as you need to validate that in a more "manual" way. A: There's a queryparam scanner that will find them for you on RIAForge: http://qpscanner.riaforge.org/ A: <cf_inputFilter scopes = "FORM,COOKIE,URL" chars = "<,>,!,&,|,%,=,(,),',{,}" tags="script,embed,applet,object,HTML"> We used this to counteract a recent SQL injection attack. We added it to the Application.cfm file for our site. A: I doubt that there is a solution that will fit your needs exactly. The only option I see is to write your own recursive search that builds a report for you or use one of the apps/scripts that people have listed above. Basically, you are going to have to edit each page or approve all of the automated changes.
{ "language": "en", "url": "https://stackoverflow.com/questions/64432", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Convert Parallels VM to Virtual PC 2007 VM I'd like to convert a Parallels Virtual Machine image on my mac into an image usable by Virtual PC 2007. Does anyone know how to do that, or if it is possible? A: It looks like qemu-img from qemu can do this, at least looking at its commandline help on a Ubuntu 8.04 machine where it claims support for, among others, the "parallels" and the "vpc" format. Have not tried myself, though. Hope this helps. A: If it's a Windows image, I would mount the VM using a tool like SmartVDK, then capture the VM with ImageX to a WIM file. You can then mount a blank VHD with SmartVDK and apply the image using ImageX /APPLY. The qemu-img tool is better if you're performing the conversion on a Mac or Linux machine. Keep in mind that you will probably encounter difficulties booting the drive if the drive serials have changed. Also, the hardware will be different. It is often better to build a new image and then to mount the converted drive, copying over anything else you need.
{ "language": "en", "url": "https://stackoverflow.com/questions/64434", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Function Overloading and UDF in Excel VBA I'm using Excel VBA to a write a UDF. I would like to overload my own UDF with a couple of different versions so that different arguments will call different functions. As VBA doesn't seem to support this, could anyone suggest a good, non-messy way of achieving the same goal? Should I be using Optional arguments or is there a better way? A: If you can distinguish by parameter count, then something like this would work: Public Function Morph(ParamArray Args()) Select Case UBound(Args) Case -1 '' nothing supplied Morph = Morph_NoParams() Case 0 Morph = Morph_One_Param(Args(0)) Case 1 Morph = Two_Param_Morph(Args(0), Args(1)) Case Else Morph = CVErr(xlErrRef) End Select End Function Private Function Morph_NoParams() Morph_NoParams = "I'm parameterless" End Function Private Function Morph_One_Param(arg) Morph_One_Param = "I has a parameter, it's " & arg End Function Private Function Two_Param_Morph(arg0, arg1) Two_Param_Morph = "I is in 2-params and they is " & arg0 & "," & arg1 End Function If the only way to distinguish the function is by types, then you're effectively going to have to do what C++ and other languages with overridden functions do, which is to call by signature. I'd suggest making the call look something like this: Public Function MorphBySig(ParamArray args()) Dim sig As String Dim idx As Long Dim MorphInstance As MorphClass For idx = LBound(args) To UBound(args) sig = sig & TypeName(args(idx)) Next Set MorphInstance = New MorphClass MorphBySig = CallByName(MorphInstance, "Morph_" & sig, VbMethod, args) End Function and creating a class with a number of methods that match the signatures you expect. You'll probably need some error-handling though, and be warned that the types that are recognizable are limited: dates are TypeName Double, for example. A: Declare your arguments as Optional Variants, then you can test to see if they're missing using IsMissing() or check their type using TypeName(), as shown in the following example: Public Function Foo(Optional v As Variant) As Variant If IsMissing(v) Then Foo = "Missing argument" ElseIf TypeName(v) = "String" Then Foo = v & " plus one" Else Foo = v + 1 End If End Function This can be called from a worksheet as =FOO(), =FOO(number), or =FOO("string"). A: VBA is messy. I'm not sure there is an easy way to do fake overloads: In the past I've either used lots of Optionals, or used varied functions. For instance Foo_DescriptiveName1() Foo_DescriptiveName2() I'd say go with Optional arguments that have sensible defaults unless the argument list is going to get stupid, then create separate functions to call for your cases. A: You mighta also want to consider using a variant data type for your arguments list and then figure out what's what type using the TypeOf statement, and then call the appropriate functions when you figure out what's what...
{ "language": "en", "url": "https://stackoverflow.com/questions/64436", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "33" }
Q: .Net NNTP implementation Is there a good .Net implementation of the NNTP protocol? A: Try libraries like http://sourceforge.net/projects/dougnewsnntp/ and http://www.codeplex.com/nntpclientlib A: There is a C# tutorial for reading posts using NNTP here. It should be enough to get you started but if you wish to start getting into processing binary posts, you're probably going to have to deal with some mime-type content too. I don't think this article covers that.
{ "language": "en", "url": "https://stackoverflow.com/questions/64445", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How do you convert a physical machine into a virtual machine image for use in MS Virtual Server or Hyper-V? I'd like to use alternatives to System Center Virtual Machine Manager 2008 is possible, in other words, any FREE tools? A: Google "Pysical to virtual conversion" or P2V. There are several solutions available. Unfortunately it sounds as though not many have had success with Microsoft's solution. Try the following: 1. Download and install the VMWare Converter and follow the instructions to convert the physical machine. 2. Download the VMWare to VHD conversion utility from VMToolkit.com and convert the image. This didn't work for me when I tried it last week, but I think it is because the drive I converted used PGP. A: Before SCVMM, Microsoft's solution was the Virtual Server Migration Toolkit. This requires Windows Server 2003 Automated Deployment Services, which in turn can only be installed on Windows Server 2003 Enterprise Edition. It's about as far from a free tool as you can get. It only works on SP1, not SP2 (unless ADS has been updated since I last checked), and you have to obtain all the patches you've applied to the physical system. ADS is limited to four partitions per physical disk, because it can't create extended partitions. If your physical system has more than four partitions you have a problem. Once you do have it running, though, it does actually work. Many disk copying tools like Ghost or True Image can now produce .vhd files from a physical system. A: Use VMWare its not free, but you can get a decent 30 day trial, which should be enough to do your conversions. VMWare also has other great advantages if you're willing to pay for the product. A: First, backup the physical system to an image, and convert it to a virtual disk which can be directly used in a virtual machine. See this article.
{ "language": "en", "url": "https://stackoverflow.com/questions/64451", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: What is the best way to make a .net client consume service from a Java server? I have a user interface in .net which needs to receive data from a server, on a request/reply/update model. The only constraint is to use Java only on the server box. What is the best approach to achieve this ? Is it by creating a Webservice in Java and then accessing it in .net, or should I create Java proxies and convert them in .net by using IKM ? Or do you have any better idea ? It can be HTTP based, used a direct socket connection, or any middleware. A: Write webservice in Java and access it in .net A: I recommend the web service route. It offers a standard interface that can be consumed by other client platforms in the future. .NET clients interact with Java web services pretty well, though there are some gotchas. The best two technologies available for you for the .NET client are Microsoft Web Service Enhancements (WSE) and Windows Communication Foundation (WCF). WSE is an older technology that is no longer being updated by Microsoft, but still works great in Visual Studio 2005 and older. I find WSE to be a bit easier to get started with in terms of how you interface with basic services, but WCF has much more support for WS-* protocols (security, trust, etc.). If your needs are basic and you're still using Visual Studio 2005 (.NET framework 2 or older), then go with WSE. If you like the cutting edge, or you anticipate more advanced security needs (doesn't sound like you will), then go with WCF. Please note that WSE will not work easily in Visual Studio 2008 and newer, and WCF will not work in Visual Studio 2005 and older. Going the web service route will mean that you will design to an interface that can be reused and will result in a more loosely coupled system when you're done than most of the other routes. The downside is primarily performance: xml serialization will be slower than binary over the wire, and web services do not handle large amounts of data well. A: Using a standard type of web service (e.g. SOAP or XML-RPC) is best because not only is it easy to produce/consume, it's easy in other languages as well.
{ "language": "en", "url": "https://stackoverflow.com/questions/64454", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: leaving a time delay in python is there any way to leave a time delay between the execution of two lines of code?
{ "language": "en", "url": "https://stackoverflow.com/questions/64468", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "22" }
Q: VB.NET on Vista, trying to get date (Today) causes security exception I have a VB6 program that someone recently helped me convert to VB.NET In the program, when saving files, I stamp them with the date which I was getting by calling the Today() function. When I try to run the new VB.NET code in Vista it throws a permission exception for the Today() . If I run Visual Studio Express (this is the 2008 Express version) in Admin mode, then the problem doesn't occur, but clearly I want to end up with a stand-alone program which runs for all users without fancy permissions. So how can a normal VB.NET program in Vista get today's date? A: Use DateTime.Now or DateTime.Today. These are entirely managed and shouldn't throw security exceptions. The old VB6 functions, such as Len(), Left(), Right(), OpenFile(), FreeFile() are all present in the .NET Framework in the Microsoft.VisualBasic DLL. To maintain backwards compatibility, they all call the old functions in unmanaged code. Unmanaged code requires special security permissions because it can be dangerous. Whenever possible, try and use the newer .NET functions. They are usually much faster (File IO using Streams for instance) and safer. A: When I try the following statement: Dim result As String = Today() It gives me today's date, as I'd expect, and I'm running VB2005 on Vista. Can you modify the question with the version of VB you're using? Also, can you try the following statement instead of Today() to see it works for you without the exception? Dim result As String = Now() A: The Today() function should behave properly on Vista. I believe behind the scenes it is simply evaluating the DateTime.Today property, so it shouldn't throw any exceptions. If you're porting VB to VB.NET you should probably go ahead and use the DateTime.Today property rather than the VB6 compatability code.
{ "language": "en", "url": "https://stackoverflow.com/questions/64469", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What are the most frequently used flow controls for handling protocol communication? I am rewriting code to handle some embedded communications and right now the protocol handling is implemented in a While loop with a large case/switch statement. This method seems a little unwieldy. What are the most commonly used flow control methods for implementing communication protocols? A: It sounds like the "while + switch/case" is a statemachine implementation. I believe that a well thought out statemachine is often the easiest and most readable way to implement a protocol. When it comes to statemachines, breaking some of the traditional programming rules comes with the territory. Rules like "every function should be less than 25 lines" just don't work. One might even argue that statemachines are GOTOs in disguise. A: For cases where you key off of a field in a protocol header to direct you to the next stage of processing for that protocol, arrays of function pointers can be used. You use the value from the protocol header to index into the array and call the function for that protocol. You must handle all possible values in this array, even those which are not valid. Eventually you will get a packet containing the invalid value, either because someone is trying an attack or because a future rev of the protocol adds new values. A: If it is all one protocol being handled then a switch/case statement may be your best bet. However you should break all the individual message handlers into their own functions. If your switch statement contains any code to actually handle the messages than you would be better off breaking them out. If it is handling multiple similar protocols you could create a class to handle each one based off the same abstract class and when the connection comes in you could determine which protocol it is and create an instance of the appropriate handler class to decode and handle the communications. A: I would think this depends largely on the language you are using, and what sort of data set objects you have available to you. In python, for example, you could create a Dictionary object of all the different handling statements, and just iterate through that to find the right method/function to call. Case/Switch statements aren't bad things, but if they get huge(like they can with massive amounts of protocol handlers) then they can become unwieldy to work with.
{ "language": "en", "url": "https://stackoverflow.com/questions/64495", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: C++ method expansion Can you specialize a template method within a template class without specializing the class template parameter? Please note that the specialization is on the value of the template parameter, not its type. This seems to compile under Visual Studio 2008 SP1 complier, but not GCC 4.2.4. #include <iostream> using namespace std; template <typename T> class A { private: template <bool b> void testme(); template <> void testme<true>() { cout << "true" << endl; }; template <> void testme<false>() { cout << "false" << endl; }; public: void test(); }; template<typename T> struct select {}; template<> struct select<int> { static const bool value = true; }; template<> struct select<double> { static const bool value = false; }; template <class T> void A<T>::test() { testme<select<T>::value>(); } int main(int argc, const char* argv[]) { A<int> aInt; A<double> aDouble; aInt.test(); aDouble.test(); return 0; } GCC tells me:"error: explicit specialization in non-namespace scope ‘class A’" If it is not supported in the standard, can anyone tell me why? A: It is not supported in the standard (and it is apparently a known bug with Visual Studio that you can do it). The standard doesn't allow an inner template (member function or class) to be specialized without the outer template being specialized as well. One of the reasons for this is that you can normally just overload the function: template<typename ty> class A { public: void foo(bool b); void foo(int i); }; Is equivalent to: template<typename ty> class A { public: template<typename ty2> void foo(ty2); template<> void foo(bool b); template<> void foo(int i); }; A: here is how you do it: template<typename A> struct SomeTempl { template<bool C> typename enable_if<C>::type SomeOtherTempl() { std::cout << "true!"; } template<bool C> typename enable_if<!C>::type SomeOtherTempl() { std::cout << "false!"; } }; You can get enable_if from my other answer where i told them how to check for a member function's existance in a class using templates. or you can use boost, but remember to change enable_if to enable_if_c then. A: Here is another workaround, also useful when you need to partialy specialize a function (which is not allowed). Create a template functor class (ie. class whose sole purpose is to execute a single member function, usually named operator() ), specialize it and then call from within your template function. I think I learned this trick from Herb Sutter, but do not remember which book (or article) was that. For your needs it is probably overkill, but nonetheless ... template <typename T> struct select; template <bool B> struct testme_helper { void operator()(); }; template <typename T> class A { private: template <bool B> void testme() { testme_helper<B>()(); } public: void test() { testme<select<T>::value>(); } }; template<> void testme_helper<true>::operator()() { std::cout << "true" << std::endl; } template<> void testme_helper<false>::operator()() { std::cout << "false" << std::endl; } A: I've never heard of that being possible; it would make sense to me if it was not supported by all compilers. So here is an idea for a workaround: Implement a template function outside of your class which takes the same action as the method. Then you can specialize this function, and it call it from the method. Of course, you'll also have to pass in any member variables that it needs (and pointers thereto if you want to modify their values). You could also create another template class as a subclass, and specialize that one, although I've never done this myself and am not 100% sure it would work. (Please comment to augment this answer if you know whether or not this second approach would work!)
{ "language": "en", "url": "https://stackoverflow.com/questions/64498", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Sending mail from Python using SMTP I'm using the following method to send mail from Python using SMTP. Is it the right method to use or are there gotchas I'm missing ? from smtplib import SMTP import datetime debuglevel = 0 smtp = SMTP() smtp.set_debuglevel(debuglevel) smtp.connect('YOUR.MAIL.SERVER', 26) smtp.login('USERNAME@DOMAIN', 'PASSWORD') from_addr = "John Doe <john@doe.net>" to_addr = "foo@bar.com" subj = "hello" date = datetime.datetime.now().strftime( "%d/%m/%Y %H:%M" ) message_text = "Hello\nThis is a mail from your server\n\nBye\n" msg = "From: %s\nTo: %s\nSubject: %s\nDate: %s\n\n%s" % ( from_addr, to_addr, subj, date, message_text ) smtp.sendmail(from_addr, to_addr, msg) smtp.quit() A: The main gotcha I see is that you're not handling any errors: .login() and .sendmail() both have documented exceptions that they can throw, and it seems like .connect() must have some way to indicate that it was unable to connect - probably an exception thrown by the underlying socket code. A: Make sure you don't have any firewalls blocking SMTP. The first time I tried to send an email, it was blocked both by Windows Firewall and McAfee - took forever to find them both. A: What about this? import smtplib SERVER = "localhost" FROM = "sender@example.com" TO = ["user@example.com"] # must be a list SUBJECT = "Hello!" TEXT = "This message was sent with Python's smtplib." # Prepare actual message message = """\ From: %s To: %s Subject: %s %s """ % (FROM, ", ".join(TO), SUBJECT, TEXT) # Send the mail server = smtplib.SMTP(SERVER) server.sendmail(FROM, TO, message) server.quit() A: following code is working fine for me: import smtplib to = 'mkyong2002@yahoo.com' gmail_user = 'mkyong2002@gmail.com' gmail_pwd = 'yourpassword' smtpserver = smtplib.SMTP("smtp.gmail.com",587) smtpserver.ehlo() smtpserver.starttls() smtpserver.ehlo() smtpserver.login(gmail_user, gmail_pwd) header = 'To:' + to + '\n' + 'From: ' + gmail_user + '\n' + 'Subject:testing \n' print header msg = header + '\n this is test msg from mkyong.com \n\n' smtpserver.sendmail(gmail_user, to, msg) print 'done!' smtpserver.quit() Ref: http://www.mkyong.com/python/how-do-send-email-in-python-via-smtplib/ A: The example code which i did for send mail using SMTP. import smtplib, ssl smtp_server = "smtp.gmail.com" port = 587 # For starttls sender_email = "sender@email" receiver_email = "receiver@email" password = "<your password here>" message = """ Subject: Hi there This message is sent from Python.""" # Create a secure SSL context context = ssl.create_default_context() # Try to log in to server and send email server = smtplib.SMTP(smtp_server,port) try: server.ehlo() # Can be omitted server.starttls(context=context) # Secure the connection server.ehlo() # Can be omitted server.login(sender_email, password) server.sendmail(sender_email, receiver_email, message) except Exception as e: # Print any error messages to stdout print(e) finally: server.quit() A: You should make sure you format the date in the correct format - RFC2822. A: Also if you want to do smtp auth with TLS as opposed to SSL then you just have to change the port (use 587) and do smtp.starttls(). This worked for me: ... smtp.connect('YOUR.MAIL.SERVER', 587) smtp.ehlo() smtp.starttls() smtp.ehlo() smtp.login('USERNAME@DOMAIN', 'PASSWORD') ... A: See all those lenghty answers? Please allow me to self promote by doing it all in a couple of lines. Import and Connect: import yagmail yag = yagmail.SMTP('john@doe.net', host = 'YOUR.MAIL.SERVER', port = 26) Then it is just a one-liner: yag.send('foo@bar.com', 'hello', 'Hello\nThis is a mail from your server\n\nBye\n') It will actually close when it goes out of scope (or can be closed manually). Furthermore, it will allow you to register your username in your keyring such that you do not have to write out your password in your script (it really bothered me prior to writing yagmail!) For the package/installation, tips and tricks please look at git or pip, available for both Python 2 and 3. A: you can do like that import smtplib from email.mime.text import MIMEText from email.header import Header server = smtplib.SMTP('mail.servername.com', 25) server.ehlo() server.starttls() server.login('username', 'password') from = 'me@servername.com' to = 'mygfriend@servername.com' body = 'That A Message For My Girl Friend For tell Him If We will go to eat Something This Nigth' subject = 'Invite to A Diner' msg = MIMEText(body,'plain','utf-8') msg['Subject'] = Header(subject, 'utf-8') msg['From'] = Header(from, 'utf-8') msg['To'] = Header(to, 'utf-8') message = msg.as_string() server.sendmail(from, to, message) A: Based on this example I made following function: import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText def send_email(host, port, user, pwd, recipients, subject, body, html=None, from_=None): """ copied and adapted from https://stackoverflow.com/questions/10147455/how-to-send-an-email-with-gmail-as-provider-using-python#12424439 returns None if all ok, but if problem then returns exception object """ PORT_LIST = (25, 587, 465) FROM = from_ if from_ else user TO = recipients if isinstance(recipients, (list, tuple)) else [recipients] SUBJECT = subject TEXT = body.encode("utf8") if isinstance(body, unicode) else body HTML = html.encode("utf8") if isinstance(html, unicode) else html if not html: # Prepare actual message message = """From: %s\nTo: %s\nSubject: %s\n\n%s """ % (FROM, ", ".join(TO), SUBJECT, TEXT) else: # https://stackoverflow.com/questions/882712/sending-html-email-using-python#882770 msg = MIMEMultipart('alternative') msg['Subject'] = SUBJECT msg['From'] = FROM msg['To'] = ", ".join(TO) # Record the MIME types of both parts - text/plain and text/html. # utf-8 -> https://stackoverflow.com/questions/5910104/python-how-to-send-utf-8-e-mail#5910530 part1 = MIMEText(TEXT, 'plain', "utf-8") part2 = MIMEText(HTML, 'html', "utf-8") # Attach parts into message container. # According to RFC 2046, the last part of a multipart message, in this case # the HTML message, is best and preferred. msg.attach(part1) msg.attach(part2) message = msg.as_string() try: if port not in PORT_LIST: raise Exception("Port %s not one of %s" % (port, PORT_LIST)) if port in (465,): server = smtplib.SMTP_SSL(host, port) else: server = smtplib.SMTP(host, port) # optional server.ehlo() if port in (587,): server.starttls() server.login(user, pwd) server.sendmail(FROM, TO, message) server.close() # logger.info("SENT_EMAIL to %s: %s" % (recipients, subject)) except Exception, ex: return ex return None if you pass only body then plain text mail will be sent, but if you pass html argument along with body argument, html email will be sent (with fallback to text content for email clients that don't support html/mime types). Example usage: ex = send_email( host = 'smtp.gmail.com' #, port = 465 # OK , port = 587 #OK , user = "xxx@gmail.com" , pwd = "xxx" , from_ = 'xxx@gmail.com' , recipients = ['yyy@gmail.com'] , subject = "Test from python" , body = "Test from python - body" ) if ex: print("Mail sending failed: %s" % ex) else: print("OK - mail sent" Btw. If you want to use gmail as testing or production SMTP server, enable temp or permanent access to less secured apps: * *login to google mail/account *go to: https://myaccount.google.com/lesssecureapps *enable *send email using this function or similar *(recommended) go to: https://myaccount.google.com/lesssecureapps *(recommended) disable A: Or import smtplib from email.message import EmailMessage from getpass import getpass password = getpass() message = EmailMessage() message.set_content('Message content here') message['Subject'] = 'Your subject here' message['From'] = "USERNAME@DOMAIN" message['To'] = "you@mail.com" try: smtp_server = None smtp_server = smtplib.SMTP("YOUR.MAIL.SERVER", 587) smtp_server.ehlo() smtp_server.starttls() smtp_server.ehlo() smtp_server.login("USERNAME@DOMAIN", password) smtp_server.send_message(message) except Exception as e: print("Error: ", str(e)) finally: if smtp_server is not None: smtp_server.quit() If you want to use Port 465 you have to create an SMTP_SSL object. A: The script I use is quite similar; I post it here as an example of how to use the email.* modules to generate MIME messages; so this script can be easily modified to attach pictures, etc. I rely on my ISP to add the date time header. My ISP requires me to use a secure smtp connection to send mail, I rely on the smtplib module (downloadable at http://www1.cs.columbia.edu/~db2501/ssmtplib.py) As in your script, the username and password, (given dummy values below), used to authenticate on the SMTP server, are in plain text in the source. This is a security weakness; but the best alternative depends on how careful you need (want?) to be about protecting these. ======================================= #! /usr/local/bin/python SMTPserver = 'smtp.att.yahoo.com' sender = 'me@my_email_domain.net' destination = ['recipient@her_email_domain.com'] USERNAME = "USER_NAME_FOR_INTERNET_SERVICE_PROVIDER" PASSWORD = "PASSWORD_INTERNET_SERVICE_PROVIDER" # typical values for text_subtype are plain, html, xml text_subtype = 'plain' content="""\ Test message """ subject="Sent from Python" import sys import os import re from smtplib import SMTP_SSL as SMTP # this invokes the secure SMTP protocol (port 465, uses SSL) # from smtplib import SMTP # use this for standard SMTP protocol (port 25, no encryption) # old version # from email.MIMEText import MIMEText from email.mime.text import MIMEText try: msg = MIMEText(content, text_subtype) msg['Subject']= subject msg['From'] = sender # some SMTP servers will do this automatically, not all conn = SMTP(SMTPserver) conn.set_debuglevel(False) conn.login(USERNAME, PASSWORD) try: conn.sendmail(sender, destination, msg.as_string()) finally: conn.quit() except: sys.exit( "mail failed; %s" % "CUSTOM_ERROR" ) # give an error message A: The method I commonly use...not much different but a little bit import smtplib from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText msg = MIMEMultipart() msg['From'] = 'me@gmail.com' msg['To'] = 'you@gmail.com' msg['Subject'] = 'simple email in python' message = 'here is the email' msg.attach(MIMEText(message)) mailserver = smtplib.SMTP('smtp.gmail.com',587) # identify ourselves to smtp gmail client mailserver.ehlo() # secure our email with tls encryption mailserver.starttls() # re-identify ourselves as an encrypted connection mailserver.ehlo() mailserver.login('me@gmail.com', 'mypassword') mailserver.sendmail('me@gmail.com','you@gmail.com',msg.as_string()) mailserver.quit() That's it A: Here's a working example for Python 3.x #!/usr/bin/env python3 from email.message import EmailMessage from getpass import getpass from smtplib import SMTP_SSL from sys import exit smtp_server = 'smtp.gmail.com' username = 'your_email_address@gmail.com' password = getpass('Enter Gmail password: ') sender = 'your_email_address@gmail.com' destination = 'recipient_email_address@gmail.com' subject = 'Sent from Python 3.x' content = 'Hello! This was sent to you via Python 3.x!' # Create a text/plain message msg = EmailMessage() msg.set_content(content) msg['Subject'] = subject msg['From'] = sender msg['To'] = destination try: s = SMTP_SSL(smtp_server) s.login(username, password) try: s.send_message(msg) finally: s.quit() except Exception as E: exit('Mail failed: {}'.format(str(E))) A: What about Red Mail? Install it: pip install redmail Then just: from redmail import EmailSender # Configure the sender email = EmailSender( host="YOUR.MAIL.SERVER", port=26, username='me@example.com', password='<PASSWORD>' ) # Send an email: email.send( subject="An example email", sender="me@example.com", receivers=['you@example.com'], text="Hello!", html="<h1>Hello!</h1>" ) It has quite a lot of features: * *Email attachments from various sources *Embedding images and plots to the HTML body *Templating emails with Jinja *Preconfigured Gmail and Outlook *Logging handler *Flask extension Links: * *Source code *Documentation *Releases A: Based on madman2890, updated a few things as well as removed the need for mailserver.quit() import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText msg = MIMEMultipart() msg['From'] = 'me@gmail.com' msg['To'] = 'you@gmail.com' msg['Subject'] = 'simple email in python' message = 'here is the email' msg.attach(MIMEText(message)) with smtplib.SMTP('smtp-mail.outlook.com',587) as mail_server: # identify ourselves to smtp gmail client mail_server.ehlo() # secure our email with tls encryption mail_server.starttls() # re-identify ourselves as an encrypted connection mail_server.ehlo() mail_server.login('me@gmail.com', 'mypassword') mail_server.sendmail('me@gmail.com','you@gmail.com',msg.as_string())
{ "language": "en", "url": "https://stackoverflow.com/questions/64505", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "134" }
Q: Guile scheme - quoted period? What does the following Guile scheme code do? (eq? y '.) (cons x '.) The code is not valid in MzScheme, is there a portable equivalent across scheme implementations? I am trying to port this code written by someone else. Guile seems to respond to '. with #{.}#, but I'm not sure what it means or how to do this in another scheme. A: Okay, it seems that '. is valid syntax for (string->symbol ".") in Guile, whereas MzScheme at least requires |.| for the period as a symbol. A: #{.}# is Guile specific way to define the symbol contains some delimiters of Scheme. http://www.gnu.org/software/guile/manual/html_node/Symbol-Read-Syntax.html For other Scheme dialect, there should be another way. A: I'm surprised any Scheme system will accept a dot symbol at all. My advice is to use another symbol as (I'm sure you're aware) the dot is a shorthand to represent a pair, and even if you can find a Scheme that will take your code you will likely confuse anyone that has the unfortunate task of actually reading your code.
{ "language": "en", "url": "https://stackoverflow.com/questions/64508", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: What's the purpose of the GtkWidget.events property for (like) GtkTreeView widgets? I have a Glade GUI description file with a GtkTreeView in a GtkHBox in a window; and there's a handler for the row_activated signal. Now, Glade has automatically set the "events" property (inherited from GtkWidget) of that treeview to some value (GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK). And there are two strange things with this: * *removing the pre-set value (so that the property is empty) doesn't seem to break the application (at least not with the old GTK 2.10 I have atm). *in fact, an annoying bug I has seen before (where the treeview items would not correctly react to expand or collapse clicks) is now gone! I have yet to test this with a newer GTK version, but the question is already there: exactly what is the purpose for this events property? And why does Glade automatically and unnecessarily set it to some value? Does this have some side effects I'm not aware of? A: It's a bug in glade, it always sets the event property of widgets it create. It has no notion of the default value of a property so it always sets it. A: Doesn't this mask indicate the events you're willing to receive? In this case, you'll probably want to receive notification that the user has clicked or double-clicked an item in the GtkTreeView, and you'll want to register callbacks to handle these events. A: me.yahoo.com/a/kUQ7zeQ: but even if I set the property to an empty string as mentioned, the row_activated handler is still called when I double-click on a row (or press Enter or Space). So the treeview still gets events...
{ "language": "en", "url": "https://stackoverflow.com/questions/64518", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I create graphs in Perl on Windows? How do I use Perl to create graphs? I'm running scheduled job that creates text reports. I'd like to move this to the next step (for the management) and also create some graphs that go along with this. Is this possible / feasible? It'd be great if I could do this using Office some how. update: solutions i'm going to investigate in this order * *Spreadsheet::WriteExcel (this seems to now have changed from the last time i investigated this .... wait, this was suggested by the author of the module. cool.) *GD Graph - this is now available for ActivePerl(wasn't last time i looked) *SVG *Open Charts look interesting. *Chartdirector A: GD and GD::Graph are probably your best bets, you can use them to create images that you can then embed into whatever you need. A: All of the methods mentioned above are really good, but personally I like SVG::TT::Graph. I really like the power that SVG gives you to draw really nice-looking graphs. A: Also you can take a look at Google Charts CPAN module use Google::Chart; my $chart = Google::Chart->new( type => "Bar", data => [ 1, 2, 3, 4, 5 ] ); print $chart->as_uri, "\n"; # or simply print $chart, "\n" $chart->render_to_file( filename => 'filename.png' ); A: At work we have used the excellent Chartdirector. It's not free, but is very cheap (maybe 50 bucks or so). The cost is well worth it, as the API and docs are both excellent (way better than GD!), so easily saved more than that amount of my time. There's also a free version, which includes a small yellow banner advertising the product on each chart - to be honest if this is for personal use, you can go for that as it's really not very intrusive at all. Chartdirector is available for lots of platforms (Win, Linux, Solaris, BSD, OSX) and has an API for lots of languages, too (Perl, ASP, .NET, Java, PHP, Python, Ruby, C++). The output is easy on the eye, as you can see at their examples page. A: Sorry for blowing my own trumpet, but you might be interested to have a look some slides I did for a short presentation about Graphing With Perl. It mentions some of the suggestions here, but also gives you some code snippets that you might be able to use to help you get the most of what you're doing. A: Spreadsheet::WriteExcel::Chart You might need something like strawberry or vanilla Perl to get this to compile. Or PPM might have the module. Tutorial link: http://search.cpan.org/dist/Spreadsheet-WriteExcel/charts/charts.pod A: Depending on the complexity of your graph, simply generating a command file for Gnuplot—or GraphViz/Dotty, depending on what kind of graph you are referring to—might do the trick? A: The Perl module Spreadsheet::WriteExcel allows you to create Excel workbooks that include charts. You first have to create the type of chart that you want in Excel and then extract it out using a utility called chartex which is installed with Spreadsheet::WriteExcel. The chart template can then be added to a new workbook and made to reference new data. The documentation is here and there are several examples in the charts directory of the distro. The mechanism is a little inflexible however and the it is sometimes tricky to get the exact result that you want. A: Haven't tried it yet but Chart::Clicker looks quite nifty. I think it uses the Cairo graphic library (alternative to GD) but is actually built on top of Graphics::Primitive which is an "interesting" graphics agnostic package. The author in question (GPHAT) seems to be putting together some integrated tools for producing reports... http://www.onemogin.com/blog/582-pixels-and-painting-my-recent-cpan-releases On a side note... have used both ChartDirector and OFC and both are good (especially if web based). A: It depends to a great extent what sort of graphs (the look of them), and the data-source. I've had some good result by using the YUI Charts and feeding them some JSON style versions of the original source data. Rolling over a live chart for exact values is quite easy for example. There are plenty of examples on the developer pages. A: It won't work with Office, but I really like Chart::OFC which will create Open Flash Charts. Very slick looking and easy to use. A: If you're set on doing this in MS Office you can use the Win32::OLE module to control Excel via OLE. Be warned, that this tends to run slowly and it can be difficult to find documentation for Excel's API. On the plus side, it allows you to do pretty much everything that you can do manually. A: PGPlot does great graphs. There are some examples here. It works fine with Perl 5.8.8 but is broken in 5.10.0 A: Metaprograming of course! Output an R script that creates the graph. A: Spreadsheet::WriteExcel will let you just get the data into Excel, then write Excel equations for the graphs.
{ "language": "en", "url": "https://stackoverflow.com/questions/64537", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Does the exe you get out of obfuscation programs vary in speed? There are a number of obfuscation programs out there for .Net and I've tried one, my exe seems much slower when obfuscated. Do all obfuscation programs have the same effect or have I chosen a bad one? I'm hoping some are better than others, if you know of a fast one let me know. A: Disclaimer: my employer is PreEmptive Solutions, the creator of the Dotfuscator .NET obfuscator. It can depend on the obfuscator you use and the options you enable in it. I am going to speak from experience with Dotfuscator. There can be load time and memory footprint improvements of obfuscated assemblies if you use renaming and removal, partly because all/most of your methods, fields, etc are renamed to much smaller names (for example "ThisVeryLongMethodName(SomeVeryLongParameterName)" becomes "a(a)" so you gain some benefit in assembly size and usually with load time. In addition with removal you remove methods, etc. that are never call and again decrease the size of your binaries. String encryption can adversely affect runtime performance to a slight degree as the strings must be converted back to human readable text at runtime. If you use any other systems/techniques like Microsoft SLP's secure vm technology to render methods unreadable that will also incur a runtime performance penalty due to the secure vm. Other obfuscation tools that do not produce managed code assemblies as an output but instead rely on a native code loader to "preprocess" their output can also incur an runtime performance hit (especially at load time). A: Obfuscation shouldn't change the runtime performance of your code. If it is then you've got a bad obfuscator that's doing much more than just obfuscating. All obfuscation should do is make your IL hard to read. A: There are different obfuscation methods that tools can use. There are the simple rename methods that should not affect performance in any way. Other methods might change the flow of the code. That could have a negative impact on performance. You might want to check out other obfuscators and try out different settings.
{ "language": "en", "url": "https://stackoverflow.com/questions/64541", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Paths in master pages I've started to work a bit with master pages for an ASP.net mvc site and I've come across a question. When I link in a stylesheet on the master page it seems to update the path to the sheet correctly. That is in the code I have <link href="../../Content/Site.css" rel="stylesheet" type="text/css" /> but looking at the source once the page is fed to a browser I get <link href="Content/Site.css" rel="stylesheet" type="text/css" /> which is perfect. However the same path translation doesn't seem to work for script files. <script src="../../Content/menu.js" type="text/javascript"></script> just comes out as the same thing. It still seems to work on a top level page but I suspect that is just the browser/web server correcting my error. Is there a way to get the src path to be globbed too? A: <script src="<%= ResolveClientUrl("~/Content/menu.js") %>" type="text/javascript"></script> A: Make an extension method. Here's a method: public static string ResolveUrl(this HtmlHelper helper, string virtualUrl) { HttpContextBase ctx = helper.ViewContext.HttpContext; string result = virtualUrl; if (virtualUrl.StartsWith("~/")) { virtualUrl = virtualUrl.Remove(0, 2); //get the site root string siteRoot = ctx.Request.ApplicationPath; if (!siteRoot.EndsWith("/")) siteRoot += "/"; result = siteRoot + virtualUrl; } return result; } You can then write your script ref like: <script type="text/javascript" src="<%= Html.ResolveUrl("~/Content/menu.js")%>"></script> A: Use this instead: <link href="~/Content/Site.css" rel="stylesheet" type="text/css" /> A: or you can use BASE tag in you HEAD section of page. All you links then are relative to location entered in "base" tag, and you don't have to use "../../" and "~" stuff. Except links in CSS files (background url,etc), where links are relative to location of css file.
{ "language": "en", "url": "https://stackoverflow.com/questions/64559", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Bluetooth parking How do I park a Bluetooth connection? I'm trying to communicate with dozens of Bluetooth devices, and the time to re-establish a connection is unacceptable. I've read that you can park connections, but not found anything that answers how to do this. A: I know that you can park a connection if it's on the MS Bluetooth stack. There is a nice API you can use called 32feet.Net. It lets you set the socket options. Here's a quick link to the documentation. I hope it helps. A: I have been creating firmware for Bluetooth modules since 2000 and can honestly say that I have never used Park nor has any customer asked for it. My advice, as per others in this trail, keep away from it. Perhaps Hold mode is worth investigating. A: Parking mode is one of connected state mode, explained in the core Bluetooth spec, right from early 1.1 or so. Please follow up with various sniff modes as well, including the newer ones such as sniff sub rating. Other than park modes, you have hold modes as well. A: Unfortunately the parking mode will be removed in next Bluetooth version(Bluetooth 5). And, the park and hold mode are seems a beautiful way to save power but in real life, due to the IOP issue, not too much device can "really" support such kind of power save mode in market. The most common used mode is sniff but this already beyond your request. So, just forget park mode. A: Once you have an Bluetooth ACL connection with a device. If your device is the master, then you can use link layer message LMP_park. Usually you can do this from application using HCI command HCI_Park_Mode (Connection_Handle, Beacon_Max_Interval, Beacon_Min_Interval) http://affon.narod.ru/BT/bluetooth_app_c9.pdf
{ "language": "en", "url": "https://stackoverflow.com/questions/64562", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Explode string into array with no empty elements? PHP's explode function returns an array of strings split on some provided substring. It will return empty strings when there are leading, trailing, or consecutive delimiters, like this: var_dump(explode('/', '1/2//3/')); array(5) { [0]=> string(1) "1" [1]=> string(1) "2" [2]=> string(0) "" [3]=> string(1) "3" [4]=> string(0) "" } Is there some different function or option or anything that would return everything except the empty strings? var_dump(different_explode('/', '1/2//3/')); array(3) { [0]=> string(1) "1" [1]=> string(1) "2" [2]=> string(1) "3" } A: Try preg_split. $exploded = preg_split('@/@', '1/2//3/', -1, PREG_SPLIT_NO_EMPTY); A: Just for variety: array_diff(explode('/', '1/2//3/'), array('')) This also works, but does mess up the array indexes unlike preg_split. Some people might like it better than having to declare a callback function to use array_filter. A: function not_empty_string($s) { return $s !== ""; } array_filter(explode('/', '1/2//3/'), 'not_empty_string'); A: array_filter will remove the blank fields, here is an example without the filter: print_r(explode('/', '1/2//3/')) prints: Array ( [0] => 1 [1] => 2 [2] => [3] => 3 [4] => ) With the filter: php> print_r(array_filter(explode('/', '1/2//3/'))) Prints: Array ( [0] => 1 [1] => 2 [3] => 3 ) You'll get all values that resolve to "false" filtered out. see http://uk.php.net/manual/en/function.array-filter.php A: I have used this in TYPO3, look at the $onlyNonEmptyValues parameter: function trimExplode($delim, $string, $onlyNonEmptyValues=0){ $temp = explode($delim,$string); $newtemp=array(); while(list($key,$val)=each($temp)) { if (!$onlyNonEmptyValues || strcmp("",trim($val))) { $newtemp[]=trim($val); } } reset($newtemp); return $newtemp; } It doesn't mess up the indexes: var_dump(trimExplode('/', '1/2//3/',1)); Result: array(3) { [0]=> string(1) "1" [1]=> string(1) "2" [2]=> string(1) "3" } A: Here is a solution that should output a newly indexed array. $result = array_deflate( explode( $delim, $array) ); function array_deflate( $arr, $emptyval='' ){ $ret=[]; for($i=0,$L=count($arr); $i<$L; ++$i) if($arr[$i] !== $emptyval) $ret[]=$arr[$i]; return $ret; } While fairly similar to some other suggestion, this implementation has the benefit of generic use. For arrays with non-string elements, provide a typed empty value as the second argument. array_deflate( $objArray, new stdClass() ); array_deflate( $databaseArray, NULL ); array_deflate( $intArray, NULL ); array_deflate( $arrayArray, [] ); array_deflate( $assocArrayArray, [''=>NULL] ); array_deflate( $processedArray, new Exception('processing error') ); . . . With an optional filter argument.. function array_deflate( $arr, $trigger='', $filter=NULL, $compare=NULL){ $ret=[]; if ($filter === NULL) $filter = function($el) { return $el; }; if ($compare === NULL) $compare = function($a,$b) { return $a===$b; }; for($i=0,$L=count($arr); $i<$L; ++$i) if( !$compare(arr[$i],$trigger) ) $ret[]=$arr[$i]; else $filter($arr[$i]); return $ret; } With usage.. function targetHandler($t){ /* .... */ } array_deflate( $haystack, $needle, targetHandler ); Turning array_deflate into a way of processing choice elements and removing them from your array. Also nicer is to turn the if statement into a comparison function that is also passed as an argument in case you get fancy. array_inflate being the reverse, would take an extra array as the first parameter which matches are pushed to while non-matches are filtered. function array_inflate($dest,$src,$trigger='', $filter=NULL, $compare=NULL){ if ($filter === NULL) $filter = function($el) { return $el; }; if ($compare === NULL) $compare = function($a,$b) { return $a===$b; }; for($i=0,$L=count($src); $i<$L; ++$i) if( $compare(src[$i],$trigger) ) $dest[]=$src[$i]; else $filter($src[$i]); return $dest; } With usage.. $smartppl=[]; $smartppl=array_inflate( $smartppl, $allppl, (object)['intelligence'=>110], cureStupid, isSmart); function isSmart($a,$threshold){ if( isset($a->intellgence) ) //has intelligence? if( isset($threshold->intellgence) ) //has intelligence? if( $a->intelligence >= $threshold->intelligence ) return true; else return INVALID_THRESHOLD; //error else return INVALID_TARGET; //error return false; } function cureStupid($person){ $dangerous_chemical = selectNeurosteroid(); applyNeurosteroid($person, $dangerous_chemical); if( isSmart($person,(object)['intelligence'=>110]) ) return $person; else lobotomize($person); return $person; } Thus providing an ideal algorithm for the world's educational problems. Aaand I'll stop there before I tweak this into something else.. A: Write a wrapper function to strip them function MyExplode($sep, $str) { $arr = explode($sep, $str); foreach($arr as $item) if(item != "") $out[] = $item; return $out; } A: Use this function to filter the output of the explode function function filter_empty(&$arrayvar) { $newarray = array(); foreach ($arrayvar as $k => $value) if ($value !== "") $newarray[$k] = $value; $arrayvar = $newarray; } A: Regular expression solutions tend to be much slower than basic text replacement, so i'd replace double seperators with single seperators, trim the string of any whitespace and then use explode: // assuming $source = '1/2//3/'; $source = str_replace('//', '/', $source); $source = trim($source); $parts = explode('/', $source); A: No regex overhead - should be reasonably efficient, strlen just counts the bytes Drop the array_values() if you don't care about indexes Make it into function explode_interesting( $array, $fix_index = 0 ) if you want $interesting = array_values( array_filter( explode('/', '/1//2//3///4/0/false' ), function ($val) { return strlen($val); } )); echo "<pre>", var_export( $interesting, true ), "</pre>"; enjoy, Jeff A: I usually wrap it in a call to array_filter, e.g. var_dump(array_filter(explode('/', '1/2//3/')) => array(3) { [0]=> string(1) "1" [1]=> string(1) "2" [3]=> string(1) "3" } Be aware, of course, that array keys are maintained; if you don't want this behaviour, remember to add an outer wrapper call to array_values(). A: PHP's split function is similar to the explode function, except that it allows you to enter a regex pattern as the delimiter. Something to the effect of: $exploded_arr = split('/\/+/', '1/2//3/');
{ "language": "en", "url": "https://stackoverflow.com/questions/64570", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "41" }
Q: .NET Web Application Portability to SilverLight The company where I work created this application which is core to our business and relies on the web browser to enforce certain "rules" that without them renders the application kinda useless to our customers. Sorry about having to be circumspect, An NDA along with a host of other things prevents me from saying exactly what the application is. Essentially, JavaScript controls certain timed events (that have to be accurate down to at least the second) that make it difficult to control with ajax/postbacks etc. My question is this: how hard is it to convert an ASP.NET application to SilverLight assuming that most of the code is really C# business logic and not asp.net controls? I just got finished listening to Deep Fried bytes and the MS people make it sounds like this really isn't that big of a deal. Is this true for web apps, or mainly Win32 ones? I know the asp.net front end is fundamentally different from SilverLight, but there is a bunch of C# code I would like to not have to rewrite if necessary. The replacement of the javascript code to silverlight I am assuming is trivial (i know bad assumption, but I have to start somewhere) since it deals with timed events, so I am not really concerned with that. I need to come up with a solution on how to mitigate this problem, and I am hoping this is a middle ground between: do nothing and watch us get pounded by our clients, and rewrite the whole application in something more secure than a web page with only front end validation. Has anyone tried to convert ASP.NET code to a SilverLight project? A: If the bulk of your application is on the back-end, you should still be able to keep the majority of the code intact and only replace the front-end. However, Silverlight requires an understanding of WPF, which is dramatically different than the HTML/JS that your app currently uses. I'd say if your UI is pretty thin, it should be pretty easy to port to Silverlight, but the more business logic is in the UI, the harder it will be. A: How heavily do you use the class libraries, and things that might be considered 'dangerous', like pinvoke, file system access and System.Diagnostics.Process? A: Porting code from ASP.NET to Silverlight is not an easy task. As Nate points outs it depends on how much of ASP.NET application is AJAX based, and how much is based around server controls. Silverlight is a state full client side technology, meaning everything is running on the client inside the browser. ASP.NET is a server technology, and is built around a request/response model. Since these two are completely different paradigms it's not a straight port. However, since ASP.NET is just HTML and HTTP POST of form data people have done experiments where they have added a Silverlight application directly on top of an ASP.NET page, and manually built the HTTP POST request by hand sending back the exact data the ASP.NET application work. It's almost like doing "screen scraping" for your own application. This could work, but wouldn't be optimal. You wouldn't get a performance increase as your ASP.NET application would have to go through a full page cycle on every request. A better alternative is to start out wrapping any functionality the user has in the APS.NET application as web services. You can add these services alongside your ASPX pages, and gradually port the application over. The UI you would build from the ground up based on these services. Good luck!
{ "language": "en", "url": "https://stackoverflow.com/questions/64575", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Display ODBC connections dialog and get chosen ODBC back Any information on how to display the ODBC connections dialog and get the chosen ODBC back? A: // a_RootKey is Microsoft.Win32.RegistryKey // DSN is a class not provided in this code sample - you can see what properties are needed from the usage below. List<DSN> DsnList = new List<DSN>(); Microsoft.Win32.RegistryKey SearchKey = a_RootKey.OpenSubKey("SOFTWARE\\ODBC\\ODBC.INI\\ODBC Data Sources"); if (SearchKey != null) { foreach (string DsnName in SearchKey.GetValueNames() ) { if ( (string)SearchKey.GetValue(DsnName) == "SQL Server" ) { Microsoft.Win32.RegistryKey anotherkey = a_RootKey.OpenSubKey("SOFTWARE\\ODBC\\ODBC.INI\\" + DSNName); DSN dsn = new DSN(); dsn.Name = DSNName; dsn.Server = (string)anotherkey.GetValue("Server"); dsn.Database = (string)anotherkey.GetValue("Database"); dsn.Driver = (string)anotherkey.GetValue("Driver"); DsnList.Add(dsn); } } } return DsnList; A: OK since no one seems to have an answer, how about iterating throught the ODBC connections by DBSource, I.e. SQLServer or MySQL
{ "language": "en", "url": "https://stackoverflow.com/questions/64581", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: C++/Java Performance for Neural Networks? I was discussing neural networks (NN) with a friend over lunch the other day and he claimed the the performance of a NN written in Java would be similar to one written in C++. I know that with 'just in time' compiler techniques Java can do very well, but somehow I just don't buy it. Does anyone have any experience that would shed light on this issue? This page is the extent of my reading on the subject. A: I'd be interested in a comparison between Hotspot JIT and profile-guided optimization optimized C++. The problem I see with the Hotspot JIT (and any runtime-profile-optimized JIT compiler) is that statistics must be kept and code modified. While there are isolated cases this will result in faster-running code, I doubt that profile-optimized JIT compilers will run faster than well optimized C or C++ code in most circumstances. (Of course I could be wrong.) Anyway, usually you're going to be at the mercy of the larger project, using the same language it is written in. Or you'll be at the mercy of the knowledge base of your co-workers. Or you'll be at the mercy of the platform you are targetting (is a JVM available on the architecture you're targetting?). In the rare case you have complete freedom and you're familiar with both languages, do some comparisons with the tools you have at your disposal. That is really the only way to determine what's best. A: The only possible answer is: make a prototype and measure for yourself. If my experience is of any interest, Java and C# were always much slower than C++ for the kind of work I was doing - I believe mostly because of the high memory consumption. Of course, you can come to a completely different conclusion. A: The Hotspot JIT can now produce code faster than C++. The reason is run-time empirical optimization. For example, it can see that a certain loop takes the "false" branch 99% of the time and reorder the machine code instructions accordingly. There's lots of articles about this. If you want all the details, read Sun's excellent whitepaper. For more informal info, try this one. A: This is not strictly about C++ vs Java performance but nonetheless interesting in that regard: A paper about the performance of programs running in a garbage collected environment. A: If excessive garbage collection is a concern, you can always reuse unused high-churn objects. Create a factory that keeps a queue of SoftReferences to recycled objects, using those before creating new objects. Then in code that uses these objects, explicitly return these objects to the factory for recycling. A: Probably C++, although I believe you'll hardly notice the difference besides a slow startup time. Java however makes development faster and maintenance easier. A: In the grand scheme of things, you're debating maybe a 5% performance difference where you'd get several orders of magnitude increase by moving to CUDA or dedicated hardware.
{ "language": "en", "url": "https://stackoverflow.com/questions/64582", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: .net: System.Web.Mail vs System.Net.Mail I am considering converting a project that I've inherited from .net 1.1 to .net 2.0. The main warning I'm concerned about is that it wants me to switch from System.Web.Mail to using System.Net.Mail. I'm not ready to re-write all the components using the obsolete System.Web.Mail, so I'm curious to hear if any community members have had problems using it under .net 2.0? A: here are 2 sites that provide documentation and samples for both http://www.systemwebmail.com/ http://www.systemnetmail.com/ A: System.Web.Mail is deprecated, but should still work. You'll be annoyed with warnings about it being obsolete, but the functionality still carries on... for the time being. I would agree with others that the conversion to System.Net.Mail was very trivial. I doubt you'd have to re-write more than a line or two. A: The few times I ran into this, I found that that the methods and properties were all almost identical- changing the object type was just about all I had to do. There were one or two other little things, but they showed up with the lines and it was obvious what to do with Intellisense. I'd vote for going with the fully managed solution, get away from cdonts as soon as possible. It's not even installed on 03 server and newer. A: System.Web.Mail is not a full .NET native implementation of the SMTP protocol. Instead, it uses the pre-existing COM functionality in CDONTS. System.Net.Mail, in contrast, is a fully managed implementation of an SMTP client. I've had far fewer problems with System.Net.Mail as it avoids COM hell. A: Biggest issue with System.Net.Mail is that it has no support for Implicit SSL. Use System.Web.Mail until you don't have a need for Implicit SSL support. A: Yes, we had the same issue, and we decided not to upgrade either. We haven't seen any problems, so you're OK ignoring the warnings. A: We had implemented .netmail it was working at the beginning now is requiring username and password. So we went back to webmail as is working OK.
{ "language": "en", "url": "https://stackoverflow.com/questions/64599", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "76" }
Q: What are differences between AssemblyVersion, AssemblyFileVersion and AssemblyInformationalVersion? There are three assembly version attributes. What are differences? Is it ok if I use AssemblyVersion and ignore the rest? MSDN says: * *AssemblyVersion: Specifies the version of the assembly being attributed. *AssemblyFileVersion: Instructs a compiler to use a specific version number for the Win32 file version resource. The Win32 file version is not required to be the same as the assembly's version number. *AssemblyInformationalVersion: Defines additional version information for an assembly manifest. This is a follow-up to What are the best practices for using Assembly Attributes? A: AssemblyVersion Where other assemblies that reference your assembly will look. If this number changes, other assemblies must update their references to your assembly! Only update this version if it breaks backward compatibility. The AssemblyVersion is required. I use the format: major.minor (and major for very stable codebases). This would result in: [assembly: AssemblyVersion("1.3")] If you're following SemVer strictly then this means you only update when the major changes, so 1.0, 2.0, 3.0, etc. AssemblyFileVersion Used for deployment (like setup programs). You can increase this number for every deployment. Use it to mark assemblies that have the same AssemblyVersion but are generated from different builds and/or code. In Windows, it can be viewed in the file properties. The AssemblyFileVersion is optional. If not given, the AssemblyVersion is used. I use the format: major.minor.patch.build, where I follow SemVer for the first three parts and use the buildnumber of the buildserver for the last part (0 for local build). This would result in: [assembly: AssemblyFileVersion("1.3.2.42")] Be aware that System.Version names these parts as major.minor.build.revision! AssemblyInformationalVersion The Product version of the assembly. This is the version you would use when talking to customers or for display on your website. This version can be a string, like '1.0 Release Candidate'. The AssemblyInformationalVersion is optional. If not given, the AssemblyFileVersion is used. I use the format: major.minor[.patch] [revision as string]. This would result in: [assembly: AssemblyInformationalVersion("1.3 RC1")] A: It's worth noting some other things: * *As shown in Windows Explorer Properties dialog for the generated assembly file, there are two places called "File version". The one seen in the header of the dialog shows the AssemblyVersion, not the AssemblyFileVersion. In the Other version information section, there is another element called "File Version". This is where you can see what was entered as the AssemblyFileVersion. *AssemblyFileVersion is just plain text. It doesn't have to conform to the numbering scheme restrictions that AssemblyVersion does (<build> < 65K, e.g.). It can be 3.2.<release tag text>.<datetime>, if you like. Your build system will have to fill in the tokens. Moreover, it is not subject to the wildcard replacement that AssemblyVersion is. If you just have a value of "3.0.1.*" in the AssemblyInfo.cs, that is exactly what will show in the Other version information->File Version element. *I don't know the impact upon an installer of using something other than numeric file version numbers, though. A: Versioning of assemblies in .NET can be a confusing prospect given that there are currently at least three ways to specify a version for your assembly. Here are the three main version-related assembly attributes: // Assembly mscorlib, Version 2.0.0.0 [assembly: AssemblyFileVersion("2.0.50727.3521")] [assembly: AssemblyInformationalVersion("2.0.50727.3521")] [assembly: AssemblyVersion("2.0.0.0")] By convention, the four parts of the version are referred to as the Major Version, Minor Version, Build, and Revision. The AssemblyFileVersion is intended to uniquely identify a build of the individual assembly Typically you’ll manually set the Major and Minor AssemblyFileVersion to reflect the version of the assembly, then increment the Build and/or Revision every time your build system compiles the assembly. The AssemblyFileVersion should allow you to uniquely identify a build of the assembly, so that you can use it as a starting point for debugging any problems. On my current project we have the build server encode the changelist number from our source control repository into the Build and Revision parts of the AssemblyFileVersion. This allows us to map directly from an assembly to its source code, for any assembly generated by the build server (without having to use labels or branches in source control, or manually keeping any records of released versions). This version number is stored in the Win32 version resource and can be seen when viewing the Windows Explorer property pages for the assembly. The CLR does not care about nor examine the AssemblyFileVersion. The AssemblyInformationalVersion is intended to represent the version of your entire product The AssemblyInformationalVersion is intended to allow coherent versioning of the entire product, which may consist of many assemblies that are independently versioned, perhaps with differing versioning policies, and potentially developed by disparate teams. “For example, version 2.0 of a product might contain several assemblies; one of these assemblies is marked as version 1.0 since it’s a new assembly that didn’t ship in version 1.0 of the same product. Typically, you set the major and minor parts of this version number to represent the public version of your product. Then you increment the build and revision parts each time you package a complete product with all its assemblies.” — Jeffrey Richter, [CLR via C# (Second Edition)] p. 57 The CLR does not care about nor examine the AssemblyInformationalVersion. The AssemblyVersion is the only version the CLR cares about (but it cares about the entire AssemblyVersion) The AssemblyVersion is used by the CLR to bind to strongly named assemblies. It is stored in the AssemblyDef manifest metadata table of the built assembly, and in the AssemblyRef table of any assembly that references it. This is very important, because it means that when you reference a strongly named assembly, you are tightly bound to a specific AssemblyVersion of that assembly. The entire AssemblyVersion must be an exact match for the binding to succeed. For example, if you reference version 1.0.0.0 of a strongly named assembly at build-time, but only version 1.0.0.1 of that assembly is available at runtime, binding will fail! (You will then have to work around this using Assembly Binding Redirection.) Confusion over whether the entire AssemblyVersion has to match. (Yes, it does.) There is a little confusion around whether the entire AssemblyVersion has to be an exact match in order for an assembly to be loaded. Some people are under the false belief that only the Major and Minor parts of the AssemblyVersion have to match in order for binding to succeed. This is a sensible assumption, however it is ultimately incorrect (as of .NET 3.5), and it’s trivial to verify this for your version of the CLR. Just execute this sample code. On my machine the second assembly load fails, and the last two lines of the fusion log make it perfectly clear why: .NET Framework Version: 2.0.50727.3521 --- Attempting to load assembly: Rhino.Mocks, Version=3.5.0.1337, Culture=neutral, PublicKeyToken=0b3305902db7183f Successfully loaded assembly: Rhino.Mocks, Version=3.5.0.1337, Culture=neutral, PublicKeyToken=0b3305902db7183f --- Attempting to load assembly: Rhino.Mocks, Version=3.5.0.1336, Culture=neutral, PublicKeyToken=0b3305902db7183f Assembly binding for failed: System.IO.FileLoadException: Could not load file or assembly 'Rhino.Mocks, Version=3.5.0.1336, Culture=neutral, PublicKeyToken=0b3305902db7183f' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040) File name: 'Rhino.Mocks, Version=3.5.0.1336, Culture=neutral, PublicKeyToken=0b3305902db7183f' === Pre-bind state information === LOG: User = Phoenix\Dani LOG: DisplayName = Rhino.Mocks, Version=3.5.0.1336, Culture=neutral, PublicKeyToken=0b3305902db7183f (Fully-specified) LOG: Appbase = [...] LOG: Initial PrivatePath = NULL Calling assembly : AssemblyBinding, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null. === LOG: This bind starts in default load context. LOG: No application configuration file found. LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework64\v2.0.50727\config\machine.config. LOG: Post-policy reference: Rhino.Mocks, Version=3.5.0.1336, Culture=neutral, PublicKeyToken=0b3305902db7183f LOG: Attempting download of new URL [...]. WRN: Comparing the assembly name resulted in the mismatch: Revision Number ERR: Failed to complete setup of assembly (hr = 0x80131040). Probing terminated. I think the source of this confusion is probably because Microsoft originally intended to be a little more lenient on this strict matching of the full AssemblyVersion, by matching only on the Major and Minor version parts: “When loading an assembly, the CLR will automatically find the latest installed servicing version that matches the major/minor version of the assembly being requested.” — Jeffrey Richter, [CLR via C# (Second Edition)] p. 56 This was the behaviour in Beta 1 of the 1.0 CLR, however this feature was removed before the 1.0 release, and hasn’t managed to re-surface in .NET 2.0: “Note: I have just described how you should think of version numbers. Unfortunately, the CLR doesn’t treat version numbers this way. [In .NET 2.0], the CLR treats a version number as an opaque value, and if an assembly depends on version 1.2.3.4 of another assembly, the CLR tries to load version 1.2.3.4 only (unless a binding redirection is in place). However, Microsoft has plans to change the CLR’s loader in a future version so that it loads the latest build/revision for a given major/minor version of an assembly. For example, on a future version of the CLR, if the loader is trying to find version 1.2.3.4 of an assembly and version 1.2.5.0 exists, the loader with automatically pick up the latest servicing version. This will be a very welcome change to the CLR’s loader — I for one can’t wait.” — Jeffrey Richter, [CLR via C# (Second Edition)] p. 164 (Emphasis mine) As this change still hasn’t been implemented, I think it’s safe to assume that Microsoft had back-tracked on this intent, and it is perhaps too late to change this now. I tried to search around the web to find out what happened with these plans, but I couldn’t find any answers. I still wanted to get to the bottom of it. So I emailed Jeff Richter and asked him directly — I figured if anyone knew what happened, it would be him. He replied within 12 hours, on a Saturday morning no less, and clarified that the .NET 1.0 Beta 1 loader did implement this ‘automatic roll-forward’ mechanism of picking up the latest available Build and Revision of an assembly, but this behaviour was reverted before .NET 1.0 shipped. It was later intended to revive this but it didn’t make it in before the CLR 2.0 shipped. Then came Silverlight, which took priority for the CLR team, so this functionality got delayed further. In the meantime, most of the people who were around in the days of CLR 1.0 Beta 1 have since moved on, so it’s unlikely that this will see the light of day, despite all the hard work that had already been put into it. The current behaviour, it seems, is here to stay. It is also worth noting from my discussion with Jeff that AssemblyFileVersion was only added after the removal of the ‘automatic roll-forward’ mechanism — because after 1.0 Beta 1, any change to the AssemblyVersion was a breaking change for your customers, there was then nowhere to safely store your build number. AssemblyFileVersion is that safe haven, since it’s never automatically examined by the CLR. Maybe it’s clearer that way, having two separate version numbers, with separate meanings, rather than trying to make that separation between the Major/Minor (breaking) and the Build/Revision (non-breaking) parts of the AssemblyVersion. The bottom line: Think carefully about when you change your AssemblyVersion The moral is that if you’re shipping assemblies that other developers are going to be referencing, you need to be extremely careful about when you do (and don’t) change the AssemblyVersion of those assemblies. Any changes to the AssemblyVersion will mean that application developers will either have to re-compile against the new version (to update those AssemblyRef entries) or use assembly binding redirects to manually override the binding. * *Do not change the AssemblyVersion for a servicing release which is intended to be backwards compatible. *Do change the AssemblyVersion for a release that you know has breaking changes. Just take another look at the version attributes on mscorlib: // Assembly mscorlib, Version 2.0.0.0 [assembly: AssemblyFileVersion("2.0.50727.3521")] [assembly: AssemblyInformationalVersion("2.0.50727.3521")] [assembly: AssemblyVersion("2.0.0.0")] Note that it’s the AssemblyFileVersion that contains all the interesting servicing information (it’s the Revision part of this version that tells you what Service Pack you’re on), meanwhile the AssemblyVersion is fixed at a boring old 2.0.0.0. Any change to the AssemblyVersion would force every .NET application referencing mscorlib.dll to re-compile against the new version! A: AssemblyVersion pretty much stays internal to .NET, while AssemblyFileVersion is what Windows sees. If you go to the properties of an assembly sitting in a directory and switch to the version tab, the AssemblyFileVersion is what you'll see up top. If you sort files by version, this is what's used by Explorer. The AssemblyInformationalVersion maps to the "Product Version" and is meant to be purely "human-used". AssemblyVersion is certainly the most important, but I wouldn't skip AssemblyFileVersion, either. If you don't provide AssemblyInformationalVersion, the compiler adds it for you by stripping off the "revision" piece of your version number and leaving the major.minor.build. A: AssemblyInformationalVersion and AssemblyFileVersion are displayed when you view the "Version" information on a file through Windows Explorer by viewing the file properties. These attributes actually get compiled in to a VERSION_INFO resource that is created by the compiler. AssemblyInformationalVersion is the "Product version" value. AssemblyFileVersion is the "File version" value. The AssemblyVersion is specific to .NET assemblies and is used by the .NET assembly loader to know which version of an assembly to load/bind at runtime. Out of these, the only one that is absolutely required by .NET is the AssemblyVersion attribute. Unfortunately it can also cause the most problems when it changes indiscriminately, especially if you are strong naming your assemblies. A: When a assembly' s AssemblyVersion is changed, If it has strong name, the referencing assemblies need to be recompiled, otherwise the assembly does not load! If it does not have strong name, if not explicitly added to project file, it will not be copied to output directory when build so you may miss depending assemblies, especially after cleaning the output directory. A: To keep this question current it is worth highlighting that AssemblyInformationalVersion is used by NuGet and reflects the package version including any pre-release suffix. For example an AssemblyVersion of 1.0.3.* packaged with the asp.net core dotnet-cli dotnet pack --version-suffix ci-7 src/MyProject Produces a package with version 1.0.3-ci-7 which you can inspect with reflection using: CustomAttributeExtensions.GetCustomAttribute<AssemblyInformationalVersionAttribute>(asm);
{ "language": "en", "url": "https://stackoverflow.com/questions/64602", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "928" }
Q: Can I Mix VBScript and JScript in a Single HTA? Is it possible to use both JScript and VBScript in the same HTA? Can I call VBScript functions from JScript and vice-versa? Are there any "gotchas," like the JScript running first and the VBScript running second (classic ASP pages have this issue). A: Yeah, just separate them into different script tags: <script language="javascript"> // javascript code </script> <script language="vbscript"> ' vbscript code </script> Edit: And, yeah, you can cross call between Javascript and VBScript with no extra work. Edit: This is also true of ANY Windows Scripting technology. It works in WSF files and can include scripts written in any supported ActiveScript language such as Perl as long as the engine is installed. Edit: The specific "gotcha" of all JScript being executed first, then VBScript is related to how ASP processes scripts. The MSHTA host (which uses IE's engine) does not have this problem. I'm not much into HTAs though, so I can't address any other possible "gotchas". A: Also you can give references between them. For example: at the background some function on vbscript handle with database and FSO issues, and let javascript create user interfaces and dialogs etc. with DOM in frontline. Whenever you need you can call both functions from each script sides. In js you can call vbs function, and also in vbscript you can call js functions. Then you can use their returns where you call them. Regards A: Event handlers (like Onclick) should have the code prefixed with "javascript:" or "vbscript:"
{ "language": "en", "url": "https://stackoverflow.com/questions/64605", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Am I turning away customers by disabling SSL 2.0 and PCT 1.0 in IIS5? Do I risk losing sales by disabling SSL 2.0 and PCT 1.0 in IIS5? Clarification: Sales would be lost by client not being able to connect via SSL to complete ecommerce transaction because SSL 2.0 or PCT 1.0 is disabled on the web server. Microsoft kbase article: http://support.microsoft.com/kb/187498 A: Modern browsers either don't appear to support SSLv2 at all (Google Chrome, Opera 9.52, Firefox) or have it disabled by default (IE7, IE8). That said, are you concerned about losing business from people using much-less-than-modern web browsers? Possibly more importantly, are you concerned about your customers' security? Even if they can only connect using SSLv2, do you want them performing secure transactions with you using a protocol that is known to be insecure (see Google)? As a computer professional, I would not hesitate to recommend to management that SSLv2 be disabled. I would leave it up to the bean counters to determine whether they think the additional income is worth the potential liability. A: No. The number of users with support for SSLv2 at all, much less SSLv2 only, is negligible. It has been obsolete since 1996, and is disabled or not even included in all modern browsers of significance. A: Only you can really answer that question. Your customers' experience of your site will be mediated by their browser. The first place to look for browser information is at a listing of the user-agents that are being used to access your website. Hopefully you have a good log analyzer such as Analog, Weblog, Google Analytics, WebTrends, etc. This is the first place to look and should give you a good idea of the SSL level that your general community supports. You may also want to alter your application to check for the SSL level supported by your users' browsers that get to the "complete ecommerce transaction" part of your website. This is the best method to determine if you are turning away customers. Remember that the SSL level is auto negotiated between the server and the client (best encryption used first) so you don't necessarily need to disable older versions, but you could pop up a message to the user encouraging them to upgrade. A: Presumably you use SSL to protect users from man-in-the-middle or other attacks, yes? SSLv2 is useless for this. Disable it -- the number of users who use a browser without SSLv3 or TLS support is vanishingly small, and it's easier to make them somebody else's problem than explain why somebody in Nigeria is using their credit card.
{ "language": "en", "url": "https://stackoverflow.com/questions/64621", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: What does a PHP developer need to know about https / secure socket layer connections? I know next to nothing when it comes to the how and why of https connections. Obviously, when I'm transmitting secure data like passwords or especially credit card information, https is a critical tool. What do I need to know about it, though? What are the most common mistakes you see developers making when they implement it in their projects? Are there times when https is just a bad idea? Thanks! A: I'm not going to go in depth on SSL in general, gregmac did a great job on that, see below ;-). However, some of the most common (and critical) mistakes made (not specifically PHP) with regards to use of SSL/TLS: * *Allowing HTTP when you should be enforcing HTTPS *Retrieving some resources over HTTP from an HTTPS page (e.g. images, IFRAMEs, etc) *Directing to HTTP page from HTTPS page unintentionally - note that this includes "fake" pages, such as "about:blank" (I've seen this used as IFRAME placeholders), this will needlessly and unpleasantly popup a warning. *Web server configured to support old, unsecure versions of SSL (e.g. SSL v2 is common, yet horribly broken) (okay, this isn't exactly the programmer's issue, but sometimes noone else will handle it...) *Web server configured to support unsecure cipher suites (I've seen NULL ciphers only in use, which basically provides absolutely NO encryption) (ditto) *Self-signed certificates - prevents users from verifying the site's identity. *Requesting the user's credentials from an HTTP page, even if submitting to an HTTPS page. Again, this prevents a user from validating the server's identity BEFORE giving it his password... Even if the password is transmitted encrypted, the user has no way of knowing if he's on a bogus site - or even if it WILL be encrypted. *Non-secure cookie - security-related cookies (such as sessionId, authentication token, access token, etc.) MUST be set with the "secure" attribute set. This is important! If it's not set to secure, the security cookie, e.g. SessionId, can be transmitted over HTTP (!) - and attackers can ensure this will happen - and thus allowing session hijacking etc. While you're at it (tho this is not directly related), set the HttpOnly attribute on your cookies, too (helps mitigate some XSS). *Overly permissive certificates - say you have several subdomains, but not all of them are at the same trust level. For instance, you have www.yourdomain.com, dowload.yourdomain.com, and publicaccess.yourdomain.com. So you might think about going with a wildcard certificate.... BUT you also have secure.yourdomain.com, or finance.yourdomain.com - even on a different server. publicaccess.yourdomain.com will then be able to impersonate secure.yourdomain.com.... While there may be instances where this is okay, usually you'd want some separation of privileges... That's all I can remember right now, might re-edit it later... As far as when is it a BAD idea to use SSL/TLS - if you have public information which is NOT intended for a specific audience (either a single user or registered members), AND you're not particular about them retrieving it specifically from the proper source (e.g. stock ticker values MUST come from an authenticated source...) - then there is no real reason to incur the overhead (and not just performance... dev/test/cert/etc). However, if you have shared resources (e.g. same server) between your site and another MORE SENSITIVE site, then the more sensitive site should be setting the rules here. Also, passwords (and other credentials), credit card info, etc should ALWAYS be over SSL/TLS. A: An HTTPS, or Secure Sockets Layer (SSL) certificate is served for a site, and is typically signed by a Certificate Authority (CA), which is effectively a trusted 3rd party that verifies some basic details about your site, and certifies it for use in browsers. If your browser trusts the CA, then it trusts any certificates signed by that CA (this is known as the trust chain). Each HTTP (or HTTPS) request consists of two parts: a request, and a response. When you request something through HTTPS, there are actually a few things happening in the background: * *The client (browser) does a "handshake", where it requests the server's public key and identification. * *At this point, the browser can check for validity (does the site name match? is the date range current? is it signed by a CA it trusts?). It can even contact the CA and make sure the certificate is valid. *The client creates a new pre-master secret, which is encrypted using the servers's public key (so only the server can decrypt it) and sent to the server *The server and client both use this pre-master secret to generate the master secret, which is then used to create a symmetric session key for the actual data exchange *Both sides send a message saying they're done the handshake *The server then processes the request normally, and then encrypts the response using the session key If the connection is kept open, the same symmetric key will be used for each. If a new connection is established, and both sides still have the master secret, new session keys can be generated in an 'abbreviated handshake'. Typically a browser will store a master secret until it's closed, while a server will store it for a few minutes or several hours (depending on configuration). For more on the length of sessions see How long does an HTTPS symmetric key last? Certificates and Hostnames Certificates are assigned a Common Name (CN), which for HTTPS is the domain name. The CN has to match exactly, eg, a certificate with a CN of "example.com" will NOT match the domain "www.example.com", and users will get a warning in their browser. Before SNI, it was not possible to host multiple domain names on one IP. Because the certificate is fetched before the client even sends the actual HTTP request, and the HTTP request contains the Host: header line that tells the server what URL to use, there is no way for the server to know what certificate to serve for a given request. SNI adds the hostname to part of the TLS handshake, and so as long as it's supported on both client and server (and in 2015, it is widely supported) then the server can choose the correct certificate. Even without SNI, one way to serve multiple hostnames is with certificates that include Subject Alternative Names (SANs), which are essentially additional domains the certificate is valid for. Google uses a single certificate to secure many of it's sites, for example. Another way is to use wildcard certificates. It is possible to get a certificate like ".example.com" in which case "www.example.com" and "foo.example.com" will both be valid for that certificate. However, note that "example.com" does not match ".example.com", and neither does "foo.bar.example.com". If you use "www.example.com" for your certificate, you should redirect anyone at "example.com" to the "www." site. If they request https://example.com, unless you host it on a separate IP and have two certificates, the will get a certificate error. Of course, you can mix both wildcard and SANs (as long as your CA lets you do this) and get a certificate for both "example.com" and with SANs ".example.com", "example.net", and ".example.net", for example. Forms Strictly speaking, if you are submitting a form, it doesn't matter if the form page itself is not encrypted, as long as the submit URL goes to an https:// URL. In reality, users have been trained (at least in theory) not to submit pages unless they see the little "lock icon", so even the form itself should be served via HTTPS to get this. Traffic and Server Load HTTPS traffic is much bigger than its equivalent HTTP traffic (due to encryption and certificate overhead), and it also puts a bigger strain on the server (encrypting and decrypting). If you have a heavily-loaded server, it may be desirable to be very selective about what content is served using HTTPS. Best Practices * *If you're not just using HTTPS for the entire site, it should automatically redirect to HTTPS as required. Whenever a user is logged in, they should be using HTTPS, and if you're using session cookies, the cookie should have the secure flag set. This prevents interception of the session cookie, which is especially important given the popularity of open (unencrypted) wifi networks. *Any resources on the page should come from the same scheme being used for the page. If you try to fetch images from http:// when the page is loaded with HTTPS, the user will get security warnings. You should either use fully-qualified URLs, or another easy way is to use absolute URLs that do not include the hostname (eg, src="/images/foo.png") because they work for both. * *This includes external resources (eg, Google Analytics) *Don't do POSTs (form submits) when changing from HTTPS to HTTP. Most browsers will flag this as a security warning. A: Be sure that, when on an HTTPS page, all elements on the page come from an HTTPS address. This means that elements should have relative paths (e.g. "/images/banner.jpg") so that the protocol is inherited, or that you need to do a check on every page to find the protocol, and use that for all elements. NB: This includes all outside resources (like Google Analytics javascript files)! The only down-side I can think of is that it adds (nearly negligible) processing time for the browser and your server. I would suggest encrypting only the transfers that need to be. A: I would say the most common mistakes when working with an SSL-enabled site are * *The site erroneously redirects users to http from a page as https *The site doesn't automatically switch to https when it's necessary *Images and other assets on an https page are being loading via http, which will trigger a security alert from the browser. Make sure all assets are using fully-qualified URIs that specify https. *The security certificate only works for one subdomain (such as www) but your site actually uses multiple subdomains. Make sure to get a wildcard certificate if you will need it. A: I would suggest any time any user data is stored in a database and communicated, use https. Consider this requirement even if the user data is mundane, because even many of these mundane details are used by that user to identify themselves on other websites. Consider all the random security questions your bank asks you (like what street do you live on?). This can be taken from address fields really easily. In this case, the data is not what you consider a password, but it might as well be. Furthermore, you can never anticipate what user data will be used for a security question elsewhere. You can also expect that with the intelligence of the average web user (think your grandmother) that that tidbit of information might make up part of that user's password somewhere else. One pointer if you use https make it so that if the user types http://www.website-that-needs-https.com/etc/yadda.php they will automatically get redirected to https://www.website-that-needs-https.com/etc/yadda.php (personal pet peeve) However, if you're just doing a plain html webpage, that will be essentially a one-way transmission of information from the server to the user, don't worry about it. A: All very good tip here... but I just want to add something.. Ive seen some sites that gives you a http login page and only redirect you to https after you post your username/pass.. This means the username is transmitted in the clear before the https connection is established.. In short make the page where you login from ssl, instead of posting to an ssl page. A: I found that trying to <link> to a non-existent style sheet also caused security warnings. When I used the correct path, the lock icon appeared.
{ "language": "en", "url": "https://stackoverflow.com/questions/64631", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Convert from scientific notation string to float in C# What's the proper way to convert from a scientific notation string such as "1.234567E-06" to a floating point variable using C#? A: Double.Parse("1.234567E-06", System.Globalization.NumberStyles.Float); A: Also consider using Double.TryParse("1.234567E-06", System.Globalization.NumberStyles.Float, out MyFloat); This will ensure that MyFloat is set to value 0 if, for whatever reason, the conversion could not be performed. Or you could wrap the Double.Parse() example in a Try..Catch block and set MyFloat to a value of your choosing when an exception is detected.
{ "language": "en", "url": "https://stackoverflow.com/questions/64639", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "33" }
Q: Parsing exact dates in C# shouldn't force you to create an IFormatProvider Someone please correct me if I'm wrong, but parsing a yyyy/MM/dd (or other specific formats) dates in C# should be as easy as DateTime.ParseExact(theDate, "yyyy/MM/dd"); but no, C# forces you to create an IFormatProvider. Is there an app.config friendly way of setting this so I don't need to do this each time? DateTime.ParseExact(theDate, "yyyy/MM/dd", new CultureInfo("en-CA", true)); A: ParseExact needs a culture : consider "yyyy MMM dd". MMM will be a localized month name that uses the current culture. A: Use the current application culture: DateTime.ParseExact("2008/12/05", "yyyy/MM/dd", System.Globalization.CultureInfo.CurrentCulture); You can set the application culture in the app.config using the Globalization tag. I think. A: Create an extension method: public static DateTime ParseExactDateTime(this string dateString, string formatString) { return DateTime.ParseExact(dateString, formatString, new CultureInfo("en-CA", true)); } A: It requires the format provider in order to determine the particular date and time symbols and strings (such as names of the days of the week in a particular language). You can use a null, in which case the CultureInfo object that corresponds to the current culture is used. If you don't want to have to specify it each time, create an extension method which either passes null or CultureInfo("en-CA", true) as the format provider. A: The IFormatProvider argument can be null. A: You could also simply create the IFormatProvider once and store it for later use. A: You could also use the Convert class Convert.ToDateTime("2008/11/25"); A: //Convert date to MySql compatible format DateTime DateValue = Convert.ToDateTime(datetimepicker.text); string datevalue = DateValue.ToString("yyyy-MM-dd"); A: What's wrong with using Globalization.CultureInfo.InvariantCulture ?
{ "language": "en", "url": "https://stackoverflow.com/questions/64640", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Define an interface in C++ that needs to be implemented in C# and C++ I have an interface that I have defined in C++ which now needs to be implemented in C#. What is the best way to go about this? I don't want to use COM at all in my interface definition. The way I have solved this right now is to to have two interface definitions, one in C++ and one in C#. I then expose the C# interfaces as a COM server. This was my application which is written in C++ can call into C#. Is there anyway I can avoid having to define my implementation in C++ as well as C#? A: If you are willing to use C++/CLI for your managed code instead of C#, then you can just consume the native C++ interface definition directly via the header file. How easy this will be will depend on exactly what is in your interface - simplest case is something that you could use from C. Take a look at Marcus Heege's Expert C++/CLI: .NET for Visual C++ Programmers, for a lot of helpful information on mixing native and managed C++ in .NET. A: Swig is a great tool for wrapping C++ classes in other languages like C#. A: Why don't you want to use COM? This would have been my suggestion. COM interop has worked really well for me, and I've used COM objects and interfaces in C# (simply reference the COM object and the runtime callable wrapper gets created automatically). Similarly marking a C# class as "Register for COM interop" has worked the other way around. A: Write the interface in C++ and use macros to make it look like a standard cpp header file on UNIX and like an IDL file on windows (If this does not work out, you can always write a python/ruby script to generate the IDL from the C++ header file). Compile the IDL to generate a typelib. Use TypeLib Importer to generate the interface definitions for C# and implement the interfaces there. A: The other approach is to use a 'flat', C-style API. You might as well use extern "C" to prevent accidental overloading. Use a DEF file to explicitly name the exported functions, so they're definitely not decorated in any way (C++ functions are 'decorated' with an encoding of the parameter types in the export table). On x86, beware of calling conventions. It's probably to explicitly declare the use of __stdcall or __cdecl. Because P/Invoke is primarily used to invoke Windows APIs, it defaults to StdCall, but C and C++ default to cdecl, because that supports varargs. I recently wrapped the COM interface IRapiStream in a flat C interface as .NET seemed to be trying to convert the IStream into a storage, which failed with the error STG_E_UNIMPLEMENTEDFUNCTION. A: You don't mention which version of .NET you're using, but something that's worked for me in using Visual Studio .NET 2003 is to provide a thin C# wrapper around the pimpled implementation of the real C++ class: public __gc class MyClass_Net { public: MyClass_Net() :native_ptr_(new MyClass()) { } ~MyClass_Net() { delete native_ptr_; } private: MyClass __nogc *native_ptr_; }; Obviously, one would prefer to use a Boost shared_ptr there, but I could never get them to play nicely with V.NET 2003... Methods simply forward to the underlying C++ methods through the pointer. Method arguments may have to be converted. For example, to call a C++ method which takes a string, the C# method should probably take a System.String (System::String in Managed C++). You'd have to use System::Runtime::InteropServices::Marshal::StringToHGlobalAnsi() to do that. One nice thing about this approach is because Managed C++ is a .NET language, you get to expose accessors as properties (__property). You can even expose attributes, very much like in C#.
{ "language": "en", "url": "https://stackoverflow.com/questions/64645", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How do I get the find command to print out the file size with the file name? If I issue the find command as follows: find . -name *.ear It prints out: ./dir1/dir2/earFile1.ear ./dir1/dir2/earFile2.ear ./dir1/dir3/earFile1.ear I want to 'print' the name and the size to the command line: ./dir1/dir2/earFile1.ear 5000 KB ./dir1/dir2/earFile2.ear 5400 KB ./dir1/dir3/earFile1.ear 5400 KB A: find . -name '*.ear' -exec du -h {} \; This gives you the filesize only, instead of all the unnecessary stuff. A: A simple solution is to use the -ls option in find: find . -name \*.ear -ls That gives you each entry in the normal "ls -l" format. Or, to get the specific output you seem to be looking for, this: find . -name \*.ear -printf "%p\t%k KB\n" Which will give you the filename followed by the size in KB. A: Awk can fix up the output to give just what the questioner asked for. On my Solaris 10 system, find -ls prints size in KB as the second field, so: % find . -name '*.ear' -ls | awk '{print $2, $11}' 5400 ./dir1/dir2/earFile2.ear 5400 ./dir1/dir2/earFile3.ear 5400 ./dir1/dir2/earFile1.ear Otherwise, use -exec ls -lh and pick out the size field from the output. Again on Solaris 10: % find . -name '*.ear' -exec ls -lh {} \; | awk '{print $5, $9}' 5.3M ./dir1/dir2/earFile2.ear 5.3M ./dir1/dir2/earFile3.ear 5.3M ./dir1/dir2/earFile1.ear A: Try the following commands: GNU stat: find . -type f -name *.ear -exec stat -c "%n %s" {} ';' BSD stat: find . -type f -name *.ear -exec stat -f "%N %z" {} ';' however stat isn't standard, so du or wc could be a better approach: find . -type f -name *.ear -exec sh -c 'echo "{} $(wc -c < {})"' ';' A: Just list the files (-type f) that match the pattern (-name '*.ear) using the disk-usage command (du -h) and sort the files by the human-readable file size (sort -h): find . -type f -name '*.ear' -exec du -h {} \; | sort -h Output 5.0k ./dir1/dir2/earFile1.ear 5.4k ./dir1/dir2/earFile2.ear 5.4k ./dir1/dir3/earFile1.ear A: Using GNU find, I think this is what you want. It finds all real files and not directories (-type f), and for each one prints the filename (%p), a tab (\t), the size in kilobytes (%k), the suffix " KB", and then a newline (\n). find . -type f -printf '%p\t%k KB\n' If the printf command doesn't format things the way you want, you can use exec, followed by the command you want to execute on each file. Use {} for the filename, and terminate the command with a semicolon (;). On most shells, all three of those characters should be escaped with a backslash. Here's a simple solution that finds and prints them out using "ls -lh", which will show you the size in human-readable form (k for kilobytes and M for megabytes): find . -type f -exec ls -lh \{\} \; As yet another alternative, "wc -c" will print the number of characters (bytes) in the file: find . -type f -exec wc -c \{\} \; A: I struggled with this on Mac OS X where the find command doesn't support -printf. A solution that I found, that admittedly relies on the 'group' for all files being 'staff' was... ls -l -R | sed 's/\(.*\)staff *\([0-9]*\)..............\(.*\)/\2 \3/' This splits the ls long output into three tokens * *the stuff before the text 'staff' *the file size *the file name And then outputs tokens 2 and 3, i.e. output is number of bytes and then filename 8071 sections.php 54681 services.php 37961 style.css 13260 thumb.php 70951 workshops.php A: Why not use du -a ? E.g. find . -name "*.ear" -exec du -a {} \; Works on a Mac A: This should get you what you're looking for, formatting included (i.e. file name first and size afterward): find . -type f -iname "*.ear" -exec du -ah {} \; | awk '{print $2"\t", $1}' sample output (where I used -iname "*.php" to get some result): ./plugins/bat/class.bat.inc.php 20K ./plugins/quotas/class.quotas.inc.php 8.0K ./plugins/dmraid/class.dmraid.inc.php 8.0K ./plugins/updatenotifier/class.updatenotifier.inc.php 4.0K ./index.php 4.0K ./config.php 12K ./includes/mb/class.hwsensors.inc.php 8.0K A: find . -name '*.ear' -exec ls -lh {} \; just the h extra from jer.drab.org's reply. saves time converting to MB mentally ;) A: You need to use -exec or -printf. Printf works like this: find . -name *.ear -printf "%p %k KB\n" -exec is more powerful and lets you execute arbitrary commands - so you could use a version of 'ls' or 'wc' to print out the filename along with other information. 'man find' will show you the available arguments to printf, which can do a lot more than just filesize. [edit] -printf is not in the official POSIX standard, so check if it is supported on your version. However, most modern systems will use GNU find or a similarly extended version, so there is a good chance it will be implemented. A: You could try this: find. -name *.ear -exec du {} \; This will give you the size in bytes. But the du command also accepts the parameters -k for KB and -m for MB. It will give you an output like 5000 ./dir1/dir2/earFile1.ear 5400 ./dir1/dir2/earFile2.ear 5400 ./dir1/dir3/earFile1.ear A: find . -name "*.ear" | xargs ls -sh A: $ find . -name "test*" -exec du -sh {} \; 4.0K ./test1 0 ./test2 0 ./test3 0 ./test4 $ Scripter World reference A: find . -name "*.ear" -exec ls -l {} \; A: If you need to get total size, here is a script proposal #!/bin/bash totalSize=0 allSizes=`find . -type f -name *.ear -exec stat -c "%s" {} \;` for fileSize in $allSizes; do totalSize=`echo "$(($totalSize+$fileSize))"` done echo "Total size is $totalSize bytes" A: You could try for loop: for i in `find . -iname "*.ear"`; do ls -lh $i; done
{ "language": "en", "url": "https://stackoverflow.com/questions/64649", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "159" }
Q: MySQL: "lock wait timeout exceeded" I am trying to delete several rows from a MySQL 5.0.45 database: delete from bundle_inclusions; The client works for a while and then returns the error: Lock wait timeout exceeded; try restarting transaction It's possible there is some uncommitted transaction out there that has a lock on this table, but I need this process to trump any such locks. How do I break the lock in MySQL? A: Linux: In mysql configuration (/etc/my.cnf or /etc/mysql/my.cnf), insert / edit this line innodb_lock_wait_timeout = 50 Increase the value sufficiently (it is in seconds), restart database, perform changes. Then revert the change and restart again. A: I had the same issue, a rogue transaction without a end. I restarted the mysqld process. You don't need to truncate a table. You may lose data from that rogue transaction. A: I agree with Erik; TRUNCATE TABLE is the way to go. However, if you can't use that for some reason (for example, if you don't really want to delete every row in the table), you can try the following options: * *Delete the rows in smaller batches (e.g. DELETE FROM bundle_inclusions WHERE id BETWEEN ? and ?) *If it's a MyISAM table (actually, this may work with InnoDB too), try issuing a LOCK TABLE before the DELETE. This should guarantee that you have exclusive access. *If it's an InnoDB table, then after the timeout occurs, use SHOW INNODB STATUS. This should give you some insight into why the lock acquisition failed. *If you have the SUPER privilege you could try SHOW PROCESSLIST ALL to see what other connections (if any) are using the table, and then use KILL to get rid of the one(s) you're competing with. I'm sure there are many other possibilities; I hope one of these help. A: Guessing: truncate table bundle_inclusions
{ "language": "en", "url": "https://stackoverflow.com/questions/64653", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: jQuery: JFrame plugin fails in IE 7 I'm using the JFrame plugin with jquery 1.2.6. It works fine in FF3, however it won't display the requested pages in IE 7. The jQuery library and the JFrame plugin are called in the included header.cfm. Page code is here (note: ignore the ColdFusion calls, I don't think they're generating the problem): http://cfm.pastebin.com/m20c1b013 A: When you have a problem like this, the best way of tracking down the problem is to reduce the page to the minimum necessary to reproduce the problem. "Ignore the [x] because I don't think that's the problem" is no good, if you don't think that's the problem, save it to a temporary static page, delete the things you think are unrelated, and then you know whether or not they are the problem. Keep deleting things you think are unrelated, and eventually you will either find the bit that's screwing things up when you remove it, or you will end up with a very small file that is: * *Much easier to debug *Much more likely to attract help from people *Much better testcase for the times when it's a genuine bug in a library Not many people are willing to pick apart Coldfusion and table layout code to get to your bug - after all, you're the one with the problem, and even you couldn't be bothered to do it, so why would anybody else? A: I would suggest updating to the newest release of jquery (v 1.3.2). This might be the simplest way to attempt to fix the bug. http://jquery.com/ A: Being new to JQuery myself, I have found the Developer tools in IE8 indispensible. In the script console I was able to find error messages that gave me the info I needed. Are you getting any error messages? There is a "Developer Toolbar" available for IE7. I do not know what it provides for script debugging: http://www.microsoft.com/downloads/details.aspx?FamilyID=E59C3964-672D-4511-BB3E-2D5E1DB91038&displaylang=en
{ "language": "en", "url": "https://stackoverflow.com/questions/64657", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: C pointers in C# Is this function declaration in C#: void foo(string mystring) the same as this one in C: void foo(char *) i.e. In C#, does the called function receive a pointer behind the scenes? A: There are pointers behind the scenes in C#, though they are more like C++'s smart pointers, so the raw pointers are encapsulated. A char* isn't really the same as System.String since a pointer to a char usually means the start of a character array, and a C# string is an object with a length field and a character array. The pointer points to the outer structure which points into something like a wchar_t array, so there's some indirection with a C# string and wider characters for Unicode support. A: No. In C# (and all other .NET languages) the String is a first-class data type. It is not simply an array of characters. You can convert back and forth between them, but they do not behave the same. There are a number of string manipulation methods (like "Substring()" and "StartsWith") that are available to the String class, which don't apply to arrays in general, which an array of characters is simply an instance of. A: Essentially, yes. In C#, string (actually System.String) is a reference type, so when foo() is called, it receives a pointer to the string in the heap. A: For value types (int, double, etc.), the function receives a copy of the value. For other objects, it's a reference pointing to the original object. Strings are special because they are immutable. Technically it means it will pass the reference, but in practice it will behave pretty much like a value type. You can force value types to pass a reference by using the ref keyword: public void Foo(ref int value) { value = 12 } public void Bar() { int val = 3; Foo(ref val); // val == 12 } A: In this specific instance, it is more like: void foo(const char *); .Net strings are immutable and passed by reference. However, in general C# receives a pointer or reference to an object behind the scenes. A: no in c# string is unicode. in c# it is not called a pointer, but a reference. A: If you mean - will the method be allowed to access the contents of the character space, the answer is yes. A: Yes, because a string is of dynamic size, so there must be heap memory behind the scenes However they are NOT the same. in c the pointer points to a string that may also be used elsewhere, so changing it will effect those other places. A: Anything that is not a "value type", which essentially covers enums, booleans, and built-in numeric types, will be passed "by reference", which is arguably the same as the C/C++ mechanism of passing by reference or pointer. Syntactically and semantically it is essentially identical to C/C++ passing by reference. Note, however, that in C# strings are immutable, so even though it is passed by reference you can't edit the string without creating a new one. Also note that you can't pass an argument as "const" in C#, regardless whether it is a value type or a reference type. A: While those are indeed equivalent in a semantic sense (i.e. the code is doing something with a string), C#, like Java, keeps pointers completely out of its everyday use, relegating them to areas such as transitions to native OS functions - even then, there are framework classes which wrap those up nicely, such as SafeFileHandle. Long story short, don't go out of your way thinking of pointers in C#. A: As far as I know, all classes in C# (not sure about the others) are reference types.
{ "language": "en", "url": "https://stackoverflow.com/questions/64689", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Simple haskell string manage Theres is a little problem I want to solve with Haskell: let substitute a function that change all of the wildcards in a string for one concrete parameter. The function has de signature of: subs :: String -> String -> String -> String -- example: -- subs 'x' "x^3 + x + sin(x)" "6.2" will generate -- "6.2^3 + 6.2 + sin(6.2)" A: You could use the Text.Regex package. Your example might look something like this: import Text.Regex(mkRegex, subRegex) subs :: String -> String -> String -> String subs wildcard input value = subRegex (mkRegex wildcard) input value A: See http://bluebones.net/2007/01/replace-in-haskell/ for an example which looks exactly as the piece of code you are looking for. A: You can use text-format-simple library for such cases: import Text.Format format "{0}^3 + {0} + sin({0})" ["6.2"] A: Use regular expressions (Text.Regex.Posix) and search-replace for /\Wx\W/ (Perl notation). Simply replacing x to 6.2 will bring you trouble with x + quux. Haskell Regex Replace for more information (I think this should be imported to SO. For extra hard-core you could parse your expression as AST and do the replacement on that level.
{ "language": "en", "url": "https://stackoverflow.com/questions/64693", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: What is a good non-recursive algorithm for deciding whether a passed in amount can be built additively from a set of numbers? What is a non recursive algorithm for deciding whether a passed in amount can be built additively from a set of numbers. In my case I'm determining whether a certain currency amount (such as $40) can be met by adding up some combination of a set of bills (such as $5, $10 and $20 bills). That is a simple example, but the algorithm needs to work for any currency set (some currencies use funky bill amounts and some bills may not be available at a given time). So $50 can be met with a set of ($20 and $30), but cannot be met with a set of ($20 and $40). The non-recursive requirement is due to the target code base being for SQL Server 2000 where the support of recursion is limited. In addition this is for supporting a multi currency environment where the set of bills available may change (think a foreign currency exchange teller for example). A: You have twice stated that the algorithm cannot be recursive, yet that is the natural solution to this problem. One way or another, you will need to perform a search to solve this problem. If recursion is out, you will need to backtrack manually. Pick the largest currency value below the target value. If it's match, you're done. If not, push the current target value on a stack and subtract from the target value the picked currency value. Keep doing this until you find a match or there are no more currency values left. Then use the stack to backtrack and pick a different value. Basically, it's the recursive solution inside a loop with a manually managed stack. A: If you treat each denomination as a point on a base-n number, where n is the maximum number of notes you would need, then you can increment through that number until you've exhausted the problem space or found a solution. The maximum number of notes you would need is the Total you require divided by the lowest denomination note. It's a brute force response to the problem, but it'll definitely work. Here's some p-code. I'm probably all over the place with my fence posts, and it's so unoptimized to be ridiculous, but it should work. I think the idea's right anyway. Denominations = [10,20,50,100] Required = 570 Denominations = sort(Denominations) iBase = integer (Required / Denominations[1]) BumpList = array [Denominations.count] BumpList.Clear repeat iTotal = 0 for iAdd = 1 to Bumplist.size iTotal = iTotal + bumplist [iAdd] * Denominations[iAdd] loop if iTotal = Required then exit true //this bit should be like a mileometer. //We add 1 to each wheel, and trip over to the next wheel when it gets to iBase finished = true for iPos from bumplist.last to bumplist.first if bumplist[iPos] = (iBase-1) then bumplist[iPos] = 0 else begin finished = false bumplist[iPos] = bumplist[iPos]+1 exit for end loop until (finished) exit false A: That's a problem that can be solved by an approach known as dynamic programming. The lecture notes I have are too focused on bioinformatics, unfortunately, so you'll have to google for it yourself. A: This sounds like the subset sum problem, which is known to be NP-complete. Good luck with that. Edit: If you're allowed arbitrary number of bills/coins of some denomination (as opposed to just one), then it's a different problem, and is easier. See the coin problem. I realized this when reading another answer to a (suspiciously) similar question. A: I agree with Tyler - what you are describing is a variant of the Subset Sum problem which is known to be NP-Complete. In this case you are a bit lucky as you are working with a limited set of values so you can use dynamic programming techniques here to optimize the problem a bit. In terms of some general ideas for the code: * *Since you are dealing with money, there are only so many ways to make change with a given bill and in most cases some bills are used more often than others. So if you store the results you can keep a set of the most common solutions and then just check them before you try and find the actual solution. *Unless the language you are working with doesn't support recursion there is no reason to completely ignore the use of recursion in the solution. While any recursive problem can be solved using iteration, this is a case where recursion is likely going to be easier to write. Some of the other users such as Kyle and seanyboy point you in the right direction for writing your own function so you should take a look at what they have provided for what you are working on. A: You can deal with this problem with Dynamic Programming method as MattW. mentioned. Given limited number of bills and maximum amount of money, you can try the following solution. The code snippet is in C# but I believe you can port it to other language easily. // Set of bills int[] unit = { 40,20,70}; // Max amount of money int max = 100000; bool[] bucket = new bool[max]; foreach (int t in unit) bucket[t] = true; for (int i = 0; i < bucket.Length; i++) if (bucket[i]) foreach (int t in unit) if(i + t < bucket.Length) bucket[i + t] = true; // Check if the following amount of money // can be built additively Console.WriteLine("15 : " + bucket[15]); Console.WriteLine("50 : " + bucket[50]); Console.WriteLine("60 : " + bucket[60]); Console.WriteLine("110 : " + bucket[110]); Console.WriteLine("120 : " + bucket[120]); Console.WriteLine("150 : " + bucket[150]); Console.WriteLine("151 : " + bucket[151]); Output: 15 : False 50 : False 60 : True 110 : True 120 : True 150 : True 151 : False A: There's a difference between no recursion and limited recursion. Don't confuse the two as you will have missed the point of your lesson. For example, you can safely write a factorial function using recursion in C++ or other low level languages because your results will overflow even your biggest number containers within but a few recursions. So the problem you will face will be that of storing the result before it ever gets to blowing your stack due to recursion. This said, whatever solution you find - and I haven't even bothered understanding your problem deeply as I see that others have already done that - you will have to study the behaviour of your algorithm and you can determine what is the worst case scenario depth of your stack. You don't need to avoid recursion altogether if the worst case scenario is supported by your platform. A: Edit: The following will work some of the time. Think about why it won't work all the time and how you might change it to cover other cases. Build it starting with the largest bill towards the smallest. This will yeild the lowest number of bills. Take the initial amount and apply the largest bill as many times as you can without going over the price. Step to the next largest bill and apply it the same way. Keep doing this until you are on your smallest bill. Then check if the sum equals the target amount. A: Algorithm: 1. Sort currency denominations available in descending order. 2. Calculate Remainder = Input % denomination[i] i -> n-1, 0 3. If remainder is 0, the input can be broken down, otherwise it cannot be. Example: Input: 50, Available: 10,20 [50 % 20] = 10, [10 % 10] = 0, Ans: Yes Input: 50, Available: 15,20 [50 % 20] = 10, [10 % 15] = 15, Ans: No
{ "language": "en", "url": "https://stackoverflow.com/questions/64723", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-4" }
Q: Moving to Android from J2ME Coming from J2ME programming are there any similarities that would make it easy to adapt to Android API. Or is Android API completely different from the J2ME way of programming mobile apps. A: A good start would be to watch the Android architecture videos and look at some of the documentation. http://www.youtube.com/view_play_list?p=586D322B5E2764CF http://code.google.com/android/what-is-android.html Google is very good about documenting. From what I've heard Android very very similar to J2ME in its goals. It may be slightly different in programming style and structure but if you have J2ME experience you should be more then ready to move on to Android. Good Luck!!! A: Actually the Android API is much more powerful than the J2ME. It is much easier to create an application for the Android. Using the J2ME you are limited to simple forms due to the absent of swing-like libraries (though now there exists a library called LWUIT, avoiding the need to recreate from scratch a swing-like library). In Android you will be able to create complex form very quickly, and software package for the android SDK is easy to install (while in J2ME you have to install the wireless development toolkit from sun, or install one of Nokia's, Samsung's or SonyEricsson's... it gets a bit confusing sometimes). The things I had to change when switching from j2me to android were: 1/ The font and graphics class is easier to use on j2me. The API is more thorough on Android, but also more complicated. 2/ If you are used to the database storage of j2me (RecordStore), well you can forget it in Android. You will have to use a SQL-like databased, so be prepared to rethink your data model. A: I've also found the path from Java ME to Android to be pretty simple. Here are a few things I've noticed: * *There is ONE ui draw thread in Android. You have to be aware of the difference between calling postInvalidate and invalidate on Views to force them to update. *The actual bit-wise graphic manipulation is very similar. I was able to port large amounts of custom J2ME draw code by writing a few shims for drawRect and drawImage. *Android's UI library is much more extensive, much less useless, and much more complicated than Java ME's *Threadwise, you have to be much more careful about thread saftey with Android. In Java ME you can get away with not making methods synchronous or variables volatile most of the time. Not so in Android. I will say, on the whole, that Android's UI library fails a critical test. I call this the "roll my own" test. Your UI library fails this test if it takes me longer to complete a detailed task task (say, changing the background on one individual menu item) than it would take me two write my own Menu from scratch. Android fails the "roll your own" test by a factor of 3 or 4. In fact, if you look, the majority of the questions on this website are "How do I make the Android UI toolkit do my bidding?" questions. Android is an amazing platform and it has been worth every frustrating moment I've sunk into it. It is, however, a young platform, and needs some serious work in times to come. A: Well, you may not actually need to adapt. There is a good chance that a J2ME stack will become available for Android before long since Android is not supposed to become as restrictive of third-party runtimes as the iPhone. I know one guy who has been working on just that: http://justanapplication.wordpress.com/ Now, of course, that doesn't mean you shouldn't have a look at the Android APIs and application lifecycle.
{ "language": "en", "url": "https://stackoverflow.com/questions/64745", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "29" }
Q: Disk Activity in Applescript How can I poll disk activity in Applescript? Check to see if disk X is being read, written, or idle every N seconds and do something. A: In general, polling is less efficient than being notified when something happens. Additionally, if you're checking whether something is reading from a disk, you will probably be accessing said disk yourself, possibly influencing what you're trying to observe. Since 10.5, OSX includes something called the File System Events framework, which provides course-grained notifications of changes to the file system. The problem in your case is that this is Objective-C only. Apple has some nice documentation about this API. Fortunately, there is also the call method AppleScript command. This allows you to work with Objective-C objects from within AppleScript. Here's the documentation on that. I have no experience with either, hence the documentation references. Hopefully, this should get you going. A: You could run the terminal command iostat periodically. You'd have to parse the results into a form you could digest. If you know enough about various UNIX command line tools, I'd suggest iostat piping the output to awk or sed to extract just the information you want. A: You should really look at Dtrace. It has the ability to do this sort of thing. #!/usr/sbin/dtrace -s /* * bitesize.d - analyse disk I/O size by process. * Written using DTrace (Solaris 10 build 63). * * This produces a report for the size of disk events caused by * processes. These are the disk events sent by the block I/O driver. * * If applications must use the disks, we generally prefer they do so * sequentially with large I/O sizes. * * 15-Jun-2005, ver 1.00 * * USAGE: bitesize.d # wait several seconds, then hit Ctrl-C * * FIELDS: * PID process ID * CMD command and argument list * value size in bytes * count number of I/O operations * * NOTES: * The application may be requesting smaller sized operations, which * are being rounded up to the nearest sector size or UFS block size. * To analyse what the application is requesting, DTraceToolkit programs * such as Proc/fddist may help. * * SEE ALSO: seeksize.d, iosnoop * * Standard Disclaimer: This is freeware, use at your own risk. * * 31-Mar-2004 Brendan Gregg Created this, build 51. * 10-Oct-2004 " " Rewrote to use the io provider, build 63. */ #pragma D option quiet /* * Print header */ dtrace:::BEGIN { printf("Sampling... Hit Ctrl-C to end.\n"); } /* * Process io start */ io:::start { /* fetch details */ this->size = args[0]->b_bcount; cmd = (string)curpsinfo->pr_psargs; /* store details */ @Size[pid,cmd] = quantize(this->size); } /* * Print final report */ dtrace:::END { printf("\n%8s %s\n","PID","CMD"); printa("%8d %s\n%@d\n",@Size); } From here. To run use sudo dtrace -s bitsize.d A: As Porkchop D. Clown mentioned, you can use iostat. A command you could use is: iostat -c 50 -w 5 Which will run iostat 50 times every 5 seconds.
{ "language": "en", "url": "https://stackoverflow.com/questions/64748", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: '^M' character at end of lines When I run a particular SQL script in Unix environments, I see a '^M' character at the end of each line of the SQL script as it is echoed to the command line. I don't know on which OS the SQL script was initially created. What is causing this and how do I fix it? A: It's caused by the DOS/Windows line-ending characters. Like Andy Whitfield said, the Unix command dos2unix will help fix the problem. If you want more information, you can read the man pages for that command. A: Fix line endings in vi by running the following: :set fileformat=unix :w A: The SQL script was originally created on a Windows OS. The '^M' characters are a result of Windows and Unix having different ideas about what to use for an end-of-line character. You can use perl at the command line to fix this. perl -pie 's/\r//g' filename.txt A: The ^M is typically caused by the Windows operator newlines, and translated onto Unix looks like a ^M. The command dos2unix should remove them nicely dos2unix [options] [-c convmode] [-o file ...] [-n infile outfile ...] A: C:\tmp\text>dos2unix hello.txt helloUNIX.txt Sed is even more widely available and can do this kind of thing also if dos2unix is not installed C:\tmp\text>sed s/\r// hello.txt > helloUNIX.txt You could also try tr: cat hello.txt | tr -d \r > helloUNIX2.txt Here are the results: C:\tmp\text>dumphex hello.txt 00000000h: 48 61 68 61 0D 0A 68 61 68 61 0D 0A 68 61 68 61 Haha..haha..haha 00000010h: 0D 0A 0D 0A 68 61 68 61 0D 0A ....haha.. C:\tmp\text>dumphex helloUNIX.txt 00000000h: 48 61 68 61 0A 68 61 68 61 0A 68 61 68 61 0A 0A Haha.haha.haha.. 00000010h: 68 61 68 61 0A haha. C:\tmp\text>dumphex helloUNIX2.txt 00000000h: 48 61 68 61 0A 68 61 68 61 0A 68 61 68 61 0A 0A Haha.haha.haha.. 00000010h: 68 61 68 61 0A haha. A: An alternative to dos2unix command would be using standard utilities like sed. For example, dos to unix: sed 's/\r$//' dos.txt > unix.txt unix to dos: sed 's/$/\r/' unix.txt > dos.txt A: The cause is the difference between how a Windows-based based OS and a Unix based OS store the end-of-line markers. Windows based operating systems, thanks to their DOS heritage, store an end-of-line as a pair of characters - 0x0D0A (carriage return + line feed). Unix-based operating systems just use 0x0A (a line feed). The ^M you're seeing is a visual representation of 0x0D (a carriage return). dos2unix will help with this. You probably also need to adjust the source of the scripts to be 'Unix-friendly'. A: To replace ^M characters in vi editor use below open the text file say t1.txt vi t1.txt Enter command mode by pressing shift + : then press keys as mentioned %s/^M/\r/g in above ^M is not (shift + 6)M instead it is (ctrl + V)(ctrl + M) A: The easiest way is to use vi. I know that sounds terrible but its simple and already installed on most UNIX environments. The ^M is a new line from Windows/DOS environment. from the command prompt: $ vi filename Then press ":" to get to command mode. Search and Replace all Globally is :%s/^M//g "Press and hold control then press V then M" which will replace ^M with nothing. Then to write and quit enter ":wq" Done! A: Try using dos2unix to strip off the ^M. A: In vi, do a :%s/^M//g To get the ^M hold the CTRL key, press V then M (Both while holding the control key) and the ^M will appear. This will find all occurrences and replace them with nothing. A: You can remove ^M from the files directly via sed command, e.g.: sed -i'.bak' s/\r//g *.* If you're happy with the changes, remove the .bak files: rm -v *.bak A: Convert DOS/Windows (\r\n) line endings to Unix (\n) line endings, with tr: tr '\r\n' '\n' < dosFile.txt > unixFile.txt Post about replacing newlines from the Unix command line A: od -a $file is useful to explore those types of question on Linux (similar to dumphex in the above). A: In Perl, if you don't want to set the $/ variable and use chomp() you can also do: $var =~ /\r\n//g; My two cents A: As already explained, Windows programs like to terminate lines with CRLF, i.e. \r\n instead of the Unix/Linux standard \n. Since I don't need all the features of dos2unix I replaced it by adding the following to my ~/.bashrc which removes the \r: function win2unix() { tmp=$(mktemp) && tr -d '\r' < $1 > $tmp && mv $tmp $1 } Now when I want to get rid of those ^M characters created e.g. when I export a CSV file from Excel or Calc, I can just do something like: win2unix filename.csv You could also use sed or something else, of course. By the way, I use cat -e $filename to visualize the ^M endings. A: Another vi command that'll do: :%s/.$// This removes the last character of each line in the file. The drawback to this search and replace command is that it doesn't care what the last character is, so be careful not to call it twice.
{ "language": "en", "url": "https://stackoverflow.com/questions/64749", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "104" }
Q: Placing a PDF inside another PDF document with Zend_PDF I have a pdf file of a logo, about 1"x2" in dimension. Can anybody provide the code snippet to import that PDF logo into another PDF file using the Zend_PDF API's? Ideally, I'd like to be able to place it like the PNG, TIFF or JPG objects with the Zend_Pdf_Image object. In other words, I want to be able to place the little 1x2" pdf document on top of a 8.5x11" page, not use the original pdf as a background. Thanks! A: It looks like as of this date, there's no way to do it using the Zend_PDF API's. The Zend_Pdf_Page class has a drawContentStream() which looked promising, but when I checked into it, the method body was empty. Maybe a later release of the API will support it. So, if you want place another PDF inside another dynamically generated PDF document like an image, use FPDI + FPDF/TCPDF. $pdf = & new FPDI ('P', 'in', 'Letter' ); $pagecount = $pdf->setSourceFile ( APP . 'logo.pdf' ); $tplidx = $pdf->importPage ( 1, '/MediaBox' ); $pdf->addPage (); $pdf->useTemplate ( $tplidx, 1, 1 ); $pdf->Output ( 'output.pdf', 'F' ); A: I believe you can clone a page --like a template. Not sure if this is enough for you, it does look like the preferred way to do things. Of course, if you have a pdf that you want to add a, say, watermark, to, uhh, this is clearly insufficient --but in this case a hi-res png would probably suffice. A: Not what you asked for, but probably what you need (: Convert the smaller logo pdf to a TIFF/PNG/WhatEver (using, for example, imagemagick's convert, or the GIMP). Then, place this image with the normal Zend API. This conversion could also be done on the fly, using the Imagick php class, I would imagine.
{ "language": "en", "url": "https://stackoverflow.com/questions/64759", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Should HTML co-exist with code? In a web application, is it acceptable to use HTML in your code (non-scripted languages, Java, .NET)? There are two major sub questions: * *Should you use code to print HTML, or otherwise directly create HTML that is displayed? *Should you mix code within your HTML pages? A: As long as your HTML-writing code is separate from your application logic, and the HTML is guaranteed to be well-formed somehow, you should be okay. The only code that should be mixed in markup-based pages (i.e, those that contain literal HTML) is the code used for formatting the HTML (e.g., a loop for writing out a list). There are trade-offs whether you put the code in with the HTML or you use pure code to write the HTML out using quoted string literals. A: Generally, it's better to keep presentation (HTML) separate from logic ("back-end" code). Your code is decoupled and easier to maintain this way. A: No, if you want to build good and maintainable software, and to achieve loose coupling. A: If I understand the question right, you're asking whether it's a good practice to mix markup with back-end code. No. While this is commonly done, it's still a bad idea. You should read up on the MVC paradigm, as well as on existing questions on the matter, such as What is the best way to migrate an existing messy webapp to elegant MVC? and Best practices for refactoring classic ASP? A: The point is to keep the display logic separate from the rest of the code. In any complex site you'll have code mixed in with your HTML, but the code should be for display purposes only. It shouldn't be doing any complex calculations. For example, templates will contain loops and conditionals. Plus you'll probably have a library of HTML-specific routines, like printing out an <option> list based on a list object. Imagine you were writing an application that has two output modes: HTML and something else. How would you write it, to avoid duplicating code? That will probably point you in the right direction. A: The HTML that makes up the view has to get sent to the browser in some way. In .net, each server control emits its own HTML markup as part of the page lifecycle. So yes it is OK to use HTML in server side code. Perhaps you should try following the ASP.net pattern. Create a bunch of controls that represent UI elements and make them responsible for emitting their own HTML based on their state. A: Its fugly, and not type safe. But people do it without consequence. I'd prefer using a DOM or, at a minimum, classes designed to write HTML using type safe semantics. Also, its not all that good to mix UI with logic... A: If I need methods that generate HTML I usually isolate them in an HtmlHelpers class. That way you keep some level of separation. The ASP.NET MVC Framework does this quite successfully. A: If you mean printing out HTML in your code, then no. Unless you have a good reason not to, you should use templates Even if you think you don't need this now, there's always a good chance you'll need it later. Maybe you want to output in a different format than HTML, or you want different presentation for the same data. You usually have the need for these things further down the road, so it's best to use one from the start. A: I hate when developers print() a bunch of html. It's completely unnecessary and looks ugly in any text editor that shows print/echo strings in red. A: I agree with everyone else that you should try as hard as you can to separate the HTML/XHTML markup from the application logic. However, sometimes you do need to generate HTML/XHTML in the application logic for various reasons. In these cases what I have been trying to do is to ensure the bare minimum amount of presentation code is in mixed in with the application logic and try to migrate everything else over to the presentation code. It is worth nothing that is some cases you have situations where you could have everything moved over to the presentation layer, but it might be a bit easier to generate the markup as part of the application logic. In those cases, your best bet is likely to be to go the route that makes the most sense in terms of time. A: I don't think there's any excuse for generating HTML inside your business logic. Don't even do it when it's just a "quick fix" or when you'll "go back and fix it later", because that never happens. To reiterate my position from other questions, using some control logic (conditionals, loops) within HTML to construct it is OK. Do NOT do any data massaging or business logic in the HTML. You have to be disciplined, but it's worth it. Maintenance is much easier if your concerns (like logic and display) are separated. A: Ideally you are aiming for a separation of concerns between your presentation (UI) code and your domain (business logic) code. The reason why you should avoid coupling these two concerns (in either direction) is simple... You will only have one reason to change a piece of code. whether this is from structural/styling changes in your html design, or from your business rules changing, you should only have to make the change in one place. To a lesser extent, although many purists would disagree, by sprinkling HTML code through your domain code or vice versa you are creating noise for the next developer who comes along to read/maintain it. A: * *I try to avoid using code to print HTML "directly". It is difficult to maintain, edit, add styles and etc. Some cases like generating an HTML email in the code, I create a text file or HTML file with markers like, [name], [verification code] and etc. I load this from the code and replace those markers. This way, you can edit the style of the email without re-compiling your code. Separating "presentation" and "logic" is a good practice in my opinion. *Mixing code within HTML is generally not a good practice in similar reasons as said in #1. However, I do use code in HTML for things like simple dynamic strings that are displayed multiple times on a page or pages. I think this is better than creating multiple server controls for same exact values to set. Since this is not code "logic" mixed in the HTML, I think this is ok.
{ "language": "en", "url": "https://stackoverflow.com/questions/64760", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Is there a terminal program that differentiates between input, output, and commands? Is there a terminal program that shows the difference between input, standard output, error output, the prompt, and user-entered commands? It should also show when standard input is needed vs. running a command. One way would be to highlight each differently. The cursor could change color depending on if it was waiting for a command, running a command, or waiting for standard input. Another way would be to have 3 frames -- a large frame on the top for output (including prompt and commands running), a small frame near the bottom for standard input, and an one-line frame at the bottom for command line input. That would possibly even allow running another command to provide input while the previous command is still waiting for standard input. From http://jamesjava.blogspot.com/2007/09/terminal-window-with-3-frames.html A: Hotwire could be a good candidate, but it's not doing that out of the box, AFAIK A: For now it appears that there is no such program. A: My program gush (Graphical User SHell) does part of this. It uses different colours for commands and program stdin/stdout/stderr. Note that the traditional separation of shell and terminal makes this impossible because the interface between them models an old serial terminal connection and therefore only has a single input and single output channel. I get around this problem by combining shell and terminal into one program. It would be nice to also indicate when a program is waiting for input, but I don't think there's any way to detect this, unless you traced the system calls of the child program to detect when it tries to read stdin. For interactive programs, you can guess that if the last output did not end with newline it's probably prompting for input, but this would not work for non-interactive programs, eg. sed.
{ "language": "en", "url": "https://stackoverflow.com/questions/64768", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Batch insert using JPA/Toplink I have a web application that receives messages through an HTTP interface, e.g.: http://server/application?source=123&destination=234&text=hello This request contains the ID of the sender, the ID of the recipient and the text of the message. This message should be processed like: * *finding the matching User object for both the source and the destination from the database *creating a tree of objects: a Message that contains a field for the message text and two User objects for the source and the destination *persisting this tree to a database. The tree will be loaded by other applications that I can't touch. I use Oracle as the backing database and JPA with Toplink for the database handling tasks. If possible, I'd stay with these. Without much optimization I can achieve ~30 requests/sec throughput in my environment. That's not much, I'd require ~300 requests/sec. So I measured where the performance bottleneck is and found that the calls to em.persist() takes most of the time. If I simply comment out that line, the throughput go well over 1000 requests/sec. I tried to write a small test application that used simple JDBC calls to persist 1 million messages to the same database. I used batching, meaning I did 100 inserts then a commit, and repeated until all the records was in the database. I measured ~500 requests/sec throughput in this scenario, that would meet my needs. It is clear that I need to optimize insert performance here. However as I mentioned earlier I would like to keep using JPA and Toplink for this, not pure JDBC. Do you know a way to create batch inserts with JPA and Toplink? Can you recommend any other technique for improving JPA persist performance? ADDITIONAL INFO: "requests/sec" means here: total number of requests / total time from beginning of test to last record written to database. I tried to make the calls to em.persist() asynchronous by creating an in-memory queue between the servlet stuff and the persister. It helped the performance greatly. However the queue did grow really fast and as the application will receive ~200 requests/second continuously, It is not an acceptable solution for me. In this decoupled approach I collected requests for 100 msec and called em.persist() on all collected items before commiting the transaction. The EntityManagerFactory is cached between each transaction. A: You should decouple from the JPA interface and use the bare TopLink API. You can probably chuck the objects you're persisting into a UnitOfWork and commit the UnitOfWork on your schedule (sync or async). Note that one of the costs of em.persist() is the implicit clone that happens of the whole object graph. TopLink will work rather better if you uow.registerObject() your two user objects yourself, saving itself the identity tests it has to otherwise do. So you'll end up with: uow=sess.acquireUnitOfWork(); for (job in batch) { thingyCl=uow.registerObject(new Thingy()); user1Cl=uow.registerObject(user1); user2Cl=uow.registerObject(user2); thingyCl.setUsers(user1Cl,user2Cl); } uow.commit(); This is very old school TopLink btw ;) Note that the batch will help a lot, because batch writing and more especially batch writing with parameter binding will kick in which for this simple example will probably have a very large impact on your performance. Other things to look for: your sequencing size. A lot of the time spent writing objects in TopLink is actually spent reading sequencing information from the database, especially with the small defaults (I would probably have several hundred or even more as my sequence size). A: What is your measure of "requests/sec"? In other words, what happens for the 31st request? What resource is being blocked? If it is the front-end/servlet/web portion, can you run em.persist() in another thread and return immediately? Also, are you creating transactions each time? Are you creating EntityManagerFactory objects with each request?
{ "language": "en", "url": "https://stackoverflow.com/questions/64781", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How do you append an int to a string in C++? int i = 4; string text = "Player "; cout << (text + i); I'd like it to print Player 4. The above is obviously wrong but it shows what I'm trying to do here. Is there an easy way to do this or do I have to start adding new includes? A: For the record, you can also use a std::stringstream if you want to create the string before it's actually output. A: cout << text << " " << i << endl; A: Your example seems to indicate that you would like to display the a string followed by an integer, in which case: string text = "Player: "; int i = 4; cout << text << i << endl; would work fine. But, if you're going to be storing the string places or passing it around, and doing this frequently, you may benefit from overloading the addition operator. I demonstrate this below: #include <sstream> #include <iostream> using namespace std; std::string operator+(std::string const &a, int b) { std::ostringstream oss; oss << a << b; return oss.str(); } int main() { int i = 4; string text = "Player: "; cout << (text + i) << endl; } In fact, you can use templates to make this approach more powerful: template <class T> std::string operator+(std::string const &a, const T &b){ std::ostringstream oss; oss << a << b; return oss.str(); } Now, as long as object b has a defined stream output, you can append it to your string (or, at least, a copy thereof). A: With C++11, you can write: #include <string> // to use std::string, std::to_string() and "+" operator acting on strings int i = 4; std::string text = "Player "; text += std::to_string(i); A: Another possibility is Boost.Format: #include <boost/format.hpp> #include <iostream> #include <string> int main() { int i = 4; std::string text = "Player"; std::cout << boost::format("%1% %2%\n") % text % i; } A: Well, if you use cout you can just write the integer directly to it, as in std::cout << text << i; The C++ way of converting all kinds of objects to strings is through string streams. If you don't have one handy, just create one. #include <sstream> std::ostringstream oss; oss << text << i; std::cout << oss.str(); Alternatively, you can just convert the integer and append it to the string. oss << i; text += oss.str(); Finally, the Boost libraries provide boost::lexical_cast, which wraps around the stringstream conversion with a syntax like the built-in type casts. #include <boost/lexical_cast.hpp> text += boost::lexical_cast<std::string>(i); This also works the other way around, i.e. to parse strings. A: For the record, you could also use Qt's QString class: #include <QtCore/QString> int i = 4; QString qs = QString("Player %1").arg(i); std::cout << qs.toLocal8bit().constData(); // prints "Player 4" A: Here a small working conversion/appending example, with some code I needed before. #include <string> #include <sstream> #include <iostream> using namespace std; int main(){ string str; int i = 321; std::stringstream ss; ss << 123; str = "/dev/video"; cout << str << endl; cout << str << 456 << endl; cout << str << i << endl; str += ss.str(); cout << str << endl; } the output will be: /dev/video /dev/video456 /dev/video321 /dev/video123 Note that in the last two lines you save the modified string before it's actually printed out, and you could use it later if needed. A: These work for general strings (in case you do not want to output to file/console, but store for later use or something). boost.lexical_cast MyStr += boost::lexical_cast<std::string>(MyInt); String streams //sstream.h std::stringstream Stream; Stream.str(MyStr); Stream << MyInt; MyStr = Stream.str(); // If you're using a stream (for example, cout), rather than std::string someStream << MyInt; A: printf("Player %d", i); (Downvote my answer all you like; I still hate the C++ I/O operators.) :-P A: cout << text << i; A: One method here is directly printing the output if its required in your problem. cout << text << i; Else, one of the safest method is to use sprintf(count, "%d", i); And then copy it to your "text" string . for(k = 0; *(count + k); k++) { text += count[k]; } Thus, you have your required output string For more info on sprintf, follow: http://www.cplusplus.com/reference/cstdio/sprintf A: cout << "Player" << i ; A: cout << text << i; The << operator for ostream returns a reference to the ostream, so you can just keep chaining the << operations. That is, the above is basically the same as: cout << text; cout << i; A: cout << text << " " << i << endl; A: The easiest way I could figure this out is the following.. It will work as a single string and string array. I am considering a string array, as it is complicated (little bit same will be followed with string). I create a array of names and append some integer and char with it to show how easy it is to append some int and chars to string, hope it helps. length is just to measure the size of array. If you are familiar with programming then size_t is a unsigned int #include<iostream> #include<string> using namespace std; int main() { string names[] = { "amz","Waq","Mon","Sam","Has","Shak","GBy" }; //simple array int length = sizeof(names) / sizeof(names[0]); //give you size of array int id; string append[7]; //as length is 7 just for sake of storing and printing output for (size_t i = 0; i < length; i++) { id = rand() % 20000 + 2; append[i] = names[i] + to_string(id); } for (size_t i = 0; i < length; i++) { cout << append[i] << endl; } } A: If using Windows/MFC, and need the string for more than immediate output try: int i = 4; CString strOutput; strOutput.Format("Player %d", i); A: You can use the following int i = 4; string text = "Player "; text+=(i+'0'); cout << (text); A: There are a few options, and which one you want depends on the context. The simplest way is std::cout << text << i; or if you want this on a single line std::cout << text << i << endl; If you are writing a single threaded program and if you aren't calling this code a lot (where "a lot" is thousands of times per second) then you are done. If you are writing a multi threaded program and more than one thread is writing to cout, then this simple code can get you into trouble. Let's assume that the library that came with your compiler made cout thread safe enough than any single call to it won't be interrupted. Now let's say that one thread is using this code to write "Player 1" and another is writing "Player 2". If you are lucky you will get the following: Player 1 Player 2 If you are unlucky you might get something like the following Player Player 2 1 The problem is that std::cout << text << i << endl; turns into 3 function calls. The code is equivalent to the following: std::cout << text; std::cout << i; std::cout << endl; If instead you used the C-style printf, and again your compiler provided a runtime library with reasonable thread safety (each function call is atomic) then the following code would work better: printf("Player %d\n", i); Being able to do something in a single function call lets the io library provide synchronization under the covers, and now your whole line of text will be atomically written. For simple programs, std::cout is great. Throw in multithreading or other complications and the less stylish printf starts to look more attractive. A: You also try concatenate player's number with std::string::push_back : Example with your code: int i = 4; string text = "Player "; text.push_back(i + '0'); cout << text; You will see in console: Player 4
{ "language": "en", "url": "https://stackoverflow.com/questions/64782", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "204" }
Q: Error handling in Bash What is your favorite method to handle errors in Bash? The best example of handling errors I have found on the web was written by William Shotts, Jr at http://www.linuxcommand.org. He suggests using the following function for error handling in Bash: #!/bin/bash # A slicker error handling routine # I put a variable in my scripts named PROGNAME which # holds the name of the program being run. You can get this # value from the first item on the command line ($0). # Reference: This was copied from <http://www.linuxcommand.org/wss0150.php> PROGNAME=$(basename $0) function error_exit { # ---------------------------------------------------------------- # Function for exit due to fatal program error # Accepts 1 argument: # string containing descriptive error message # ---------------------------------------------------------------- echo "${PROGNAME}: ${1:-"Unknown Error"}" 1>&2 exit 1 } # Example call of the error_exit function. Note the inclusion # of the LINENO environment variable. It contains the current # line number. echo "Example of error with line number and message" error_exit "$LINENO: An error has occurred." Do you have a better error handling routine that you use in Bash scripts? A: Reading all the answers on this page inspired me a lot. So, here's my hint: file content: lib.trap.sh lib_name='trap' lib_version=20121026 stderr_log="/dev/shm/stderr.log" # # TO BE SOURCED ONLY ONCE: # ###~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~## if test "${g_libs[$lib_name]+_}"; then return 0 else if test ${#g_libs[@]} == 0; then declare -A g_libs fi g_libs[$lib_name]=$lib_version fi # # MAIN CODE: # ###~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~## set -o pipefail # trace ERR through pipes set -o errtrace # trace ERR through 'time command' and other functions set -o nounset ## set -u : exit the script if you try to use an uninitialised variable set -o errexit ## set -e : exit the script if any statement returns a non-true return value exec 2>"$stderr_log" ###~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~## # # FUNCTION: EXIT_HANDLER # ###~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~## function exit_handler () { local error_code="$?" test $error_code == 0 && return; # # LOCAL VARIABLES: # ------------------------------------------------------------------ # local i=0 local regex='' local mem='' local error_file='' local error_lineno='' local error_message='unknown' local lineno='' # # PRINT THE HEADER: # ------------------------------------------------------------------ # # Color the output if it's an interactive terminal test -t 1 && tput bold; tput setf 4 ## red bold echo -e "\n(!) EXIT HANDLER:\n" # # GETTING LAST ERROR OCCURRED: # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # # # Read last file from the error log # ------------------------------------------------------------------ # if test -f "$stderr_log" then stderr=$( tail -n 1 "$stderr_log" ) rm "$stderr_log" fi # # Managing the line to extract information: # ------------------------------------------------------------------ # if test -n "$stderr" then # Exploding stderr on : mem="$IFS" local shrunk_stderr=$( echo "$stderr" | sed 's/\: /\:/g' ) IFS=':' local stderr_parts=( $shrunk_stderr ) IFS="$mem" # Storing information on the error error_file="${stderr_parts[0]}" error_lineno="${stderr_parts[1]}" error_message="" for (( i = 3; i <= ${#stderr_parts[@]}; i++ )) do error_message="$error_message "${stderr_parts[$i-1]}": " done # Removing last ':' (colon character) error_message="${error_message%:*}" # Trim error_message="$( echo "$error_message" | sed -e 's/^[ \t]*//' | sed -e 's/[ \t]*$//' )" fi # # GETTING BACKTRACE: # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # _backtrace=$( backtrace 2 ) # # MANAGING THE OUTPUT: # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # local lineno="" regex='^([a-z]{1,}) ([0-9]{1,})$' if [[ $error_lineno =~ $regex ]] # The error line was found on the log # (e.g. type 'ff' without quotes wherever) # -------------------------------------------------------------- then local row="${BASH_REMATCH[1]}" lineno="${BASH_REMATCH[2]}" echo -e "FILE:\t\t${error_file}" echo -e "${row^^}:\t\t${lineno}\n" echo -e "ERROR CODE:\t${error_code}" test -t 1 && tput setf 6 ## white yellow echo -e "ERROR MESSAGE:\n$error_message" else regex="^${error_file}\$|^${error_file}\s+|\s+${error_file}\s+|\s+${error_file}\$" if [[ "$_backtrace" =~ $regex ]] # The file was found on the log but not the error line # (could not reproduce this case so far) # ------------------------------------------------------ then echo -e "FILE:\t\t$error_file" echo -e "ROW:\t\tunknown\n" echo -e "ERROR CODE:\t${error_code}" test -t 1 && tput setf 6 ## white yellow echo -e "ERROR MESSAGE:\n${stderr}" # Neither the error line nor the error file was found on the log # (e.g. type 'cp ffd fdf' without quotes wherever) # ------------------------------------------------------ else # # The error file is the first on backtrace list: # Exploding backtrace on newlines mem=$IFS IFS=' ' # # Substring: I keep only the carriage return # (others needed only for tabbing purpose) IFS=${IFS:0:1} local lines=( $_backtrace ) IFS=$mem error_file="" if test -n "${lines[1]}" then array=( ${lines[1]} ) for (( i=2; i<${#array[@]}; i++ )) do error_file="$error_file ${array[$i]}" done # Trim error_file="$( echo "$error_file" | sed -e 's/^[ \t]*//' | sed -e 's/[ \t]*$//' )" fi echo -e "FILE:\t\t$error_file" echo -e "ROW:\t\tunknown\n" echo -e "ERROR CODE:\t${error_code}" test -t 1 && tput setf 6 ## white yellow if test -n "${stderr}" then echo -e "ERROR MESSAGE:\n${stderr}" else echo -e "ERROR MESSAGE:\n${error_message}" fi fi fi # # PRINTING THE BACKTRACE: # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # test -t 1 && tput setf 7 ## white bold echo -e "\n$_backtrace\n" # # EXITING: # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # test -t 1 && tput setf 4 ## red bold echo "Exiting!" test -t 1 && tput sgr0 # Reset terminal exit "$error_code" } trap exit_handler EXIT # ! ! ! TRAP EXIT ! ! ! trap exit ERR # ! ! ! TRAP ERR ! ! ! ###~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~## # # FUNCTION: BACKTRACE # ###~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~## function backtrace { local _start_from_=0 local params=( "$@" ) if (( "${#params[@]}" >= "1" )) then _start_from_="$1" fi local i=0 local first=false while caller $i > /dev/null do if test -n "$_start_from_" && (( "$i" + 1 >= "$_start_from_" )) then if test "$first" == false then echo "BACKTRACE IS:" first=true fi caller $i fi let "i=i+1" done } return 0 Example of usage: file content: trap-test.sh #!/bin/bash source 'lib.trap.sh' echo "doing something wrong now .." echo "$foo" exit 0 Running: bash trap-test.sh Output: doing something wrong now .. (!) EXIT HANDLER: FILE: trap-test.sh LINE: 6 ERROR CODE: 1 ERROR MESSAGE: foo: unassigned variable BACKTRACE IS: 1 main trap-test.sh Exiting! As you can see from the screenshot below, the output is colored and the error message comes in the used language. A: Another consideration is the exit code to return. Just "1" is pretty standard, although there are a handful of reserved exit codes that bash itself uses, and that same page argues that user-defined codes should be in the range 64-113 to conform to C/C++ standards. You might also consider the bit vector approach that mount uses for its exit codes: 0 success 1 incorrect invocation or permissions 2 system error (out of memory, cannot fork, no more loop devices) 4 internal mount bug or missing nfs support in mount 8 user interrupt 16 problems writing or locking /etc/mtab 32 mount failure 64 some mount succeeded OR-ing the codes together allows your script to signal multiple simultaneous errors. A: I use the following trap code, it also allows errors to be traced through pipes and 'time' commands #!/bin/bash set -o pipefail # trace ERR through pipes set -o errtrace # trace ERR through 'time command' and other functions function error() { JOB="$0" # job name LASTLINE="$1" # line of error occurrence LASTERR="$2" # error code echo "ERROR in ${JOB} : line ${LASTLINE} with exit code ${LASTERR}" exit 1 } trap 'error ${LINENO} ${?}' ERR A: I've used die() { echo $1 kill $$ } before; i think because 'exit' was failing for me for some reason. The above defaults seem like a good idea, though. A: This has served me well for a while now. It prints error or warning messages in red, one line per parameter, and allows an optional exit code. # Custom errors EX_UNKNOWN=1 warning() { # Output warning messages # Color the output red if it's an interactive terminal # @param $1...: Messages test -t 1 && tput setf 4 printf '%s\n' "$@" >&2 test -t 1 && tput sgr0 # Reset terminal true } error() { # Output error messages with optional exit code # @param $1...: Messages # @param $N: Exit code (optional) messages=( "$@" ) # If the last parameter is a number, it's not part of the messages last_parameter="${messages[@]: -1}" if [[ "$last_parameter" =~ ^[0-9]*$ ]] then exit_code=$last_parameter unset messages[$((${#messages[@]} - 1))] fi warning "${messages[@]}" exit ${exit_code:-$EX_UNKNOWN} } A: Not sure if this will be helpful to you, but I modified some of the suggested functions here in order to include the check for the error (exit code from prior command) within it. On each "check" I also pass as a parameter the "message" of what the error is for logging purposes. #!/bin/bash error_exit() { if [ "$?" != "0" ]; then log.sh "$1" exit 1 fi } Now to call it within the same script (or in another one if I use export -f error_exit) I simply write the name of the function and pass a message as parameter, like this: #!/bin/bash cd /home/myuser/afolder error_exit "Unable to switch to folder" rm * error_exit "Unable to delete all files" Using this I was able to create a really robust bash file for some automated process and it will stop in case of errors and notify me (log.sh will do that) A: An equivalent alternative to "set -e" is set -o errexit It makes the meaning of the flag somewhat clearer than just "-e". Random addition: to temporarily disable the flag, and return to the default (of continuing execution regardless of exit codes), just use set +e echo "commands run here returning non-zero exit codes will not cause the entire script to fail" echo "false returns 1 as an exit code" false set -e This precludes proper error handling mentioned in other responses, but is quick & effective (just like bash). A: Inspired by the ideas presented here, I have developed a readable and convenient way to handle errors in bash scripts in my bash boilerplate project. By simply sourcing the library, you get the following out of the box (i.e. it will halt execution on any error, as if using set -e thanks to a trap on ERR and some bash-fu): There are some extra features that help handle errors, such as try and catch, or the throw keyword, that allows you to break execution at a point to see the backtrace. Plus, if the terminal supports it, it spits out powerline emojis, colors parts of the output for great readability, and underlines the method that caused the exception in the context of the line of code. The downside is - it's not portable - the code works in bash, probably >= 4 only (but I'd imagine it could be ported with some effort to bash 3). The code is separated into multiple files for better handling, but I was inspired by the backtrace idea from the answer above by Luca Borrione. To read more or take a look at the source, see GitHub: https://github.com/niieani/bash-oo-framework#error-handling-with-exceptions-and-throw A: This trick is useful for missing commands or functions. The name of the missing function (or executable) will be passed in $_ function handle_error { status=$? last_call=$1 # 127 is 'command not found' (( status != 127 )) && return echo "you tried to call $last_call" return } # Trap errors. trap 'handle_error "$_"' ERR A: This function has been serving me rather well recently: action () { # Test if the first parameter is non-zero # and return straight away if so if test $1 -ne 0 then return $1 fi # Discard the control parameter # and execute the rest shift 1 "$@" local status=$? # Test the exit status of the command run # and display an error message on failure if test ${status} -ne 0 then echo Command \""$@"\" failed >&2 fi return ${status} } You call it by appending 0 or the last return value to the name of the command to run, so you can chain commands without having to check for error values. With this, this statement block: command1 param1 param2 param3... command2 param1 param2 param3... command3 param1 param2 param3... command4 param1 param2 param3... command5 param1 param2 param3... command6 param1 param2 param3... Becomes this: action 0 command1 param1 param2 param3... action $? command2 param1 param2 param3... action $? command3 param1 param2 param3... action $? command4 param1 param2 param3... action $? command5 param1 param2 param3... action $? command6 param1 param2 param3... <<<Error-handling code here>>> If any of the commands fail, the error code is simply passed to the end of the block. I find it useful when you don't want subsequent commands to execute if an earlier one failed, but you also don't want the script to exit straight away (for example, inside a loop). A: Sometimes set -e , trap ERR ,set -o ,set -o pipefail and set -o errtrace not work properly because they attempt to add automatic error detection to the shell. This does not work well in practice. In my opinion, instead of using set -e and other stuffs, you should write your own error checking code. If you wise to use set -e, be aware of potential gotchas. To avoid Error while running the code you can use exec 1>/dev/null or exec 2>/dev/null /dev/null in Linux is a null device file. This will discard anything written to it and will return EOF on reading. you can use this at end of the command For try/catch you can use && or || to achieve Similar behaviour use can use && like this { # try command && # your command } || { # catch exception } or you can use if else : if [[ Condition ]]; then # if true else # if false fi $? show output of the last command ,it return 1 or 0 A: Use a trap! tempfiles=( ) cleanup() { rm -f "${tempfiles[@]}" } trap cleanup 0 error() { local parent_lineno="$1" local message="$2" local code="${3:-1}" if [[ -n "$message" ]] ; then echo "Error on or near line ${parent_lineno}: ${message}; exiting with status ${code}" else echo "Error on or near line ${parent_lineno}; exiting with status ${code}" fi exit "${code}" } trap 'error ${LINENO}' ERR ...then, whenever you create a temporary file: temp_foo="$(mktemp -t foobar.XXXXXX)" tempfiles+=( "$temp_foo" ) and $temp_foo will be deleted on exit, and the current line number will be printed. (set -e will likewise give you exit-on-error behavior, though it comes with serious caveats and weakens code's predictability and portability). You can either let the trap call error for you (in which case it uses the default exit code of 1 and no message) or call it yourself and provide explicit values; for instance: error ${LINENO} "the foobar failed" 2 will exit with status 2, and give an explicit message. Alternatively shopt -s extdebug and give the first lines of the trap a little modification to trap all non-zero exit codes across the board (mind set -e non-error non-zero exit codes): error() { local last_exit_status="$?" local parent_lineno="$1" local message="${2:-(no message ($last_exit_status))}" local code="${3:-$last_exit_status}" # ... continue as above } trap 'error ${LINENO}' ERR shopt -s extdebug This then is also "compatible" with set -eu. A: That's a fine solution. I just wanted to add set -e as a rudimentary error mechanism. It will immediately stop your script if a simple command fails. I think this should have been the default behavior: since such errors almost always signify something unexpected, it is not really 'sane' to keep executing the following commands. A: I prefer something really easy to call. So I use something that looks a little complicated, but is easy to use. I usually just copy-and-paste the code below into my scripts. An explanation follows the code. #This function is used to cleanly exit any script. It does this displaying a # given error message, and exiting with an error code. function error_exit { echo echo "$@" exit 1 } #Trap the killer signals so that we can exit with a good message. trap "error_exit 'Received signal SIGHUP'" SIGHUP trap "error_exit 'Received signal SIGINT'" SIGINT trap "error_exit 'Received signal SIGTERM'" SIGTERM #Alias the function so that it will print a message with the following format: #prog-name(@line#): message #We have to explicitly allow aliases, we do this because they make calling the #function much easier (see example). shopt -s expand_aliases alias die='error_exit "Error ${0}(@`echo $(( $LINENO - 1 ))`):"' I usually put a call to the cleanup function in side the error_exit function, but this varies from script to script so I left it out. The traps catch the common terminating signals and make sure everything gets cleaned up. The alias is what does the real magic. I like to check everything for failure. So in general I call programs in an "if !" type statement. By subtracting 1 from the line number the alias will tell me where the failure occurred. It is also dead simple to call, and pretty much idiot proof. Below is an example (just replace /bin/false with whatever you are going to call). #This is an example useage, it will print out #Error prog-name (@1): Who knew false is false. if ! /bin/false ; then die "Who knew false is false." fi A: Using trap is not always an option. For example, if you're writing some kind of re-usable function that needs error handling and that can be called from any script (after sourcing the file with helper functions), that function cannot assume anything about exit time of the outer script, which makes using traps very difficult. Another disadvantage of using traps is bad composability, as you risk overwriting previous trap that might be set earlier up in the caller chain. There is a little trick that can be used to do proper error handling without traps. As you may already know from other answers, set -e doesn't work inside commands if you use || operator after them, even if you run them in a subshell; e.g., this wouldn't work: #!/bin/sh # prints: # # --> outer # --> inner # ./so_1.sh: line 16: some_failed_command: command not found # <-- inner # <-- outer set -e outer() { echo '--> outer' (inner) || { exit_code=$? echo '--> cleanup' return $exit_code } echo '<-- outer' } inner() { set -e echo '--> inner' some_failed_command echo '<-- inner' } outer But || operator is needed to prevent returning from the outer function before cleanup. The trick is to run the inner command in background, and then immediately wait for it. The wait builtin will return the exit code of the inner command, and now you're using || after wait, not the inner function, so set -e works properly inside the latter: #!/bin/sh # prints: # # --> outer # --> inner # ./so_2.sh: line 27: some_failed_command: command not found # --> cleanup set -e outer() { echo '--> outer' inner & wait $! || { exit_code=$? echo '--> cleanup' return $exit_code } echo '<-- outer' } inner() { set -e echo '--> inner' some_failed_command echo '<-- inner' } outer Here is the generic function that builds upon this idea. It should work in all POSIX-compatible shells if you remove local keywords, i.e. replace all local x=y with just x=y: # [CLEANUP=cleanup_cmd] run cmd [args...] # # `cmd` and `args...` A command to run and its arguments. # # `cleanup_cmd` A command that is called after cmd has exited, # and gets passed the same arguments as cmd. Additionally, the # following environment variables are available to that command: # # - `RUN_CMD` contains the `cmd` that was passed to `run`; # - `RUN_EXIT_CODE` contains the exit code of the command. # # If `cleanup_cmd` is set, `run` will return the exit code of that # command. Otherwise, it will return the exit code of `cmd`. # run() { local cmd="$1"; shift local exit_code=0 local e_was_set=1; if ! is_shell_attribute_set e; then set -e e_was_set=0 fi "$cmd" "$@" & wait $! || { exit_code=$? } if [ "$e_was_set" = 0 ] && is_shell_attribute_set e; then set +e fi if [ -n "$CLEANUP" ]; then RUN_CMD="$cmd" RUN_EXIT_CODE="$exit_code" "$CLEANUP" "$@" return $? fi return $exit_code } is_shell_attribute_set() { # attribute, like "x" case "$-" in *"$1"*) return 0 ;; *) return 1 ;; esac } Example of usage: #!/bin/sh set -e # Source the file with the definition of `run` (previous code snippet). # Alternatively, you may paste that code directly here and comment the next line. . ./utils.sh main() { echo "--> main: $@" CLEANUP=cleanup run inner "$@" echo "<-- main" } inner() { echo "--> inner: $@" sleep 0.5; if [ "$1" = 'fail' ]; then oh_my_god_look_at_this fi echo "<-- inner" } cleanup() { echo "--> cleanup: $@" echo " RUN_CMD = '$RUN_CMD'" echo " RUN_EXIT_CODE = $RUN_EXIT_CODE" sleep 0.3 echo '<-- cleanup' return $RUN_EXIT_CODE } main "$@" Running the example: $ ./so_3 fail; echo "exit code: $?" --> main: fail --> inner: fail ./so_3: line 15: oh_my_god_look_at_this: command not found --> cleanup: fail RUN_CMD = 'inner' RUN_EXIT_CODE = 127 <-- cleanup exit code: 127 $ ./so_3 pass; echo "exit code: $?" --> main: pass --> inner: pass <-- inner --> cleanup: pass RUN_CMD = 'inner' RUN_EXIT_CODE = 0 <-- cleanup <-- main exit code: 0 The only thing that you need to be aware of when using this method is that all modifications of Shell variables done from the command you pass to run will not propagate to the calling function, because the command runs in a subshell.
{ "language": "en", "url": "https://stackoverflow.com/questions/64786", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "287" }
Q: Why aren't Xcode breakpoints functioning? I have breakpoints set but Xcode appears to ignore them. A: See this post: Breakpoints not working in Xcode?. You might be pushing "Run" instead of "Debug" in which case your program is not running with the help of gdb, in which case you cannot expect breakpoints to work! A: In Xcode 7, what worked for me was: * *Make sure that the Target > Scheme > Run - is in Debug mode (was Release) *Make sure to check the option "Debug executable": A: Issue * *Background * *Xcode: 13.0 * *code: Objective-C *Issue: added breakpoint, but not work * * (possible) Reason and Solution * *Reason: Xcode bug * *Solution: Product ->Clean Build Folder, then retry debug (multiple time) * * *Reason: disabled Debug * *Solution: enable it: Product->Scheme->Edit Scheme->Run->Info * *Build Configuration set to Debug *choose/select/enable: Debug executable * *Reason: disabled all breakpoint * *Solution: enable it: Debug panel -> click breakpoint icon * * *Reason: debug info be optimized * *Solution: not optimize *click Project -> Build Settings -> Apple Clang - Code Generation -> Optimization Level -> Debug make sure is None[-O0] * * Related XCode's Symbolic breakpoint not work * *Background XCode crash log Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSCFConstantString stringByAppendingString:]: nil argument' add XCode symbolic breakpoint -[__NSCFConstantString stringByAppendingString:]: but breakpoint not working * *Solution change to: -[NSString stringByAppendingString:] related doc: stringByAppendingString: A: Solution for me with XCode 9.4.1 (did not stop at any breakpoint): Under build Target -> Build Settings -> Optimization Level: Switched from "Optimize for speed" -> "No optimization" (now it's slower but works) A: What solved it in my case was quite simple, in Xcode - Product - Clean Build Folder followed by Product - Run (not the Play Xcode button). (Had the issue on Xcode 11 -beta 4 after switching to unit testing with Xcode play button long press) A: This had me in Xcode 9 for half a frustrating day. It ended up been a simple debug setting. Go Debug > Debug Workflow and make sure 'Always Show Disassembly' is turned off. Simple as that. :( A: For Xcode 4: go Product -> Debug -> Activate Breakpoints This is applicable for all Xcode version. Shortcut key is: command key + Y. Press this key combination to activate/deactivate breakpoints. A: Came to this page with the same problem (C code in Xcode 6 not stopping at breakpoints) and none of the solutions above worked (the project was practically out of the box, settings-wise, so little chance for any of the debugger settings to be set to the wrong value)... After wasting quite some time reducing the problem, I finally figured out the culprit (for my code): Xcode (/LLVM) does not like Bison-style #line preprocessor commands. Removing them fixed the problem (debugger stopped at my breakpoints). A: Go to the Xcode Debugging preferences. Make sure that "Load Symbols lazily" is NOT selected. A: I have a lot of problems with breakpoints in Xcode (2.4.1). I use a project that just contains other projects (like a Solution in Visual Studio). I find sometimes that breakpoints don't work at all unless there is at least one breakpoint set in the starting project (i.e. the one containing the entry point for my code). If the only breakpoints are in "lower level" projects, they just get ignored. It also seems as if Xcode only handles breakpoint operations correctly if you act on the breakpoint when you're in the project that contains the source line the breakpoint's on. If I try deleting or disabling breakpoints via another project, the action sometimes doesn't take effect, even though the debugger indicates that it has. So I will find myself breaking on disabled breakpoints, or on a (now invisible) breakpoint that I removed earlier. A: I've had my breakpoints not work and then done Build / Clean All Targets to get them working again. A: I think the problem could be incompatibility between device versions and Xcode. I have this problem when attempting to debug on my iPhone 4S running iOS 5.0.1. I am still using Xcode 3.2.5. I got the symbols from the handset by selecting "use this device for development" in the Organiser window. This phone refuses to breakpoint however. My old 3GS will breakpoint, same Xcode project, same settings... just different device and it's running iOS 4.0. I guess this is an Xcode bug in 3.2.5, since I have the symbols. Having tried all the solutions posted here so far, I have decided the solution to my problem is to go ahead and upgrade to XCode 4. Perhaps you cannot debug effectively unless your base SDK is at least as high as the system on which to debug. Maybe that's obvious - can anyone confirm? Edit: I will update when I can confirm this is true. A: Deleting my Build folder solved the problem for me. A: For this, and also for Xcode 6 and above make sure that the breakpoint state button is activated (the blue arrow-like button): A: If all else fails, instead of a breakpoint, you can call the following function: void BreakPoint(void) { int i=1; #if !__OPTIMIZE__ printf("Code is waiting; hit pause to see.\n"); while(i); #endif } To resume, manually set i to zero, then hit the resume button. A: It has happened the same thing to me in XCode 6.3.1. I managed to fix it by: * *Going to View->Navigators->Show Debug Navigators *Right click in the project root -> Move Breakpoints (If selected the User option) *(I also Selected the option share breakpoints, even though I'm not sure if that necessary). After doing that change I set the Move breakpoints options back to the project, and unselecting the Share breakpoints option, and still works. I don't exactly know why but this get my breakpoints back. A: I was just having this same issue (again). After triple-checking "Load symbols lazily" and stripping and debug info generation flags, I did the following: * *quit Xcode *open a terminal window and cd to the project directory *cd into the .xcodeproj directory *delete everything except the .pbxproj file (I had frank.mode1v3 and frank.pbxuser) You can accomplish the same task in finder by right/option-clicking on the .xcodeproj bundle and picking "Show Package Contents". When I restarted Xcode, all of my windows had reset to default positions, etc, but breakpoints worked! A: First of all, I agree 100% with the earlier folks that said turn OFF Load Symbols Lazily. I have two more things to add. (My first suggestion sounds obvious, but the first time someone suggested it to me, my reaction went along these lines: "come on, please, you really think I wouldn't know better...... oh.") * *Make sure you haven't accidentally set "Active Build Configuration" to "Release." *Under "Targets" in the graphical tree display of your project, right click on your Target and do "Get Info." Look for a property named "Generate Debug Symbols" (or similar) and make sure this is CHECKED (aka ON). Also, you might try finding (also in Target >> Get Info) a property called "Debug Information Format" and setting it to "Dwarf with dsym file." There are a number of other properties under Target >> Get Info that might affect you. Look for things like optimizing or compressing code and turn that stuff OFF (I assume you are working in a debug mode, so that this is not bad advice). Also, look for things like stripping symbols and make sure that is also OFF. For example, "Strip Linked Product" should be set to "No" for the Debug target. A: One of the possible solutions for this could be ....go to Product>Scheme>Edit scheme>..Under Run>info>Executable check "Debug executable". A: For Xcode 4.x: Goto Product>Debug Workflow and uncheck "Show Disassembly When Debugging". For Xcode 5.x Goto Debug>Debug Workflow and uncheck "Show Disassembly When Debugging". A: Another reason Set DeploymentPostprocessing to NO in BuildSettings - details here In short - Activating this setting indicates that binaries should be stripped and file mode, owner, and group information should be set to standard values. [DEPLOYMENT_POSTPROCESSING] A: In Xcode 4 - Product menu > Manage Schemes - Select the scheme thats having debugging problems (if only one choose that) - Click Edit button at bottom - Edit Scheme dialog appears - in left panel click on Run APPNAME.app - on Right hand panel make sure youre on INFO tab - look for drop down DEBUGGER: - someone had set this to None - set to LLDB if this is your preferred debugger - can also change BUILD CONFIGURATION drop down to Debug - but I have other targets set to AdHoc which debug fine once Debugger is set A: I found the problem. Somehow the "Show Disassembly when debugging" was enabled in my XCode which creates that problem. When I disabled it, all my debugger stopped in my source code. You can find it under: Product->Debug Workflow->Show Disassembly when debugging. A: You can Activate / Disactivate Breakpoints in dropdown menu A: I tried all the above things but for me only deactivating the debugging breakpoints once and then activating them worked. A: When setting your break point, right click and you should get several options about how the break point is handled (log vars and continue, pause execution, etc) Also make sure the "Load Symbols lazily" is not selected in the debug preferences. (Applies to Xcode 3.1, not sure about past/future versions) A: I haven't done Xcode in a bit, but I recommend that you disable "Zerolink" and "Load Symbols Lazily"; that will fix most problems. Zerolink is an abomination anyway. A: There appears to be 3 states for the breakpoints in Xcode. If you click on them they'll go through the different settings. Dark blue is enabled, grayed out is disabled and I've seen a pale blue sometimes that required me to click on the breakpoint again to get it to go to the dark blue color. Other than this make sure that you're launching it with the debug command not the run command. You can do that by either hitting option + command + return, or the Go (debug) option from the run menu. A: I believe that a project can also become corrupted in regards to breakpoints. I have a project, for example, that WILL NOT break on any breakpoints that it remembers from the previous session. I first wrote about this here A: Also make sure that the AppStore distribution of the app is not also installed on the device. A: Another thing to check is that if you have an "Entitlements" plist file for your debug mode (possibly because you're doing stuff with the Keychain), make sure that plist file has the "get-task-allow" = YES row. Without it, debugging and logging will be broken. A: I have Xcode 3.2.3 SDK 4.1 Breakpoints will fail at random. I have found if you clean the build and use the touch command under build they work again. A: Here's an obscure one I've run into: if you're working on a shared library (or a plugin), your breakpoints will go yellow on startup, which might cause you to hammer your keyboard in frustration and kill the debug process. Well, don't do that! The symbols won't get loaded until the app loads the library, at which point the breakpoints will become valid. I ran into this problem with a browser plugin... BPs were disabled until I browsed to a page that instantiated my plugin. A: I was facing the same problem when I wanted to debug a web plug-in where the custom executable was Safari 5.1. It was working fine till upgraded my Safari to 5.1 from 4.0.5. Once I installed Safari 4.0.5 again, all breakpoints started working without modifying any Xcode setting. A: If you are using subversion, just revert your project files (only) to the last time you knew the debugger was working. A: Just solved this in XCode 4.2, none of above helped. The thing was (I'm not sure what actually happened, but, maybe this helps someone): my teammate created new build configurations and updated project in SVN. I had old build configuration set up in Run Scheme settings, so the steps for me were: * *Product -> Edit Scheme... *Select "Run %project_name.app%" (or whatever causes problem) *In build configuration combo select that new build configuration from my teammate And that's all, breakpoints are back again. Hope this helps. A: Another reason the breakpoints can turn yellow is if the application binary you are debugging has been modified since it was first run. In my case, I added a folder to the application's Contents/Resources folder after having debugged the program once. On the debug run after adding the folder, the breakpoints turned yellow and were ignored. I modified my procedure: I did a clean, a build, added the folder, then ran, and all was well. Perhaps Xcode (or OS X) creates and remembers its own digital signature of the application (which was not digitally signed) and then, sensing that the application was modified, refuses to try to set breakpoints. By making my mods before the first (debug) run of the application, the digital signature was made with my mods. All this on OS X 10.6.8 using Xcode 3.2.2. A: You can check one setting in target setting Apple LLVM Compiler 4.1 Code Generation Section Generate Debug Symbol = YES A: This happens from time to time with an iOS project at least. To fix it, I had to reboot the iOS device, quit Xcode, and rebuild the project. A: Having both Xcode 5 and 6 GM caused the former to lose breakpoint functionality (Xcode 6 betas were ok). I tried many of the suggested methods but finally gave up and I'm just using Xcode 6 now. A: On Xcode 6.4, I needed to reboot my Mac. (Tried enabling/disabling breakpoints, rebooting iOS device, restarting Xcode, deleting breakpoint files from the workspace package...) A: I've had problems with Xcode losing breakpoints when using the simulator and having the Scheme Launch setting to "wait for executable". Change that to "launch automatically" and breakpoints come back to life. A: I have started to get this issue when updated my xCode into Version 11.0 (11A420a). To solved that I have installed additional simulator version 12.2 and updated my iPhone version into 13.1. Now both on iOs simulator and on my device break points get hit. A: In my case i was overriding the existing app store build with my build.I removed the same and its working now. A: if you using Xcode Version 11.1 (11A1027) make sure you are not using the app store credential(provisioning profiles) , because in this case build will be installed and no log or debugger will work, it took me hell lot of time to figure it out , updated Xcode has chagned . now build getting installed on the device without any warning. A: For those who are facing issue in Swift Package and the breakpoints are not working. the issue is the case sensitivity of path property in of target The path was set to source, Issue fixed once It is set to Source A: In my case breakpoints were turning off themselves because the function in which I put them was private and was not available and never called. So check for access level A: I had the similar issue. I re-installed xcode. that solved my problem A: I have Xcode Version 4.6.3 and Breakpoints were never working in sub-groups of included projects. The project would compile and run fine; it would even attach to the debugger and spit out NSLog output appropriately. The issue was related to my Header Search Paths. I had some of them set 'recursive' instead of the default 'non-recursive'. Changing them all to 'non-recursive' and updating all of the related imports appropriately fixed the problem. A: In my case, I found out that the breakpoints have been accidentally deactivated. You can reactivate it again via Debug->Activate Breakpoints [Cmd+Y]. If you notice grey'ed out breakpoint markers instead of the usual blue marker, this is likely the case. As it turned out you can always toggle breakpoints activation with Cmd+Y keys, you might have hits this combination key not noticing it. This report is based on Xcode 7.2. A: Thing to try : 1 ) restart xcode 2 ) select another simulator -- which was my case 3 ) reboot mac. if none of this works. then look at the project settings. ( which is leeast possible thing. )
{ "language": "en", "url": "https://stackoverflow.com/questions/64790", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "136" }
Q: How do I see the list of open files within Emacs? Or browse a directory within Emacs? Most text editors have a navigation pane that lets you see all the files you currently have open. Or a pane that lets you browse a file directory. How do I do this in Emacs? A: C-x C-b will open the *Buffer List* buffer. In that buffer, you can navigate with the usual keys C-p, C-n, up-arrow, down-arrow, etc. Browsing a directory is as simple as editing a file. Just open the directory instead of the file. On my Linux machine, C-x C-f /tmp ENTER opens a directory while C-x C-f /tmp/myfile ENTER opens a file. A: C-x d accesses the directory editor. C-x C-f will do it as well if you give it a directory instead of a file. There's also ibuffer-mode, which lets you deal with your open buffers in a very similar fashion to Dired: http://www.emacswiki.org/cgi-bin/wiki/IbufferMode It's included with recent versions of Emacs, so you may not have to download it separately: try M-x ibuffer first. A: M-x speedbar (speedbar website) will pop up an emacs frame that lists the contents of the current directory depending on the buffer you're in. The frame is small and stays out of the way so you can always glance at it while you're editing files. It also can filter this display based on file type using the variable speedbar-supported-extension-expressions. To see all the speedbar options, type M-x customize-group RET speedbar RET. A: C-x b TAB will give you an auto complete with all open buffers. Alternatively, click on the Buffers menu item if you are in a windowed version (not sure if there is a terminal equivalent of that). EDIT: Also C-x C-f will let you open a file, and you can use TAB for autocomplete, then TAB again to view files/directories in that current directory (assuming the first tab did not autocomplete something). A: If you are interested in seeing a tree like structure for your directories, sources, methods etc try using emacs code browser http://ecb.sourceforge.net/. A: Try Ctrl-x followed by Ctrl-b (in Emacs terminology C-x C-b) to list buffers. A: M-x shell opens a shell where you can browse directories A: When browsing directories with diredit, consider using a instead of RET to change directory. Otherwise, each new directory is visited in a new buffer, which will clutter up you buffer list pretty quickly. A: If you are just looking for files and not for any other buffers, look a the file-history.el https://github.com/akicho8/file-history A: I just discovered neotree package which displays the tree of all files from a root directory. Visiting the files in the neotree buffer opens them of switches to the buffer if already opened. neotree can be installed either by M-x package-install Ret neotree or from its gitbub repository. A: You could try the sidebar package A: Also, if you want to get rid of the list of open buffers, type C-x 1. A: I often need to find another file in the "current directory", ie. the directory of the file I'm editing. To quickly open this directory in diredit, I use: C-x C-f C-j A: You can also try http://code.google.com/p/emacs-nav/
{ "language": "en", "url": "https://stackoverflow.com/questions/64808", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: Private Accessor class ignores generic constraint These days, i came across a problem with Team System Unit Testing. I found that the automatically created accessor class ignores generic constraints - at least in the following case: Assume you have the following class: namespace MyLibrary { public class MyClass { public Nullable<T> MyMethod<T>(string s) where T : struct { return (T)Enum.Parse(typeof(T), s, true); } } } If you want to test MyMethod, you can create a test project with the following test method: public enum TestEnum { Item1, Item2, Item3 } [TestMethod()] public void MyMethodTest() { MyClass c = new MyClass(); PrivateObject po = new PrivateObject(c); MyClass_Accessor target = new MyClass_Accessor(po); // The following line produces the following error: // Unit Test Adapter threw exception: GenericArguments[0], 'T', on // 'System.Nullable`1[T]' violates the constraint of type parameter 'T'.. TestEnum? e1 = target.MyMethod<TestEnum>("item2"); // The following line works great but does not work for testing private methods. TestEnum? e2 = c.MyMethod<TestEnum>("item2"); } Running the test will fail with the error mentioned in the comment of the snippet above. The problem is the accessor class created by Visual Studio. If you go into it, you will come up to the following code: namespace MyLibrary { [Shadowing("MyLibrary.MyClass")] public class MyClass_Accessor : BaseShadow { protected static PrivateType m_privateType; [Shadowing(".ctor@0")] public MyClass_Accessor(); public MyClass_Accessor(PrivateObject __p1); public static PrivateType ShadowedType { get; } public static MyClass_Accessor AttachShadow(object __p1); [Shadowing("MyMethod@1")] public T? MyMethod(string s); } } As you can see, there is no constraint for the generic type parameter of the MyMethod method. Is that a bug? Is that by design? Who knows how to work around that problem? A: I vote bug. I don't see how this could be by design. A: Here is a similar issue on connect for reference. https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=324473&wa=wsignin1.0 A: I didn't verify everything, but it looks like the call to: TestEnum? e1 = target.MyMethod("item2"); uses type inference to determine the generic type param T. Try calling the method differently in the test if possible: TestEnum? e1 = target.MyMethod<TestEnum>("item2"); That may yield different results. Hope that helps! A: Looks like a bug. The workaround would be to change the method to internal and add [assembly: InternalsVisibleTo("MyLibrary.Test")] to the assembly containing class under test. This would be my preferred way of testing non-public methods as it produces much cleaner looking unit tests. A: Search for unit tests with generics on msdn. This is a known limitation. Vote for a resolution on Microsoft Connect, as it is definately needs resolving.
{ "language": "en", "url": "https://stackoverflow.com/questions/64813", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: how to implement shortcut key combination of CTRL or SHIFT + through javascript? ASP.NET 2.0 web application, how to implement shortcut key combination of CTRL + Letter, preferably through JavaScript, to make web application ergonomically better? How to capture multiple-key keyboard events through JavaScript? A: Your event listener function, gets passed an Event object. That has a lot of useful information on it, including the properties "altKey", "ctrlKey", "shiftKey" and "metaKey". If any of the modifier keys are being held down when that event fires, the corresponding property is set to true. This applies to keyboard as well as mouse events (onclick, etc). Note that if you have a onkeydown event listener, the modifier key itself will fire the event. window.onkeyup = function(e) { if (e.altKey) alert("Alt pressed"); if (e.shiftKey) alert("Shift pressed"); } This tested on Firefox 3, Windows XP. A: Javascript has support for ctrl+alt+shift keys. I assume you can figure out the rest. Link. A: The short answer is that you use Javascript to capture a keydown event and use that event to fire off a function. Relevant articles: * *http://www.openjs.com/scripts/events/keyboard_shortcuts/ *http://udayms.wordpress.com/2006/03/17/ajax-key-disabling-using-javascript/ *http://protocolsofmatrix.blogspot.com/2007/09/javascript-keycode-reference-table-for.html *http://www.quirksmode.org/js/keys.html If you're using the jQuery library, I'd suggest you look at the HotKeys plugin for a cross-browser solution. I know this is not answering the orginal question, but here is my advice: Don't Use Key Combination Shortcuts In A Web Application! Why? Because it might break de the usability, instead of increasing it. While it's generally accepted that "one-key shortcut" are not used in common browsers (Opera remove it as default from its last major version), you cannot figure out what are, nor what will be, the key combination shortcuts used by various browser. Gizmo makes a good point. There's some information about commonly-used accesskey assignments at http://www.clagnut.com/blog/193/. If you do change the accesskeys, here are some articles with good suggestions for how to do it well: * *Accesskeys: Unlocking Hidden Navigation *Using accesskey attribute in HTML forms and links And you may find this page of Firefox's default Keyboard and Mouse Shortcuts useful (Another version of same information). Keyboard shortcuts for Internet Explorer 7 and Internet Explorer 6. Keyboard shortcuts for Opera and Safari. You're more likely to run into problems with JAWS or other screen readers that add more keyboard shortcuts. A: I know this is not answering the orginal question, but here is my advice: Don't Use Key Combination Shortcuts In A Web Application! Why? Because it might break de the usability, instead of increasing it. While it's generally accepted that "one-key shortcut" are not used in common browsers (Opera remove it as default from its last major version), you cannot figure out what are, nor what will be, the key combination shortcuts used by various browser. Moreover, if your visitors use a higly customisable browser, such as Firefox or Opera, There is a high risk that they have either configure their own shortcuts or use additional plug-ins that define some additional ones. Keep in mind that web applications are browser dependend and that you should NEVER assumes that if it works on your favorite-tweak-most-powerfull-browser, it will react the same way on your friend's one.
{ "language": "en", "url": "https://stackoverflow.com/questions/64820", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: How to substring in jsp? Is there a way to substring in JSP files, using struts2 technologies? I mean, struts2 has its own taglib and also uses ognl. How can I get a substring from a stacked value or bean value? A: http://java.sun.com/products/jsp/jstl/1.1/docs/tlddocs/index.html Look for fn:substring and its variants. I've used Struts 1, but not 2. A: Don't. If you need to parse data (substring) in your JSP, then you are probably mixing business logic (how it works) with your presentation logic (how it is displayed)--they should be separate. If you are doing lots of conditionals, calculations, parsing, etc. in your JSPs, then you are creating a lot of (future) pain for yourself. Instead, separate those concerns--make the JSP dead simple, with no logic other than displaying data as is or not at all, plus simple loops where needed. Put all the nontrivial logic into a Java class that pushes the data into the JSP, where you will have the full power of Java available. As much as you can, make the JSPs merely a thin "skin" over your Java-based application. For a detailed discussion, see Terence Parr's white paper at http://www.cs.usfca.edu/~parrt/papers/mvc.templates.pdf. Save yourself a lot of heartache and maintenance. A: fn:substring(YOUR_FIELD, START_INDEX, END_INDEX) for example if you wanted to get the first 3 characters of a string, you could do this: ${fn:substring('scrooge', -1, 3)} here is the XML namespace you can use, it should be the same address for a <% include%> statement xmlns:fn="http://java.sun.com/jsp/jstl/functions" A: Struts2 uses OGNL. That means you can call object methods directly in S2 tags. Like so: <s:property value="str.substring(0, 5)"/> A: Watch out for the functions library in certain situations, especially when using Websphere to deploy! The company I work for deploys to Websphere 6.0 version 11, which does not support the functions library properly (it does not function properly when placed inside a tag body). I remember somewhere that they fixed it in version 13. You can always create your own JSP Tag to do anything, though, so you can do that to get around the problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/64825", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Rails, Restful Authentication & RSpec - How to test new models that require authentication I've created a learning application using Bort, which is a base app that includes Restful Authentication and RSpec. I've got it up and running and added a new object that requires users to be logged in before they can do anything(before_filter :login_required in the controller). [edit: I should also mention that the user has_many of the new class and only the user should be able to see it.] I've created the new model/controller using Rspec's generators which have created a number of default tests. They all pass if there is no before_filter but several fail, as should be expected, once the before_filter is in place. How do I get the generated tests to run as if there is/is not a logged in user? Do I need a whole batch of matching not logged in - redirect tests? I assume it is some sort of mocking or fixture technique but I am new to RSpec and a bit adrift. Good RSpec tutorial links would also be appreciated. A: I have a very similar setup, and below is the code I'm currently using to test this stuff. In each of the describes I put in: it_should_behave_like "login-required object" def attempt_access; do_post; end If all you need is a login, or it_should_behave_like "ownership-required object" def login_as_object_owner; login_as @product.user; end def attempt_access; do_put; end def successful_ownership_access response.should redirect_to(product_url(@product)) end If you need ownership. Obviously, the helper methods change (very little) with each turn, but this does most of the work for you. This is in my spec_helper.rb shared_examples_for "login-required object" do it "should not be able to access this without logging in" do attempt_access response.should_not be_success respond_to do |format| format.html { redirect_to(login_url) } format.xml { response.status_code.should == 401 } end end end shared_examples_for "ownership-required object" do it_should_behave_like "login-required object" it "should not be able to access this without owning it" do attempt_access response.should_not be_success respond_to do |format| format.html { response.should be_redirect } format.xml { response.status_code.should == 401 } end end it "should be able to access this if you own it" do login_as_object_owner attempt_access if respond_to?(:successful_ownership_access) successful_ownership_access else response.should be_success end end end A: When not testing the authentication but testing the controllers that needs the user to be authenticated I usually stub the filter method: before(:each) do controller.stub!(:authenticate).and_return(true) end The above example works where my before_filter is set to the authenticate method: before_filter :authenticate and the authenticate in my app uses HTTP Basic Authentication, but it really can be any other authentication mechanism. private def authenticate authenticate_or_request_with_http_basic do |user,password| user == USER_NAME && password == PASSWORD end end I think it's a pretty straightforward way to test. A: I found a few answers to my own question. Basically, I needed to understand how to mock out the user from restful_authentication so that the autogenerated rspec controller tests could pass even though I had added before_filter: login_required. Here are a few of my just found resources: RSpec: It Should Behave Like rspec, restful_authentication, and login_required using restful_authentication current_user inside controller specs DRYing up your CRUD controller RSpecs A: To mock a user being logged in, I hack into the controller to set @current_user manually: module AuthHelper protected def login_as(model, id_or_attributes = {}) attributes = id_or_attributes.is_a?(Fixnum) ? {:id => id} : id_or_attributes @current_user = stub_model(model, attributes) target = controller rescue template target.instance_variable_set '@current_user', @current_user if block_given? yield target.instance_variable_set '@current_user', nil end return @current_user end def login_as_user(id_or_attributes = {}, &block) login_as(User, id_or_attributes, &block) end end
{ "language": "en", "url": "https://stackoverflow.com/questions/64827", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: Writing C# client to consume a Java web service that returns array of objects I am writing a C# client that calls a web service written in Java (by another person). I have added a web reference to my client and I'm able to call methods in the web service ok. The service was changed to return an array of objects, and the client does not properly parse the returned SOAP message. MyResponse[] MyFunc(string p) class MyResponse { long id; string reason; } When my generated C# proxy calls the web service (using SoapHttpClientProtocol.Invoke), I am expecting a MyResponse[] array with length of 1, ie a single element. What I am getting after the Invoke call is an element with id=0 and reason=null, regardless of what the service actually returns. Using a packet sniffer, I can see that the service is returning what appears to be a legitimate soap message with id and reason set to non-null values. Is there some trick to getting a C# client to call a Java web service that returns someobject[] ? I will work on getting a sanitized demo if necessary. Edit: This is a web reference via "Add Web Reference...". VS 2005, .NET 3.0. A: Thanks to Xian, I have a solution. The wsdl for the service included a line <import namespace="http://mynamespace.company.com"/> The soap that the client sent to the server had the following attribute on all data elements: xmlns="http://mynamespace.company.com" But the xml payload of the response (from the service back to the client) did not have this namespace included. By tinkering with the HTTP response (which I obtained with WireShark), I observed that the .NET proxy class correctly picked up the MyResponse values if I forced the xmlns attribute on every returned data element. Short of changing the service, which I don't control, the workaround is to edit the VS generated proxy class (eg Reference.cs) and look for lines like this: [System.Xml.Serialization.XmlTypeAttribute(Namespace="http://mynamespace.company.com")] public partial class MyResponse { and comment out the XmlType attribute line. This will tell the CLR to look for response elements in the default namespace rather than the one specied in the wsdl. You have to redo this whenever you update the reference, but at least it works. A: It has been a while, but I seem to remember having trouble with the slight differences in how default namespaces were handled between .Net and Java web services. Double check the generated c# proxy class and any namespaces declared within (especially the defaults xmlns=""), against what the Java service is expecting. There will be probably be very subtle differences which you will have to recreate. If this is the case then you will to provide more namespace declarations in the c# attributes. A: From your question, it looks like you had the client working at one point, and then the service was changed to return an array. Make sure you re-generate the proxy so the returned SOAP message is deserialized on the client. It wasn't clear you had done this - just making sure.
{ "language": "en", "url": "https://stackoverflow.com/questions/64833", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Visual Studio 2008: Is it worth the upgrade from 2005? As of the fall of 2008 I'm about to embark on a new development cycle for a major product that has a winforms and an asp.net interface. We use Telerik, DevExpress and Infragistics components in it and all are going to have a release within a month or so which will be the one I target for our spring release of our product. They all support VS2005 and we will continue to target .net 2+ so I can't see any compelling reason so far to upgrade to VS2008. Has anyone found a compelling reason for upgrading to VS2008? A: These are Microsoft's 10 reasons to upgrade (.DOC): * *LINQ support *Same designer elements as Microsoft Expression (Web and Blend) *AJAX and WCF/REST *Better WPF support *Improved MSTEST (also included in Professional edition) *Improved HTML, CSS, and JavaScript editors *Choose from Project settings which version of the framework to target *Improved Office dev tools, including ribbon UI and Click-Once support *Integrated WCF and WWF support *Better performance and stability A: Yes, it's definately worth the upgrade. I would actaully say go straight to VS2008 SP1 as well. There have been a lot of IDE improvements (usability features and speed) and improvements in the web development experience as well including better JS and CSS support. A: If you have a release within a month, I'd suggest not upgrading. Make the upgrade to 2k8 part of the next major release ... no reason you should risk something not working quite the same or some other complication if everything is working as is. A: To add to John's post, there is also built in unit testing, built in refactoring, code analysis, and the web designer for html\javascript is vastly improved. I can't think of any reason why you wouldn't upgrade. A: It's worth it. It's faster, the designer is vastly improved (split view, faster context switching), it has better support for javascript and when you're ready to target 3.5, you'll be ready to go. A: It is worth the upgrade for me for the main reason that I can target different .NET versions (2, 3, 3.5) from the same IDE whereas in the past, one version of Visual Studio supported one version of .NET. The UI seems much more responsive now, but the core set of tools and processes hasn't changed that much. A: The new C# language features are compelling for me: automatic properties, object initializers, collection initializers, extension methods, lambda expressions. For a quick overview from the guy responsible, see: http://weblogs.asp.net/scottgu/archive/2007/03/08/new-c-orcas-language-features-automatic-properties-object-initializers-and-collection-initializers.aspx http://weblogs.asp.net/scottgu/archive/2007/03/13/new-orcas-language-feature-extension-methods.aspx http://weblogs.asp.net/scottgu/archive/2007/04/08/new-orcas-language-feature-lambda-expressions.aspx A: I agree with Mr. Martinez in that I wouldn't port any existing projects up to the 3.5 framework, but the split designer and javascript debugging is worthwhile on its own. A: Upgrade, you will not regret it in the slightest. In particular, Linq is going to make your life so much easier. There there are the extensions for c#. That's barely touching the surface, there is certainly new toys in the area you are developing as well, either web, desktop or server. A: I'd upgrade, but set aside some time for the install process. It took two hours on my moderately fast dev workstation, and I'm still doing updates, patches, hotfixes, two hours after the install finished... (haven't gotten any "real work" done today at all!) A: It is helpful in the particular case you describe. Consider the following: 1) You are at the start of a development cycle. It is always easier to make these types of changes at the start of or between cycles as opposed to in the middle of one. Given this principle, your next convenient time to upgrade (if the schedule is not delayed) would be next Spring. 2) VS2008 allows for the compiler to target any specific .NET runtime version including 2.0 if you need to continue supporting an older framework. Also, as some of the other answers have suggested, go straight to SP1. The service pack upgrade experience was not nearly as big of an ordeal as VS2005 SP1... at least in my experience. A: VS 2008 is not the point. The latest .Net package is the point. You can use Linq and all the other new Features with notepad and the commandline compiler but i guess that is more theoretical. So my statement is yes, .net 3.5 is the recommendation but using it without VS 2008 isn't a good idea.
{ "language": "en", "url": "https://stackoverflow.com/questions/64839", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: What do I need to manage XML files? I believe I need a DTD to define the schema and an XSLT if I want to display it in a browser and have it look "pretty". But I'm not sure what else I would need to have a well-defined XML document that can be queried using XQuery and displayed in a web browser. A: Strictly speaking, you need nothing. XML, even without a schema definition, works. A schema definition (in XSD, RelaxNG or DTD) helps various tools that work with the XML, because they can verify that the structure of the XML conforms to what you want. An XSLT translation to HTML is nice if the XML contains information you'll want to look at with a browser. It's far from necessary, though. To query the XML with XPath or XQuery, you need an XPath or XQuery processor. A: For a XML document to be queryable using XQquery you do not have to define a DTD or XSD. The purpose of DTD or XSD is to define the strict structure of a XML document and to allow validation before usage. Modern browsers interpret XML files very nicely and show a DOM tree. If enhanced formatting of XML for browser display is necessary you have to create a XSLT transformation file and then add a directive to the original XML document pointing to the XSLT file. The browser picks that directive and uses the built-in XSLT processor to obtain the output that is then interpreted by the browser. info.xml <?xml version="1.0" encoding="iso-8859-1"?> <?xml-stylesheet type="text/xsl" href="info.xslt"?> <info> <appName>My App</appName> <version>1.0.129</version> <buildTime>10-09-2008 12:44:03</buildTime> </info> info.xslt <?xml version="1.0" encoding="iso-8859-1"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="/"> <html> <head> <title>Application</title> <style type="text/css"> body { font-family: Lucida Console; } #outer { text-align: left; } #name { font-weight: bold; font-size: 1.2em; } #logo { float: left; padding-right: 20px; padding-bottom: 200px; } </style> </head> <body> <xsl:apply-templates select="info" /> </body> </html> </xsl:template> <xsl:template match="info"> <img id="logo" src="image.png" /> <div id="outer"> <div id="name"> <xsl:value-of select="appName"/> </div> <div id="version"> <xsl:value-of select="version"/> </div> <div id="date"> <xsl:value-of select="buildTime"/> </div> </div> </xsl:template> </xsl:stylesheet>
{ "language": "en", "url": "https://stackoverflow.com/questions/64841", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Write a Servlet that Talks to JMS (ActiveMQ) and OnMessage Update the Site I am building a site that uses a simple AJAX Servlet to talk JMS (ActiveMQ) and when a message arrives from the topic to update the site. I have Javascript that creates an XMLHttpRequest for data. The Servlet processes the Get Request and sends back JSON. However I have no idea how to connect my Servlet into my ActiveMQ Message Broker. It just sends back dummy data right now. I am thinking the Servelt should implement the messagelistener. Then onMessage send data to the JavaScript page. But I'm not sure how to do this. A: The problem with having a servlet implement MessageListener is that servlets are synchronous and MessageListeners are asynchronous. Instead you should create some other object to act as the MessageListener and update some state somewhere (possibly a database or a JMX MBean or a Stateful Session EJB) when messages come in. Then the servlet can query that state to see if there's data to report back to the client, and your web page can periodically ping the servlet to ask for fresh data. A: As James Strachan says - http://activemq.apache.org/ajax.html is an ideal out-of-the-box solution for your problem. If you still want to create such solution manually you can just create JMS connection in your Ajax servlet (connection per request). Consider using Spring JMS template for that reason ( http://static.springsource.org/spring/docs/2.5.x/reference/jms.html ). Then just receive the message in the Servlet doGet/doPost method. Consider low timeout value for receiving in that case. Such solution will work for the Queues and durable Topics. For non-durable Topics consider external message listener. Spring MessageListenerContainer is an excellent tool for that purpose: <bean class="org.springframework.jms.listener.DefaultMessageListenerContainer <property name="connectionFactory" ref="jmsFactory"/> <property name="destination" ref="myTopic" /> <property name="messageListener" ref="lastTenUpdatesCache" /> </bean> Bean lastTenUpdatesCache will be a singleton bean implementing MesssageListener. This bean would be responsible for caching last ten messages (just putting it into a java.util list). It will be injected into your Ajax servlet so in your doGet/doPost method you can ask it about last 10 messages sent to the topic. A: Have you tried reading the answers for this question which links to the ActiveMQ Ajax support. Basically ActiveMQ has native support for Ajax so you can use its JavaScript library to directly subscribe from an ActiveMQ topic. Also see the ActiveMQ web samples which show how to do things like real time chat or real time stock portfolio screens using Ajax with ActiveMQ A: You probably need to get a JMS connection from JNDI, like this: Properties props = new Properties(); props.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.activemq.jndi.ActiveMQInitialContextFactory"); props.setProperty(Context.PROVIDER_URL, "tcp://hostname:61616"); javax.naming.Context ctx = new InitialContext(props); // lookup the connection factory javax.jms.TopicConnectionFactory factory = (javax.jms.TopicConnectionFactory)ctx.lookup("ConnectionFactory"); // create a new TopicConnection for pub/sub messaging javax.jms.TopicConnection conn = factory.getTopicConnection(); // lookup an existing topic javax.jms.Topic mytopic = (javax.jms.Topic)ctx.lookup("MyTopic"); // create a new TopicSession for the client javax.jms.TopicSession session = conn.createTopicSession(false,TopicSession.AUTO_ACKNOWLEDGE); // create a new subscriber to receive messages javax.jms.TopicSubscriber subscriber = session.createSubscriber(mytopic);
{ "language": "en", "url": "https://stackoverflow.com/questions/64843", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Sample code for using IBM's PCOMM in C# o write an as400 screenscraper Has anybody used C# to write a sample screen scraper for IBM as400? A: When using interop.AutOIATypeLibrary and interop.AutPSTypeLibrary for building a class library. It throws error as below Unable to cast COM object of type 'AutPSTypeLibrary.AutPSClass' to interface type 'AutPSTypeLibrary.IAutPS'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{891FC4A1-7DD8-11D0-9112-0004AC3617E1}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)) I am using VS2017, Framework 4.5. Interop Dlls are registered using regasm.exe in framework64, Reference added Above Dlls works fine, while creating project with Console Application/Win form application. A: http://www.codeproject.com/KB/cs/all_ehllapi.aspx I've modified this example and it works just fine. A: I work with these libraries every day. Feel free to message me if you need anything. Example: using AutOIATypeLibrary; using AutPSTypeLibrary; namespace MyNamespace { public class Program { public AutPS PS = new AutPS(); public AutOIA OI = new AutOIA(); static void Main() { PS.SetConnectionByName("A"); OI.SetConnectionByName("A"); // Gets a string from the presentation space at row 1, col 1, length 5 PS.GetText(1, 1, 5); // Gets the entire screen as a string. parse as needed. PS.GetText(1, 1, PS.NumRows * PS.NumCols); // Searches for a literal string in the presentation space by going forward from your row/col PS.SearchText("LiteralString".ToUpper(), PsDir.pcSrchForward, 1, 1); } } } A: I wrote one in C many years ago for a project at Frigidaire. The internal card would cause all sorts of fun with memory leaks but I eventually found a solution by allocating arrays at the boundary of the communication card. This was over 8 years ago, I'm sure today's cards are much better and/or using native comm to read the AS400 screens. A: You might want to look at the new features in PHP. The latest version of PHP has a 5250 processor that allows you to create a webapp that acts like it is interacting with the green-screen. 5250 Bridge Info I realize that you wanted C#, but I haven't seen anything supported that directly interacts with the screens. Maybe write a PHP app to connect to the 5250 and connect your C# from there.
{ "language": "en", "url": "https://stackoverflow.com/questions/64848", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Macro to test whether an integer type is signed or unsigned How would you write (in C/C++) a macro which tests if an integer type (given as a parameter) is signed or unsigned? #define is_this_type_signed (my_type) ... A: In C++, use std::numeric_limits<type>::is_signed. #include <limits> std::numeric_limits<int>::is_signed - returns true std::numeric_limits<unsigned int>::is_signed - returns false See https://en.cppreference.com/w/cpp/types/numeric_limits/is_signed. A: If you want a macro then this should do the trick: #define IS_SIGNED( T ) (((T)-1)<0) Basically, cast -1 to your type and see if it's still -1. In C++ you don't need a macro. Just #include <limits> and: bool my_type_is_signed = std::numeric_limits<my_type>::is_signed; A: If what you want is a simple macro, this should do the trick: #define is_type_signed(my_type) (((my_type)-1) < 0) A: Your requirement isn't exactly the best, but if you'd like to hack together a define, one option could be: #define is_numeric_type_signed(typ) ( (((typ)0 - (typ)1)<(typ)0) && (((typ)0 - (typ)1) < (typ)1) ) However, this isn't considered nice or portable by any means. A: I was actually just wondering the same thing earlier today. The following seems to work: #define is_signed(t) ( ((t)-1) < 0 ) I tested with: #include <stdio.h> #define is_signed(t) ( ((t)-1) < 0 ) #define psigned(t) printf( #t " is %s\n", is_signed(t) ? "signed" : "unsigned" ); int main(void) { psigned( int ); psigned( unsigned int ); } which prints: int is signed unsigned int is unsigned A: In C++ you can do: bool is_signed = std::numeric_limits<typeof(some_integer_variable)>::is_signed; numeric_limits is defined in the <limits> header. A: Althout typeof is not legal C++ at the moment, you can use template deduction instead. See sample code below: #include <iostream> #include <limits> template <typename T> bool is_signed(const T& t) { return std::numeric_limits<T>::is_signed; } int main() { std::cout << is_signed(1) << " " << is_signed((unsigned char) 0) << " " << is_signed((signed char) 0) << std::endl; } This code will print 1 0 1 A: For c++, there is boost::is_unsigned<T>. I'm curious why you need it though, there are few good reasons IMHO. A: A more "modern" approach is to use type_traits: #include <type_traits> #include <iostream> int main() { std::cout << ( std::is_signed<int>::value ? "Signed" : "Unsigned") <<std::endl; } A: You could do this better with a template function, less macro nasty business. template <typename T> bool IsSignedType() { // A lot of assumptions on T here T instanceAsOne = 1; if (-instanceAsOne > 0) { return true; } else { return false; } } Forgive the formatting... I would try this out and see if it works... A: In C, you can't write a macro that works on as-yet unknown typedef's of fundamental integer types. In C++, you can as long as your type is a fundamental integer type or a typedef of a fundamental integer type. Here's what you'd do in C++: template <typename T> struct is_signed_integer { static const bool value = false; }; template <> struct is_signed_integer<int> { static const bool value = true; }; template <> struct is_signed_integer<short> { static const bool value = true; }; template <> struct is_signed_integer<signed char> { static const bool value = true; }; template <> struct is_signed_integer<long> { static const bool value = true; }; // assuming your C++ compiler supports 'long long'... template <> struct is_signed_integer<long long> { static const bool value = true; }; #define is_this_type_signed(my_type) is_signed_integer<my_type>::value
{ "language": "en", "url": "https://stackoverflow.com/questions/64851", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "19" }
Q: Best way to convert text files between character sets? What is the fastest, easiest tool or method to convert text files between character sets? Specifically, I need to convert from UTF-8 to ISO-8859-15 and vice versa. Everything goes: one-liners in your favorite scripting language, command-line tools or other utilities for OS, web sites, etc. Best solutions so far: On Linux/UNIX/OS X/cygwin: * *Gnu iconv suggested by Troels Arvin is best used as a filter. It seems to be universally available. Example: $ iconv -f UTF-8 -t ISO-8859-15 in.txt > out.txt As pointed out by Ben, there is an online converter using iconv. *recode (manual) suggested by Cheekysoft will convert one or several files in-place. Example: $ recode UTF8..ISO-8859-15 in.txt This one uses shorter aliases: $ recode utf8..l9 in.txt Recode also supports surfaces which can be used to convert between different line ending types and encodings: Convert newlines from LF (Unix) to CR-LF (DOS): $ recode ../CR-LF in.txt Base64 encode file: $ recode ../Base64 in.txt You can also combine them. Convert a Base64 encoded UTF8 file with Unix line endings to Base64 encoded Latin 1 file with Dos line endings: $ recode utf8/Base64..l1/CR-LF/Base64 file.txt On Windows with Powershell (Jay Bazuzi): * *PS C:\> gc -en utf8 in.txt | Out-File -en ascii out.txt (No ISO-8859-15 support though; it says that supported charsets are unicode, utf7, utf8, utf32, ascii, bigendianunicode, default, and oem.) Edit Do you mean iso-8859-1 support? Using "String" does this e.g. for vice versa gc -en string in.txt | Out-File -en utf8 out.txt Note: The possible enumeration values are "Unknown, String, Unicode, Byte, BigEndianUnicode, UTF8, UTF7, Ascii". * *CsCvt - Kalytta's Character Set Converter is another great command line based conversion tool for Windows. A: Assuming, you don't know the input encoding and still wish to automate most of the conversion, I concluded this one liner from summing up previous answers. iconv -f $(chardetect input.text | awk '{print $2}') -t utf-8 -o output.text A: DOS/Windows: use Code page chcp 65001>NUL type ascii.txt > unicode.txt Command chcp can be used to change the code page. Code page 65001 is Microsoft name for UTF-8. After setting code page, the output generated by following commands will be of code page set. A: Under Linux you can use the very powerful recode command to try and convert between the different charsets as well as any line ending issues. recode -l will show you all of the formats and encodings that the tool can convert between. It is likely to be a VERY long list. A: PHP iconv() iconv("UTF-8", "ISO-8859-15", $input); A: Stand-alone utility approach iconv -f ISO-8859-1 -t UTF-8 in.txt > out.txt -f ENCODING the encoding of the input -t ENCODING the encoding of the output You don't have to specify either of these arguments. They will default to your current locale, which is usually UTF-8. A: iconv(1) iconv -f FROM-ENCODING -t TO-ENCODING file.txt Also there are iconv-based tools in many languages. A: Get-Content -Encoding UTF8 FILE-UTF8.TXT | Out-File -Encoding UTF7 FILE-UTF7.TXT The shortest version, if you can assume that the input BOM is correct: gc FILE.TXT | Out-File -en utf7 file-utf7.txt A: Try EncodingChecker EncodingChecker on github File Encoding Checker is a GUI tool that allows you to validate the text encoding of one or more files. The tool can display the encoding for all selected files, or only the files that do not have the encodings you specify. File Encoding Checker requires .NET 4 or above to run. For encoding detection, File Encoding Checker uses the UtfUnknown Charset Detector library. UTF-16 text files without byte-order-mark (BOM) can be detected by heuristics. A: Try iconv Bash function I've put this into .bashrc: utf8() { iconv -f ISO-8859-1 -t UTF-8 $1 > $1.tmp rm $1 mv $1.tmp $1 } ..to be able to convert files like so: utf8 MyClass.java A: Try Notepad++ On Windows I was able to use Notepad++ to do the conversion from ISO-8859-1 to UTF-8. Click "Encoding" and then "Convert to UTF-8". A: Oneliner using find, with automatic character set detection The character encoding of all matching text files gets detected automatically and all matching text files are converted to utf-8 encoding: $ find . -type f -iname *.txt -exec sh -c 'iconv -f $(file -bi "$1" |sed -e "s/.*[ ]charset=//") -t utf-8 -o converted "$1" && mv converted "$1"' -- {} \; To perform these steps, a sub shell sh is used with -exec, running a one-liner with the -c flag, and passing the filename as the positional argument "$1" with -- {}. In between, the utf-8 output file is temporarily named converted. Whereby file -bi means: * *-b, --brief Do not prepend filenames to output lines (brief mode). *-i, --mime Causes the file command to output mime type strings rather than the more traditional human readable ones. Thus it may say for example text/plain; charset=us-ascii rather than ASCII text. The sed command cuts this to only us-ascii as is required by iconv. The find command is very useful for such file management automation. Click here for more find galore. A: Try VIM If you have vim you can use this: Not tested for every encoding. The cool part about this is that you don't have to know the source encoding vim +"set nobomb | set fenc=utf8 | x" filename.txt Be aware that this command modify directly the file Explanation part! * *+ : Used by vim to directly enter command when opening a file. Usualy used to open a file at a specific line: vim +14 file.txt *| : Separator of multiple commands (like ; in bash) *set nobomb : no utf-8 BOM *set fenc=utf8 : Set new encoding to utf-8 doc link *x : Save and close file *filename.txt : path to the file *" : qotes are here because of pipes. (otherwise bash will use them as bash pipe) A: to write properties file (Java) normally I use this in linux (mint and ubuntu distributions): $ native2ascii filename.properties For example: $ cat test.properties first=Execução número um second=Execução número dois $ native2ascii test.properties first=Execu\u00e7\u00e3o n\u00famero um second=Execu\u00e7\u00e3o n\u00famero dois PS: I writed Execution number one/two in portugues to force special characters. In my case, in first execution I received this message: $ native2ascii teste.txt The program 'native2ascii' can be found in the following packages: * gcj-5-jdk * openjdk-8-jdk-headless * gcj-4.8-jdk * gcj-4.9-jdk Try: sudo apt install <selected package> When I installed the first option (gcj-5-jdk) the problem was finished. I hope this help someone. A: With ruby: ruby -e "File.write('output.txt', File.read('input.txt').encode('UTF-8', 'binary', invalid: :replace, undef: :replace, replace: ''))" Source: https://robots.thoughtbot.com/fight-back-utf-8-invalid-byte-sequences A: Simply change encoding of loaded file in IntelliJ IDEA IDE, on the right of status bar (bottom), where current charset is indicated. It prompts to Reload or Convert, use Convert. Make sure you backed up original file in advance. A: In powershell: function Recode($InCharset, $InFile, $OutCharset, $OutFile) { # Read input file in the source encoding $Encoding = [System.Text.Encoding]::GetEncoding($InCharset) $Text = [System.IO.File]::ReadAllText($InFile, $Encoding) # Write output file in the destination encoding $Encoding = [System.Text.Encoding]::GetEncoding($OutCharset) [System.IO.File]::WriteAllText($OutFile, $Text, $Encoding) } Recode Windows-1252 "$pwd\in.txt" utf8 "$pwd\out.txt" For a list of supported encoding names: https://learn.microsoft.com/en-us/dotnet/api/system.text.encoding A: There is also a web tool to convert file encoding: https://webtool.cloud/change-file-encoding It supports wide range of encodings, including some rare ones, like IBM code page 37. A: Use this Python script: https://github.com/goerz/convert_encoding.py Works on any platform. Requires Python 2.7. A: My favorite tool for this is Jedit (a java based text editor) which has two very convenient features : * *One which enables the user to reload a text with a different encoding (and, as such, to control visually the result) *Another one which enables the user to explicitly choose the encoding (and end of line char) before saving A: If macOS GUI applications are your bread and butter, SubEthaEdit is the text editor I usually go to for encoding-wrangling — its "conversion preview" allows you to see all invalid characters in the output encoding, and fix/remove them. And it's open-source now, so yay for them . A: Visual Studio Code * *Open your file in Visual Studio Code *Reopen with Encoding: In the bottom status bar, to the right, you should see your current file encoding (eg "UTF-8"). Click this and select "Reopen with Encoding". *Select the correct encoding of the file (eg: ISO 8859-2). *Confirm that your content is displaying as expected. *Save with Encoding: The bottom status bar should now display your new encoding format (eg: ISO 8859-2). Click this and choose "Save with Encoding" and select UTF-8 (or whatever new encoding you want). NOTE: THIS WILL OVERWRITE YOUR ORGINIAL FILE. MAKE A BACKUP FIRST. A: As described on How do I correct the character encoding of a file? Synalyze It! lets you easily convert on OS X between all encodings supported by the ICU library. Additionally you can display some bytes of a file translated to Unicode from all the encodings to see quickly which is the right one for your file.
{ "language": "en", "url": "https://stackoverflow.com/questions/64860", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "600" }
Q: Is there a good tutorial on Websphere 6.1 ND deployments? I need to deploy an application on the WAS ND 6.1 and do not know anything about it and cannot afford to go to training... A: There is the RedBook WebSphere Application Server V6.1: System Management and Configuration with Chapter 14 talking about application deployment, this could help. A: Getting started with WAS ND can be a bit overwhelming. The redbooks mentioned above to give you a good introduction, especially the first few chapters but they are often over 500 pages long. IBM also provides an educational assistant which is a presentation style overview and that may give a good point to start with. The link to the educational assistant is shown below: http://publib.boulder.ibm.com/infocenter/ieduasst/v1r1m0/index.jsp A: This course from IBM would also be excellent but a bit pricy!!! http://www.redbooks.ibm.com/abstracts/sg247304.html?Open
{ "language": "en", "url": "https://stackoverflow.com/questions/64873", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: How to replace a character programmatically in Oracle 8.x series Due to repetitive errors with one of our Java applications: Engine engine_0: Error in application action. org.xml.sax.SAXParseException: An invalid XML character (Unicode: 0x13) was found in the element content of the document. I need to "fix" some Unicode character in an Oracle database, ideally in a programmatic fashion. Once identified, what would be a simple way to "search and replace" it? A: Assuming the characters are present in a text field: update TABLE set COLUMN=REPLACE(convert(varchar(5000), COLUMN), 'searchstring', 'replacestring') (note that this will only work on a text field with no more than 5000 characters, for larger text fields increase the number in the query).
{ "language": "en", "url": "https://stackoverflow.com/questions/64875", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why is my cocoa program getting EXC_BAD_ACCESS during startup? During the load of my cocoa application, my program crashes with the messsage EXC_BAD_ACCESS. The stack trace is not helpful. Any clues to how I can find the problem? A: I've seen times where this can happen when you are trying to access a object that you didn't retain properly so its either not pointing to a valid copy of your object or its pointing to an object of another type. Placing breakpoints early and analyzing the objects as you step through startup using po and print in gdb is your best bet. A: This is typically indicative of a memory management error. Make sure all your outlet declarations follow best practice: @interface MyClass : MySuperclass { UIClass *myOutlet; } @property (nonatomic, retain) IBOutlet UIClass *myOutlet; @end This format ensures that you get memory management right on any platform with any superclass. Check any awakeFromNib methods to ensure that you're not over-releasing objects etc. A: A new answer to an old thread... in XCode 4 the most effective way to diagnose EXC_BAD_ACCESS exceptions is to use Instruments to profile your app (from XCode click Product/Profile and choose Zombies). This will help you identify messages sent to deallocated objects. A: To add: the foremost reason for unarchiving failure is forgetting "return self;" from the -init of a custom class. It hurts a lot :( A: Check console log ( Applications/Utilities/Console.app ) . When program crashes on startup, and there's something wrong with initialization, it often writes out some helpful error messages there, before it crashes. A: This is one possible reason. There is a IBOutlet object that isn't being initialized and a message is being invoked on nil. The stack trace might look like this: #0 0x90a594c7 in objc_msgSend #1 0xbffff7b8 in ?? #2 0x932899d8 in loadNib #3 0x932893d9 in +[NSBundle(NSNibLoading) _loadNibFile:nameTable:withZone:ownerBundle:] #4 0x9328903a in +[NSBundle(NSNibLoading) loadNibFile:externalNameTable:withZone:] #5 0x93288f7c in +[NSBundle(NSNibLoading) loadNibNamed:owner:] #6 0x93288cc3 in NSApplicationMain #7 0x00009f80 in main at main.mm:17 Since the stack trace is not helpful you will have to step through your code to find the error. If for some reason you aren't able to set breakpoints early in your execution, try inserting some Debugger(); calls which will break to the debugger.
{ "language": "en", "url": "https://stackoverflow.com/questions/64881", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Select data from "show tables" MySQL query Is it possible to select from show tables in MySQL? SELECT * FROM (SHOW TABLES) AS `my_tables` Something along these lines, though the above does not work (on 5.0.51a, at least). A: You can't put SHOW statements inside a subquery like in your example. The only statement that can go in a subquery is SELECT. As other answers have stated, you can query the INFORMATION_SCHEMA directly with SELECT and get a lot more flexibility that way. MySQL's SHOW statements are internally just queries against the INFORMATION_SCHEMA tables. User @physicalattraction has posted this comment on most other answers: This gives you (meta)information about the tables, not the contents of the table, as the OP intended. – physicalattraction On the contrary, the OP's question does not say that they want to select the data in all the tables. They say they want to select from the result of SHOW TABLES, which is just a list of table names. If the OP does want to select all data from all tables, then the answer is no, you can't do it with one query. Each query must name its tables explicitly. You can't make a table name be a variable or the result of another part of the same query. Also, all rows of a given query result must have the same columns. So the only way to select all data from all tables would be to run SHOW TABLES and then for each table named in that result, run another query. A: You may be closer than you think — SHOW TABLES already behaves a lot like a SELECT statement. Here's a PHP example of how you might fetch its "rows": $pdo = new PDO("mysql:host=$host;dbname=$dbname",$user,$pass); foreach ($pdo->query("SHOW TABLES") as $row) { print "Table $row[Tables_in_$dbname]\n"; } SHOW TABLES behaves like a SELECT on a one-column table. That column name is Tables_in_ plus the database name. A: I think you want SELECT * FROM INFORMATION_SCHEMA.TABLES See http://dev.mysql.com/doc/refman/5.0/en/tables-table.html A: Have you looked into querying INFORMATION_SCHEMA.Tables? As in SELECT ic.Table_Name, ic.Column_Name, ic.data_Type, IFNULL(Character_Maximum_Length,'') AS `Max`, ic.Numeric_precision as `Precision`, ic.numeric_scale as Scale, ic.Character_Maximum_Length as VarCharSize, ic.is_nullable as Nulls, ic.ordinal_position as OrdinalPos, ic.column_default as ColDefault, ku.ordinal_position as PK, kcu.constraint_name, kcu.ordinal_position, tc.constraint_type FROM INFORMATION_SCHEMA.COLUMNS ic left outer join INFORMATION_SCHEMA.key_column_usage ku on ku.table_name = ic.table_name and ku.column_name = ic.column_name left outer join information_schema.key_column_usage kcu on kcu.column_name = ic.column_name and kcu.table_name = ic.table_name left outer join information_schema.table_constraints tc on kcu.constraint_name = tc.constraint_name order by ic.table_name, ic.ordinal_position; A: SELECT * FROM INFORMATION_SCHEMA.TABLES That should be a good start. For more, check INFORMATION_SCHEMA Tables. A: I think what you want is MySQL's information_schema view(s): http://dev.mysql.com/doc/refman/5.0/en/tables-table.html A: SELECT column_comment FROM information_schema.columns WHERE table_name = 'myTable' AND column_name = 'myColumnName' This will return the comment on: myTable.myColumnName A: Not that I know of, unless you select from INFORMATION_SCHEMA, as others have mentioned. However, the SHOW command is pretty flexible, E.g.: SHOW tables like '%s%' A: Yes, SELECT from table_schema could be very usefull for system administration. If you have lot of servers, databases, tables... sometimes you need to DROP or UPDATE bunch of elements. For example to create query for DROP all tables with prefix name "wp_old_...": SELECT concat('DROP TABLE ', table_name, ';') FROM INFORMATION_SCHEMA.TABLES WHERE table_schema = '*name_of_your_database*' AND table_name LIKE 'wp_old_%'; A: in MySql 5.1 you can try show tables like 'user%'; output: mysql> show tables like 'user%'; +----------------------------+ | Tables_in_test (user%) | +----------------------------+ | user | | user_password | +----------------------------+ 2 rows in set (0.00 sec) A: You can create a stored procedure and put the table names in a cursor, then loop through your table names to show the data. Getting started with stored procedure: http://www.mysqltutorial.org/getting-started-with-mysql-stored-procedures.aspx Creating a cursor: http://www.mysqltutorial.org/mysql-cursor/ For example, CREATE PROCEDURE `ShowFromTables`() BEGIN DECLARE v_finished INTEGER DEFAULT 0; DECLARE c_table varchar(100) DEFAULT ""; DECLARE table_cursor CURSOR FOR SELECT table_name FROM information_schema.tables WHERE table_name like 'wp_1%'; DECLARE CONTINUE HANDLER FOR NOT FOUND SET v_finished = 1; OPEN table_cursor; get_data: LOOP FETCH table_cursor INTO c_table; IF v_finished = 1 THEN LEAVE get_data; END IF; SET @s=CONCAT("SELECT * FROM ",c_table,";"); PREPARE stmt FROM @s; EXECUTE stmt; DEALLOCATE PREPARE stmt; END LOOP get_data; CLOSE table_cursor; END Then call the stored procedure: CALL ShowFromTables(); A: To count: SELECT COUNT(*) as total FROM (SELECT TABLE_NAME as tab, TABLES.* FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA='database_name' GROUP BY tab) tables; To list: SELECT TABLE_NAME as table, TABLES.* FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA='database_name' GROUP BY table; A: I don't understand why you want to use SELECT * FROM as part of the statement. 12.5.5.30. SHOW TABLES Syntax
{ "language": "en", "url": "https://stackoverflow.com/questions/64894", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "61" }
Q: parsings strings: extracting words and phrases [JavaScript] I need to support exact phrases (enclosed in quotes) in an otherwise space-separated list of terms. Thus splitting the respective string by the space-character is not sufficient anymore. Example: input : 'foo bar "lorem ipsum" baz' output: ['foo', 'bar', 'lorem ipsum', 'baz'] I wonder whether this could be achieved with a single RegEx, rather than performing complex parsing or split-and-rejoin operations. Any help would be greatly appreciated! A: Try this: var input = 'foo bar "lorem ipsum" baz'; var R = /(\w|\s)*\w(?=")|\w+/g; var output = input.match(R); output is ["foo", "bar", "lorem ipsum", "baz"] Note there are no extra double quotes around lorem ipsum Although it assumes the input has the double quotes in the right place: var input2 = 'foo bar lorem ipsum" baz'; var output2 = input2.match(R); var input3 = 'foo bar "lorem ipsum baz'; var output3 = input3.match(R); output2 is ["foo bar lorem ipsum", "baz"] output3 is ["foo", "bar", "lorem", "ipsum", "baz"] And won't handle escaped double quotes (is that a problem?): var input4 = 'foo b\"ar bar\" \"bar "lorem ipsum" baz'; var output4 = input4.match(R); output4 is ["foo b", "ar bar", "bar", "lorem ipsum", "baz"] A: A simple regular expression will do but leave the quotation marks. e.g. 'foo bar "lorem ipsum" baz'.match(/("[^"]*")|([^\s"]+)/g) output: ['foo', 'bar', '"lorem ipsum"', 'baz'] edit: beaten to it by shyamsundar, sorry for the double answer A: Thanks a lot for the quick responses! Here's a summary of the options, for posterity: var input = 'foo bar "lorem ipsum" baz'; output = input.match(/("[^"]+"|[^"\s]+)/g); output = input.match(/"[^"]*"|\w+/g); output = input.match(/("[^"]*")|([^\s"]+)/g) output = /(".+?"|\w+)/g.exec(input); output = /"(.+?)"|(\w+)/g.exec(input); For the record, here's the abomination I had come up with: var input = 'foo bar "lorem ipsum" "dolor sit amet" baz'; var terms = input.split(" "); var items = []; var buffer = []; for(var i = 0; i < terms.length; i++) { if(terms[i].indexOf('"') != -1) { // outer phrase fragment -- N.B.: assumes quote is either first or last character if(buffer.length === 0) { // beginning of phrase //console.log("start:", terms[i]); buffer.push(terms[i].substr(1)); } else { // end of phrase //console.log("end:", terms[i]); buffer.push(terms[i].substr(0, terms[i].length - 1)); items.push(buffer.join(" ")); buffer = []; } } else if(buffer.length != 0) { // inner phrase fragment //console.log("cont'd:", terms[i]); buffer.push(terms[i]); } else { // individual term //console.log("standalone:", terms[i]); items.push(terms[i]); } //console.log(items, "\n", buffer); } items = items.concat(buffer); //console.log(items); A: var str = 'foo bar "lorem ipsum" baz'; var results = str.match(/("[^"]+"|[^"\s]+)/g); ... returns the array you're looking for. Note, however: * *Bounding quotes are included, so can be removed with replace(/^"([^"]+)"$/,"$1") on the results. *Spaces between the quotes will stay intact. So, if there are three spaces between lorem and ipsum, they'll be in the result. You can fix this by running replace(/\s+/," ") on the results. *If there's no closing " after ipsum (i.e. an incorrectly-quoted phrase) you'll end up with: ['foo', 'bar', 'lorem', 'ipsum', 'baz'] A: 'foo bar "lorem ipsum" baz'.match(/"[^"]*"|\w+/g); the bounding quotes get included though A: how about, output = /(".+?"|\w+)/g.exec(input) then do a pass on output to lose the quotes. alternately, output = /"(.+?)"|(\w+)/g.exec(input) then do a pass n output to lose the empty captures. A: ES6 solution supporting: * *Split by space except for inside quotes *Removing quotes but not for backslash escaped quotes *Escaped quote become quote Code: input.match(/\\?.|^$/g).reduce((p, c) => { if(c === '"'){ p.quote ^= 1; }else if(!p.quote && c === ' '){ p.a.push(''); }else{ p.a[p.a.length-1] += c.replace(/\\(.)/,"$1"); } return p; }, {a: ['']}).a Output: [ 'foo', 'bar', 'lorem ipsum', 'baz' ] A: One that's easy to understand and a general solution. Works for all delimiters and 'join' characters. Also supports 'joined' words that are more than two words in length.... ie lists like "hello my name is 'jon delaware smith fred' I have a 'long name'".... A bit like the answer by AC but a bit neater... function split(input, delimiter, joiner){ var output = []; var joint = []; input.split(delimiter).forEach(function(element){ if (joint.length > 0 && element.indexOf(joiner) === element.length - 1) { output.push(joint.join(delimiter) + delimiter + element); joint = []; } if (joint.length > 0 || element.indexOf(joiner) === 0) { joint.push(element); } if (joint.length === 0 && element.indexOf(joiner) !== element.length - 1) { output.push(element); joint = []; } }); return output; } A: This might be a very late answer, but I am interested in answering ([\w]+|\"[\w\s]+\") http://regex101.com/r/dZ1vT6/72 Pure javascript example 'The rain in "SPAIN stays" mainly in the plain'.match(/[\w]+|\"[\w\s]+\"/g) Outputs: ["The", "rain", "in", ""SPAIN stays"", "mainly", "in", "the", "plain"] A: Expanding on the accepted answer, here's a search engine parser that, * *can match phrases or words *treats phrases as regular expressions *does a boolean OR across multiple properties (e.g. item.title and item.body) *handles negation of words or phrases when they are prefixed with - Treating phrases as regular expressions makes the UI simpler for my purposes. const matchOrIncludes = (str, search, useMatch = true) => { if (useMatch) { let result = false try { result = str.match(search) } catch (err) { return false } return result } return str.includes(search) } const itemMatches = (item, searchString, fields) => { const keywords = searchString.toString().replace(/\s\s+/g, ' ').trim().toLocaleLowerCase().match(/(-?"[^"]+"|[^"\s]+)/g) || [] for (let i = 0; i < keywords.length; i++) { const negateWord = keywords[i].startsWith('-') ? true : false let word = keywords[i].replace(/^-/,'') const isPhraseRegex = word.startsWith('"') ? true : false if (isPhraseRegex) { word = word.replace(/^"(.+)"$/,"$1") } let word_in_item = false for (const field of fields) { if (item[field] && matchOrIncludes(item[field].toLocaleLowerCase(), word, isPhraseRegex)) { word_in_item = true break } } if ((! negateWord && ! word_in_item) || (negateWord && word_in_item)) { return false } } return true } const item = {title: 'My title', body: 'Some text'} console.log(itemMatches(item, 'text', ['title', 'body']))
{ "language": "en", "url": "https://stackoverflow.com/questions/64904", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: How do you create templates for SQL Server 2005 Reporting Services reports? I want to create templates for base new reports on to have common designs. How do you do it? A: The need to produce reports with a common starting design and format is key to any project involving clients and their reports. I have been working on reports for over 10 years now. This has not been the largest portion of my jobs through the years but it has been a very import one. The key to any report project is not to recreate the mundane aspects of the reports for each but to use templates. The use of templates is not a common task or knowledge for Microsoft's SQL Server Reporting Services. Knowing how to save reports templates so that you and your team can create these shortcuts at the creation of a new report in Visual Studio 2005 will help save time and have all reports use the same layout and design. Create of a set of reports with the following suggestions: * *Page size -- 8.5 by 11 (letter) and 8.5 by 14 (legal) *Orientation -- portrait and landscape for all paper sizes *Header -- Text Box for report name, Text Box for report subtitle, client or brand logo *Footer -- page number/total pages, date and time report printed Take all the rdl files for the reports created from the suggestions and copy the files to the following directory: C:\Program Files\Microsoft Visual Studio 8\Common7\IDE\PrivateAssemblies\ProjectItems\ReportProject When creating a new report in your Visual Studio 2005 report project through Add|New Item alt text http://www.cloudsocket.com/images/image-thumb14.png The new report dialog will present the list of items from the directory where the new templates were placed. alt text http://www.cloudsocket.com/images/image-thumb15.png Select the report that fits the requirement needed and proceed to develop your reports without needing to create the basics. A: Further more, I would suggest wrapping up your template perhaps with externally linked images into an .msi for easier distribution. It is a lot easier to ask people in a department to run an installer than it is to hope they find the right path to put the reporting template in. Make sure you use the proper program files variables etc to account for "Program Files" vs "Program Files(x86)" and other variations users sometimes do with their environment variable settings.
{ "language": "en", "url": "https://stackoverflow.com/questions/64905", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Best PHP thumbnailer/resizer class? What is the nest PHP thumbnailer/resizer class that preferably works on most shared hosts? Clarification: I'm looking for a PHP class/wrapper (eg. phpThumb(), Asido), so I don't have to run GD or ImageMagick functions directly. I'm specifically looking for resizing and framing functions. A: I have good experiences with both phpThumb and Wideimage. Wideimage is the more modern PHP5 approach while phpThumb has much more features. A: Asido works great with some modifications ;) It supports most features that I need (resizing, framing), has drivers for both GD and Imagemagick, nice simple API, and organized codebase. A: GD is supported on many hosts http://uk3.php.net/manual/en/book.image.php A: I guess the best two (and by far the most common) are either GD or ImageMagick. I've had a lot of joy with the second. A: Imagick is a native PHP extension to create and modify images using the ImageMagick API. It is used on many shared hosts: http://pecl.php.net/package/imagick A: Imagemagick is good, and has two APIs for PHP: http://www.imagemagick.org/script/api.php#php http://www.imagemagick.org/script/api.php#php A: I've found that both ImageMagick and GD are too slow for creating un-cacheable dynamic images on the fly if you have more than one request per second. I had to serve dozens of requests per second, and found that I could get around 50 times speed improvement by writing the routine as FastCGI with C & jpeglib. A: I use Greg_Photo as an accessor to the underlying GD commands. For pretty basic resizing it works great. A: ImageMagick will definitely produce really sharp images, but it's not easy to install or manage. ImageMagick itself needs to be installed on the server, and then a compatinble version of MagickWand needs to be installed. I've also found that it has a habit of creating massive temporary files of up to a GB or more and then dumping them into your /tmp directory, which you need to be careful of. It will also eat up a massive amount of memory unpredictably. For these reasons, I would not recommend ImageMagick if you are on a shared host. A: Here's a great script with great documentation. http://phpthumb.gxdlabs.com/
{ "language": "en", "url": "https://stackoverflow.com/questions/64907", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: exposition on arrows in haskell What would be a good place to go to understand arrows? Ideally, I am just looking for some place with a concise definition with motivation from some good examples, something similar to Wadler's exposition on monads. A: http://en.wikibooks.org/wiki/Haskell/Understanding_arrows A: I found Hughes' original paper ("Generalizing Monads to Arrows") to be fairly accessible. You can read an older draft of it here. It has some differences from the original paper, which are noted on the bibliography page of Ross Patterson's own overview of Arrows. A: If you learn better from practice than theory, try using HXT for XML manipulation, or PArrows for general parsing. They both have APIs centered around arrows.
{ "language": "en", "url": "https://stackoverflow.com/questions/64933", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }