text
stringlengths
8
267k
meta
dict
Q: get n rows beyond the given row in SQL Server I have a table with a column period. the value in this column will be like this, 201101, 201102, 201103,etc, 201112, 201201 etc If i give a number n and any period p, then it has to retrieve a period = p - n. That means it has to go n period before. Please help me how to do this. Im using SQL Server 2008. Period column is integer type. A: If I understand what you need, try this: SELECT TOP 1 * FROM ( SELECT TOP n * FROM your_table WHERE period < p ORDER BY period DESC) as tb ORDER BY tb.period My idea is first to take n periods backward (with subquery) and then take (with main query) the last record from subquery. If you want a period (not only one record) you could use: SELECT TOP n * FROM your_table WHERE period < p ORDER BY period DESC A: If I'm understanding correctly, it looks like you'll need a between statement. SELECT period from table where period between n and p N and P are integer numbers in this case. For further information about SQL, check out http://w3schools.com/sql/default.asp A: you can try this ... select * from your_table where period = convert(varchar(6),dateadd(m,addnumber,convert(datetime,convert(varchar(6),startperiod)+'01')),112) addnumer = month to add (positiv) or remove (negativ) startperiod = start period i think this is a better solution because if a period is actualy not in your table, then you would not get wrong results!
{ "language": "en", "url": "https://stackoverflow.com/questions/7528713", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ClearCase UCM: Is it possible to delete a project? Can a ClearCase administrator or a project manager delete a project including all its streams, views, baselines, activities etc.? How? A: * *You cannot easily delete a project, unless all its streams are deleted *You cannot easily delete a stream if there are versions created on a branch made from that streams (or if there are any views or any activities attached to that stream). *You cannot easily activities unless you have deleted first every versions in it (or move them to another activity) *and so on... Bottom line, ask for the owner of the project to obsolete it (and its streams): cleartool lock -obs stream:astream@\myPVob cleartool lock -obs project:myProject@\myPVob It is a much more lightweight operation with less side-effects and: * *the project and its streams will be invisible *nobody will be able to checkout/checkin any file on those streams (ie on the branches created from those streams)
{ "language": "en", "url": "https://stackoverflow.com/questions/7528718", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Track position Indoor (with smartphone) Possible Duplicate: Indoor Positioning System based on Gyroscope and Accelerometer Very simple question for you guys. Suppose I wanted to track my location accurately with no real reference points (gps). And what I mean by that the only thing i know is my location (0,0) on a 2-dimensional map, is it possible with use of a gyro and accelerometer to track my position as I walk away from that point? I have read quit a lot of paper on that subject but no one is clearly telling how this could be realized. I especially had a look to that video http://www.youtube.com/watch?v=C7JQ7Rpwn2k (Google talk) It's about how to integrate all the sensors.. it's really nicely explained, but once again... After having watched that video I have still no idea (formulas? Technique? etc..) how to use those sensor to track my position Can someone guide me too some good tutorial? About calculate the next position from the angle, velocity etc. ? Thank you. A: You need to understand that accelerometer measures acceleration - thus if you move with a constant walking speed, the accelerometer will not detect any movement. It will only detect if you start walking faster/slower. Distance can't be tracked with an accelerometer. You could only very very roughly estimate the position. Maybe also counting the steps with a sort of "pedometer" algorithm that would count your steps by measuring the cyclic vibrations while walking. You will still need the direction when you are going - which could be only roughly estimated with the accelerometer.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528722", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Sorting of Field having special characters in SoLR i am new at SoLR indexing. I want to sort location field which have different values.it also contains values which starts with 'sAmerica, #'Japan, %India and etc. Now when i sort this field i do want to consider special characters like 's,'#,!,~ and etc. i want sorting which will ignore this chars and returns results like America at 1st position, %India at 2nd and #'Japan at 3rd position.. How to make it possbile? i am using PatternReplaceFilterFactory,but don't know about this. <analyzer type="query"> <tokenizer class="solr.KeywordTokenizerFactory"/> <filter class="solr.LowerCaseFilterFactory" /> <filter class="solr.WordDelimiterFilterFactory" catenateWords="1" /> <filter class="solr.PatternReplaceFilterFactory" pattern="'s" replacement="" replace="all" /> </analyzer> </fieldType> A: IF you want to ignore the special characters, try using the following field type. This would lower case the words and catenate the words excluding all special chars. <fieldType name="string_sort" class="solr.TextField" positionIncrementGap="1"> <analyzer type="index"> <tokenizer class="solr.KeywordTokenizerFactory" /> <filter class="solr.LowerCaseFilterFactory" /> <filter class="solr.WordDelimiterFilterFactory" catenateWords="1" /> </analyzer> </fieldType> However, this would not work for 'sAmerica as s is not a special character. <filter class="solr.PatternReplaceFilterFactory" pattern="'s" replacement="" replace="all" /> If this is fixed pattern you need to replace it before the word delimiter with above. Edit -- Are you using this config ? <fieldType name="string_sort" class="solr.TextField" positionIncrementGap="1"> <analyzer type="index"> <tokenizer class="solr.KeywordTokenizerFactory" /> <filter class="solr.LowerCaseFilterFactory" /> <filter class="solr.PatternReplaceFilterFactory" pattern="'s" replacement="" replace="all" /> <filter class="solr.WordDelimiterFilterFactory" catenateWords="1" /> </analyzer> </fieldType> Have tested the following through analysis and it produces the following tokens - KT - 'sAlgarve LCF - 'salgarve PRF - algarve WDF - algarve Can you check through the analysis.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528723", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to publish application update on Android market? I have to publish first update for my publish application. I want to do it right, but have no idea how :( Any help please? A: In your AndroidManifest.xml, increment the versionCode (e.g. from 1 to 2), and optional, increase the versionName. Then just create the signed .apk exactly as before (same key) and upload it to the Market. Edit In the developer console, select your application and go to the apk files tab. When your in 'simple' mode, you can indeed just upload the file and be done. When in advanced mode, you can upload the file, turn off the old apk, and turn on the new .apk file. And, as @Eamorr said, don't forget to save ofcourse :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7528725", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Disabling orientation change with Phonegap I need to fix the screen in landscape orientation at one point in my application, with the possibility to change back to normal. So far I have only seen suggestions of setting the orientation at launch time. I don't want to use Appcelerator for many reasons, and It should work on Android 2.2+ and Iphone. A: For iOS apps you can modify the project plist file (/Prject name/supporting files/Project name.plist). It will work.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528727", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: automatic updating an application with git is there any way to use git as an automatic updating mechanism for applications. something like what google chrome does (or Github for Mac). I want to create a central git repo that contains the whole app (including binaries) and be able to make the application pull in changes from the repo in the background. The new version should be installed on the next start. Thanks A: I made a java program that uses Git as an autoupdater. What the program does is that it checks the raw text of a CurrentVersion.txt. If the number is greater than the program version, it downloads an updater from the git repo. The updater then acts as a medium between the versions and deleting the old version and replacing it with the newly downloaded one. It was pretty simple. A: Aren't you giving the answer to your own question? Git pull on startup of your application. After a git pull you could run some scripts to execute update-specific actions. If you've got a webapplication I wouldn't do this on each request to your application, but in a cron job that runs every N minutes. A: It could look like a good idea, since git is quite efficient at storing files delta, but after it's not: you'd have to embed git with your application. Not sure it is desireable. Better look at courgette, the Chrome's auto-update mechanism (only for Windows AFIK), and the most voted answers to auto-update tag A: If you're on Windows machine, you can use my graphic solution Or create a DOS batch file the way I did it Here is my solution: rem first install GIT Bash rem then add C:\Program Files\Git\bin to the environment variable PATH and reboot you PC set VisualStudioVersion=2012 set VisualStudioName=Visual Studio %VisualStudioVersion% cd \ cd %userprofile% cd "Documents" cd %VisualStudioName% cd "Projects" echo Press a key to update all choosen git repositories if you're in the correct directory otherwise press CTRL-C to cancel pause cd AddFeatures git pull origin master cd .. cd CodeGeneration git pull origin master cd .. A: you always can make a workaround like a text file in server, that will store the last version. On your software startup, download this file, verify if version of file is different from version of installed software, and do the download the new version installer and run it. is quite simple to implement...
{ "language": "en", "url": "https://stackoverflow.com/questions/7528730", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SharePoint Designer 2010 Can't open Page Layout in Edit Mode Every time I try to open any page layout in my site collection SharePoint Designer 2010 throws the the following error at me. Can't figure out what's wrong. I've used it fine with other site collections before. Any ideas? A: when opening your site collection, try to specify the full name for this collection. for example, instead of http://localhost, try something like this: http://fullname.domain.com Or, probably a better way to fix it: go to Central Administration (/_admin/AlternateUrlCollections.aspx) and check your alternative access names. When you open your collection in Designer you have to use exactly the same URLs. A: I have since found out what caused this issue. I was missing the following handler for asmx within my web.config file <add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
{ "language": "en", "url": "https://stackoverflow.com/questions/7528732", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What is an efficient MongoDB schema design for a multilingual e-commerce site? I'm designing a multilingual e-commerce site. Products have different properties. Some properties are different for each language (like color), other properties are the same for all languages (like SKU). Properties are not predefined, for example cars have other properties than espresso machines. I'd like to design the database schema such that: * *Searching and representing all products from category x in language y is fast *The amount of duplicate data is low *I don't want to use files with translations I'm thinking about using a schema like this: { _id: ObjectID("5dd87bd8d77d094c458d2a33"), multi-lingual-properties: ["name", "description"], name: { en: "Super fast car", nl: "Hele snelle auto"}, description: { en: "Buy this car", nl: "Koop deze auto"}, price: 20000, sku: "SFC106X", categories: [ObjectID("4bd87bd8277d094c458d2a43")] } Is there a better alternative to this schema? What problems will I encounter when I use this schema? A: Later than I expected, but here's what we're implementing now... Background: Our system is supposed to be able to import product inventory from multiple ecommerce sites, so flexibility & i18n are important. EAV model: db.products.find() { "_id" : ObjectId("4e9bfb4b4403871c0f080000"), "name" : "some internal name", "sku" : "10001", "company" : { /* reference to another collection */ }, "price" : 99.99, "attributes": { "description": { "en": "english desc", "de": "deutsche Beschreibung" }, "another_field": { "en": "something", "de": "etwas"}, "non_i18n_field": { "*": xxx } } } We also need metadata for attributes, which includes admin editing tips (what input forms to use) and i18n for names of the attributes. Example: db.eav.attributes.find() { "_id" : ObjectId("127312318"), "code" : "description", "labels" : { "en" : "Description", "de": "Beschreibung" }, "type" : "text-long", "options" : [], "constraints" : [ ] } The idea is that attribute metadata will be quite large and won't get copied. Most of the time operations will be done using values of the (dynamic) attributes. If attribute metadata is necessary to display UI etc. it can be loaded & cached separately, and referenced by the attribute code. So by default everything that's an attribute is i18n-enabled. Queries for i18n-enabled-attributes are simple: db.products.find({ attributes.description.en: "searched val" }) Non translated attributes may be a hassle though since they'd need special treatment in queries: attributes.description.* Not sure what we'll do with those attributes yet. E.g. numeric values don't require translation. Any thoughts on that are welcome. We're still not using this structure though, so these are really pre-implementation ideas. I'm expecting more issues to surface while we start using this in practice, i.e. doing UI for CRUD operations etc.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528733", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: In official android.jar library i've not Fragment and FragmentList classes In official android.jar library i've not Fragment and FragmentList classes, where i can find them? Thank u very much, guys! A: In Compatibility package, or in later android SDK (3.0 and higher). A: To include fragments in your projects you need to add the compatibility package jar for your project which is a library of api's that was developed for honeycomb. If should be in your sdk folder, for eg in path like E:\Softwares\Android\android-compatibility\v4\android-support-v4.jar
{ "language": "en", "url": "https://stackoverflow.com/questions/7528734", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ASP.net MVC 3 user registration I am new to asp.net mvc 3 world I looked at some tutorials to get started. I want to know what is the best option to manage users? I intended use of the membership provider (and modify this for extend the default fields) or use the user profiling + membership provider? What are the advantages and disadvantages of these? once I made ​​my application the idea is create a mobile application: a user must be able access by user and password (my web application)... it affects my choice? A: Start from here : http://www.asp.net/mvc You can take advantage of a sample application : http://www.asp.net/mvc/tutorials/mvc-music-store-part-1 And the following one is specific to membership : http://www.asp.net/mvc/tutorials/mvc-music-store-part-7 I would also consider integrating OpenAuth. DotNetOpenAuth oAuth in ASP.NET MVC A: Another good example is the NerdDinner project. Site: http://www.nerddinner.com Source Code: http://nerddinner.codeplex.com
{ "language": "en", "url": "https://stackoverflow.com/questions/7528737", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Can I do content based polling in Biztalk server using WSS Adapter I have scenario where I have to poll documents from sharepoint library based on some conditions. e.g. fetch documents which has status==Readytoprocess and then based upon unique number present in document fetch its content file from another sharepoint library. What is the best approach doing in biztalk? Is there any way where I can create Dynamic Receive? A: * *Create a view in Sharepoint, with a status==Readytoprocess-filter, and let BizTalk poll from there. * *Make a request to the Sharepoint service for the content file. Regards Martin
{ "language": "en", "url": "https://stackoverflow.com/questions/7528740", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: way to open and load a file in memory Is there a way such that I can open and load a file directly in memory? I have lot of legacy code that opens a file present on network, and then does seeks and reads from this file. I want to avoid the reads and seeks over the network. Hence, if I could load the file in memory, when I open it, I could have efficient seeks. Any ideas? I'm working wtih C on Linux. A: You could use the mmap function, or plain open and read it all into a buffer you've allocated with malloc. But please do benchmark. You might get very little (or none at all) improvement from this "manual buffering". The OS already does caching for you. A: As Mat said, have a look at the mmap function. (It's probably the easier way) http://linux.die.net/man/2/mmap If you prefer malloc, this link should help you: http://www.anyexample.com/programming/c/how_to_load_file_into_memory_using_plain_ansi_c_language.xml
{ "language": "en", "url": "https://stackoverflow.com/questions/7528743", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I run an infinite loop on my website? (for a reminder/deadline announcer) I'm building a website and i want to implement a reminder feature that alerts people if they have any projects or activities that are due or simply alert them of any timer they may have set. I have a clue about how i could do it with javascript's timer functions but i want it to run all the time and add reminders to a queue if the users are not online when the event occurs. Is there any way of doing this or do i have to use bash or python on the server? Further explanation on how it's supposed to work: - infinite loop checks for the time every X seconds, if there's a a reminder up between now and X seconds ago, print it to the user it belongs to - if the user is not online, put it in a file or something which is checked, when the user logs in, for any missed reminders. another way i thought of is to use a local script (pyton or something) to check the database for reminders that are due, every X seconds, and write them in a file on the web server. then, server-side scripting will read it every X seconds and print the reminders to each logged account (and delete it at that point). This way no reminders are skipped even if the person it belongs to is logged out. Any idea on how to do this more elegantly? A: Use Cron Job instead and run your script with that to connect to your database and to do other tasks. A: this functionality can be done with ajax and php. I wouldn't check the db when the user isn't online. I guess it is better to check reminders on login (unless you want to for example email them when they occur->then you need cron like mentioned in the other answers). you'll need to make a php script that checks which reminders have to be set and return them in an array/json. on login call this page. when user is logged in you can request your reminder php periodically/timer with ajax. A: Having an infinite loop is by default bad design. PHP won't like it at all (memory). Javascript isn't ideal for the same reason too. Apart from that you don't want a javascript sleep to block your UI when waiting between tries. Also, I wouldn't check notices when the user is not online. This is a useless way of using resources. Simply save the last time a user was online and display past notices that he hasn't seen before on login. The cleanest solution in my book is some javascript library capable of eventdriven actions. An example of that is node.js. With events you don't need to check every N time but simply have an event triggered if some condition is met.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528744", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Iphone Game development Esimate I have been asked to give an estimate for an iphone game application. I really have bad estimates for game application. Can you share me links or stuff which will give me some idea of how long it will take me to develop the game. I know this is very crude data, but some link that will give me database or share experiences about how much time other developers took for different games. A: It really depends on your skills Amol. Among other elements: * *will you be doing the art assets, or are they given to you *are you designing the game, or just implementing it *do you "discover" Objective-C or are you an experienced iPhone or even Mac business application developer? All these change your estimate drastically. You also have to take into account the technique you will use: * *pure OpenGL *Cocos2D *Unity which partly depends on the previous questions. Then you need to know which frameworks you intend to use: * *Quartz *Core Graphics *Core Data *Game Center and many other possibilities. If the game is very simple, you probably won't need a database or a leaderboard. If you're implementing a huge tridimensional multiplayer online roleplaying game client, you might need a team to help you out. You need to figure out the answers to all this before you can even put out a time estimate...
{ "language": "en", "url": "https://stackoverflow.com/questions/7528746", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: How to do joins on subqueries in AREL within Rails I have a simple model class User has_many :logs class Logs related in the usual way through the foreign key logs.user_id. I'm trying to do the following using Arel and according to the Arel doc it should work. u_t = Arel::Table::new :users l_t = Arel::Table::new :logs counts = l_t. group(l_t[:user_id]). project( l_t[:user_id].as("user_id"), l_t[:user_id].count.as("count_all") ) l_t.joins(counts).on(l_t[:id].eq(counts[:user_id])) When I do that I get the error TypeError: Cannot visit Arel::SelectManager However the author of Arel explicitly suggests that Arel can do this kind of thing. Please do not write responses on how I can achieve the same query with raw sql, another type of Arel query etc. It is the pattern I am interested in not the specific results of this query. A: You can use join_sources to retrieve the Arel::Nodes::Join from the instance of Arel::SelectManager, and pass that to joins Using your example: l_t.joins(counts.join_sources).on(l_t[:id].eq(counts[:user_id])) A: This achieves a join of nested select subquery with Arel: You can add the nested inner_query and an outer_query scope in your Model file and use ... inner_query = Model.inner_query(params) result = Model.outer_query(params).joins(Arel.sql("(#{inner_query.to_sql})")) .group("...") .order("...") For variations on this, for example to use INNER JOIN on the subquery, do the following: inner_query = Model.inner_query(params) result = Model.outer_query(params).joins(Arel.sql("INNER JOIN (#{inner_query.to_sql}) tablealias ON a.id = b.id")) .group("...") .order("...") Add in the specific joins, constraints and groupings to each of the queries' scopes to modify the sql statement further ie: scope :inner_query , -> (company_id, name) { select("...") .joins("left join table1 on table1.id = table2.id") .where("table1.company_id = ? and table1.name in (?)", company_id, name) .group("...") } This allows you to put WHERE conditions on the nested query as well as the outer query
{ "language": "en", "url": "https://stackoverflow.com/questions/7528750", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: $.post vs $.ajax I'm trying to use the $.post method to call a web service, I've got it working using the $.ajax method: $.ajax({ type: "POST", url: "StandardBag.aspx/RemoveProductFromStandardBag", data: "{'standardBagProductId': '" + standardBagProductId.trim() + "' }", success: function(){ $((".reload")).click(); }, dataType: "json", contentType: "application/json" }); But when I move the same method into the $.post method, it will not work: $.post("StandardBag.aspx/RemoveProductFromStandardBag", "{'standardBagProductId': '" + standardBagProductId.trim() + "' }", function () { $((".reload")).click(); }, "json" ); What am I missing? A: It doesn't work because in your $.post method you cannot set the content type of the request to application/json. So it is not possible to invoke an ASP.NET PageMethod using $.post because an ASP.NET PageMethod requires a JSON request. You will have to use $.ajax. I would just modify the data in order to ensure that it is properly JSON encoded: $.ajax({ type: "POST", url: "StandardBag.aspx/RemoveProductFromStandardBag", data: JSON.stringify({ standardBagProductId: standardBagProductId.trim() }), success: function() { $(".reload").click(); }, dataType: "json", contentType: "application/json" }); A: This is another way to do it not using ajax. It uses post and returns a json object. data = {}; data.standardBagProductId = standardBagProductId.trim(); $.post("StandardBag.aspx/RemoveProductFromStandardBag", data , function(response){ $(".reload").click(); },"json"); A: for $.post function second param should not be in "". $.post("StandardBag.aspx/RemoveProductFromStandardBag", {'standardBagProductId': standardBagProductId.trim() }, function () { $(".reload").click(); }, "json" ); A: Try changing your post data like this, {standardBagProductId: standardBagProductId.trim() }
{ "language": "en", "url": "https://stackoverflow.com/questions/7528757", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: How to trigger when TextEdit value changed? I tried this: houseField.addTextChangedListener(new TextWatcher() { @Override public void afterTextChanged(Editable s) { // TODO Auto-generated method stub } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // TODO Auto-generated method stub Toast.makeText( getApplicationContext(), s, 15000).show(); } }); But event triggered after each symbol inserted but I dont want that.. I need to trigger event when user leaves textedit and text is changed, becouse i will do query to google maps api. I can't do query after each character entered. A: Have you tried onFocusChanged() yourTextView.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if(hasFocus) { //do your logic here } } } The other option is to use onTextChanged to start a timer which checks to delay the process and reset if another key stroke happens. This approach may be more suitable to your application but is trickier to implement EDIT Alternatively you can override boolean View.onKeyPreIme(int keyCode, KeyEvent event) and capture the enter key ( but you will also need to think about the user tapping the back key to dismiss keyboard). A: use String sChange =""; boolean change=false; @Override public void afterTextChanged(Editable s) { // TODO Auto-generated method stub String new=s.toString(); if(!sChange.equalsIgnoreCase(new)) { Toast.makeText( getApplicationContext(), sChange, 15000).show(); change=true; } else change=false; } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { sChange=s; } yourTextView.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if(hasChanged) { if(change) //google logic } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7528760", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What is wrong with this Thread? It only gets runned one time. (Thread with GPS Location) i have a activity that must capture GPS position of the user each 500ms and write it on the screen (Textview tv2). But something is going wrong It only captures the GPS position sent by the DDMS of the emulator one time, and i put some log prints on the code ( method run() ) to check the Thread and i saw that the prints are only writted ONE TIME on the log cat. Also the last log print never get's called.... wtf. I mean this print: Log.w("PABLO", "despues loop"); it never get's called.... it's like the thread stops after Looper.loop or something. This is the code: public class AugmentedRealitySampleActivity extends Activity implements Runnable{ private TextView tv2; //variables para obtener mi posicion: LocationManager mLocationManager; Location mLocation; MyLocationListener mLocationListener; Location currentLocation = null; double lat=-1; double lon=-1; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); FrameLayout rl = new FrameLayout(this.getApplicationContext()); LinearLayout ll= new LinearLayout(this.getApplicationContext()); ll.setOrientation(LinearLayout.VERTICAL); setContentView(rl); rl.addView(ll); tv2=new TextView(getApplicationContext()); tv2.setBackgroundColor(Color.BLACK); ll.addView(tv2); tv2.setText("Test2"); Log.w("PABLO", "on create"); Thread thread = new Thread(this); thread.start(); } //////////////////////////////////////////////////////////////////////// //Métodos del Hilo que obtiene la posicion GPS del usuario periodicamente. /////////////////////////////////////////////////////////////////////// public void run() { mLocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); if (mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { Log.w("PABLO", "principio hilo"); Looper.prepare(); mLocationListener = new MyLocationListener(); try{ Log.w("PABLO", "antes mLocationManager"); mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 500, 0, mLocationListener); Log.w("PABLO", "despues mLocationManager"); }catch(Exception e){} //try { // wait(100); //}catch (InterruptedException e) {} Log.w("PABLO", "antes loop"); Looper.loop(); Log.w("PABLO", "despues loop"); } } private class MyLocationListener implements LocationListener { public void onLocationChanged(Location loc) { if (loc != null) { try{ currentLocation = loc; handler.sendEmptyMessage(0); }catch(Exception e){} } } public void onProviderDisabled(String provider) { } public void onProviderEnabled(String provider) { } public void onStatusChanged(String provider, int status, Bundle extras) { } } private Handler handler = new Handler() { public void handleMessage(Message msg) { if (currentLocation!=null) { lat=currentLocation.getLatitude(); lon=currentLocation.getLongitude(); if (lat==-1 && lon ==-1) /// si no existe ninguna posicion GPS anterior en el telefono, no hago nada { } else //// si existe alguna posicion anterior (es decir, si el GPS del telefono ha sido activado al menos alguna vez en su vida util) { tv2.setText("Location= "+lat+" "+lon); } } } }; } A: Either the last log call is not flushed, the Looper.loop() does not end, or a runtime exception is thrown. I would first add a catch on Throwable around Looper.loop(). As these things must be obvious to you too, I would look for (1) simple non-reentrance errors, (2) leaking resources, especially unclosed files, URL connections.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528762", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I put an actionlistener to the OK button of JOptionpane.showInputDialog? I have a showInputDialog. Whenever I type something to that field, I want it to be save as textfile when I click the ok button. My problem is I don't know where/how to put the listener. Could somebody help me about this matter? A: The saving code shouldn't be in the InputDialog context, but in your code. InputDialog is just a way to prompt for data. String whatHeTyped = JOptionPane.showInputDialog("Type something..."); saveToFile(whatHeTyped); A: No need to add actionListener just check variable value associated with JOptionPane. Something like this:int i = JOptionPane.showConfirmDialog(null, "hi","Test Message", JOptionPane.OK_CANCEL_OPTION); System.out.println(i); if(i==0){ /// OK is clicked. } To check for input dialog do as follows: String i = JOptionPane.showInputDialog("hi"); System.out.println(i!=null); If user has pressed OK then i will be not null even if he has not entered anything in textbox. For Cancel button i will be null.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528768", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: configure linux launcher to passed variables I have found that i can use something called a launcher in linux by right clicking the desktop. i have set this to run my program in the terminal which i am happy about but i want to give it some default values when it runs. Im guessing i should put the values after the program path with - befor them but im not sure about what im doing. can some point me to a document or something that lists the ways to include values and what i can include in the path. also if i do this how will my program read them ? will they be passed to main ? Is it possible to set it up in a way that the program does not know how many variables are coming at start up but will read as many as it gets. im using c++. A: If I recall correctly running a terminal is something like rxvt -backspacekey -sl 2500 -tn msys -geometry 80x25 -e 'script.sh -param' --login -i -e command arg ... command to execute So create a file named myApp.sh (pretty much an equivalent of a .bat on windows) enter the following: !/bin/sh rxvt -geometry 80x25 -e 'yourExecutableName yourCommandLine' --login -i After saving, just chmod +x on the file (so Linux will consider it as an executable) chmod +x myApp.sh After this, you can run it from anywhere on your machine (if the dir is in the PATH enviroment variable) or via double click in Gnome File Manager. If you need to pass args also to the shell, you can access every single param with $0, $1, $2 (equivalents to %1, %2 in MS batch). For command lines, a C/C++ program starts usually with a function main int main (int argc, char ** argv) { exit(0); } argc is the number of arguments received in input, while argv is a pointer to an array of char * (the actual commandline), you may parse 'em directly. PS: note that I use rxvt, you probably want to change this to xterm o gterm or whatever terminal you prefer to use. A: You don't need C++ for this. Basically, you do it pretty much as you would do it under Windows, but the exact details depend on the window manager you are using (Gnome, KDE, etc.). The program information is passed to main via argv (which is also the preferred way of getting it in Windows, I believe). You do not have access to the raw command line.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528772", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Troubleshooting SQLiteException (unable to open database file) This is the databasehelper class. I amtrying to get a string from database stored in mTable. public class KamaDBAdapter extends SQLiteOpenHelper { protected static final String TAG = "TAG"; private Context mContext; private SQLiteDatabase mDb; //private DataBaseHelper mDbHelper; private static String TABLE="mTable"; private static String DB_NAME="mdb12.db"; private static String ROW_ID="_id"; public static String ROW_QUOTES= "quote"; private String DB_PATH = "/data/data/com.android.android/databases/"; public KamaDBAdapter(Context context) { super(context,DB_NAME,null,2); this.mContext = context; //mDb = new DataBaseHelper(mContext); } /*public KamaDBAdapter createDatabase() throws SQLException { this.createDatabase(); return this; }*/ public void readDataBase() { this.getReadableDatabase(); } public void openDataBase() throws SQLException{ //Open the database String myPath = DB_PATH + DB_NAME; mDb = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY); } public void close() { mDb.close(); } public String retriveData() { Cursor mCursor = mDb.query(TABLE, new String[] {ROW_ID},null , null, null, null, null); //mCursor.moveToFirst(); String mReturn = mCursor.getString(mCursor.getColumnIndex(ROW_ID)); mCursor.close(); return mReturn; } public boolean checkdatabase() { SQLiteDatabase mCheckDataBase = null; try { String myPath = DB_PATH + DB_NAME; mCheckDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.NO_LOCALIZED_COLLATORS); } catch(SQLiteException mSQLiteException) { Log.e(TAG, "DatabaseNotFound " + mSQLiteException.toString()); } if(mCheckDataBase != null) { mCheckDataBase.close(); } return mCheckDataBase != null; } public void copydatabase() throws IOException { //Open your local db as the input stream InputStream myinput = mContext.getAssets().open(DB_NAME); // Path to the just created empty db String outfilename = DB_PATH + DB_NAME; //Open the empty db as the output stream OutputStream myoutput = new FileOutputStream(outfilename); // transfer byte to inputfile to outputfile byte[] buffer = new byte[1024]; int length; while ((length = myinput.read(buffer))>0) { myoutput.write(buffer,0,length); } //Close the streams myoutput.flush(); myoutput.close(); myinput.close(); } @Override public void onCreate(SQLiteDatabase arg0) { // TODO Auto-generated method stub } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // TODO Auto-generated method stub } And Main Activity code is. public class DbActivity extends Activity { /** Called when the activity is first created. */ private static KamaDBAdapter mDbHelper=null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mDbHelper = new KamaDBAdapter(this); TextView tv=(TextView)findViewById(R.id.text); boolean b= mDbHelper.checkdatabase(); if(b==true) { mDbHelper.readDataBase(); try { mDbHelper.openDataBase(); } catch (SQLException e) { e.printStackTrace(); } } try { mDbHelper.copydatabase(); } catch (IOException e) { // TODO Auto-generated catch block throw new Error("Unable to copy database"); } try { mDbHelper.openDataBase(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } String s= mDbHelper.retriveData(); tv.setText(s); } } I m getting error: 09-23 17:29:17.872: ERROR/Database(2658): sqlite3_open_v2("/data/data/com.android.android/databases/mdb12.db", &handle, 2, NULL) failed 09-23 17:29:17.882: ERROR/TAG(2658): DatabaseNotFound android.database.sqlite.SQLiteException: unable to open database file How can I fix it? A: it should be DB_NAME="mdb12.sqlite"; instead of DB_NAME="mdb12.db"; A: Try this one instead of ...... public void readDataBase() { this.getReadableDatabase(); } Change and try........ public void readDataBase() { SQLiteDatabase db_Read = null; db_Read = this.getReadableDatabase(); db_Read.close(); } A: Should be like this: DB_NAME="mdb12"; Also unless you are working for android.com DB_PATH = "/data/data/com.android.android/databases/"; is probably wrong. Put correct package name(you can check it from your manifest file)
{ "language": "en", "url": "https://stackoverflow.com/questions/7528774", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: User specific dashboard in Sharepoint So I'm building dashboard that consists of more sections. I'm planning to build each section as a web-part. Dashboard is going to be Site Page. Problem is I have more levels of users, and these levels have different dashboards (different sections and layout). How to make site page dynamic and user specific? A: there are two approaches you could use. I think the best one is the AudienceFilter where you could make elements available for various audiences. Another apporach is to group users into SharePoint groups and build a GroupTrimmedControl SharePoint already offers the SPSecurityTrimmedControl which is a great starting point. But when you're not limited to MSF (SharePoint Foundation) you should have a look at the AudienceFilter.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528777", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Displaying a string in two lines in crystal report How can I display string in two lines like AlphaBravo is a string i am receiving in crystal report i want to display it as:- Alpha Bravo The code is as follows in my content field Replace (Alpha@Bravo,'@',' + Chr(13) + ') The above didnt work for me A: The code which you have given in your edit is correct but little modification, see below code Replace (Alpha@Bravo,'@', Chr(10)) or Replace (Alpha@Bravo,'@', Chr(13))
{ "language": "en", "url": "https://stackoverflow.com/questions/7528778", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Do I include temporial events in UML Use Case diagrams? Suppose a system will generate reports every month. In the event table, I capture that event, but do I include that in a Use Case diagram? If so how? Do all entries in an event table need to have a place in the use case diagram? A: No: the event table contains the use cases, but the use case diagrams don't dontain the events which trigger them, just the actors involved in each use case. When you elaborate the use cases, you can add the event as a Receive Event at the beginning of the activity (provided you're using activity diagrams for elaboration). As to the second part of your question, if by "entries" you mean use cases, then yes: they all have to be shown in use case diagrams, because they explain how each actor interacts with the system. But you are of course free to use as many diagrams as you wish, and it's also a good idea to group the use cases into packages. One way of grouping would be into packages "external", "internal" and "temporal", but whether that's suitable in your specific case is impossible to answer without the actual list of use cases. A: In case your system generate report monthly, I suggest using the "System Timer" as the actor who trigger this use case. You can read more on this article http://www.umlchannel.com/en/uml/item/24-use-case-actor-system-timer/24-use-case-actor-system-timer
{ "language": "en", "url": "https://stackoverflow.com/questions/7528790", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Edit Text and its curser position? Is it possible in Edit Text view in android that we write the text in middle of the edit text view, like in MS Word. means that Writing alignment right,left our middle of the view? A: In xml file Use: android:gravity="top | bottom | left | right | center" A: Yes. Set the gravity of the edittext to center. A: use public int getSelectionStart () and public int getSelectionEnd (), more on http://developer.android.com/reference/android/widget/TextView.html#getSelectionStart() A: Yes, try this code: editText.setGravity(Gravity.CENTER_HORIZONTAL); A: The cursor position part is missing in the body of the question - how is that relevant? If you want to set the text centered statically you can use android:gravity="center_horizontal" <EditText android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="1234" android:layout_weight="1" android:id="@+id/editText1" android:gravity="center_horizontal"></EditText> will look like: What is not quite clear in your question is if you want to have a mixture of alignments within one text field, so I assume that one alignment definition is sufficient
{ "language": "en", "url": "https://stackoverflow.com/questions/7528796", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I write data to csv file in columns and rows from a list in python? I have a list of lists and I want to write them in a csv file with columns and rows. I have tried to use writerows but it isn't what I want. An example of my list is the following: [[1, 2], [2, 3], [4, 5]] With this: example = csv.writer(open('test.csv', 'wb'), delimiter=' ') example.writerows([[1, 2], [2, 3], [4, 5]]) I get 1 2 in a cell, 2 3 in a cell, etc. And not 1 in a cell and 2 in the next cell. I need to write this example list to a file so when I open it with Excel every element is in its own cell. My output should be like this: 1 2 2 3 4 5 Each element in a different cell. A: Well, if you are writing to a CSV file, then why do you use space as a delimiter? CSV files use commas or semicolons (in Excel) as cell delimiters, so if you use delimiter=' ', you are not really producing a CSV file. You should simply construct csv.writer with the default delimiter and dialect. If you want to read the CSV file later into Excel, you could specify the Excel dialect explicitly just to make your intention clear (although this dialect is the default anyway): example = csv.writer(open("test.csv", "wb"), dialect="excel") A: Have a go with these code: >>> import pyexcel as pe >>> sheet = pe.Sheet(data) >>> data=[[1, 2], [2, 3], [4, 5]] >>> sheet Sheet Name: pyexcel +---+---+ | 1 | 2 | +---+---+ | 2 | 3 | +---+---+ | 4 | 5 | +---+---+ >>> sheet.save_as("one.csv") >>> b = [[126, 125, 123, 122, 123, 125, 128, 127, 128, 129, 130, 130, 128, 126, 124, 126, 126, 128, 129, 130, 130, 130, 130, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 134, 134, 134, 134, 134, 134, 134, 134, 133, 134, 135, 134, 133, 133, 134, 135, 136], [135, 135, 136, 137, 137, 136, 134, 135, 135, 135, 134, 134, 133, 133, 133, 134, 134, 134, 133, 133, 132, 132, 132, 135, 135, 133, 133, 133, 133, 135, 135, 131, 135, 136, 134, 133, 136, 137, 136, 133, 134, 135, 136, 136, 135, 134, 133, 133, 134, 135, 136, 136, 136, 135, 134, 135, 138, 138, 135, 135, 138, 138, 135, 139], [137, 135, 136, 138, 139, 137, 135, 142, 139, 137, 139, 138, 136, 137, 141, 138, 138, 139, 139, 139, 139, 138, 138, 138, 138, 137, 137, 137, 137, 138, 138, 136, 137, 137, 137, 137, 137, 137, 138, 148, 144, 140, 138, 137, 138, 138, 138, 137, 137, 137, 137, 137, 138, 139, 140, 141, 141, 141, 141, 141, 141, 141, 141, 141], [141, 141, 141, 141, 141, 141, 141, 139, 139, 139, 140, 140, 141, 141, 141, 140, 140, 140, 140, 140, 141, 142, 143, 138, 138, 138, 139, 139, 140, 140, 140, 141, 140, 139, 139, 141, 141, 140, 139, 145, 137, 137, 145, 145, 137, 137, 144, 141, 139, 146, 134, 145, 140, 149, 144, 145, 142, 140, 141, 144, 145, 142, 139, 140]] >>> s2 = pe.Sheet(b) >>> s2 Sheet Name: pyexcel +-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+ | 126 | 125 | 123 | 122 | 123 | 125 | 128 | 127 | 128 | 129 | 130 | 130 | 128 | 126 | 124 | 126 | 126 | 128 | 129 | 130 | 130 | 130 | 130 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 134 | 134 | 134 | 134 | 134 | 134 | 134 | 134 | 133 | 134 | 135 | 134 | 133 | 133 | 134 | 135 | 136 | +-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+ | 135 | 135 | 136 | 137 | 137 | 136 | 134 | 135 | 135 | 135 | 134 | 134 | 133 | 133 | 133 | 134 | 134 | 134 | 133 | 133 | 132 | 132 | 132 | 135 | 135 | 133 | 133 | 133 | 133 | 135 | 135 | 131 | 135 | 136 | 134 | 133 | 136 | 137 | 136 | 133 | 134 | 135 | 136 | 136 | 135 | 134 | 133 | 133 | 134 | 135 | 136 | 136 | 136 | 135 | 134 | 135 | 138 | 138 | 135 | 135 | 138 | 138 | 135 | 139 | +-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+ | 137 | 135 | 136 | 138 | 139 | 137 | 135 | 142 | 139 | 137 | 139 | 138 | 136 | 137 | 141 | 138 | 138 | 139 | 139 | 139 | 139 | 138 | 138 | 138 | 138 | 137 | 137 | 137 | 137 | 138 | 138 | 136 | 137 | 137 | 137 | 137 | 137 | 137 | 138 | 148 | 144 | 140 | 138 | 137 | 138 | 138 | 138 | 137 | 137 | 137 | 137 | 137 | 138 | 139 | 140 | 141 | 141 | 141 | 141 | 141 | 141 | 141 | 141 | 141 | +-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+ | 141 | 141 | 141 | 141 | 141 | 141 | 141 | 139 | 139 | 139 | 140 | 140 | 141 | 141 | 141 | 140 | 140 | 140 | 140 | 140 | 141 | 142 | 143 | 138 | 138 | 138 | 139 | 139 | 140 | 140 | 140 | 141 | 140 | 139 | 139 | 141 | 141 | 140 | 139 | 145 | 137 | 137 | 145 | 145 | 137 | 137 | 144 | 141 | 139 | 146 | 134 | 145 | 140 | 149 | 144 | 145 | 142 | 140 | 141 | 144 | 145 | 142 | 139 | 140 | +-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+ >>> s2[0,0] 126 >>> s2.save_as("two.csv") A: The provided examples, using csv modules, are great! Besides, you can always simply write to a text file using formatted strings, like the following tentative example: l = [[1, 2], [2, 3], [4, 5]] out = open('out.csv', 'w') for row in l: for column in row: out.write('%d;' % column) out.write('\n') out.close() I used ; as separator, because it works best with Excell (one of your requirements). Hope it helps! A: >>> import csv >>> with open('test.csv', 'wb') as f: ... wtr = csv.writer(f, delimiter= ' ') ... wtr.writerows( [[1, 2], [2, 3], [4, 5]]) ... >>> with open('test.csv', 'r') as f: ... for line in f: ... print line, ... 1 2 <<=== Exactly what you said that you wanted. 2 3 4 5 >>> To get it so that it can be loaded sensibly by Excel, you need to use a comma (the csv default) as the delimiter, unless you are in a locale (e.g. Europe) where you need a semicolon. A: import pandas as pd header=['a','b','v'] df=pd.DataFrame(columns=header) for i in range(len(doc_list)): d_id=(test_data.filenames[i]).split('\\') doc_id.append(d_id[len(d_id)-1]) df['a']=doc_id print(df.head()) df[column_names_to_be_updated]=np.asanyarray(data) print(df.head()) df.to_csv('output.csv') Using pandas dataframe,we can write to csv. First create a dataframe as per the your needs for storing in csv. Then create csv of the dataframe using pd.DataFrame.to_csv() API.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528801", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "19" }
Q: Capturing the Enter key I am trying to capture the Enter key as follows, $("#txt1").keypress(function(event){ if(event.which==13) //Also tried using event.keycode $("#add").load("newjsp.jsp?q="+this.value) }) But everytime I press enter, The text gets erased and does not show in the form(#add) it should. How can I do this? Also I encountered a problem in the following code, $("#txt1").keyup(function(event){ $("#add").load("newjsp.jsp?q="+this.value) }) <form> Comment: <input type="text" id="txt1"></input> </form> <p><p></p></p> <form id="add"> </form> When I run this code, the text in the textbox gets added to my form (#add) but as I press the spacebar key, the text is erased (from the #add form and not from the textbox) and then no more text is added. I have tried using keydown and keypress but same problem remains. I cannot understand where the problem lies since this.value gives me the complete value in the textbox! Including the spaces. A: this.value will indeed add the pressed key to the load request. However, your browser might trim the spaces off the requested url turning "q=hello " into "q=hello" You should escape the value before you use it in the request. Take a look at the javascript escape() function here: http://www.w3schools.com/jsref/jsref_escape.asp A: Your first example is the correct one. Except you need to prevent event bubbling after you press 'enter'. Pressing enter by default submits the form. FinalFrag is correct about the spaces $('#txt1').keypress(function(e){ if (e.which===13) { e.preventDefault(); e.stopImmediatePropagation(); $("#add").load("newjsp.jsp", {q: $(this).val()} ); } }); *Editied to reflect Tomalak's comment. A: For the second problem you should use encodeUricomponent() to encode the values so that you can use them in a url: $("#txt1").keyup(function(event){ $("#add").load("newjsp.jsp?q="+encodeURIComponent(this.value)); }) For the first problem you should prevent the default action and stop the propagation: $('#txt1').keypress(function(e){ e.preventDefault(); e.stopImmediatePropagation() if (e.which===13) { $("#add").load("newjsp.jsp?q=" + $(this).val()); } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7528803", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Problem with C char[] swapping I have this short code: #include <stdio.h> void fastSwap (char **i, char **d) { char *t = *d; *d = *i; *i = t; } int main () { char num1[] = "hello"; char num2[] = "class"; fastSwap ((char**)&num1,(char**)&num2); printf ("%s\n",num1); printf ("%s\n",num2); return 0; } The output of this short program is: claso hells and I just don't understand why the last letters of each char[] are swapped. Any ideas? A: fastSwap ((char**)&num1,(char**)&num2); This is undefined behavior. You can't cast a pointer to array of char to a pointer to pointer to char. What you need is: const char* num1 = "hello"; const char* num2 = "class"; fastSwap (&num1,&num2); Also, you'll need to change the declaration of fastSwap and add inner-level const to arguments void fastSwap (const char **i, const char **d) A: I'm assuming you're trying to swap the contents of the num1 and num2 arrays by just manipulating pointers, so that after calling fastswap the contents of num1 will be "class" and num2 will be "hello". If that's the case, then this won't work for a number of reasons. Arrays are not pointers, even though array expressions are often converted to pointer types. Secondly, you cannot modify the value of an array expression. If you want to keep num1 and num2 as arrays (as opposed to pointers to string literals) and be able to swap their contents, you'll need to something more along these lines: void fastswap(char *i, char *d) { while (*i && *d) { char t = *i; *d++ = *i; *i++ = t; } } which will be called as fastswap(num1, num2); A: You are passing pointers to pointers to chars. You probably just want to pass pointers to chars like this: #include <stdio.h> void fastSwap (char *i, char *d) { char t = *d; *d = *i; *i = t; } int main () { char num1[] = "hello"; char num2[] = "class"; fastSwap (num1,num2); printf ("%s\n",num1); printf ("%s\n",num2); return 0; } This swaps the first character of the 2 char arrays.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528811", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I change notice & alert's class? I'm trying to adjust the standard application template in Rails to insert a class around the notice and alert messages, but I can't seem to find an elegant way of doing it. At present, I have the scaffold: <p class="notice"><%= notice %></p> <p class="alert"><%= alert %></p> I want it to only show the surrounding tags if a notice or alert is present. A: Use an if statement. <% if notice %> <p class="notice"><%= notice %></p> <% end %> A: <% flash.each do |name, msg| %> <%= content_tag :div, :id => "flash_#{name}", :class => "my_class" do %> <%= msg %> <% end %> <% end %> Define styling for the .my_class A: Wrap the parts in if like this: <% if alert %> <p class="alert"><%= alert %></p> <% end %> You can also use unless if you like
{ "language": "en", "url": "https://stackoverflow.com/questions/7528815", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Trim scanned images with PIL? What would be the approach to trim an image that's been input using a scanner and therefore has a large white/black area? A: the entropy solution seems problematic and overly intensive computationally. Why not edge detect? I just wrote this python code to solve this same problem for myself. My background was dirty white-ish, so the criteria that I used was darkness and color. I simplified this criteria by just taking the smallest of the R, B or B value for each pixel, so that black or saturated red both stood out the same. I also used the average of the however many darkest pixels for each row or column. Then I started at each edge and worked my way in till I crossed a threshold. Here is my code: #these values set how sensitive the bounding box detection is threshold = 200 #the average of the darkest values must be _below_ this to count (0 is darkest, 255 is lightest) obviousness = 50 #how many of the darkest pixels to include (1 would mean a single dark pixel triggers it) from PIL import Image def find_line(vals): #implement edge detection once, use many times for i,tmp in enumerate(vals): tmp.sort() average = float(sum(tmp[:obviousness]))/len(tmp[:obviousness]) if average <= threshold: return i return i #i is left over from failed threshold finding, it is the bounds def getbox(img): #get the bounding box of the interesting part of a PIL image object #this is done by getting the darekest of the R, G or B value of each pixel #and finding were the edge gest dark/colored enough #returns a tuple of (left,upper,right,lower) width, height = img.size #for making a 2d array retval = [0,0,width,height] #values will be disposed of, but this is a black image's box pixels = list(img.getdata()) vals = [] #store the value of the darkest color for pixel in pixels: vals.append(min(pixel)) #the darkest of the R,G or B values #make 2d array vals = np.array([vals[i * width:(i + 1) * width] for i in xrange(height)]) #start with upper bounds forupper = vals.copy() retval[1] = find_line(forupper) #next, do lower bounds forlower = vals.copy() forlower = np.flipud(forlower) retval[3] = height - find_line(forlower) #left edge, same as before but roatate the data so left edge is top edge forleft = vals.copy() forleft = np.swapaxes(forleft,0,1) retval[0] = find_line(forleft) #and right edge is bottom edge of rotated array forright = vals.copy() forright = np.swapaxes(forright,0,1) forright = np.flipud(forright) retval[2] = width - find_line(forright) if retval[0] >= retval[2] or retval[1] >= retval[3]: print "error, bounding box is not legit" return None return tuple(retval) if __name__ == '__main__': image = Image.open('cat.jpg') box = getbox(image) print "result is: ",box result = image.crop(box) result.show() A: For starters, Here is a similar question. Here is a related question. And a another related question. Here is just one idea, there are certainly other approaches. I would select an arbitrary crop edge and then measure the entropy* on either side of the line, then proceed to re-select the crop line (probably using something like a bisection method) until the entropy of the cropped-out portion falls below a defined threshold. As I think, you may need to resort to a brute root-finding method as you will not have a good indication of when you have cropped too little. Then repeat for the remaining 3 edges. *I recall discovering that the entropy method in the referenced website was not completely accurate, but I could not find my notes (I'm sure it was in a SO post, however.) Edit: Other criteria for the "emptiness" of an image portion (other than entropy) might be contrast ratio or contrast ratio on an edge-detect result.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528816", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Import class only if it's available (e.g. UIPopOverControllerDelegate only on >= 3.2) I've got a class which is implementing the UIPopOverControllerDelegate: #if ios_atleast_32 @interface MyClass : UIViewController <UIPopoverDelegate> #elsif @interface MyClass : UIViewController #endif Is it possible to make determine at runtime if the class is available and therefore should be used as delegate? The same for imports: #if ios_4_available #import "MyClassWhichIsUsingIos4Stuff.h" #endif A: You're building against the latest SDK so you can always #import new stuff and don't need any preprocessor macros there. The same is true for the protocol. Just make sure that before using classes that are not available on all your supported OS versions you check whether that class exists or your app will crash: Class someNewClass = NSClassFromString(@"SomeNewClass"); if (someNewClass) { ... } else { ... } In newer versions of the SDK (don't ask me what exactly is the requirement) you can also do something like this: if ([SomeNewClass class]) { ... } else { ... } A: You can simply implement the protocol regardless of which iOS version will be used at runtime, and it will work fine. A: as the two above mentioned, it's no problem to import classes - but UIKit has to be weakly linked... that was the missing point in my case!
{ "language": "en", "url": "https://stackoverflow.com/questions/7528818", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Simple javascript regex help needed I have a simple regex: \[quote\](.*?)\[\/quote\] Which will replace [quote] by table, tr and td. (and [/quote] by /td, /tr and /table) It works perfectly for multiple separate quotes in the same string: IE: [quote] Person 1 [/quote] Person 3 talking about a quote [quote] Person 2 [/quote] Person 3 talking about another quote. BUT when it tries to replace multiple (non-seperate) quote in the same string: IE: [quote] [quote] Person 1 [/quote] Person 2 quoting person 1 [/quote] Person 3 quoting person 2 and 1 It messes up, (matches the first quote to the first /quote when it should be matching second quote to first /quote and first quote to last /quote) How would I edit the regex so it works in both examples? Thanks alot, James A: Regex isn't a good choice for parsing nested structured text. See this question for JavaScript BBCode parser A: Try this one: \[quote\]{1,}(.*?)\[\/quote\] A: I created an example JavaScript BBCode parser that handles that situation. I think I got around that situation because JavaScript's string replace function can take in another function, so you can make your parser recursively work with smaller sections of the input. However, it's been a while since I've looked at it. You can see it in action here and download it on the same page (the download link is under the header - "You can download the JavaScript module for this here."): http://patorjk.com/bbcode-previewer/
{ "language": "en", "url": "https://stackoverflow.com/questions/7528821", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Intercepting annotated method calls without AOP Is it possible to intercept the execution of a method that is annotated with a custom annotation without using any AOP framework such as AspectJ, Spring AOP, Guice, etc... I'm curious to find out if any of the default java apis can be used for this purpose (such as Reflection). Thanks. A: You cannot directly intercept method calls of existing methods without hooking into e.g., instantiation logic. One approach is to separate instantiation logic into a factory which can employ e.g., a Proxy. public class FooFactry() { private InvocationHandler handler; public FooFactory(InvocationHandler handler) { this.handler = handler; } public Foo newInstance() { return (Foo) Proxy.newProxyInstance(Foo.class.getClassLoader(), new Class[] { Foo.class }, handler); } } You can use a custom InvocationHandler to intercept any method issued on Foo. You could also create your own wrapper to avoid dynamic proxies, class FooWrapper extends Foo{} to achieve the same result. A: It cannot be done using reflection because does not provide any control over execution. But you can write your own agent. You would need to instrument classes, which might be easier using something like BCEL. It is very much with the Java framework and kosher. A: You can use reflection to invoke methods, but you can't use it to intercept method invocations. Likewise, you can create Proxies with dynamic invocation handlers with the Proxy class, but you can't intercept existing code that doesn't target a proxy. So the answer is no.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528826", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Generics and Marshal / UnMarshal. What am I missing here? Better mention this : I'm using Delphi XE2 - but XE or 2010 should do the trick too :-) This Question is now in Quality Central QC#99313 please vote it up :-) As of 10-20-2011 Embarcadero has marked the QC report as RESOLVED. Solution was provided by SilverKnight. But the lack of information from Embarcadero worries me. Since the solution suggests using other source code than the one explained in XE(2) Help system, other forums and CC. But have a look at the QC yourself. Given these type declarations: type TTestObject : Class aList : TStringList; function Marshal : TJSonObject; end; TTestObjectList<T:TestObject> : Class(TObjectList<T>) function Marshal : TJSonObject; // How to write this ? end; I would like to implement a Marshal method for TTestObjectList. To my best knowledge - I should register a converter for TTestObject and for the beauty of it - call Marshal for each element. The Marshal for TTestObject registers this converter: RegisterConverter(TStringList, function(Data: TObject): TListOfStrings var i, Count: Integer; begin Count := TStringList(Data).Count; SetLength(Result, Count); for i := 0 to Count - 1 do Result[i] := TStringList(Data)[i]; end); The Generic TTestObjectList Marshal method: function TTestObjectList<T>.Marshal: TJSONObject; var Mar : TJsonMarshal; // is actually a property on the list. begin Mar := TJsonMarshal.Create(TJSONConverter.Create); try RegisterConverter(TTestObject, function(Data: TObject): TObject begin Result := TTestObject(Data).Marshal; end); Result := Mar.Marshal(Self) as TJSONObject; finally Mar.Free; end; end; Here is a simplified example of using the list. var aTestobj : TTestObject; aList : TTestObjectList<TTestObject>; aJsonObject : TJsonObject; begin aTestObj := TTestObject.Create; // constructor creates and fills TStringlist with dummy data. aJsonObject := aTestObj.Marshal; // This works as intended. aList := TTestObjectList<TTestObject>.Create; aJsonObject := aList.Marshal; // Fails with tkpointer is unknown .... end; Of course I have similar functionality for restoring (unmarshal). But the above code should work - at least to my best knowledge. So if anyone can point out to me : Why the List fails to marshal? I know I have the TJsonMarshal property on my list - but it also has a converter/reverter. Changing to a TTypeStringConverter (instead of TTypeObjectConverter) will return a valid string. But I like the idea of working on a TJsonObject all along. Otherwise I would have the same problem (or something similar) when doing the unmarshalling from a string to TTestObject. Any advice / ideas are most welcome. A: Here is a "workaround" to "fix" the problem on Delphi XE2 (I was able to duplicate the same run time error). Note that when Creating the Marshal variable that the following code is defined in the project: Marshal := TJSONMarshal.Create(TJSONConverter.Create); Changing BOTH lines to this: Marshal := TJSONMarshal.Create; //use the default constructor - which does the same thing as TJSONConvert.Create already resolves the problem - the test application provided by TOndrej then executes without error. A: I'm not sure why you get that error. The following seems to work for me, in Delphi XE: program Project1; {$APPTYPE CONSOLE} uses SysUtils, Classes, Contnrs, Generics.Defaults, Generics.Collections, DbxJson, DbxJsonReflect; type TTestObject = class(TObject) aList : TStringList; function Marshal : TJSonObject; public constructor Create; destructor Destroy; override; end; TTestObjectList<T:TTestObject,constructor> = class(TObjectList<T>) function Marshal: TJSonObject; constructor Create; end; { TTestObject } constructor TTestObject.Create; begin inherited Create; aList := TStringList.Create; aList.Add('one'); aList.Add('two'); aList.Add('three'); end; destructor TTestObject.Destroy; begin aList.Free; inherited; end; function TTestObject.Marshal: TJSonObject; var Marshal: TJSONMarshal; begin Marshal := TJSONMarshal.Create(TJSONConverter.Create); try Marshal.RegisterConverter(TStringList, function (Data: TObject): TListOfStrings var I, Count: Integer; begin Count := TStringList(Data).Count; SetLength(Result, Count); for I := 0 to Count - 1 do Result[I] := TStringList(Data)[I]; end ); Result := Marshal.Marshal(Self) as TJSONObject; finally Marshal.Free; end; end; { TTestObjectList<T> } constructor TTestObjectList<T>.Create; begin inherited Create; Add(T.Create); Add(T.Create); end; function TTestObjectList<T>.Marshal: TJSonObject; var Marshal: TJsonMarshal; begin Marshal := TJSONMarshal.Create(TJSONConverter.Create); try Marshal.RegisterConverter(TTestObject, function (Data: TObject): TObject begin Result := T(Data).Marshal; end ); Result := Marshal.Marshal(Self) as TJSONObject; finally Marshal.Free; end; end; procedure Main; var aTestobj : TTestObject; aList : TTestObjectList<TTestObject>; aJsonObject : TJsonObject; begin aTestObj := TTestObject.Create; aJsonObject := aTestObj.Marshal; Writeln(aJsonObject.ToString); Writeln; aList := TTestObjectList<TTestObject>.Create; aJsonObject := aList.Marshal; Writeln(aJsonObject.ToString); Readln; end; begin try Main; except on E: Exception do begin ExitCode := 1; Writeln(Format('[%s] %s', [E.ClassName, E.Message])); end; end; end.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528829", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: regex (preg_match_all) I can match this string {string} by using this regex : /{(.*)}/s in PHP's preg_replace_callback function. But I don't what to match that string if that string is contained between tags like {tag}{/tag}, For example : I don't want to match {string} in {tag} Anything Here {string} Anything Here {/tag}. Any suggestions (or maybe examples) are most welcome. A: You can play with that : preg_match_all("/(\{string\})|(\{tag\}.+\{.+tag\})/", $str, $m); echo "<pre>"; print_r($m); echo "</pre>"; As you will see, that expression will return a m with three array elements. The second array ellement contain all the {string} that are not into {tag}....{string}....{/tag}
{ "language": "en", "url": "https://stackoverflow.com/questions/7528834", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Efficiently generating a document index for a large number of small documents in a large file Goal I have a very large corpus of the following format: <entry id=1> Some text ... Some more text </entry> ... <entry id=k> Some text ... Some more text </entry> There are tens of millions of entries for this corpus, and more for other corpora I want to deal with. I want to treat each entry as a separate document and have a mapping from words of the corpus to the list of documents they occur in. Problem Ideally, I would just split the file into separate files for each entry and run something like a Lucene indexer over the directory with all the files. However, creating millions and millions of files seems to crash my lab computer. Question Is there a relatively simple way of solving this problem? Should I keep all the entries in a single file? How can I track where they are in the file for use in an index? Should I use some other tool than separate files for each entry? If it's relevant, I do most of my coding in Python, but solutions in another language are welcome. A: Well, keeping all entries in a single file is not a good idea. You can process your big file using generators, so as to avoid memory issues, entry by entry, and then I'd recommend storing each one in a database. While on the process, you can dynamically construct all the relevant stuff, such as term frequencies, document frequencies, posting lists etc, which you can also save in a database. This question might have some useful info. Take also a look at this to get an idea.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528835", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to change view from tab view to normal view in android How can we enter from Tab view to normal view in android.After clicking a tab we need to enter in the next view which don't need to have tab bar. A: set listener to the tab.In the listener start new activity tabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() { // @Override public void onTabChanged(String arg0) { if(arg0.equals("tabname")) { Intent intent=new Intent(Activityname.this,newactivityname.class); startActivity(intent); } } }); where tabhost is the object of TabHost and Activityname is the name of your activity,tabname is the name of your tab A: Well the whole point of a tab view is that you can click the tab and it will have some data in it then click another it will have other data. If you click the tab and it brings you to a new screen then its a waste of time using a tab view just create 3 buttons which launch a new intent. Perhaps im reading the question wrong. In any way here is a helpful guide for setting up a tab view in android you can mess with this a bit to get what you want. http://nerdburglars.net/tutorial.php?ID=8
{ "language": "en", "url": "https://stackoverflow.com/questions/7528846", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Are end of string regex's optimized in .NET? Aside: Ok, I know I shouldn't be picking apart HTML like this with a regex, but its the simplest for what I need. I have this regex: Regex BodyEndTagRegex = new Regex("</body>(.*)$", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Multiline); Notice how I'm looking for the end of the string with $. Are .NET's regular expressions optimized so that it doesn't have to scan the entire string? If not, how can I optimize it to start at the end? A: You can control it itself by specifying Right-to-Left Mode option, but regex engine does not optimize it itself automatically until you do it yourself by specifying an option: I believe key point is: By default, the regular expression engine searches from left to right. You can reverse the search direction by using the RegexOptions.RightToLeft option. The search automatically begins at the last character position of the string. For pattern-matching methods that include a starting position parameter, such as Regex.Match(String, Int32), the starting position is the index of the rightmost character position at which the search is to begin. Important: The RegexOptions.RightToLeft option changes the search direction only; it does not interpret the regular expression pattern from right to left
{ "language": "en", "url": "https://stackoverflow.com/questions/7528852", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How to attach submit listener to all forms including those in iframes and nested iframes I want to attach an event listener to every form on my site so that when a form is submitted, a confirm box will pop up asking if the user is sure they want to proceed. If the user is not sure, I don't want the form to fire. So far I have this code: window.onload = function() { for(var i=0; i<document.forms.length; i++){ document.forms[i].addEventListener("submit",formSubmit,false); } } function formSubmit(e) { if (confirm("Are you sure?")) { return true; } return false; } Notes: * *I can't use jQuery *I can't use an onDOMReady type function because the iframes may not have loaded yet - so window.onload is my only option (I think?) *This code does not work because when the "Are you sure?" confirm box pops up when I submit a form, whichever button I click, the form still submits. *This code also does not work because it does not pick up forms inside iframes. I need to not only catch forms within iframes, but also forms that may be within iframes that are within iframes... I've tried this: var frame = document.getElementById("frameID").contentDocument; for(var i=0; i<frame.forms.length; i++){ frame.forms[i].addEventListener("submit",formSubmit,false); } But it only works for the first frame, and it doesn't seem to work if I have got to the page via the "Back" button. Is that something to do with the way wondow.onload works? Thanks for your help in advance! Update From the answer given by @Jan Pfeifer I have the following code which solves the problem of the form still submitting even when you choose "Cancel", but it does not add the listener to every form in every frame properly. I'm starting a bounty for this - can anyone make it work for nested iframes in every browser? function attach(wnd,handler){ for(var i=0; i<wnd.document.forms.length; i++){ var form = wnd.document.forms[i]; form.addEventListener('submit',handler,false); } for(var i=0; i<wnd.frames.length; i++){ var iwnd = wnd.frames[i]; attach(iwnd,handler); } } function formSubmit(e){ if(!confirm('Are you sure?')) { e.returnValue = false; if(e.preventDefault) e.preventDefault(); return false; } return true; } window.addEventListener('load',function(){attach(window,formSubmit);},false); A: So I've managed to solve this myself. There were two main problems: * *wnd.frames[i] was sometimes returning the window of the iframe and sometimes the document depending on the browser - I've changed the method of selecting the iframe to wnd.document.getElementsByTagName("iframe")[i].contentWindow which is more reliable if a bit wordy. *Chrome and IE both stopped execution if the returned window had an undefined document or name so I've added a simple if statement to catch this. The result is this: function attach(wnd,handler){ if (!(wnd.document === undefined)) { for(var i=0; i<wnd.document.forms.length; i++){ var form = wnd.document.forms[i]; form.addEventListener('submit',handler,false); alert("Found form in " + wnd.name); } for(var i=0; i<wnd.document.getElementsByTagName("iframe").length; i++){ var iwnd = wnd.document.getElementsByTagName("iframe")[i].contentWindow; alert("Found " + iwnd.name + " in " + wnd.name); attach(iwnd,handler); } } } function formSubmit(e){ if(!confirm('Are you sure?')) { e.returnValue = false; if(e.preventDefault) e.preventDefault(); return false; } return true; } window.addEventListener('load', function(){ attach(window,formSubmit); },false); A: You will need recursion. attach function will add handler to every form and call itself on every iframe to do the same with it. Return value is not passed, so you will need to cancel the event manually. UPDATE Corrected errors function attach(wnd,handler){ for(var i=0; i<wnd.document.forms.length; i++){ var form = wnd.document.forms[i]; form.addEventListener('submit', handler,false); } for(var i=0; i<wnd.frames.length; i++){ var iwnd = wnd.frames[i]; attach(iwnd,handler); } } function formSubmit(e){ if(!confirm('Are you sure?')) { e.returnValue = false; if(e.preventDefault) e.preventDefault(); return false; } return true; } window.addEventListener('load', function(){attach(window,formSubmit);},false);
{ "language": "en", "url": "https://stackoverflow.com/questions/7528857", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Can I extract the CLSID of a type from a typelib on the command line? I have an ActiveX control implemented as a DLL; this DLL has the type library embedded as a resource. I know that the type library contains a coclass with a special name (say "FooPlugin.BarClass"). How can I extract the CLSID of this class on the command line if I have just the DLL at the name of the class whose CLSID I would like to extract? I saw the similiar question How to Extract TypeLib from a COM exe on Command Line which made me start tinkering with the tlbimp.exe and tlbexp.exe tools - but without success so far. Maybe I need a third tool to get a textual representation of the binary type library files or something? A: * *You can develop an automation tool which starts from LoadTypeLib and gets you what you need *You can register the DLL (or expect it to be registered) and walk through registry HKCR for the information you want, such as starting with identifying type library identifier for your file, enumerating classes referencing type library, choosing those of your interest
{ "language": "en", "url": "https://stackoverflow.com/questions/7528861", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Exception NoClassDefFoundError for CacheProvider I'm kind of new in Spring and hibernate so I'm trying to implement some simple web application based on Spring 3 + hibernate 4 while I start tomcat I have this exception: java.lang.NoClassDefFoundError: org/hibernate/cache/CacheProvider at java.lang.Class.getDeclaredMethods0(Native Method) at java.lang.Class.privateGetDeclaredMethods(Class.java:2427) at java.lang.Class.getDeclaredMethods(Class.java:1791) ... Caused by: java.lang.ClassNotFoundException: org.hibernate.cache.CacheProvider at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1678) at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1523) I've found that this class was in hibernate-core for hibernate 3 but I've not found it in hibernate 4. The part of my context.xml for persistence: <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="org.hsqldb.jdbcDriver"/> <property name="url" value="jdbc:oracle:thin:@IP_Address:SID"/> <property name="username" value="xxx"/> <property name="password" value="xxx"/> <property name="initialSize" value="5"/> <property name="maxActive" value="20"/> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="packagesToScan" value="com.huawei.vms.user"/> <property name="hibernateProperties"> <props> <prop key="dialect">org.hibernate.dialect.Oracle10gDialect</prop> </props> </property> </bean> Please help me to figure out why it's trying to load CacheProvider because I dont have any settings for that in context.xml and which jar I have to add in my project. Thanks! A: updating AnnotationSessionFactoryBean to hibernate4 works perfect. Also make sure your transactionManager also points to hibernate4, <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <property name="packagesToScan" value="PACKAGE_NAME"></property> <property name="hibernateProperties"> <props> <prop key="dialect">org.hibernate.dialect.MySQLDialect</prop> </props> </property> </bean> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> A: Change your AnnotationSessionFactoryBean to org.springframework.orm.hibernate4.LocalSessionFactoryBean (Hibernate 4) and you'll be good to go. The AnnotationSessionFactoryBean was replaced with the LocalSessionFactoryBean as it does class path scanning now. A: This might be due to changes introduced in Hibernate 4 that are not compatible with Spring support for Hibernate. This issue talks about adding separate package to support hibernate 4. You will need spring 3.1 for this. The other option is to stick to hibernate 3 if you don't need any specific feature introduced in 4. A: A really simple problem that will cause the same error is simply to have a mismatch between the hibernate version in the pom (4.something) and the version specified in the spring config.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528862", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "93" }
Q: Is it possible to use an Internet Explorer plugin as a control in a WinForms project? As the topic asks. Is it possible for me to use any plugin written for Internet Explorer in my WinForms project without having to use the WebBrowser control? (I want to be able to use the IBM AFP viewer in my own viewer app) A: The paticular plugin is a part of IBM Web Interface for Content Management, it is not supported outside Internet Explorer. You probably want to look though IBM's documents to find if there is any other interface. The AFP2PDF viewer looks like a good choice for an http client with an PDF viewer.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528869", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Only first letter by DataFormatString I have a column when I bind enum: <telerik:GridViewComboBoxColumn Header="N/U" DataMemberBinding="{Binding VehicleCondition}" ItemsSourceBinding="{Binding Source={StaticResource Locator}, Path=CarSalon.VehicleConditions}" IsGroupable="False" DataFormatString="" /> How can I display only first letter by DataFormatString? Or maybe another solution without DataFormatString? A: In this case you want to implement a ValueConverter which will look something like this (using LINQ string extensions): public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { return ((string)value).First().ToString(); } Obviously if your input value (VehicleCondition) isn't a string you'll need to do something more complicated. Your XAML will become something like this: <telerik:GridViewComboBoxColumn Header="N/U" DataMemberBinding="{Binding VehicleCondition, Converter={StaticResource initialLetterConverter}}" ... If you need to access other information about the item not just the VehicleCondition then you can change the binding to: <telerik:GridViewComboBoxColumn Header="N/U" DataMemberBinding="{Binding, Converter={StaticResource initialLetterConverter}}" ... which will bind to the object. Your converter then becomes something like: public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { var carSalon = (CarSalon)value; string result = string.Empty; if (carSalon != null && <whatever else you need to test>) { result = temp.VehicleCondition.First().ToString(); } return result; } where you can do any checks on the object or get other properties of the object you need.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528879", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MYSQL REGEXP search in JSON string I'm a beginner in regexp and i try to search in json formatted text, but i cannot make it work right: SELECT DISTINCT tag, body FROM pages WHERE (body REGEXP BINARY '"listeListeOuiNon":".*1.*"') It shows me as results text with "listeListeOuiNon":"1" and "listeListeOuiNon":"1,2" and "listeListeOuiNon":"0,1" as expected, but also "listeListeOuiNon":"2" (not expected) Any idea? Maybe it's because it's greedy, but i'm not sure... Thanks in advance! A: Well, it's quite easy to debug: SELECT '"listeListeOuiNon":"2"' REGEXP BINARY '"listeListeOuiNon":".*1.*"' returns 0 SELECT '"listeListeOuiNon":"1"' REGEXP BINARY '"listeListeOuiNon":".*1.*"' returns 1 SELECT '"listeListeOuiNon":"1,2"' REGEXP BINARY '"listeListeOuiNon":".*1.*"' returns 1 So something is not right at your side... because it just could not return rows where body equals "listeListeOuiNon":"2". But it is possible, that body has several of these statements, something like: body => '"listeListeOuiNon":"1,2", "listeListeOuiNon":"2"' So you have to modify your regexp: '^"listeListeOuiNon":".*1.*"$' Well, then you have to modify your query: SELECT DISTINCT tag, body FROM pages WHERE (body REGEXP BINARY '"listeListeOuiNon":".*1.*"') AND NOT (body REGEXP BINARY '"listeListeOuiNon":"2"') A: I would try to replace the two .* with [^"]*... That'll however only be sufficient if your listeListeOuiNon cannot contain litteral "s, or you'd have to also handle the escape sequence. Basically with the . you'll match any JSON string that has a 1 "after" "listListOuiNon":", even if it's in another field, and yes, that's because it's greedy. A: Returns 0.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528881", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Saving files with slash in file name - objective-c I can't save file with slash in file name. I download file, and if file has slash in the name, it doesn't want to save. For example full name of the song: "H/F ArtistName - Song name.mp3". Is it possible to save files with slash in name? Or how to properly replace slash? A: From another post: NSString *s = @"foo/bar:baz.foo"; NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:@"/:."]; s = [[s componentsSeparatedByCharactersInSet: doNotWant] componentsJoinedByString: @""]; NSLog(@"%@", s); // => foobarbazfoo or just look here A: / is generally used as a separator between files or folders in the operating system. therefore the filename can not contain a slash as that would confuse the H in the name for a folder. The best idea is to replace it with a whitespace or simple delete it to give: "HF ArtistName - Songname.mp3" A: workaround: Xcode 12.3, iOS 14 fileName.replacingOccurrences(of: "/", with: ":") // just have a try... full demo code: public extension Data { func saveToTemporaryDirectory(fileName: String, completionHandler: @escaping (Result<URL, Error>) -> Void) { var localURL = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true) localURL.appendPathComponent(fileName.replacingOccurrences(of: "/", with: ":")) do { try self.write(to: localURL) completionHandler(.success(localURL)) } catch { completionHandler(.failure(error)) } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7528886", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SslStream, BEAST and TLS 1.1 With the recent advent of BEAST (exploits a vulnerability in SSL/TLS1.0 where the initial bytes of the payload are always the same) I looked into the SslStream class to see if it supported TLS 1.1, TLS 1.2, etc. It only supports (SslProtocol) SSL 2 and 3 (which both predate TLS) and TLS 1.0. Given that SslProtocol only advertises support for TLS 1.0 and below, is it at all possible to use SslStream for TLS 1.1 and beyond? A: Looks like an update is in order. As of .NET 4.5, SslProtocol (and consequently SslStream) now supports TLS 1.1 and TLS 1.2. These protocols are enabled by default in 4.6. For 4.5, you'll need to activate them in your SslStream object by using the overloaded AuthenticateAsClient call: sslStream.AuthenticateAsClient(hostname, null, SslProtocols.Tls12 | SslProtocols.Tls11, true);
{ "language": "en", "url": "https://stackoverflow.com/questions/7528887", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Apache Wicket - refreshing ListView triggered from inside the ListView i got the following structure which display editable rows in an html table Panel + WebMarkupContainer - in HTML <tbody wicket:id="container"> + ListView which for each item in the list does (in HTML this) + item.add(new PopTable1Row("Pop1Panel", popTable1Item, ComponentMode.EDIT)); + PopTable1Row component contains + Form + some inputs and a 2 submit buttons (Save, Delete) Now i want to achieve that for example by clicking on delete the list view will AJAX like reload without reloading the whole page. The Delete button deletes a row from a table, so one row should disappear. I achieved reloading the ListView by using AjaxSelfUpdatingTimerBehavior: WebMarkupContainer.add(new AjaxSelfUpdatingTimerBehavior(Duration.seconds(5))); It refreshed the listView every 5 seconds. OK, but now i want to refresh the listView in onSubmit of the for example the Delete Button. And here;s the question: how to do this? I tried in the onSubmit: this.getParent().getParent().getParent().getParent().render(); this.getParent().getParent().getParent().getParent().renderComponent(); But both did not work. A: First you have to set outputId to true in yours listView. So Wicket will generate an id for the list tag, required to be updated by ajax. yourListView.setOutputMarkupId(true); And then in your onSubmit method tell Wicket to repaint the list. Note that in the example the save button is a AjaxLink, but you can use other components. AjaxLink<Void> dltBttn = new AjaxLink<Void>("yourButtonId") { public void onClick(AjaxRequestTarget target) { // your stuff if(target != null) { // tells wicket to repaint your list target.addComponent(yourListViewComponent); } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7528890", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android: View by id? (from Widget Provider) I know only one way to get a view by id: getViewById(R.drawable.imageButton) But how am I supposed to get this imageButton if i don't have an activity (developing a widget application) I am able to get a context. I suppose it is enough to get the view - context contains only one widget isn't it? And if not - then how to get each widget views ? A: For Widgets you have to work with RemoteViews, for example RemoteViews updateViews = new RemoteViews(this.getPackageName(), R.layout.widget); Here you can find a tutorial of how to use them A: Inside onReceive AppWidgetManager mgr = AppWidgetManager.getInstance(context); int[] appWidgetIds = mgr.getAppWidgetIds(new ComponentName(context, YourWidgetProvider.class)); RemoteViews rv = new RemoteViews(context.getPackageName(),R.layout.widget_layout); rv.setImageViewResource(R.id.yourImageView, R.drawable.yourBitmap); mgr.updateAppWidget(appWidgetIds, rv); A: There is no way you can get handle of ImageView. But you can use setImageViewBitmap or setImageViewResource or setImageViewUri from RemoteView class to set the bitmap of ImageView. http://developer.android.com/reference/android/widget/RemoteViews.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7528891", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How does the IMDB search work so fast? There is a search box in header navigation bar (http://www.imdb.com/) and when I type 2 (or 3) letters fast, for less than half a second, I can see 6 results coming out!!?? Does anyone have any idea how can one search a large amount of data and get the result with a picture. :) Are the data read from RAM ? If you don't know for IMDB, this question is about quick search with a large number of data in general (IMDB is just very fast search I found so far), if anyone has any experience with this, it would be of great help to tell me the best way to do such a thing. Thanks in advance. A: I do not know much about, but from my investigation, they do the calculations on a different server. further more, they are all precompile as "json" files. if you go to: "http://sg.media-imdb.com/suggests/a/all.json" all the suggestions for the query "all" (the a in the /a/all is the first letter of the query, so for "hello" it would be /h/hello.json) A: Im just guessing, but I'm suspicious the imdb apps (iPhone, iPad) use some kind of offline (local) search initially. I'm going to look into it...
{ "language": "en", "url": "https://stackoverflow.com/questions/7528892", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to build a pipeline of jobs in Jenkins? In my project, I have 3 web-applications, all depend on one all-commons project. In my Jenkins server, I built 4 jobs, all-commons_RELEASE, web-A_RELEASE, web-B_RELEASE and web-C_RELEASE. The role of these jobs is to build the artifacts, which are deployed on our Nexus. Then, someone retrieve these artifacts in Nexus and deploy them on our dev / homologation servers. What I want, is to have one (additional?) job that will launch all the 4 builds, in a sequential way. This way, once this job is finished, all the RELEASE jobs have been executed. Of course, if one build fails, the process is stopped. My first thought was to indicate the web-A_RELEASE in the Build other projects list of the Post-build Actions of all-commons_RELEASE. Then, web-B_RELEASE is dependent on web-A_RELEASE, and so on. However, I want to be able to start any of them separately, which is not possible if I indicate a dependency on the projects. For example, if I manually start web-B_RELEASE, then web-C_RELEASE will be built after that, which is not what I want... Do you have any idea how I can achieve that, or a plugin to help me to do that? Regards. ps: Jenkins 1.430, and all RELEASE jobs are free-style projects (they mix Maven and bash commands). A: Perhaps you could use the Parametrized Trigger Plugin? Using the plugin you can set the trigger as a build step in your "Pipeline" Job. There is a checkbox "Block until triggered job is finished", which you need to activate. You could simply configure your three jobs to be triggered this way, and the triggering would only occur if you run this new Pipeline Job, so running the other jobs without triggering anything would work fine. This should be exactly what you need. A: Don't know if you've found your answer yet, but for others who are curious: You can create another job build_all, and then have each of the other builds triggered as build steps. The setup you'd want would look like this for build_all, with each build step being "Trigger/Call builds on other projects" * * Build Step 1 : all-commons_RELEASE * Build Step 2 : web-A_RELEASE * Build Step 3 : web-B_RELEASE * Build Step 4 : web-C_RELEASE Make sure you check the "Block until the triggered projects finish their builds" option to ensure the builds happen sequentially. A: Try this Build Flow plugin you can sequentially run or build your job like this : build("job1") build("job2") . . build("job-n")
{ "language": "en", "url": "https://stackoverflow.com/questions/7528894", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Creation of viewmodel for treeview in WPF with grouping of objects I am creating an application for chatting in WPF(C#.net). I have created a class User with following attributes: 1.Company_name 2.Branch 3.Designation 4.User_name I am getting the list of objects of class user. I want to display the users in treeview as: Company name1 -Branch1 -:Designation1 *User name1 *User name2 -Branch2 -:Designation1 *User name3 -:Designation2 *User name4 when user list is refreshed, the tree structure will reloaded. I want to create this tree structure considering users with same parent. I am getting the user list at run time when a new user logs in. How to create such tree? I want to know, how to create such treeview using "ViewModel and display it in WPF window"?? A: Your question is not clear enough, I guess that your question is about how to create a hierarchy from a list of users by grouping on every property. for that purpose you may use linq's grouping functionality. Here is a sample for the first level, you may repeat it in itself to create a hierarchy: var users = new[] { new { CompanyName = "c1", Branch = "b1", Destination = "d1", UserName= "u1", }, new { CompanyName = "c1", Branch = "b1", Destination = "d1", UserName= "u1", }, new { CompanyName = "c1", Branch = "b1", Destination = "d1", UserName= "u1", }, new { CompanyName = "c2", Branch = "b1", Destination = "d2", UserName= "u2", }, }; var data = from u in users group u by u.CompanyName into ug select new { Node = ug.Key, Childs = ug }; foreach (var i in data) { Console.WriteLine(i.Node); foreach (var node in i.Childs) { Console.WriteLine("\t" + node.UserName); } } And this is the code with the nested groupings: var users = new[] { new { CompanyName = "c1", Branch = "b3", Destination = "d1", UserName= "u1", }, new { CompanyName = "c1", Branch = "b1", Destination = "d1", UserName= "u1", }, new { CompanyName = "c1", Branch = "b1", Destination = "d1", UserName= "u1", }, new { CompanyName = "c2", Branch = "b1", Destination = "d2", UserName= "u2", }, }; var data = from u1 in users group u1 by u1.CompanyName into gByCompanyName select new { Node = gByCompanyName.Key, Childs = from u2 in gByCompanyName group u2 by u2.Branch into gByBranch select new { Node = gByBranch.Key, Childs = from u3 in gByBranch group u3 by u3.Destination into gByDestination select new { Node = gByDestination.Key, Childs = from u4 in gByDestination select new { Node = u4.UserName } } } }; foreach (var n1 in data) { Console.WriteLine(n1.Node); foreach (var n2 in n1.Childs) { Console.WriteLine("\t" + n2.Node); foreach (var n3 in n2.Childs) { Console.WriteLine("\t\t" + n3.Node); foreach (var n4 in n3.Childs) { Console.WriteLine("\t\t\t" + n4.Node); } } } } Console.ReadLine(); I hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528896", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to handle the exception? #include<iostream> using namespace std; class test { public: test() { cout<<"hello";} ~test() { cout<<"hi"; throw "const"; } void display() { cout<<"faq"; } }; int main() { test t; try{ } catch(char const *e) { cout<<e; } t.display(); } output: i know by throwing exception from destructor i'm violating basic c++ laws but still i want to know is their any way the exception can be handled. A: Your destructor runs outside the try-catch block - t's scope is the main function. but then raising exceptions from a destructor is a Bad IdeaTM. A: The creation of your test object must be done inside the try block: try { test t; t.Display(); } and a full version: #include<iostream> using namespace std; class test { public: test() { cout << "hello" << endl; } ~test() { cout << "hi" << endl; throw "const"; } void display() { cout << "faq" << endl; } }; int main() { try { test t; t.display(); } catch(char const *e) { cout << e << endl; } } A: There's nothing in your try block. Try this: try { test t; } catch(char const *e) { cout << e; } Also, in general throwing an exception in a destructor is a bad idea (as with most rules, there are exceptions). A: Why not just call the destructor function explicitly in try block?
{ "language": "en", "url": "https://stackoverflow.com/questions/7528898", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: After insert, update timestamp trigger with two column primary key I have a simple details table like so: listid custid status last_changed The primary key consists of both listid and custid. Now I'm trying to setup a trigger that sets the last_changed column to the current datetime every time an insert or update happens. I've found lots of info on how to do that with a single PK column, but with multiple PKs it gets confusing on how to correctly specify the PKs from the INSERTED table. The trigger has to work in SQL Server 2005/2008/R2. Thanks for a working trigger code! Bonus would be to also check if the data was actually altered and only update last_changed in that case but for the sake of actually understanding how to correctly code the main question I'd like to see this as a separate code block if at all. A: Hmm.... just because the primary key is made up of two columns shouldn't really make a big difference.... CREATE TRIGGER dbo.trgAfterUpdate ON dbo.YourTable AFTER INSERT, UPDATE AS UPDATE dbo.YourTable SET last_changed = GETDATE() FROM Inserted i WHERE dbo.YourTable.listid = i.listid AND dbo.YourTable.custid = i.custid You just need to establish the JOIN between the two tables (your own data table and the Inserted pseudo table) on both columns... Are am I missing something?? ..... A: CREATE TRIGGER dbo.trgAfterUpdate ON dbo.YourTable AFTER INSERT, UPDATE AS UPDATE dbo.YourTable SET last_changed = GETDATE() FROM Inserted i JOIN dbo.YourTable.listid = i.listid AND dbo.YourTable.custid = i.custid WHERE NOT EXISTS (SELECT 1 FROM Deleted D Where D.listid=I.listid AND D.custid=i.custid AND (D.status=i.status) Here i assuming that stasus column is not nullable. If yes, you should add additional code to check if one of columns is NULL A: You can check every field in trigger by comparing data from inserted and deleted table like below : CREATE TRIGGER [dbo].[tr_test] ON [dbo].[table] AFTER INSERT, UPDATE AS BEGIN DECLARE @old_listid INT DECLARE @old_custid INT DECLARE @old_status INT DECLARE @new_listid INT DECLARE @new_custid INT DECLARE @new_status INT SELECT @old_listid=[listid], @old_custid=[custid], @old_status = [status] FROM [deleted] SELECT @new_listid=[listid], @new_custid=[custid], @new_status = [status] FROM [inserted] IF @oldstatus <> @new_status BEGIN UPDATE TABLE table SET last_changed = GETDATE() WHERE [listid] = @new_listid AND [custid] = @new_custid END END
{ "language": "en", "url": "https://stackoverflow.com/questions/7528899", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Py2exe bundling files into a single exe I'm having some trouble getting Py2exe to bundle all the files into a single .exe. It works fine for me when I don't bundle them together. So this is the setup.py script I use when I'm not bundling them together, and it always works: from distutils.core import setup import py2exe setup(console=['test.py']) So I wanted to bundle all the files into a single executable, so I used this setup.py script for that, and this is the one that doesn't work: from distutils.core import setup # I took this off the Internet import py2exe, sys, os sys.argv.append('py2exe') setup( options = {'py2exe': {'bundle_files': 1}}, windows = [{'script': "test.py"}], zipfile = None, ) When I run this script, a dist directory is created with the test.exe file. If I execute it by typing "test.exe" this error message pops up: See the logfile 'c:\Python26\dist\test.ext.log' for details And this is the contents of that logfile: Traceback (most recent call last): File "test.py", line 1, in <module> EOFError: EOF when reading a line So does anyone know how I can do this? I just want to bundle all the files Py2exe generates with test.py into a single executable. I know it can do this. Or are there any other ways in which this can be done? A: just from the errorlog message, could you try again after assuring the last line of test.py ends with a carriage return? (press enter after the last line in test.py and save again)
{ "language": "en", "url": "https://stackoverflow.com/questions/7528904", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: function to replace strings except images with alt need to be adjust i have my own SEO function it used to replace a word in string to clickable link this is the function function myseo($t){ $url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']; $a = array('computer','films', 'playstation'); $uu = count($a); $theseotext = $t; for ($i = 0; $i < $uu; $i++) { $theseotext = str_replace($a[$i], '<a href="'.$url.'" title="'.$a[$i].'">'.$a[$i].'</a>', $theseotext); } return $theseotext; } it's working great with strings but when there is an image inside the string and this image have ALT="" or somtime TITLE="" the code got error and the images not showing. this image before do the seo function: <img src="mypic.jpg" alt="this is my computer pic" title="this is my computer pic" /> the image after do the seo function <img src="mypic.jpg" alt="this is my <a href="index.php" title="computer">computer</a> pic" title="this is my <a href="index.php" title="computer">computer</a>pic" /> is there any way to let the code do not replace the word if it inside the TITLE or the ALT. A: You can't make the str_replace approach context-sensitive. Using a DOM parser is obviously overkill as usual. But the simple workaround would be to just filter text content between existing tags. Meaning you need a wrapper call around your existing rewrite function. This might suffice: $html = preg_replace_callback('/>[^<>]+</', 'myseo', $html); // Will miss text nodes before the first, or after the last tag. You would have to adapt your callback slightly: function myseo($t) { $theseotext = $t[0];
{ "language": "en", "url": "https://stackoverflow.com/questions/7528906", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: SQL equivalent of Math.Floor() in c# I just want to convert 10.111 to 10 based on some condition in the following Query Select case when 2=1 then CONVERT(decimal(10,3), 10.111) else CONVERT(decimal(10,0), 10.111) end But it return 10.000 How can i get 10? A: The CASE expression as a whole must all evaluate to the same datatype. The only way of having one branch evaluate to decimal(10,3) and the other to a different datatype would be to do a cast to sql_variant Select case when 2=1 then CONVERT(decimal(10,3), 10.111) else CAST(FLOOR( 10.111) AS SQL_VARIANT) end
{ "language": "en", "url": "https://stackoverflow.com/questions/7528907", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to make an ajax form that adds things to db, and has the same page be updated? I have a sandbox where I am trying to create a form where a person can add data, and the flow I want is an ajax call that add things to the database, and without refreshing the page, another panel in the original page gets updated with the added information. How can I pull this off? I currently don't see any such exact examples just by googling. A: One simple example (jQ). Bind the JS functionName with some event, on click/submit or something else. function functionName(val1, val2, and so on) { $.get('/ServletOrPhpFileOrSomeOther?valueOne=' + val1+ '&valueTwo=' + val2 + '&timestamp=' + $.timestamp(), function(data) { //data is the return stuff from you ServletOrPhpFileOrSomeOther //do something with it... example $('#ElementToUpdate').html(data); } ); } On the server side 'ServletOrPhpFileOrSomeOther' compute the values and return someting back. Instead of passing values val1, val2 and so on you can read the form values within the function if you prefer. I used the timeStamp as a dummy because i had some issues with values not getting updated. You can try without. A: Have a look at agiletoolkit.org - it is a php framework that provides out of the box crud that does exactly what you are looking for - it opens a jquery dialog for edit and add and makes Ajax calls in the background to refresh a grid with the data. A: You can try this url :http://www.9lessons.info/2009/04/submit-form-jquery-and-ajax.html In join.php, after insert,you can use a select * from tablename and be listed. that you can display a ajax response in another panel of same page.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528909", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Loading UserControl to the region of the Window on ComboBox change I have got ComboBox which is populated with collection of customTypes. On comboBox change, I would like to load/change content in the particular region so that it loads related data for the selected ComboBox item (it could be in the form of loading userControl or I i dont mind specifying DataTemplate for it). It is similar to this question WPF Load Control question. But in this question, he is talking about individual DataTemplates in the actual Listbox, while I am talking about populating certain window region on ComboBox change. I am using MVVM (and not PRISM) .Net 3.5. A: U could use ContentControl which is the placeholder for the actual Content that is dynamically decided as per combobox selection. The follwoing code is just for guidance <Window ...> <Window.Resources> <MyView1 x:Key="MyView1" /> <MyView2 x:Key="MyView2" /> </Window.Resources> ... <ComboBox x:Name="MyCombo"> <ComboBox.ItemsSource> <sys:String>"MyView1"</sys:String> <sys:String>"MyView2"</sys:String> .... </ComboBox.ItemsSource> </ComboBox> ... <!-- This is where your region is loaded --> <ContentControl> <ContentControl.Style> <Style TargetType="{x:Type ContentControl}"> <Style.Triggers> <DataTrigger Binding="{Binding Path=SelectedItem, ElementName=MyCombo}" Value="MyView1"> <Setter Property="Content" Value="{StaticResource MyView1}" </DataTrigger> <DataTrigger Binding="{Binding Path=SelectedItem, ElementName=MyCombo}" Value="MyView2"> <Setter Property="Content" Value="{StaticResource MyView2}" </DataTrigger> </Style.Triggers> </Style> </ContentControl.Style> </ContentControl> </Window> The data loading can be part of the MyView1 and MyView2 user control's constructor or your main UI's data context view model. A: As far as I understand the question is how to change underlying data being bound to UI and not a DataTemplate only. You can use EventSetter which will be handled in code behind where you can switch DataContext for a region you've mentioned: <ComboBox> <ComboBox.Resources> <Style TargetType="ComboBoxItem"> <EventSetter Event="Selector.SelectionChanged" Handler="YourHandler"/> </Style> </ComboBox.Resources> </ComboBox> But from MVVM perspectives it could be not perfect solution so you can introduce your own ComboBox class wich is Command aware, see this SO post: WPF command support in ComboBox In this way you can decouple logic from UI using Command.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528912", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Persisting Checklists on a UITableView using NSUserDefults I have a very simple table view which shows a list of days. Once the user selects which days are relevant to them this data is saved in NSUserdefaults. I then need the check marks to remain once the user has exited then re-entered the table view. I am very close to getting my desired functionality - I can save the array of check marked items and get it to persist using NSUserDefaults but I don't know how to make these selections persist (keep a check mark next to the selected item) once a user has exited then re-entered the table view. I know that I need to edit the cellForRowAtIndexPath method but I am not sure exactly what to do. Any help would be greatly appreciated. I have attached my code below: #import "DayView.h" @implementation DayView @synthesize sourceArray; @synthesize selectedArray; - (id)init { self = [super initWithStyle:UITableViewStyleGrouped]; if (self) { // Custom initialization [[self navigationItem] setTitle:@"Days"]; [[self tableView] setBackgroundColor:[UIColor clearColor]]; } return self; } - (void)viewWillDisappear:(BOOL)animated { // create a standardUserDefaults variable NSUserDefaults * standardUserDefaults = [NSUserDefaults standardUserDefaults]; // Convert array to string NSString *time = [[selectedArray valueForKey:@"description"] componentsJoinedByString:@","]; // saving an NSString [standardUserDefaults setObject:time forKey:@"string"]; NSLog(@"Disapear: %@", time); } - (void)didReceiveMemoryWarning { // Releases the view if it doesn't have a superview. [super didReceiveMemoryWarning]; // Release any cached data, images, etc that aren't in use. } #pragma mark - View lifecycle - (void)viewDidLoad { [super viewDidLoad]; // create a standardUserDefaults variable NSUserDefaults * standardUserDefaults = [NSUserDefaults standardUserDefaults]; // getting an NSString object NSString *myString = [standardUserDefaults stringForKey:@"string"]; NSLog(@"Appear: %@", myString); NSMutableArray * tempArray = [[NSMutableArray alloc] init]; [self setSelectedArray:tempArray]; [tempArray release]; NSArray * tempSource = [[NSArray alloc] initWithObjects:@"Monday", @"Tuesday", @"Wednesday", @"Thursday", @"Friday", @"Saturday",nil]; [self setSourceArray:tempSource]; [tempSource release]; [self.tableView reloadData]; } #pragma mark - #pragma mark Table view data source // Customize the number of sections in the table view. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } // Customize the number of rows in the table view. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [self.sourceArray count];; } // Customize the appearance of table view cells. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; } NSString *time = [sourceArray objectAtIndex:indexPath.row]; cell.textLabel.text = time; if ([self.selectedArray containsObject:[self.sourceArray objectAtIndex:indexPath.row]]) { [cell setAccessoryType:UITableViewCellAccessoryCheckmark]; } else { [cell setAccessoryType:UITableViewCellAccessoryNone]; } NSLog(@"Selected Days: %@", selectedArray); return cell; } - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { return @"Which times you are available?"; } #pragma mark - #pragma mark Table view delegate - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { if ([self.selectedArray containsObject:[self.sourceArray objectAtIndex:indexPath.row]]){ [self.selectedArray removeObjectAtIndex:[self.selectedArray indexOfObject: [self.sourceArray objectAtIndex:indexPath.row]]]; } else { [self.selectedArray addObject:[self.sourceArray objectAtIndex:indexPath.row]]; } [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone]; [tableView deselectRowAtIndexPath:indexPath animated:YES]; } - (void)viewDidUnload { [super viewDidUnload]; // Release any retained subviews of the main view. // e.g. self.myOutlet = nil; } - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { // Return YES for supported orientations return (interfaceOrientation == UIInterfaceOrientationPortrait); } @end A: Create your tempSource as follows: NSMutableArray * tempSource = [[NSMutableArray alloc] init]; NSArray *daysOfWeek = [NSArray arrayWithObjects:@"Monday", @"tuestay", @"wednesday", @"thursday", @"friday", @"saturday", @"sunday",nil]; for (int i = 0; i < 7; i++) { NSString *dayOfWeek = [daysOfWeek objectAtIndex:i]; NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:dayOfWeek, @"day", [NSNumber numberWithBool:NO], @"isSelected",nil]; [tempSource addObject:dict]; } [self setSourceArray:tempSource]; [tempSource release]; Then use this Array in cellForRow and didSelect as follows: cellForRow NSDictionary *dayOfWeekDictionary = [sourceArray objectAtIntex:indexPath.row]; cell.textLabel.text = [dayOfWeekDictionary objectForKey:@"day"]; if ([[dayOfWeekDictionary objectForKey:@"isSelected"] boolValue]) [cell setAccessoryType:UITableViewCellAccessoryCheckmark]; else [cell setAccessoryType:UITableViewCellAccessoryNone]; didSelect NSDictionary *dayOfWeekDictionary = [sourceArray objectAtIntex:indexPath.row]; if ([[dayOfWeekDictionary objectForKey:@"isSelected"] boolValue]) [dayOfWeekDictionary setObject:[NSNumber numberWithBool:NO] forKey:@"isSelected"]; else [dayOfWeekDictionary setObject:[NSNumber numberWithBool:YES] forKey:@"isSelected"]; To save this Array use this statement: [[NSUserDefaults standardUserDefaults] setObject:sourceArray forKey:@"array"];
{ "language": "en", "url": "https://stackoverflow.com/questions/7528917", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Emulating CSS3 background-size with jQuery I have a circular image carousel that pretty much covers the whole of the browser viewport. Each carousel item is an image that needs to be rendered in the style of CSS3's background-size: cover for landscape images, and background-size: contain for portrait images. Of course, for browsers that support it, that's what I use and it works fine. I'm trying to implement a jQuery-based fallback for browsers that don't support these CSS3 properties. if (Modernizr.backgroundsize) { // all good, do nothing (except some housekeeping) } else { // emulate background-size:cover $('.slide img').each(function() { iw = $(this).width(); ih = $(this).height(); iratio = iw/ih; if (iw >= ih) { // landscape var newHeight = w / iratio; if (ih<h) { $(this).css({height:newHeight, width:w}); // fix this // use negative margin-left to show center? } else { $(this).css({height:newHeight, width:w}); // set negative margin-top to show the center of the image } } else { // portrait var newWidth = h * iratio; $(this).css({height:h, width:newWidth}); } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7528919", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Server-side clustering for google maps api v3 I am currently developing a kind of google maps overview widget that displays locations as markers on the map. The amount of markers varies from several hundreds up to thousands of markers (10000 up). Right now I am using MarkerClusterer for google maps v3 1.0 and the google maps javascript api v3 (premier) and it works pretty decent for lets say a hundred markers. Due to the fact that the number of markers will increase I need a new way of clustering the markers. From what I read the only way to keep the performance up is moving the clustering from the client-side to the server-side. Does anyone know a good PHP5 library which is able to get this done for me? Atm I am digging deeper into the layer mechanisms of google maps. Maybe there are also a few leading PHP librarys I could start to check out? I also ran across FusionTables but since I need clustering I think this might not be the right solution. Thanks in advance! A: This article has some PHP examples for marker clustering: http://www.appelsiini.net/2008/11/introduction-to-marker-clustering-with-google-maps A: I don't know of a server-side library that'll do the job for you. I can however give you some pointers on how to implement one yourself. The basic approach to clustering is simply to calculate the distance between your markers and when two of them are close enough you replace them with a single marker located at the mid-point between the two. Instead of just having a limitation on how close to each other markers may be, you may also (or instead) choose to limit the number of clusters/markers you want as a result. To accomplish this you could calculate the distance between all pairs of markers, sort them, and then merge from the top until you only have as many markers/clusters as you wish. To refine the mid-point positioning when forming a cluster you may take into account the number of actual markers represented by each of the two to be merged. Think of that number as a weight and the line between the two markers as a scale. Then instead of always choosing the mid-point, choose the point that would balance the scale. I'd guess that this simple form of clustering is good enough if you have a limited number of markers. If your data set (# of markers and their position) is roughly static you can calculate clustering on the server once in a while, cache it, and server clients directly from the cache. However, if you need to support large scale scenarios potentially with markers all over the world you'll need a more sophisticated approach. The mentioned cluster algorithm does not scale. In fact its computation cost would typically grow exponentially with the number of markers. To remedy this you could split the world into partitions and calculate clustering and serve clients from each partition. This would indeed support scaling since the workload can be split and performed by several (roughly) independent servers. The question then is how to find a good partitioning scheme. You may also want to consider providing different clustering of markers at different zoom levels, and your partitioning scheme should incorporate this as well to allow scaling. Google divide the map into tiles with x, y and z-coordinates, where x and y are the horizontal and vertical position of the tile starting from the north-west corner of the map, and where z is the zoom level. At the minimum zoom level (zero) the entire map consist of a single tile. (all tiles are 256x256 pixels). At the next zoom level that tile is divided into four sub tiles. This continues, so that in zoom level 2 each of those four tiles has been divided into four sub tiles, which gives us a total of 16 tiles. Zoom level 3 has 64 tiles, level 4 has 256 tiles, and so on. (The number of tiles on any zoom level can be expressed as 4^z.) Using this partitioning scheme you could calculate clustering per tile starting at the lowest zoom level (highest z-coordinate), bubbling up until you reach the top. The set of markers to be clustered for a single tile is the union of all markers (some of which may represent clusters) of its four sub tiles. This gives you a limited computational cost and also gives you a nice way of chunking up the data to be sent to the client. Instead of requesting all markers for a given zoom level (which would not scale) clients can request markers on a tile-by-tile basis as they are loaded into the map. There is however a flaw in this approach: Consider two adjacent tiles, one to the left and one to the right. If the left tile contains a marker/cluster at its far right side and the right tile contains a marker/cluster at its far left side, then those two markers/clusters should be merged but won't be since we're performing the clustering mechanism for each tile individually. To remedy this you could post-process tiles after they have been clustered so that you merge markers/clusters that lay on the each of the four edges, taking into account each of the eight adjacent tiles for a given tile. This post-merging mechanism will only work if we can assume that no single cluster is large enough to affect the surrounding markers which are not in the same sub tile. This is, however, a reasonable assumption. As a final note: With the scaled out approach you'll have clients making several small requests. These requests will have locality (i.e. tiles are not randomly requested, but instead tiles that are geographically close to each other are also typically accessed together). To improve lookup/query performance you would benefit from using search keys (representing the tiles) that also have this locality property (since this would store data for adjacent tiles in adjacent data blocks on disk - improving read time and cache utilization). You can form such a key using the tile/sub tile partitioning scheme. Let the top tile (the single one spanning the entire map) have the empty string as key. Next, let each of its sub tiles have the keys A, B, C and D. The next level would have keys AA, AB, AC, AD, BA, BC, ..., DC, DD. Apply this recursively and you'll end up with a partitioning key that identifies your tiles, allows quick transformation to x,y,z-coordinates and has the locality property. This key naming scheme is sometimes called a Quad Key stemming from the fact that the partitioning scheme forms a Quad Tree. The locality property is the same as you get when using a Z-order curve to map a 2D-value into a 1D-value. Please let me know if you need more details. A: You could try my free clustering app. It is capable of more pins than the clientside google maps api. It offers kmeans an grid based clustering. https://github.com/biodiv/anycluster
{ "language": "en", "url": "https://stackoverflow.com/questions/7528922", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Fileupload inside detailsview in edit mode Hello i try to add a fileupload inside of a detailsview i attach here some parts from my code: <asp:DetailsView ID="DetailsView1" runat="server" Height="50px" Width="586px" DefaultMode="Edit" AutoGenerateRows="False" BorderColor="White" BorderStyle="None" DataSourceID="EntityDataSource1" GridLines="None" DataKeyNames="UserName" OnItemUpdated="DetailsView1_ItemUpdated" ONItemEditing="DetailsView1_ItemEditing"> then the fileupload control is placed inside of template field: <asp:TemplateField HeaderText="Foto"> <EditItemTemplate> <asp:FileUpload ID="FileUpload1" runat="server" /> </EditItemTemplate> </asp:TemplateField> and the datasource is : <asp:EntityDataSource ID="EntityDataSource1" runat="server" ConnectionString="name=mesteriEntities" DefaultContainerName="mesteriEntities" EnableFlattening="False" EntitySetName="Users" EnableUpdate="True" AutoGenerateWhereClause="True" EnableInsert="True"> <WhereParameters> <asp:SessionParameter Name="UserName" SessionField="New" Type="String" /> </WhereParameters> </asp:EntityDataSource> The code behind: protected void DetailsView1_ItemEditing(object sender, DetailsViewInsertEventArgs e) { FileUpload fu1 = (FileUpload)DetailsView1.FindControl("FileUpload1"); if (fu1 == null) e.Cancel = true; if (fu1.HasFile) { try { string fileName = Guid.NewGuid().ToString(); string virtualFolder = "~/UserPics/"; string physicalFolder = Server.MapPath(virtualFolder); // StatusLabel.Text = "Upload status: File uploaded!"; string extension = System.IO.Path.GetExtension(fu1.FileName); fu1.SaveAs(System.IO.Path.Combine(physicalFolder, fileName + extension)); e.Values["foto"] = System.IO.Path.Combine(physicalFolder, fileName + extension); } catch (Exception ex) { Response.Write(ex.Message); } } else e.Cancel = true; } I'm not sure why doesn't work. It doesn't upload the file on the server and doesn't add reference inside database of the file . Whay i did wrong here? thank you A: As far as I can tell (from looking at the class documentation: DetailsView Class) there is no OnItemEditing event to handle? There is however a DetailsView.ItemUpdating event which looks like it could do the trick: Occurs when an Update button within a DetailsView control is clicked, but before the update operation. Also I think the FileUpload control cannot be found because the FindControl method is not searching the full hierarchy of controls it contains. Try using the following method and modifying your code like so: FileUpload fu1 = (FileUpload)FindControl(DetailsView1, "FileUpload1"); ... private Control FindControl(Control parent, string id) { foreach (Control child in parent.Controls) { string childId = string.Empty; if (child.ID != null) { childId = child.ID; } if (childId.ToLower() == id.ToLower()) { return child; } else { if (child.HasControls()) { Control response = FindControl(child, id); if (response != null) return response; } } } return null; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7528924", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Based on my requirements, should I use NSIS or jprofiler/install4j We have a web application that we need to make easier to deploy for our clients. The current workflow for a fresh install: * *Ensure there is a JRE on machine (32 or 64bit) *Install Tomcat (32 or 64bit) *Create a database in Oracle or SQL Server (we provide SQL scripts for this) *Write some values into our settings table, like hostname. (Can get user to verify these, but dont want user to have to tap them in. *Create a connections properties file (we provide a mini JAR app to help with this) that will sit under Tomcat. *We have two WAR files for our actual web application. These can be split across two machines, but for now, lets assume they both get dumped under Tomcat. *Start Tomcat so that it deploys the WARs This is a tedious process for our users I want to encapsulate it into an installer and have been looking at doing this in NSIS which seems to have a large community, but then also stumbled across install4j, which although seems to be lesser known, is more specific to java based applications. Just wanted to get some feedback from more experiennced users out there on the best choice for platform. I do not want to get half way in, and then realise I have chosen the wrong installer platform. A: Disclaimer: My company develops install4j. First of all, install4j is a commercial tool, so that's a considerable difference to NSIS. Other major differences are: * *install4j is a multi-platform installer builder for Windows, Mac OS X and all POSIX compatible Linux and Unix platforms. *install4j's main focus is for installing Java-based applications, for example it handles the creation of launchers and services and provides several strategies for bundling JREs. Many things that you need for a Java application will work out of the box. *install4j provides its own IDE which focuses on ease of use *Scripting is done in Java. The IDE provides a built-in editor with code-completion and error analysis. Actions, screens and form components have a wide range of "script properties" that allow you to customize the behavior of the installer. For install4j, I can address your single requirements: Ensure there is a JRE on machine (32 or 64bit) In the media wizard, select a JRE bundle. If you select the "dynamic bundle" option, it will only be downloaded if no suitable JRE is found. Install Tomcat (32 or 64bit) I would recommend to simply add the root directory of an existing tomcat installation to your distribution tree. As for the service, you can either use the Tomcat service launcher from the Tomcat distribution or create a service launcher in install4j. In both case you can use the "Install a service" action on order to install the service. Generated services have the advantage that an update installer knows that they are running and automatically shuts them down before installing any new files. Create a database in Oracle or SQL Server (we provide SQL scripts for this) Use the "Run executable or batch file" action in order to run these scripts. Write some values into our settings table, like hostname. (Can get user to verify these, but dont want user to have to tap them in. Any kind of user interaction is done with configurable forms. With a couple of text field form components you can query your settings. This also works transparently in the console installer and the automatically generated response file will allow you to automate installations in unattended mode based on a single execution of the GUI installer. Create a connections properties file (we provide a mini JAR app to help with this) that will sit under Tomcat. If you already have a JAR file which does that, just add it under Installer->Custom Code & Resources and add a "Run script" action to your installer to use the classes in your JAR file. Any user input from form components that has been saved to installer variables can be accessed with calls like context.getVariable("greetingOption") in the script property of the "Run script" action (or any other script in install4j). We have two WAR files for our actual web application. These can be split across two machines, but for now, lets assume they both get dumped under Tomcat. If you just add the Tomcat directory structure to your distribution tree, you can have these WAR file pre-deployed. Otherwise you can use "Copy file" actions to place the WAR files anywhere. Start Tomcat so that it deploys the WARs That's done with the "Start a service" action.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528932", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Reduce the pattern matching type ErrorOrValue = Either InterpreterError Value evaluateExpression :: [Value] -> IR.Expression -> ErrorOrValue evaluateExpression as (IR.Application l r) | Left _ <- arg = arg | Right (Partial ac b as) <- f = foo as f arg | Right _ <- f = Left NonFunctionApplication | otherwise = f where f = evaluateExpression as l >>= forceValue arg = evaluateExpression as r I need to call foo with f and arg making sure that they are not Left. Can I reduce the pattern matching and instead use binds and other monad operations? A: I need to call foo with f and arg making sure that they are not Left. For this, you can use the Applicative instance for Either. foo <$> f <*> arg or liftA2 foo f arg If f and arg are Right values, this will extract those, apply foo to them and give the answer back in a Right constructor. If either f or arg are Left values, that value will be returned (favoring the one from f if both are Left). A: You can use do. Your code checks arg before f, and foo appears to return an ErrorOrValue, so it does not need to be lifted into the Monad. Also, the as that is passed to foo is that extracted from the Partial, not the argument to evaluateExpression. Here is some completely untested code: type ErrorOrValue = Either InterpreterError Value evaluateExpression :: [Value] -> IR.Expression -> ErrorOrValue evaluateExpression as (IR.Application l r) = do arg <- evaluateExpression as r f <- evaluateExpression as l >>= forceValue case f of Partial ac b as -> foo as f arg otherwise -> Left NonFunctionApplication
{ "language": "en", "url": "https://stackoverflow.com/questions/7528936", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Unresolved external symbol referenced in function I realize this is a hard one to answer without providing you with huge amounts of code (which I'll try to spare you). Essentially i'm getting this error in class X, which #includes the class Y header. The class Y header has three definitions for getters // Getters static ID3D10Device* PDevice(); static ID3D10Buffer* PBuffer(); static ID3D10Buffer* IBuffer(); I get three identical errors, all occur in class X. so essentially the error is: Unresolved external symbol ID3D10Device* PDevice() referenced in function (constructor of class X) sorry if that's a bit vague. Any idea why this might be happening? I've googled it but I can only really make an educated guess as to what this error is. A: First of all this is a linker error. This linker error means that the mangled name PDevice et al is not found. Can you make sure that you have an implementation of a function that matches the definition? Also, maybe obvious but just check that you actualy have an implementation. If your implementation is in an external lib, be sure you have included the other lib in your linker. Hope that helps! A: Make sure the files that contain the definition and implementation of class Y are added to the project, so that the linker finds the symbols in the Y.o file A: Make sure you set the dependencies right (add the lib file). In Visual Studio you can do so by Properties -> Linker -> Input -> Additional Dependencies. In the textbox you can now enter the name of your .lib file. A: Another reason this can happen is when both C and C++ source files are used to create a binary. The compiler uses a different naming mechanism for C symbols vs C++ symbols. Please read the "Adding C++ To The Picture" section in this great article. One reason for example is function overloading in C++. The symbol name of the function includes the function signature (argument types and their order). To quote from the article, "all of the information about the function signature is mangled into a textual form, and that becomes the actual name of the symbol as seen by the linker." So, when C code file needs to call a function defined in a C++ file, the C code's object file only mentions the name of that C++ function (doesn't include function signature). The C++ object file however contains the mangled name (which includes the function signature). Hence, the linker reports an "error LNK2019: unresolved external symbol FOO_CPP_FUNC referenced in BAR_C_FUNC". The solution suggested there is to add an extern "C" around the declaration & definition of the C++ function.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528937", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Is there a theorical expression size limit for "or" operator on Regex.Replace Is there a theorical expression size limit for "or" operator on Regex.Replace such as Regex.Replace("abc","(a|c|d|e...continue say 500000 elements here)","zzz") ? Any stackoverflowException on .NET's implementation ? Thanks A: There is no theoretical limit, though each regular expression engine will have its own implementation limits. In this case, since you are using .NET the limit is due to the amount of memory the .NET runtime can use. A regular expression with one million alernations works fine for me: string input = "a<142>c"; var options = Enumerable.Range(0, 1000000).Select(x => "<" + x + ">"); string pattern = string.Join("|", options); string result = Regex.Replace(input, pattern, "zzz"); Result: azzzc It's very slow though. Increasing the number of options to 10 million gives me an OutOfMemoryException. You probably would benefit from looking at another approach. A: The way regular expressions work mean that the memory requirements and performance for a simple a|b|c.....|x|y|z expression as described are not too bad, even for a very large number of variants. However, if your expression is even slightly more complex than that, you could cause the expression to lose performance exponentially, as well as massively growing its memory footprint, as an large number of or options like this can cause it to have to do massive amounts of backtracking if other parts of the expression don't match immediately. You may therefore want to excersise caution either doing this sort of thing. Even if it works now, it would only take a small and relatively innocent change to make the whole thing come to a grinding halt.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528938", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Convert CA-signed JKS keystore to PEM I have a JKS keystore with certicate signed by CA. I need to export it in PEM format in order to use it with nginx. I need to do it in such a way that it includes the whole chain, so that my client can verify the signature. If I do something like: keytool -exportcert -keystore mykestore.jks -file mycert.crt -alias myalias openssl x509 -out mycert.crt.pem -outform pem -in mycert.crt -inform der It only includes the lowest level certificate. The verification fails: $ openssl s_client -connect localhost:443 CONNECTED(00000003) depth=0 /O=*.mydomain.com/OU=Domain Control Validated/CN=*.mydomain.com verify error:num=20:unable to get local issuer certificate verify return:1 depth=0 /O=*.mydomain.com/OU=Domain Control Validated/CN=*.mydomain.com verify error:num=27:certificate not trusted verify return:1 depth=0 /O=*.mydomain.com/OU=Domain Control Validated/CN=*.mydomain.com verify error:num=21:unable to verify the first certificate verify return:1 --- Certificate chain 0 s:/O=*.mydomain.com/OU=Domain Control Validated/CN=*.mydomain.com i:/C=US/ST=Arizona/L=Scottsdale/O=GoDaddy.com, Inc./OU=http://certificates.godaddy.com/repository/CN=Go Daddy Secure Certification Authority/serialNumber=123123 ... (only one certificate!) ... SSL-Session: ... Verify return code: 21 (unable to verify the first certificate) From Java: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target Whereas Jetty with the same JKS keystore prints the following: $ openssl s_client -connect localhost:8084 CONNECTED(00000003) depth=2 /C=US/O=The Go Daddy Group, Inc./OU=Go Daddy Class 2 Certification Authority verify error:num=19:self signed certificate in certificate chain verify return:0 --- Certificate chain 0 s:/O=*.mydomain.com/OU=Domain Control Validated/CN=*.mydomain.com i:/C=US/ST=Arizona/L=Scottsdale/O=GoDaddy.com, Inc./OU=http://certificates.godaddy.com/repository/CN=Go Daddy Secure Certification Authority/serialNumber=1234 1 s:/C=US/ST=Arizona/L=Scottsdale/O=GoDaddy.com, Inc./OU=http://certificates.godaddy.com/repository/CN=Go Daddy Secure Certification Authority/serialNumber=1234 i:/C=US/O=The Go Daddy Group, Inc./OU=Go Daddy Class 2 Certification Authority 2 s:/C=US/O=The Go Daddy Group, Inc./OU=Go Daddy Class 2 Certification Authority i:/C=US/O=The Go Daddy Group, Inc./OU=Go Daddy Class 2 Certification Authority ... SSL-Session: Verify return code: 19 (self signed certificate in certificate chain) Although openssl returns that 19 error, it no longer is an issue for Java HttpsURLConnection and that is all I care about. So, how can I export the whole chain from JKS in a format (e.g. PEM) which works with both nginx server and Java client? What am I missing? A: You can easily convert a JKS file into a PKCS12 file: keytool -importkeystore -srckeystore keystore.jks -srcstoretype JKS -deststoretype PKCS12 -destkeystore keystore.p12 You can then extract the private key and any certs with: openssl pkcs12 -in keystore.p12 A: A rather large problem that I frequently encounter is that, when generating the CSR to get our certificate, the keystore (Sun formatted jks keystore) does not output the .key or provide any facility for obtaining the .key. So I always had ended up with a .pem/.crt with no way of using it with Apache2, which cannot read a JKS keystore like Tomcat can, but instead requires a unpackaged .key + .pem/.crt pair. To start, get a “copy” of your existing keystore and skip to the 5th command below, or create your own like this: C:\Temp>keytool -genkey -alias tomcat -keyalg RSA -keystore keystore.jks -keysize 2048 -validity 730 -storepass changeit Then, optionally, create a 2-year CSR and then import the CSR response, in the next 3 step process: C:\Temp>keytool -certreq -alias mydomain -keystore keystore.jks -file mydomain.csr C:\Temp>keytool -import -trustcacerts -alias root -file RootPack.crt -keystore keystore.jks -storepass changeit C:\Temp>keytool -import -trustcacerts -alias tomcat -file mydomain.response.crt -keystore keystore.jks -storepass changeit To get this working, and if you already have your JKS keystore file that you use for a Tomcat application server, follow the following steps: First, get the DER (binary) formatted certificate into a file called “exported-der.crt”: C:\Temp>keytool -export -alias tomcat -keystore keystore.jks -file exported-der.crt Then, view & verify it: C:\Temp>openssl x509 -noout -text -in exported-der.crt -inform der Now you will want to convert it to PEM format, which is more widely used in applications such as Apache and by OpenSSL to do the PKCS12 conversion: C:\Temp>openssl x509 -in exported-der.crt -out exported-pem.crt -outform pem -inform der Then, download and use ExportPriv to get the unencrypted private key from your keystore: C:\Temp>java ExportPriv <keystore> <alias> <password> > exported-pkcs8.key By now you probably realize, the private key is being exported as PKCS#8 PEM format. To get it into the RSA format that works with Apache (PKCS#12??) you can issue the following command: C:\Temp>openssl pkcs8 -inform PEM -nocrypt -in exported-pkcs8.key -out exported-pem.key A: I'm not sure it is possible to extract the chain with keytool but it can be done with a small Java program: public void extract(KeyStore ks, String alias, char[] password, File dstdir) throws Exception { KeyStore.PasswordProtection pwd = new KeyStore.PasswordProtection(password); KeyStore.PrivateKeyEntry entry = (KeyStore.PasswordKeyEntry)ks.getEntry(alias, pwd); Certificate[] chain = entry.getCertificateChain(); for (int i = 0; i < chain.length; i++) { Certificate c = chain[i]; FileOutputStream out = new FileOutputStream(new File(dstdir, String.format("%s.%d.crt", alias, i))); out.write(c.getEncoded()); out.close(); } } This code should write all certificates of the chain in DER format in the submitted directory.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528944", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: What happens when an integration stream tries to rebase from or deliver to an integration stream it was seeded from? Scenario: Integration stream B (of project B) was created by seeding from baseline A_2.5 of integration A of project A). After parallel development in both the streams the current recommended baseline of A is A_3.2 and B is B_1.5. Question: * *What happens if B tries to rebase from A_3.2? *What happens if B tried to deliver to A? A: * *B tries to rebase from A_3.2 That will trigger a merge between B LATEST content and A_3.2 baseline content. * *B tried to deliver to A It is a merge from every new versions created on B since A_2.5 (which is B's baseline) and A LATEST content. Obviously, is the deliver takes place after the aforementioned rebase, the delta to merge which be much smaller, and the deliver will be shorter and quicker.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528946", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: google-gin a provider needs a dependency. NullPointerException BindingsProcessor.java:498 In my GWT application i'm trying to setup a DI mechanism wihich would allow me to have all the commonly necessary stuff at hand everywhere. I'm using google-gin which is an adaptation of guice for GWT. I have an injector interface defined as this: @GinModules(InjectionClientModule.class) public interface MyInjector extends Ginjector { public PlaceController getPlaceController(); public Header getHeader(); public Footer getFooter(); public ContentPanel getContent(); public EventBus getEventBus(); public PlaceHistoryHandler getPlaceHistoryHandler(); } My injection module is this: public class InjectionClientModule extends AbstractGinModule { public InjectionClientModule() { super(); } protected void configure() { bind(Header.class).in(Singleton.class); bind(Footer.class).in(Singleton.class); bind(ContentPanel.class).in(Singleton.class); bind(EventBus.class).to(SimpleEventBus.class).in(Singleton.class); bind(PlaceController.class).toProvider(PlaceControllerProvider.class).asEagerSingleton(); bind(PlaceHistoryHandler.class).toProvider(PlaceHistoryHandlerProvider.class).asEagerSingleton(); } } When calling MyInjector injector = GWT.create(MyInjector.class); i'm gettign the following exception: java.lang.NullPointerException: null at com.google.gwt.inject.rebind.BindingsProcessor.createImplicitBinding(BindingsProcessor.java:498) at com.google.gwt.inject.rebind.BindingsProcessor.createImplicitBindingForUnresolved(BindingsProcessor.java:290) at com.google.gwt.inject.rebind.BindingsProcessor.createImplicitBindingsForUnresolved(BindingsProcessor.java:278) at com.google.gwt.inject.rebind.BindingsProcessor.process(BindingsProcessor.java:240) at com.google.gwt.inject.rebind.GinjectorGeneratorImpl.generate(GinjectorGeneratorImpl.java:76) at com.google.gwt.inject.rebind.GinjectorGenerator.generate(GinjectorGenerator.java:47) at com.google.gwt.core.ext.GeneratorExtWrapper.generate(GeneratorExtWrapper.java:48) at com.google.gwt.core.ext.GeneratorExtWrapper.generateIncrementally(GeneratorExtWrapper.java:60) at com.google.gwt.dev.javac.StandardGeneratorContext.runGeneratorIncrementally(StandardGeneratorContext.java:647) at com.google.gwt.dev.cfg.RuleGenerateWith.realize(RuleGenerateWith.java:41) at com.google.gwt.dev.shell.StandardRebindOracle$Rebinder.rebind(StandardRebindOracle.java:78) at com.google.gwt.dev.shell.StandardRebindOracle.rebind(StandardRebindOracle.java:268) at com.google.gwt.dev.shell.ShellModuleSpaceHost.rebind(ShellModuleSpaceHost.java:141) at com.google.gwt.dev.shell.ModuleSpace.rebind(ModuleSpace.java:585) at com.google.gwt.dev.shell.ModuleSpace.rebindAndCreate(ModuleSpace.java:455) at com.google.gwt.dev.shell.GWTBridgeImpl.create(GWTBridgeImpl.java:49) at com.google.gwt.core.client.GWT.create(GWT.java:97) The problem is that the PlaceController class actually depends on one of the other dependencies. I've implemented it's provider like this: public class PlaceControllerProvider implements Provider<PlaceController> { private final PlaceController placeController; @Inject public PlaceControllerProvider(EventBus eventBus) { this.placeController = new PlaceController(eventBus); } @Override public PlaceController get() { return placeController; } } what should i change for this to work? A: Old question but having the same problem I kept falling here. I finally found the way to know which class is messing during ginjection. When I launch my app in development mode and put stack to Trace, I noticed there is a step called : "Validating newly compiled units". Under this, I had an error but I didn't notice it since I had to expand 2 nodes which weren't even in red color. The error was "No source code available for type com.xxx.xxxx ...", which was due to a bad import on client side which couldn't be converted to Javascript. Hope this may help other here ! A: While I'm not actually seeing how the errors you're getting are related to the PlaceController being injected, I do see that the provider is returning a singleton PlaceController even if the provider were not bound as an eager singleton or in a different scope. The correct way to write that provider would be: public class PlaceControllerProvider implements Provider<PlaceController> { private final EventBus eventBus; @Inject public PlaceControllerProvider(EventBus eventBus) { this.eventBus = eventBus; } @Override public PlaceController get() { return new PlaceController(eventBus); } } Let guice handle the scoping i.e. "Letting guice work for you". Other than that, I almost bet that your problem is due to the use of asEagerSingleton. I recommend you try this with just in(Singleton.class) and I further posit that you didn't really need the singleton to be eager. It seems others had problems with the behavior too, there's some indication that it has to do with overusing asEagerSingleton or misunderstanding the @Singleton annotation in a few cases. A: I also got a lot of NullPointerException warnings using GIN 1.x with no real explanation of what happened. When I upgraded to gin 2.0 I was told with high accuracy what the error was. You might be helped by upgrading to the 2.0 version that was released a year after you asked this question. A: Had the same problem problem, same trace, and the error was that I used "server" classes in my "client" classes, so GIN can't find these classes. I mean by "server" and "client" the packages in my project. Hope this could help
{ "language": "en", "url": "https://stackoverflow.com/questions/7528952", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Suggest: Non RDBMS database for a noob For a new application based on Erlang, Python, we are thinking of trying out a non-RDBMS database(just for the sake of it). Some of the databases I've researched are Mongodb, CouchDB, Cassandra, Redis, Riak, Scalaris). Here is a list of simple requirements. * *Ease of development - I need to make a quick proof-of-concept demo. So the database needs to have good adapters for Eralang and Python. *I'm working on a new application where we have lots of "connected" data. Somebody recommended Neo4j for graph-like data. Any ideas on that? *Scalable - We are looking at a distributed architecture, hence scalability is important. *For the moment performance(in any form) isn't exactly on top of my list, and I don't think we'll be hitting the limitations of any of the above mentioned databases anytime soon. I'm just looking for a starting point for non-RDBMS database. Any recommendations? A: We have used Mnesia in building an Enterprise Application. Mnesia when in a mode where the tables are Fragmented performs at its best because it would not have table size limits. Mnesia has performed well for the last 1 year and is still on. We have around 15 million records per table on the average and around 24 tables in a given database Schema. I recommend mnesia Database especially the one that comes shipped within Erlang 14B03 at the Erlang.org website. We have used CouchDB and Membase Server (http://www.couchbase.com)for some parts of the system but mnesia is the main data storage (primary storage). Backups have been automated very well and the system scales well against increasing size of data yet tables running under many checkpoints. Its distribution, auto-replication and Complex Data Model enabled us to build the application very quickly without worrying about replication, scalability and fail-over / take-over of systems. Mnesia Scales well and it's schema can be configured and changes while the database is running. Tables can be moved, copied, altered e.t.c while the system is live. Generally, it has all features of powerful systems built on top of Erlang/OTP. When you google mnesia DBMS, you will get a number of books and papers that will tell you more. Most importantly, our application is Web based, powered by Yaws web server (yaws.hyber.org) and we are impressed with Mnesia's performance. Its record look up speeds are very good and the system feels so light yet renders alot of data. Do give mnesia a try and you will not regret it. EDIT: To quickly use it in your application, look at the answer given here A: * *Ease of development - I need to make a quick proof-of-concept demo. So the database needs to have good adapters for Eralang and Python. Riak is written in Erlang => speaks Erlang natively * *I'm working on a new application where we have lots of "connected" data. Somebody recommended Neo4j for graph-like data. Any ideas on that? Neo4j is great for "connected" data. It has Python bindings, and some Erlang adapters How to Use Neo4j From Erlang. Thing to note, Neo4j is not as easy to Scale Out, at least for free. But.. it is fully transactional ( even JTA ), it persists things to disk, it is baked into Spring Data. * *Scalable - We are looking at a distributed architecture, hence scalability is important. For the moment performance(in any form) isn't exactly on top of my list, and I don't think we'll be hitting the limitations of any of the above mentioned databases anytime soon. I believe given your input, Riak would be the best choice for you: * *Written in Erlang *Naturally Distributed *Very easy to develop for/with *Lots of features ( secondary indicies, virtual nodes, fully modular, pluggable persistence [LevelDB, Bitcask, InnoDB, flat file, etc.. ], extremely reliable, built in full text search, etc.. ) *Has an extremely passionate and helpful community with Basho backing it up
{ "language": "en", "url": "https://stackoverflow.com/questions/7528963", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to grant MySQL privileges in a bash script? I need to grant privileges to a database from within a bash script. Some parameters are in the form of variables, say, the username and the password. The command in a mysql shell would look like this: GRANT ALL ON *.* TO "$user"@localhost IDENTIFIED BY "$password"; ...Except that $user and $password would be replaced by their values. Is there a way to perform such a command from within a bash script? Thank you! A: There you go :) #!/bin/bash MYSQL=`which mysql` EXPECTED_ARGS=3 Q1="USE $1;" Q2="GRANT ALL ON *.* TO '$1'@'localhost' IDENTIFIED BY '$2';" Q3="FLUSH PRIVILEGES;" SQL="${Q1}${Q2}${Q3}" if [ $# -ne $EXPECTED_ARGS ] then echo "Usage: $0 dbname dbuser dbpass" exit $E_BADARGS fi $MYSQL -uroot -p -e "$SQL" A: If we don´t know the password we can get it with: cat /etc/psa/.psa.shadow So we can get into mysql without prompt password like: mysql -uadmin -p`cat /etc/psa/.psa.shadow`
{ "language": "en", "url": "https://stackoverflow.com/questions/7528967", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Find out date difference in SQL Server I have from date and to date in my table, I want to know total number of days between two dates without sunday, in SQL Server 2008. give me a query.. Accept my question... A: OK, so work out the total number of days, subtract the total number of weeks, and a fiddle factor for the case where the from date is a Sunday: SELECT DATEDIFF(dd, FromDate, ToDate) -DATEDIFF(wk, FromDate, ToDate) -(CASE WHEN DATEPART(dw, FromDate) = 1 THEN 1 ELSE 0 END) A: try to use this as an example and work it.. DECLARE @StartDate DATETIME DECLARE @EndDate DATETIME SET @StartDate = '2008/10/01' SET @EndDate = '2008/10/31' SELECT (DATEDIFF(dd, @StartDate, @EndDate) + 1) -(DATEDIFF(wk, @StartDate, @EndDate) * 2) -(CASE WHEN DATENAME(dw, @StartDate) = 'Sunday' THEN 1 ELSE 0 END) -(CASE WHEN DATENAME(dw, @EndDate) = 'Saturday' THEN 1 ELSE 0 END) A: You could do this with a CTE, and this couuld easily be turned into a scalar function: DECLARE @startDate DATETIME = '2011-09-01' DECLARE @endDate DATETIME = '2011-09-23' ;WITH DateRange (date) AS ( SELECT @startDate UNION ALL SELECT Date+1 FROM DateRange WHERE date<@endDate ) SELECT COUNT(*) FROM DateRange WHERE DATENAME(dw,Date) != 'Sunday' Returns 20 which is the number of days this month so far which are not sundays. Here's an equivalent function which can be used: CREATE FUNCTION dbo.NumberOfDaysExcludingSunday( @startDate DATETIME, @endDate DATETIME ) RETURNS INT AS BEGIN DECLARE @rtn INT ;WITH DateRange (date) AS ( SELECT @startDate UNION ALL SELECT Date+1 FROM DateRange WHERE date<@endDate ) SELECT @rtn = COUNT(*) FROM DateRange WHERE DATENAME(dw,Date) != 'Sunday' RETURN @rtn END Usage: SELECT dbo.NumberOfDaysExcludingSunday(startDate,endDate) FROM myTable
{ "language": "en", "url": "https://stackoverflow.com/questions/7528969", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Setting PHPMyAdmin Language The user interface for phpmyadmin is displayed in german for some reason and i'd like to change it to english but don't know how. I installed the latest xampp. Thanks A: At the first site is a dropdown field to select the language of phpmyadmin. In the config.inc.php you can set: $cfg['Lang'] = ''; More details you can find in the documentation: http://www.phpmyadmin.net/documentation/ A: In config.inc.php in the top-level directory, set $cfg['DefaultLang'] = 'en-utf-8'; // Language if no other language is recognized // or $cfg['Lang'] = 'en-utf-8'; // Force this language for all users If Lang isn't set, you should be able to select the language in the initial welcome screen, and the language your browser prefers should be preselected there. A: sounds like you downloaded the german xampp package instead of the english xampp package (yes, it's another download-link) where the language is set according to the package you loaded. to change the language afterwards, simply edit the config.inc.php and set: $cfg['Lang'] = 'en-utf-8';
{ "language": "en", "url": "https://stackoverflow.com/questions/7528972", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "94" }
Q: What does "R"c mean when mapping a network drive using this function I copied code to map a network drive from http://www.vbforums.com/showthread.php?t=616519 to map the drive and http://cjwdev.wordpress.com/2010/05/30/delete-network-drive/ to delete the drive. I want to know what "R"c means in this code: RemoveNetworkDrive("R"c, True) which came from the first link and then I want to know how to simulate this notation in a variable so I can check for the first available drive and map the network drive to that letter. I would Google search it but since I don't know what "R"c means it makes it difficult. A: "R"c is the Char version of "R". You use it when you want to specify a character rather than a string. MSDN has some details here: You can also create an array of strings from a single string by using the String.Split Method. The following example demonstrates the reverse of the previous example: it takes a shopping list and turns it into an array of shopping items. The separator in this case is an instance of the Char data type; thus it is appended with the literal type character c. Dim shoppingList As String = "Milk,Eggs,Bread" Dim shoppingItem(2) As String shoppingItem = shoppingList.Split(","c) A: It converts your string "R" to a char, as requested from function Public Shared Sub RemoveNetworkDrive(ByVal DriveLetter As Char, ...) A: It's the syntax for a character literal, basically - it's the equivalent of 'R' in C#, if that makes it any clearer.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528978", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is there a command to list all syscall names and numbers on linux in bash? I know syscall 1 means write, but is there a command to list all implemented syscall names and numbers on linux in bash? A: The man page points to the header file sys/syscall.h. It has all the defined constants, and it's located at /usr/include/sys/syscall.h. (That's the location on OS X, which I'm using, but I think it'll be the same for most Linux distros, too.) A: Here is a oneliner that I just wrote. It works at least on Linux and requires a C compiler on the machine as it uses /usr/bin/cpp and system include files. { echo -e '#include <sys/syscall.h>\n#define X(c) #c c'; sed -n 's/#define \(SYS_[^ ]*\).*/X(\1)/p' $(echo -e '#include <sys/syscall.h>' | cpp | sed -n 's/# [0-9]* "\([^<"]*\)".*/\1/p') | sort -u; } | cpp -P | grep ' [0-9]*$' A: I tries @dolmen's answer, but it didn't work for me, so I did something similar like this (linux mint x86_64) echo -e '#include <sys/syscall.h>' | \ cpp -dM | grep "#define __NR_.*[0-9]$" | \ cut -d' ' -f 2,3 | cut -d_ -f 4- .. outputs about 500 lines like: waitid 247 fdatasync 75 mq_getsetattr 245 sched_getaffinity 204 connect 42 epoll_pwait 281 init_module 175 .... I can create a sed command file with this: echo -e '#include <sys/syscall.h>' | cpp -dM | grep "#define __NR_.*[0-9]$" | cut -d' ' -f 2,3 | cut -d_ -f 4- | sed 's|\(.*\) \(.*\)|s/syscall=\2 /syscall=\1 /|' > syscalls.sed So I can translate those numbers from logs, like this: dmesg | grep ' audit:' | sed -f syscalls.sed which looks like: [171511.625242] audit: type=AUDIT_AVC audit(1677790613.406:135): apparmor="DENIED" operation="capable" profile="/usr/bin/man" pid=211339 comm="nroff" capability=1 capname="dac_override" [173576.575868] audit: type=AUDIT_SECCOMP audit(1677847162.251:136): auid=4294967295 uid=33 gid=33 ses=4294967295 pid=200272 comm="apache2" exe="/usr/sbin/apache2" sig=31 arch=c000003e syscall=madvise compat=0 ip=0x7f5cf03eea7b code=0x80000000 [173593.434960] audit: type=AUDIT_SECCOMP audit(1677847179.107:137): auid=4294967295 uid=33 gid=33 ses=4294967295 pid=200266 comm="apache2" exe="/usr/sbin/apache2" sig=31 arch=c000003e syscall=madvise compat=0 ip=0x7f5cf03eea7b code=0x80000000 (it converts '28' to 'madvise')
{ "language": "en", "url": "https://stackoverflow.com/questions/7528981", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to swap items in treeview control? I have a treeview control: * *Parent Item 1 * *Child Item 1 *Child Item 2 *Child Item 3 *Parent Item 2 * *Child Item 1 *Child Item 2 *Child Item 3 *Parent Item 3 * *Child Item 1 *Child Item 2 *Child Item 3 I want to move, for example Parent Item 2, up or down with its child items as well as i want to move child items up/down for its parent level. p.s. I've done this with database, but it's performance issue to rebind treeview every move operation. A: I have used a modified version of the code found here here in the past to drag/drop UI items in a TreeView Basically it finds the parent control that holds the collection, uses the ItemContainerGenerator to find the container that holds the dragged item, then moves the container to the new location within the parent control A: Perhaps a two way binding with your custom object ? You can add a custom sorter for the treeview View model by order property for example... A: Couldn't that work? TreeNode node1 = treeView.Nodes[1]; TreeNode node2 = treeView.Nodes[2]; treeView.Nodes[1] = node2; treeView.Nodes[2] = node1; A: The following example is workable for me. Select a child node and swap with its parent node. TreeNode currentNode, targetNode; currentNode = TreeView1.SelectedNode; targetNode = currentNode.Parent; if (currentNode.Parent != null) { CopyedTreeNode = (TreeNode)targetNode.Clone(); CopyedTreeNode02 = (TreeNode)currentNode.Clone(); targetNode.Text = CopyedTreeNode02.Text; targetNode.Tag = CopyedTreeNode02.Tag; targetNode.ImageIndex = CopyedTreeNode02.ImageIndex; targetNode.SelectedImageIndex = CopyedTreeNode02.SelectedImageIndex; currentNode.Text = CopyedTreeNode.Text; currentNode.Tag = CopyedTreeNode.Tag; currentNode.ImageIndex = CopyedTreeNode.ImageIndex; currentNode.SelectedImageIndex = CopyedTreeNode.SelectedImageIndex; CopyedTreeNode.Remove(); CopyedTreeNode02.Remove(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7528985", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to resolve following htaccess code <IfModule mod_rewrite.c> RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteCond $1 !^(index\.php|images|robots\.txt) RewriteRule ^(.*)$ /index.php/$1 [L] </IfModule> can any body explain me how above htaccess rule works e.g. if I have URL http://mydomain/edituser so what php script will match with given URL earlier I write different rules for each given URL but in above case how I know that witch php script get run please help me A: That rewrite rule matches any request that does not match an existing file, and routes the request to to index.php using PATH_INFO A: Translation of the above code is like that: RewriteEngine On: Activate the RewriteEngine if not already activated RewriteCond %{REQUEST_FILENAME} !-f: If the requested file name is not a regular file RewriteCond %{REQUEST_FILENAME} !-d: If the requested file name is not a regular directory RewriteCond $1 !^(index\.php|images|robots\.txt): If the request is not the index.php, the images or robots.txt file RewriteRule ^(.*)$ /index.php/$1 [L]: Send the request to index.php and stop ([L]) A: This looks as a part from WordPress. If the file doesn't exists (-f) and a directory also not exists (-d) and the request is not for index.php or images or robots.txt when call index.php with the path as a parameter.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528993", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MkMapView tap + Annotation Selection Issue I have a MkMapView on which I have some Annotations. When I click an annotation Its detail is opened in another view which has scroll view in bottom half of map view. When we scroll through scrollview the map centers on next annotation and its details are shown in scrollview. My problem is that I want to add a tap gesture on Map so that when i tap on map the scrollview should hide. For this purpose I added a UiTapGesture on map which also works fine but the issue is that annotations on map no longer remain tapable. The map always goes to action of tapgesture and it never call again the selectannotation method? How can I fix this issue???? A: You can tell your gesture recognizer and the map's to work simultaneously by implementing the shouldRecognizeSimultaneouslyWithGestureRecognizer delegate method. When creating the tap gesture, set its delegate: tapGR.delegate = self;  //also add <UIGestureRecognizerDelegate> to @interface and implement the method: - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer     shouldRecognizeSimultaneouslyWithGestureRecognizer         :(UIGestureRecognizer *)otherGestureRecognizer {     return YES; } Now both your tap gesture method and the didSelectAnnotationView will get called. Assuming your tap handler gets called first, you can remove and nil the scrollview there and then the didSelectAnnotationView would create and add the scrollview. If the sequence turns out to be different, you might need to add some flags to coordinate the removal/creation. A: Not a clean way but the only way I could find was checking for all visible annotations inside shouldBeginGestureRecognizer method : - (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer { CGPoint p = [gestureRecognizer locationInView:self.mapView]; NSLog(@"touch %f %f",p.x,p.y); MKMapRect visibleMapRect = self.mapView.visibleMapRect; NSSet *visibleAnnotations = [self.mapView annotationsInMapRect:visibleMapRect]; for ( MyCustomAnnotation *annotation in visibleAnnotations ){ UIView *av = [self.mapView viewForAnnotation:annotation]; if( CGRectContainsPoint(av.frame, p) ){ // do what you wanna do when Annotation View has been tapped! return NO; } } return YES; } A: I think you should do only add a gesture recognizer when the scrollview is shown. Like I do with the keyboard in the exampble below 1. When keyboard is show the mapView adds a tap gesture 2. When away I remove the gesture recognizer. // Call this method somewhere in your view controller setup code. - (void)registerForKeyboardNotifications { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardDidShowNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillBeHidden:) name:UIKeyboardWillHideNotification object:nil]; } // Called when the UIKeyboardDidShowNotification is sent. - (void)keyboardWasShown:(NSNotification*)aNotification { self.tapMapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)]; self.tapMapGestureRecognizer.cancelsTouchesInView = NO; [self.parkingsMapView addGestureRecognizer:self.tapMapGestureRecognizer]; } // Called when the UIKeyboardWillHideNotification is sent - (void)keyboardWillBeHidden:(NSNotification*)aNotification { [self.parkingsMapView removeGestureRecognizer:self.tapMapGestureRecognizer]; } -(void) hideKeyboard{ [self.searchbar resignFirstResponder]; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7529011", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: AOL openid website verification Iam trying to use AOL openid, nut am getting "AOL is unable to verify this website" can somebody tell me the steps to avoid this error, what should I don on my end. If there is some sample code please share it - thanks in advance Regards, Navin George thank you for you answer, however I have issue in make it work, my xrds file as follows <?php header('Content-type: application/xrds+xml'); $xrdstext = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"; $xrdstext =$xrdstext . "<xrds:XRDS"; $xrdstext =$xrdstext ." xmlns:xrds=\"xri://$xrds\""; $xrdstext =$xrdstext ." xmlns:openid=\"http://openid.net/xmlns/1.0\""; $xrdstext =$xrdstext ." xmlns=\"xri://$xrd*($v*2.0)\">\n"; $xrdstext =$xrdstext ."<XRD>\n"; $xrdstext =$xrdstext ."<Service xmlns=\"xri://$xrd*($v*2.0)\">\n"; $xrdstext =$xrdstext ."<Type>http://specs.openid.net/auth/2.0/return_to</Type>\n"; $xrdstext =$xrdstext ."<URI>http://localhost:56709/myproject/socialoauth.aspx</URI>\n"; $xrdstext =$xrdstext ."</Service>\n"; $xrdstext =$xrdstext ."</XRD>\n"; $xrdstext =$xrdstext ."</xrds:XRDS>"; echo $xrdstext; ?> and my request url is https://api.screenname.aol.com/auth/openidServer?openid.claimed_id=http://openid.aol.com/navinleon&openid.identity=http://openid.aol.com/navinleon&openid.return_to=http://localhost:56709/myproject/socialoauth.aspx&openid.realm=http://mydomain.com/xrds/&openid.mode=checkid_setup&openid.assoc_handle=f457ae42e94c11e0811b002655277584&openid.ns=http://specs.openid.net/auth/2.0&openid.ns.alias3=http://openid.net/srv/ax/1.0&openid.alias3.if_available=alias5&openid.alias3.required=alias1,alias2,alias3,alias4,alias6,alias7&openid.alias3.mode=fetch_request&openid.alias3.type.alias1=http://axschema.org/namePerson/friendly&openid.alias3.count.alias1=1&openid.alias3.type.alias2=http://axschema.org/namePerson/first&openid.alias3.count.alias2=1&openid.alias3.type.alias3=http://axschema.org/namePerson/last&openid.alias3.count.alias3=1&openid.alias3.type.alias4=http://axschema.org/contact/country/home&openid.alias3.count.alias4=1&openid.alias3.type.alias5=http://axschema.org/pref/language&openid.alias3.count.alias5=1&openid.alias3.type.alias6=http://axschema.org/contact/email&openid.alias3.count.alias6=1&openid.alias3.type.alias7=http://axschema.org/birthDate&openid.alias3.count.alias7=1 am not sure what am doing wrong please help... A: So the reason for this error is that AOL is unable to verify the Rely Party return_to URL (per section 13 of the OpenID 2 spec [http://openid.net/specs/openid-authentication-2_0.html#rp_discovery]). This step is performed to protect the user from an attack where the realm specified doesn't match the return_to URL. To get rid of this error, you need to support XRDS discovery via the specified realm string. Based on the screenshot, this just means adding support into the server running on localhost. Basically, an HTTP request to http://localhost:56709 with an Accept HTTP header of application/xrds+xml should return either a response HTTP header of X-XRDS-Location with a value specifying the location of the XRDS file, or it can return the XRDS document directly. The XRDS document should look something like this... <?xml version="1.0" encoding="UTF-8"?> <xrds:XRDS xmlns:xrds="xri://$xrds" xmlns:openid="http://openid.net/xmlns/1.0" xmlns="xri://$xrd*($v*2.0)"> <XRD> <Service xmlns="xri://$xrd*($v*2.0)"> <Type>http://specs.openid.net/auth/2.0/return_to</Type> <URI>http://localhost:56709/return_to/url/path</URI> </Service> </XRD> </xrds:XRDS> NOTE: HTTP requests to localhost will fail as it's not possible to reach that site. The warning will continue until the XRDS document is deployed to a reachable site.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529013", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to deploy both applications using 1 apk file? Possible Duplicate: Is it possible to install multiple android applications in one APK file? Actually I have 2 applications 1. Main application (contains many activities) 2. Additional application (contains one widjet) My goal is to avoid 2 apk files and deploy 2 applications using only one apk file. Please suggest how to implement this A: What you want is not supported. Put them in a single application. You do not need separate applications here, and there is but one application per APK file.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529015", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: CakePhp localization I'm setting the localization on a website, but I've some trouble. I've found a tutorial, which does exactly what I need: http://nuts-and-bolts-of-cakephp.com/2008/11/28/cakephp-url-based-language-switching-for-i18n-and-l10n-internationalization-and-localization/ (having directly the language after the hostname). So I've done everything which is written on this website: * *I've generated a pot file, with this pot file, I create three po files(eng, ger and fre) with PoEdit, I translated two tests fields. *I've put those files into app/locale/eng|fre|ger *I've added the route Router::connect('/:language/:controller/:action/*', array(),array('language' => '[a-z]{3}')); in the correct file *I've set the default language: Configure::write('Config.language', 'fre'); *I've created three links to change the language: link('Français', array('language'=>'fre')); ?> *I've set the _setLanguage method in my appController(and calling it in the beforeFilter()) *I've created an appHelper to don't have to specify everytime the current language My links are well generated, I don't have any exception/errors, my locals files are readable, but when I go on the template where I try to use variable( ) I just see "testTranslation" as text, no translated text. Why this isn't working? Looks like it can't find my files but I don't know why :( Any help would be really appreciated! Edit: I did some debugging with cakePhp, and it appears that when the method translate of the i18n.php file is called, I receive a $domain = default_ger var. My translations are all in default.po files, and I suppose that he is searching into default_ger.po? why this? how can i force it to read in the default.po file? Edit: I found something: I had a problem with my controller, I forgot to declare the parent::beforeFilter() in my children controller, then the method in the controller wasn't called and the language was always the german one. After I fixed this, the french and the english are working fine, but the german is still only displaying key and not values that I've in the translation file. This is really weird, I've deleted all files in the cache, deleted my /app/locale/ger folder and copied my /app/locale/fre to /app/locale/ger(without changing anything in files) and this still doesn't work. What can be different? A: Try this file layout: ***\app\locale>tree /F ├───eng │ └───LC_MESSAGES │ default.po │ └───spa └───LC_MESSAGES default.po A: I finally found the problem: My App controller wasn't called, so the German language was always used(because it worked once when changing the language to german, and register it through cookies). All other languages than german were displaying correctly my values. So I searched about this problem, and I tried to use "deu" instead of "ger", and it worked! The locale folder has to be "deu", the language value can be deu or ger. This is very strange, because for the french, I've a "fre"(FREnch) and not a "fra"(FRAnçais), and this is working. Anyway, this work with this change A: ** * *CakePHP 3.x Localization ** use App\Middleware\TranslationMiddleware; $routes->registerMiddleware('translation', new TranslationMiddleware()); $routes->applyMiddleware('translation'); //Change language route $routes->connect('/swtich-language/:lang', ['controller' => 'Translations', 'action' => 'switchLanguage', ['pass' => ['lang'], '_name' => 'switch-language']); Runtime language change for action use Cake\I18n\I18n; use Cake\Cache\Cache; /** * Change language run time * @param type $lang local */ public function switchLanguage($lang = null) { if (array_key_exists($lang, Configure::read('Translations'))) { Cache::write('Config.language', $lang); $this->redirect($this->referer()); } else { Cache::write('Config.language', I18n::getLocale()); $this->redirect($this->referer()); } } namespace App\Middleware; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Cake\I18n\I18n; use Cake\Cache\Cache; class TranslationMiddleware { public function __invoke(ServerRequestInterface $request, ResponseInterface $response, $next) { if (Cache::read('Config.language')) { I18n::setLocale(Cache::read('Config.language')); } else { I18n::setLocale(I18n::getLocale()); } return $next($request, $response); } } Create .po file /src/locale/fr/default.po msgid "Dashboard" msgstr "Tableau de bord" msgid "Companies" msgstr "Entreprises" msgid "Log Out" msgstr "Connectez - Out" Use of msgid key Ex. <?= __(‘Log Out);?>
{ "language": "en", "url": "https://stackoverflow.com/questions/7529020", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Rave Reports - Access Violation in rtl150.bpl on intToStr or StrToFloat 20/01/2012 I have now given up on rave and reworked the reports in FastReport. I have now got the report working by downloading DelphiXE2 and re-compiling the report with Rave version 10. I am Using RAD Studio XE Version 15.0.3953.35171 with RV90RAVBE Build 100610. 1) I am converting an old delphi2005 project to DelphiXE and encountering problems in Rave. The error message is Access Violation at address 5003c0a0 in module ‘rtl50.bpl’. Read of address 000006F9 I believe this is happening in a rave OnGetText Event. The data is a floating point number representing duration in days and I am going to display in days, hours, minutes, seconds. Running the code without the event in displays the correct number but as soon as I put in the strToFloat conversion it fails. I have sandboxed the code and sometimes get a failure when introducing an intToStr and sometimes a strToFloat The specific line of code that fails is tmp := StrToFloat(value); Here is the code: { Event for Duration.OnGetText } function Duration_OnGetText(Self: TRaveDataText; var Value: string); var tmp :Extended; days :Integer; hours: Integer; minutes: Integer; seconds: Integer; begin if(value <> '') then tmp := StrToFloat(value); days := Trunc(tmp); tmp := Frac(tmp)*24;//fraction of a day in hours hours := Trunc(tmp); tmp := Frac(tmp)*60; minutes := Trunc(tmp); tmp := Frac(tmp)*60; seconds := Trunc(tmp); Value := IntToStr(days) + ':' + IntToStr(hours)+ ':' + IntToStr(minutes)+ ':' + IntToStr(seconds); end; * *Is it possible to set break points and debug in rave? I can’t find anything in the help about debugging. A: Please look at the formatting changes I made above (particularly indentation levels to indicate blocks), and then my annotated code below, and the problem should be pretty easy to figure out. (Stepping through with the debugger might have helped as well.) { Event for Duration.OnGetText } function Duration_OnGetText(Self: TRaveDataText; var Value: string); var tmp :Extended; days :Integer; hours: Integer; minutes: Integer; seconds: Integer; begin if(value <> '') then tmp := StrToFloat(value); // This only gets called if Value <> '' // Note that value could contain 'Pete', '123.45', 'Argh!', etc. // This gets called no matter what the value of tmp is, // whether it's a valid floating point created by StrToFloat // above, or a random value picked up from memory (since it // may never have been initialized above. The same applies to // every line of code that follows. days := Trunc(tmp); tmp := Frac(tmp)*24;//fraction of a day in hours hours := Trunc(tmp); tmp := Frac(tmp)*60; minutes := Trunc(tmp); tmp := Frac(tmp)*60; seconds := Trunc(tmp); Value := IntToStr(days) + ':' + IntToStr(hours)+ ':' + IntToStr(minutes)+ ':' + IntToStr(seconds); end; You're not handling the failure of StrToFloat if Value is something other than a floating point value. You might try using StrToFloatDef with a default value, or TryStrToFloat and testing the boolean return value to see if you should proceed or exit. Your code as posted doesn't compile, btw. You have an extra end OnGetText; at the bottom that's mismatched with the code above. Please post actual, compilable code with your questions, especially those about exceptions or access violations you're trying to track down. Also, as a suggestion - replace your final line of code with Value := Format('%d:%d:%d:%d', [days, hours, minutes, seconds]);
{ "language": "en", "url": "https://stackoverflow.com/questions/7529022", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Javascript - trying to locate an image I am not expert in javascript, so, excuse my lack of knowledge. I am trying to interact with an image on a page on the web, to create some automation. I need to click on that image using javascript, from a script. I did everything to discover how to access that image and no success at all. The image is not responding to anything. I suppose I am not reaching the right object. Trying to discover the object, I created a very simple script, that will scale every image on that page, to see at least if I can reach all img object. This is the script for (i=0;i<=100;i++) { document.image[i].width.value = '300'; } No changes at all. Is the script correct? is that anything that may be preventing the image to respond from external scripts? Any clues? thanks. ___ EDIT the image I need to click is declared like this: <div class="leaderboard-text"> <span id="addon-add-language-button"><image class="ajaxListAddButtonEnabled" listId="localizationList" src="/itc/images/blue-add-language-button.png"><image class="ajaxListAddButtonDisabled" listId="localizationList" style="display:none;" src="/itc/images/blue-add-language-button-disabled.png"></span> </div> A: There is no document.image, there is document.images for (var i=0, l=document.images.length; i<l; i++) { var ing = document.images[i]; img.width = 300; // but why do you want all images to be equal width? } A: You missed an 's' in images and some other things. for (i=0, lughez = document.images.length; i<lughez ; i++) { document.images[i].width= '300'; } but if the image has an id you could do: document.getElementById('id').click() to click your image where 'id' is the id you are using
{ "language": "en", "url": "https://stackoverflow.com/questions/7529024", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to insert variable number of spaces necessary to align textual columns in Vim? I’m a fan of Visual mode in Vim, as it allows to insert text before any given column. For example, insertion of spaces after the quotation leaders below: > one > two > three can be done via <Ctrl-V>jjI <Esc>: > one > two > three as follows: * *Start Visual mode with Ctrl-V. *Extend visual selection with jj. *Insert some spaces with I__. *Propagate the change to all the lines of the block selection with Esc. Now I have a text file that needs some formatting. This is what it looks like: start() -- xxx initialize() -- xxx go() -- xxx Now I want to align part of this text to arrange it into columns like this: start() -- xxx initialize() -- xxx go() -- xxx The problem I have is that I cannot insert a different amount of indentation into each line and merely indenting a fixed amount of spaces/tabs is insufficient. How can you do an indentation where all indented text will have to be aligned at the same column? Update I only figured out a rather verbose and unwieldy method: * *Find the string position to indent from: \--. *Insert n (let's say 20) spaces before that: 20i <Esc>. *Delete a part of those spaces back to a certain column (let's say 15): d|15. *Save those steps as a macro and repeat the macro as often as necessary. But this approach is very ugly, though! A: You have to use a specific plugin, you can use either Tabular or Align plugin in this case. They both allow you to align text on specific characters, like -- in your example. Their syntax is a bit different though. Pick the one that suit you the most. A: Without plugin and if you have already entered your comments without emix's solution: :,+2 s/--/ & This will ensure all comments are to be shifted leftwise in order to align them properly. Then blockwise select the column to which you want to align the text, and : 100< A: An easy way to align text in columns is to use the Tabular or Align plugin. If neither of these is ready at hand, one can use the following somewhat tricky (and a little cumbersome looking) yet perfectly working (for the case in question) commands.1,2 :let m=0|g/\ze -- /let m=max([m,searchpos(@/,'c')[1]]) :%s//\=repeat(' ',m-col('.')) The purpose of the first command is to determine the width of the column to the left of the separator (which I assume to be -- here). The width is calculated as a maximum of the lengths of the text in the first column among all the lines. The :global command is used to enumerate the lines containing the separator (the other lines do not require aligning). The \ze atom located just after the beginning of the pattern, sets the end of the match at the same position where it starts (see :help \ze). Changing the borders of the match does not affect the way :global command works, the pattern is written in such a manner just to match the needs of the next substitution command: Since these two commands could share the same pattern, it can be omitted in the second one. The command that is run on the matched lines, :let m=max([m,searchpos(@/,'c')[1]]) calls the searchpos() function to search for the pattern used in the parent :global command, and to get the column position of the match. The pattern is referred to as @/ using the last search pattern register (see :help "/). This takes advantage of the fact that the :global command updates the / register as soon as it starts executing. The c flag passed as the second argument in the searchpos() call allows the match at the first character of a line (:global positions the cursor at the very beginning of the line to execute a command on), because it could be that there is no text to the left of the separator. The searchpos() function returns a list, the first element of which is the line number of the matched position, and the second one is the column position. If the command is run on a line, the line matches the pattern of the containing :global command. As searchpos() is to look for the same pattern, there is definitely a match on that line. Therefore, only the column starting the match is in interest, so it gets extracted from the returning list by the [1] subscript. This very position equals to the width of the text in the first column of the line, plus one. Hence, the m variable is set to the maximum of its current value and that column position. The second command, :%s//\=repeat(' ',m-col('.')) pads the first occurrence of the separator on all of the lines that contain it, with the number of spaces that is missing to make the text before the separator to take m characters, minus one. This command is a global substitution replacing an empty interval just before the separator (see the comment about the :global command above) with the result of evaluation of the expression (see :help sub-replace-\=) repeat(' ',m-col('.')) The repeat() function repeats its first argument (as string) the number of times given in the second argument. Since on every substitution the cursor is moved to the start of the pattern match, m-col('.') equals exactly to the number of spaces needed to shift the separator to the right to align columns (col('.') returns the current column position of the cursor). 1 Below is a one-line version of this pair of commands. :let m=0|exe'g/\ze -- /let m=max([m,searchpos(@/,"c")[1]])'|%s//\=repeat(' ',m-col('.')) 2 In previous revisions of the answer the commands used to be as follows. :let p=[0]|%s/^\ze\(.*\) -- /\=map(p,'max([v:val,len(submatch(1))+1])')[1:0]/ :exe'%s/\ze\%<'.p[0].'c -- /\=repeat(" ",'.p[0].'-col("."))' Those who are interested in these particular commands can find their detailed description in this answer’s edit history. A: I'm much better off without any vim plugins. Here is my solution: <Shift-V>jj:!column -ts -- Then insert -- into multiple lines just as you wrote in the question. You can also append a number of comments at insertion time. :set virtualedit=all <Ctrl-V>jjA-- xxx<Esc> A: This is a modification on Benoit's answer that has two steps. First step, block select text search and replace -- with lots of spaces. '<,'>s/--/ --/ Now all the comments should have lots of spaces, but still be uneven. Second step, block select the text again and use another regex to match all the characters you want to keep (say the first 20 characters or so) plus all the spaces following, and to replace it with a copy of those first 20 characters: '<,'>s/\(.\{20}\)\s*/\1/ Not quite as easy as Benoit's, but I couldn't figure out how to make his second step work.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529029", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: JDBC PreparedStatements vs Objects - Where to put initialization What is the best place to put PreparedStatement initialization, when i want to use it for all instances of given class? My solution is so far to create static methods for opening and closing, but i don't find it quite the right choice: class Person { protected static PreparedStatement stmt1; protected static PreparedStatement stmt2; protected static void initStatements(Connection conn) { stmt1 = conn.PrepareStatement("select job_id from persons where person_id=:person_id"); stmt2 = conn.PrepareStatement("update persons set job_id=:job_id where person_id=:person_id"); } protected static void closeStatements() { stmt1.close(); stmt2.close(); } public void increaseSalary() { stmt1.execute(); // just a example stmt2.execute(); } } void main { // create prepared statements Person.initStatements(conn); // for each person, increase do some action which require sql connection for (Person p : getAllPersons()) { p.increaseSalary(); } // close statements Person.closeStatements(); } Isn't there any other way how to use PreparedStatements inside multiple instances of class? A: Will person be your domain logic class? Then I recommend not to put the data access methods and PreparedStatements in there but in a separate data access object. Will the DAO methods be called asynchronously for example in a web application? Then I recommend to not reuse either PreparedStatements or Connections between those calls at all. For Connections I'd use a Connection pool. More on reusing PreparedStatements: Reusing a PreparedStatement multiple times A: Usually it is better to use a ConnectionSurvivalPack and give this to everyone involved: Class SurvivalPack { private Connection connection; private PreparedStatement st1; // add constructor and appropriate getter/setter // getter for PreparedStatements could create statements on demand void close(){ st1.close(); con.close(); } } void main(...){ SurvivalPack survivalPack = new SurvivalPack(conn); for(Person p: getAllPersons()){ p.increaseSalary(survivalPack); } survivalPack.close(); } Pros: * *Multithreading is no problem, since the resources are not shared between threads. *All database resources are bundled in one place. This makes management of resources easier and more consistent. *It is much easier to follow the flow of the code and the involved resources because no side effects from semiglobal variables can happen.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529037", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Uploading Files to ftp server by selecting an account? I would like to upload files to ftp server by choosing account using Alert Dialog. The Alert Dialog show when the Activity starts. I know how to create Alert Dialog when activity starts. But, i don't know get the values from database within the Alert Dialog. I've used SQLiteOpenHelper for database and using ContentValues for store the records. How can i choose this in Alert Dialog? Anyone help me to find out that? Thanks in Advance. A: Try this stuff, Fetch the database values in an String array. Cursor c = mydb.readFromLogin(); final String[] array = new String[c.getCount()]; if(c.getCount() > 0){ c.moveToFirst(); for (int i = 0; i < c.getCount() - 1; i++) { array[i] = c.getString(0); c.moveToNext(); } } Builder mbBuilder = new AlertDialog.Builder(LoginActivity.this); mbBuilder.setItems(array, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if(which == 0) { Toast.makeText(getApplicationContext(), array[which], Toast.LENGTH_SHORT).show(); } else if(which == 1) { Toast.makeText(getApplicationContext(), array[which], Toast.LENGTH_SHORT).show(); } } }); mbBuilder.setNegativeButton("Cancel", null); mbBuilder.create().show();
{ "language": "en", "url": "https://stackoverflow.com/questions/7529042", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Lvalue error when attempting to change webview.bounds.origin.x/y So basically, I'm trying to create an NSTimer which will scroll through a UIWebView (here named _webView). The timer is firing correctly, but the other lines are giving me an "Lvalue required as left operand of assignment" error. All I want to do is increment the y coordinate of the origin by, say, 10, every time the NSTimer fires. What's going wrong here? NSLog(@"Value of webView.bounds.origin.y = %f", _webView.bounds.origin.y); CGPoint topLeft = {_webView.bounds.origin.x, _webView.bounds.origin.y}; topLeft.y = topLeft.y + 10; _webView.bounds.origin = topLeft; A: Try... CGRect newRect = _webView.bounds; newRect.origin.y += 10; _webView.bounds = newRect;
{ "language": "en", "url": "https://stackoverflow.com/questions/7529043", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Problem with c:forEach inside rich:dataTable I have this page: <?xml version='1.0' encoding='UTF-8' ?> <!DOCTYPE composition PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <ui:composition xmlns:ui="http://java.sun.com/jsf/facelets" template="./templates/template.xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" xmlns:rich="http://richfaces.org/rich" xmlns:c="http://java.sun.com/jstl/core"> <ui:define name="main_title">AO MMS Messages</ui:define> <ui:define name="main"> <rich:dataTable value="#{dataProviderBean.aoRequests}" var="item"> <f:facet name="noData">No messages are available.</f:facet> <rich:column> <f:facet name="header">Profile</f:facet> #{item.profile.username} </rich:column> <rich:column> <f:facet name="header">Timestamp</f:facet> #{item.timestamp} </rich:column> <rich:column> <f:facet name="header">Recipient</f:facet> #{item.recipient} </rich:column> <rich:column> <f:facet name="header">Sender</f:facet> #{item.sender} </rich:column> <rich:column> <f:facet name="header">Text</f:facet> <h:outputText value="Contents: #{item.getContentByStringType('text/plain')}" /> <c:forEach var="content" items="#{item.getContentByStringType('text/plain')}"> <h:outputText value="Content: #{content}" /> </c:forEach> </rich:column> <rich:column> <f:facet name="header">Headers</f:facet> #{item.headers} </rich:column> </rich:dataTable> </ui:define> </ui:composition> But the column Text prints only this: Contents: [TextContent [content=Hello World in MMS]] Content: Why does it not iterate over the list? Request class for more info: public class Request { private Profile profile; private Map<String, String> headers; private Date timestamp; private MessageType messageType; private Map<String, ArrayList<Content>> contents; public Request(MessageType messageType) { this.messageType = messageType; this.timestamp = new Date(); } public Profile getProfile() { return profile; } public void setProfile(Profile profile) { this.profile = profile; } public Map<String, String> getHeaders() { return headers; } public void setHeaders(Map<String, String> headers) { this.headers = headers; } public Date getTimestamp() { return timestamp; } public void setTimestamp(Date timestamp) { this.timestamp = timestamp; } public MessageType getMessageType() { return messageType; } public void setMessageType(MessageType messageType) { this.messageType = messageType; } public Map<String, ArrayList<Content>> getContents() { return contents; } public void setContents(Map<String, ArrayList<Content>> contents) { this.contents = contents; } public List<Content> getContentByStringType(String type) { return contents.get(type); } public String getSender() { return headers.get(HttpHeaders.X_NOKIA_MMSC_FROM.getValue()).replaceAll("/.*", ""); } public String getRecipient() { return headers.get(HttpHeaders.X_NOKIA_MMSC_TO.getValue()).replaceAll("/.*", ""); } @Override public String toString() { return "Request [profile=" + profile + ", headers=" + headers + ", timestamp=" + timestamp + ", messageType=" + messageType + ", contents=" + contents + "]"; } } A: Use ui:repeat instead of c:forEach in that situation. c:forEachdoes not work here because you are trying to refer var item which is not defined (c:forEach is a TagHandler so it is trying to evaluate item when the tree is being built; rich:dataTable is a Component and it defines the var item only on render response). For more information on the matter you could read the following article: . TagHandler vs Component
{ "language": "en", "url": "https://stackoverflow.com/questions/7529046", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Anomaly detection using mapreduce I'm new to Apache Hadoop and i'm really looking forward to explore more features of it. After the basic wordcount example i wanted to up the ante a little bit. So i sat down with this problem statement which i got by going through Hadoop In Action book. "Take a web server log file . Write a MapReduce program to aggregate the number of visits for each IP address. Write another MapReduce program to find the top K IP addresses in terms of visits. These frequent visitors may be legitimate ISP proxies (shared among many users) or they may be scrapers and fraudsters (if the server log is from an ad network)." Can anybody help me out as to how i should start ? Its kind of tough to actually write our own code since hadoop only gives wordcount as a basic example to kick start . Any help gratefully appreciated . Thanks. A: Write a MapReduce program to aggregate the number of visits for each IP address. The wordcount example is not much different from this one. In the wordcount example the map emits ("word",1) after extracting the "word" from the input, in the IP address case the map emits ("192.168.0.1",1) after extracting the ""192.168.0.1" IP address from the log files. Write another MapReduce program to find the top K IP addresses in terms of visits. After the completion of the first MapReduce job, there will be a lot of output files based on the # of reducers with content like this <visits> <ip address> All these files have to merged using the getmerge option. The getmerge option will merge the file and also get the file locally. Then the local file has to be sorted using the sort command based on the 1st column, which is the # of visits. Then using the head command you can get the first n lines to get the top n IP address by visits. There might be a better approach for the second MR Job.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529047", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Custom routes in CakePHP: regex not limiting matches I'm trying to configure my custom routes in cakephp such that the url /objects/id/action => ObjectsController.action() with params['id']=id (This is so that I don't have to have urls like /objects/action/id which logically make less sense to me than objects/id/action). I still want /objects/action to trigger ObjectsController.action() (e.g. for add, index, search). My routes config looks like this: Router::connect('/:controller/:id', array('action'=>'view'), array( ':id' => '^[0-9]+$' ) ); Router::connect('/:controller/:id/:action/*', array('action'=>'view'), array( ':id' => '^[0-9]+$', ':action' => '[A-Za-z0-9_\-]*' ) ); This works with (for example): * */objects/54 */objects/54/edit */objects/add But not with * */objects/index/page:2 For which it gives me the error that I need to define the action "page:2" in ObjectsController... Surely it should work, because :id should only match digits, no? A: Try to remove ":" from second param: 'id' => '^[0-9]+$' Also see 'pass' option. @see google on "cakephp routes": * *http://book.cakephp.org/view/945/Routes-Configuration
{ "language": "en", "url": "https://stackoverflow.com/questions/7529055", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Custom fields on new contact This is the 'add new contact' window. Is it possible to create custom data fields in this window? My current custom fields are only visible on the 'contact details' window. A: It seems like the only way to do it, is to catch the intent and show you're own edit contact activity( at least with android 2.1 and 2.3 ). I tries all day long to make a workable BroadcastReceiver working. but I never succed. source : https://groups.google.com/forum/?fromgroups#!topic/android-developers/bKpXE1kn4kI and Custom accountType "edit contact" and "add contact" shows only name A: It is possible to launch a new Add New Contact activity when the user clicks on the add new contact button. For that you will have to create your own activity and setContentView(R.layout.YOUR_CUSTOM_ACTIVITY_SCREEN). Now the next step is important. Add the following lines to the ManifestFile of your application: <activity android:name=".YOUR_CUSTOM_ACTIVITY" > <intent-filter> <action android:name="android.intent.action.INSERT" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="vnd.android.cursor.dir/contact"/> </intent-filter> </activity> Now when the user click to add a new contact he will be shown 2 options. One will be your application and other would be the default activity to add contact. Hope this answer helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529056", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Disable .htaccess for a directory Im using a Framework which has this .htaccess file: Options +FollowSymLinks +ExecCGI <IfModule mod_rewrite.c> RewriteEngine On RewriteCond %{REQUEST_URI} !(\.png|\.jpg|\.gif|\.jpeg|\.bmp|\.ico)$ RewriteRule ^(.*)$ entryPoint.php [QSA] </IfModule> thats very good, because entryPoint.php runs everytime. But I have a PhpBB forum, placed in SITEROOT/forum directory. It would be the best that in this /forum directory to .htaccess be ignored. How to set a rule to be ignored in a directory? A: I'm a bit rusty with my rewrite rules but, RewriteCond $1 !^/forum Should work.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529058", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What happens with the local changes on svn export from working copy I am developing a web-site and keep its code an SVN. For development purposes I have two local copies: 1. A normal working copy that is always at HEAD (I am the only developer) 2. svn export'ed copy for the final tests and uploading to the server svn export from the server guaranteed that exported directory is identical to HEAD, but takes hell a lot of time svn export from the working directory is super-fast, but I am not sure what happens if there are some uncommitted changes in the local copy. Does anybody know what happens if I try svn export from the working directory and there's some of the following? 1. I just forgot to commit local changes (file addition/deletion/modification) 2. I deleted/moved the whole directory by mistake (i.e. together with .svn folders) Will svn export from a working copy still produce a full clone of HEAD and/or stop with some error message if it's impossible? A: From SVN docs: svn export [-r REV] PATH1[@PEGREV] [PATH2] ...exports a clean directory tree from the working copy specified by PATH1 into PATH2. All local changes will be preserved, but files not under version control will not be copied. A: Just do this: svn export -r BASE /path/to/wc /path/to/export By specifying BASE for the revision you will export the pristine version from the working copy. Uncommitted edits will not be included. Uncommited adds will not be included. Unversioned files will not be include. Uncommitted deleted files will be included.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529060", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: iOSCheck if uislider value is increasing or decreasing. how would one check wether or not a slider's value is increasing or decreasing? Any help would be greatly appreciated. I know I should use a temporary value, but nothing beyond that. A: TESTED CODE : 100% WORKS .h float lastSlidedValue; -(IBAction)sliderMoving:(id)sender; -(IBAction)sliderValueDidChanged:(id)sender; .m -(IBAction)sliderValueDidChanged:(id)sender{//UIControlEventTouchUpInside connected method UISlider *sliderr=(UISlider*)sender; lastSlideValue=sliderr.value; } -(IBAction)sliderMoving:(id)sender{//UIControlEventValueChanged connected method UISlider *sliderr=(UISlider*)sender; if (lastSlideValue < sliderr.value) { NSLog(@"big"); } else if (lastSlideValue == sliderr.value) { NSLog(@"equal"); } else { NSLog(@"low"); } } A: You would be adding a target and writing a selector for your slider. So keep track of slider.value in that selector and keep comparing with the previous slider.value. The selector would be called everytime the value of slider changes (UIControlEventValueChanged) A: You can set minimum and maximum value for slider during initialization whom you can understand whether slider is increasing or decreasing Code is: Slider.maximumValue=10; Slider.minimumValue=0;
{ "language": "en", "url": "https://stackoverflow.com/questions/7529064", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Reading Bulk data from CSV and writring into another csv I had one csv file of 1 cr lines of data. From this file I have to read data from csv and using first field I need do check conditions with in my db and from that Db took one key and append all prevoius data and write to another csv. Which ever I read from CSV I written code for this but it takes days of time to read and write for one 2 lakhs line of data. Here I am using single thread to do this all. Sample code is I followed below steps: 1).reading data from CSF. 2).Read first field from csv and checking condition(in this i am checking 5 conditions). 3).And written into CSV. A: In my opinion, reading the CSV into the database and then writing a statement to filter the data would be more efficient than reading the file line by line using the code. You may refer the links below to know more about csv to database import if you use MySQL: http://dev.mysql.com/doc/refman/5.0/en/mysqlimport.html http://support.modwest.com/content/6/253/en/how-do-i-import-delimited-data-into-mysql.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7529067", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Regex to remove HTML attribute from any HTML tag (style="")? I'm looking for a regex pattern that will look for an attribute within an HTML tag. Specifically, I'd like to find all instances of ... style="" ... and remove it from the HTML tag that it is contained within. Obviously this would include anything contained with the double quotes as well. I'm using Classic ASP to do this. I already have a function setup for a different regex pattern that looks for all HTML tags in a string and removes them. It works great. But now I just need another pattern for specifically removing all of the style attributes. Any help would be greatly appreciated. A: Perhaps a simpler expression is style="[^\"]*" so everything between the double quotes except a double quote. A: Try this, it will replace style attribute and it's value completely const regex = /style="(.*?)"/gm; const str = `<div class="frame" style="font-family: Monaco, Consolas, &quot;Courier New&quot;, monospace; font-size: 12px; background-color: rgb(245, 245, 245);">some text</div>`; const subst = ``; // The substituted value will be contained in the result variable const result = str.replace(regex, subst); console.log('Substitution result: ', result); A: In visual studio find and replace, this is what i do to remove style and class attributes: \s*style|class="[^"]*\n*" This removes the beginning spaces and style and class attributes. It looks for anything except a double quote in these attributes and then newline(s), in case if it spreads out to new lines, and lastly adds the closing double quote A: I think this might do it: /style="[a-zA-Z0-9:;\.\s\(\)\-\,]*"/gi You could also put these in capturing groups, if you wanted to replace some parts only /(style=")([a-zA-Z0-9:;\.\s\(\)\-\,]*)(")/gi Working Example: http://regexr.com?2up30 A: I tried Jason Gennaro's regular expression and slightly modified it /style="[a-zA-Z0-9:;&\."\s\(\)\-\,]*|\\/ig This regular expression captures some specific cases with &quot inside the string for example <div class="frame" style="font-family: Monaco, Consolas, &quot;Courier New&quot;, monospace; font-size: 12px; background-color: rgb(245, 245, 245);">some text</div> A: This works with perl. Maybe you need to change the regex to match ASP rules a little bit but it should work for any tag. $file=~ s/(<\s*[a-z][a-z0-9]*.*\s)(style\s*=\s*".*?")([^<>]*>)/$1 $3/sig; Where line is an html file. Also this is in .net C# string resultString = null; string subjectString = "<html style=\"something\"> "; resultString = Regex.Replace(subjectString, @"(<\s*[a-z][a-z0-9]*.*\s)(style\s*=\s*"".*?"")([^<>]*>)", "$1 $3", RegexOptions.Singleline | RegexOptions.IgnoreCase); Result : <html > A: This expression work for me: style=".+"/ig A: The following expression should remove anything within a style attribute (including the attribute itself); crucially this includes whether the attribute uses double or single quotes: /style=("|')(?:[^\1\\]|\\.)+?\1/gi This splits the capture groups so that they can match on single or double-quotes, and then capture anything in between, including URL-encoded characters & line breaks, whilst leaving other attributes (like classes or names) intact. Tested here: https://regexr.com/4rovf A: try it: (style|class)=(["'])(.*?)(["'])
{ "language": "en", "url": "https://stackoverflow.com/questions/7529068", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: Best way to start fragments I have the following scenario. A tabhost manages four ListFragmnet. For every ListFragment I have several fragment. For instance associated with the ListFragmnet 1 I have the fragments A, B, C and can happens that fragment A "launch" fragment B which can launch fragment C. Is correct to allow fragments to start each other or is there a more correct way? Thanks Edit: TabFragmentActivity: tab1(ListFragment): fragment 1 -> fragment 2 -> .... -> fragment N tab2(ListFragment): fragment 1 -> fragment 2 -> .... -> fragment N tab3(ListFragment): fragment 1 -> fragment 2 -> .... -> fragment N tab4(ListFragment): fragment 1 -> fragment 2 -> .... -> fragment N this is want to achieve. So, my question is what is the best way to manage transaction from fragment 1 to fragment N per tab? Again thanks A: The point of having fragments is to separate the logic ! try to think of than like a pieces that doesn't know the existent of anything else except the activity in which they are placed. how the things should works: -the activity implements interface let say that interface have method startFragmentB(); -than from the fragmentA you can do this ((myInterface)getActivity()).startFragmentB(); -all of the transactions logic should be in the activity -keep reference to all of the fragments in the activity... this should give you a nice starting point with fragments, if you have any question just ask, i comment, as a general answer to you question: NO it is not correct from one fragment to start other, everything should go through the activity,YES you can decide if you want to start another fragment or not but you should not do the actual starting there(in the fragment).
{ "language": "en", "url": "https://stackoverflow.com/questions/7529069", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: is using attributes for microdata storage and as a selector a bad thing So I have a habit of using the attribute lang as my selector and store microdata,in jquery. Althought it is not w3 compliant.But is it a good thing. Also is there any alternative to this. something like this. $('[lang=153]') to get this dom and $(this)[0].lang to get the data. A: As you said, it's not w3 compliant. That's not the worst thing your site can face, but it's definetly not a good one. The advantage of your method is that you can make more use of selectors this way. I recommend, since you use jquery, using the data method to store data(any type of object - much more than a simple lang=) right on the selected dom element. A: To store data with jquery you should use data(). You store data: $('#myid').data('mydata', 'mydata') and you retrieve it: $('#myid').data('mydata') You can also write your element with an attribute and access it: <div id='myid' data-mydata='this is the data'></div> var my = $('#myid').data('mydata'); //my is equal to 'this is the data' A: It doesn't cause a problem, although it causes your HTML to be 'non compliant'. HTML5 is introducing a valid way of doing this using attributes that start with data- like this: <div data-billy="bob"></div> I would suggest switching to that style. See John Resig's explanation for more info. A: You can put the data into your element using the data- prefix: <div data-lang="123">Text</div> Then you can select this element and read the data like this: var lang = $('[data-lang="123"]').data('lang'); http://jsfiddle.net/C3LCp/
{ "language": "en", "url": "https://stackoverflow.com/questions/7529072", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Windows 8 + VS11 doesn't work? I've downloaded the W8 Developer Preview, installed VS11 Ultimate on it, and I get errors when I try to build the applications. My W8 copy has something wrong with a character set, and I'm unable to read what the errors are. A: I had a similar problem, but I actually received error messages about makepri.exe. In the msdn forums they said I should have installed the iso with visual studio included to be able to build metro applications. Then google-translated this site http://www.umutcankoseali.com/?p=338, followed the instructions, and it fixed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529078", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }