text
stringlengths
8
267k
meta
dict
Q: Run tasks after checking out project from svn? I have a project (this is a maven project) in svn. After the project has been checked out I would like to run some small tasks automatically (eg. some of the subprojects must be build etc). Is it possible to add specific task to svn checkout? A: I think (and hope) that feature does not exist. It would be a serious security hole. (Imagine that you checkout an open source code from the internet and it formats your hard drive too.) A workaround: create a batch file/shell script for your tasks and commit it to the root folder of your project (autorun.sh for example). After checkout you just have to run this script and it runs you tasks. If the checkout takes too much time you can create an other shell script which checkouts your project and run the aurorun.sh from its root folder. Of course this script have to be on your machine before the checkout somehow. A: Rather than [ab]use SVN, use a continuous integration server such as Jenkins. It will check things out of SVN and run build scripts, tests, etc. It can do it every time a commit is made to SVN, or overnight, or whatever you want.
{ "language": "en", "url": "https://stackoverflow.com/questions/7595488", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Decreasing the size of listitem? I've listed something in one listview using android.R.layout.simple_list_item_multiple_choice It takes core listview. And, i can't decrease the font size of their items. How can i decrease that? I've search the size element in XML files but, i've not found yet. Anyone know the answer for this? See my result here Thanks in Advance. A: If you are adding the textViews in the listItem, you can control the font Size , with android:textSize EDIT i see you are using a standard list item. then copy the simple_list_item_multiple_choice.xml from android resources to your own custom xml, change the size attribute, and use it in the listAdapter. you can get the resources from here
{ "language": "en", "url": "https://stackoverflow.com/questions/7595489", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Stop a thread after period of time How can I stop a thread running after it has been running for 5 seconds ? I am unable to use java 5+ threading features (must work in j2me). Possible solution - Schedule two threads. One which performs the actual work(T1) and the other which acts as monitor of T1(T2). Once T1 has started then start T2. T2 calls the isalive() method on T1 every second and if after 10 seconds T2 has not died then T2 invokes an abort on T1, which kills the T1 thread. is this viable ? Timer timer = new Timer(); TimerTask timerTask = new TimerTask() { public void run() { getPostData(); } }; timer.schedule(timerTask, 0); public void abortNow() { try { _httpConnection.close(); } catch(Exception e){ e.printStackTrace(); } } A: There is no unique answer to your question. It depends on what the thread does. First of all, how do you plan to stop that thread? * *If it elaborates some stuff, and this stuff is made of "tokens" such as single "tasks" to do, and the thread grabs them from a BlockingQueue for example, then you can stop the thread with a so-called "poison pill", like a mock task that the thread reads as: "Hey man, I have to shut down". *If the thread does something which cannot be "divided" into "steps" then you should actually tell us how do you think it can be shut down. If it blocks on read()s on a socket, you can only close the socket to unblock it. Please note interrupt() is not meant to stop a Thread in normal circumstances, and if you interrupt() a thread, in most cases it'll just go on doing its stuff. In 99.9% of cases, it is just bad design to stop a thread with interrupt(). Anyway, to stop it after 5 seconds, just set a Timer which does so. Or better join it with a timeout of 5 seconds, and after that, stop it. Problem is "how" to stop it. So please tell me how do you think the thread should be stopped so that I can help you in better way. Tell me what the thread does. EDIT: in reply to your comment, just an example class MyHTTPTransaction extends Thread { public MyHTTPTransaction(.....) { /* ... */ } public void run() { /* do the stuff with the connection */ } public void abortNow() { /* roughly close the connection ignoring exceptions */ } } and then MyHTTPTransaction thread = new MyHTTPTransaction(.....); thread.start(); thread.join(5000); /* check if the thread has completed or is still hanging. If it's hanging: */ thread.abortNow(); /* else tell the user everything went fine */ :) You can also set a Timer, or use Condition on Locks because I bet there can be some race condition. Cheers.
{ "language": "en", "url": "https://stackoverflow.com/questions/7595490", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: android media player streaming issue sorry for my english my problem is in my app media player plays streaming urls. if user clicks next button immediateley then ui blocks for some time and giving ANR problem If it is working on GPRS how to resolve that issue Please some body help me Thanks in advance A: If the UI thread does not get any response within 5 seconds from your action, it will hang and will show you ANR. So, do one thing: whenever user clicks on the button, start a progress loader (spinner) and as soon as you get response from your action, dismiss the progress dialog and show the result.
{ "language": "en", "url": "https://stackoverflow.com/questions/7595493", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Use existing windows mobile 5 app for making android app I have to develop android app which is already made for windows mobile 5 using Visual Studio with C# language. So is there any way to use this existing code to build android app? Anybody knows how to use Rhomobile framework which is used to create multiplatform applications? A: I would give mono for android a try. A: So is there any way to use this existing code to build android app? Nope... sorry. Two different languages. Plus a lot has moved on since Windows Mobile 5! You'll probably want to make something a bit more modern. Anybody knows how to use Rhomobile framework which is used to create multiplatform applications? That's a very broad question, one which can't really be answered here. What I would suggest is having a look at Appcelerator Titanium. It has its own syntax in a javascript-esque style and its pretty good for cross platform apps. Its not as powerful or as diverse as creating apps from scratch natively in each language but its still pretty good, well worth looking into.
{ "language": "en", "url": "https://stackoverflow.com/questions/7595494", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SWT TreeViewer is slow when filling with many elements I'm new in the java world, so I'm sorry if my question is trivial. I'm developing a Eclipse view part, and I'm filling a SWT tree view with the following data structure. All data is in memory: Node1 Child1 Child2 Node2 Child1 ... Child2915 I think that is not a very big tree, but it is slow being drawn (10 seconds). I have manage trees in .NET with more than 10.000 elements and it loaded smoothly. I don't know if I've implemented the code, but the same problem appeared in .NET if I did not call BeginUpdate() - EndUpdate(). Must I call something similar in Java/SWT? Any other tips about why the tree is so slow? A: You could use the SWT.VIRTUAL flag when creating the Tree to help with the performance For more information, see this article on Virtual Trees and Tables This can also be combined with the JFace TreeViewer. See this article on the JFace TreeViewer for more details (although this doesn't specifically mention the virtual flag) A: Finally, I used setRedraw(boolean value) after calling refresh in my TreeViewer. public void refresh() { try { mTreeViewer.getControl().setRedraw(false); mTreeViewer.refresh(true); mTreeViewer.expandAll(); } finally { mTreeViewer.getControl().setRedraw(true); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7595495", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: PHP: tcpdf security considerations of cache folder with write permission I have installed tcpdf on my web server and use it to generate pdf invoices. It has a cache folder and my web server user group www-data can create and delete files. Could a hacker a) create files in that folder and b) execute them as php? Should I move the cache folder outside of the www directory? I tried to cd into the folder but get a permission error with my own username, so I was wondering if that step is necessary. A: If you have not made any changes to your user groups a www-data group is only used for logging purposes and is not able to accessed by the browser. The data user will be able to create but it should not be deleting anything. But as for worrying about hackers accessing your site as long as you have not changed any permissions for this user No.
{ "language": "en", "url": "https://stackoverflow.com/questions/7595496", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: View is not rendering correctly in ASP.NET MVC 3 I have moved a view from folder to Shared folder. When I try to navigate from controller to the shared view it is navigating to the default view and not the shared view. I checked in Global.asax, I created new route in the Global.asax, but it is still pointing to the default route and loading the default view. Could anyone help me in resolving this issue? A: Make sure the old view is deleted, otherwise it will always pick that one over the shared folder. A: if you have not explicitly defined the name of the view e.g lets suppose you have an ActionResult in Home controller public ActionResult Index() { return View(); } the view by the name of Index.aspx and/or Index.ascx is searched first in the Home folder which is present in the Views folder if a matching veiw is found there it is not searched further. If it is not found then it will be searched in the Shared folder make sure you have deleted the view form the Default location
{ "language": "en", "url": "https://stackoverflow.com/questions/7595498", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is it possible to define the execution order in Parallel.For? // parameters.Count == 10 // actualFreeLicenses == 2 Parallel.For(0, parameters.Count, new ParallelOptions() { MaxDegreeOfParallelism = actualFreeLicenses }, i => { ExternalProgram(i); } ); When I execute the above code I notice that the value of i passed to the ExternalProgram method are 1 & 6, later 2 & 7, later 3 & 8 ... If I have 14 Parameters and 2 licenses it always launch 1 & 8, later 2 & 9 ... Is it possible to define order: first 1 & 2, later 3 & 4 etc? A: If you are using Parallel the order in which they are executed is not of relevance therefore "Parallel". You should use a sequential workflow if the order is relevant for you. A: It sounds like you might want to use Parallel.ForEach with a custom partitioner instead - but don't forget that it's not really doing "1 & 6, then 2 & 7" - it's doing (say) 1 on thread 1, 6 on thread 2, then 7 on thread 2, etc. It's not launching pairs of processes as such. If you want to launch groups of processes, you should probably perform the grouping yourself, then loop over those groups in series, only providing the parallelism within the group, by specifying a maximum degree of parallelization equal to the group size. A: How about using a Queue/ConcurrentQueue and dequeueing items in the body of your parallel loop? This will ensure that ordering is preserved. A: If you could switch to using a ForEach (after having generated a range of numbers, perhaps, using IEnumerable.Range), you could use one of the overloads that takes a Partitioner<T>. That third link includes a sample partitioner that provides a single element at a time. A: It would appear that the runtime is looking at how many threads you want to use and dividing the workload up into that. e.g. the first thread is working on the first half of the dataset and the second thread is working on the second half of the data.
{ "language": "en", "url": "https://stackoverflow.com/questions/7595503", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: jQuery jGrowl not working I am trying to get this jGrowl working but I am not having any luck and I am struggling to find any help with the issue I have. I have connected to the CSS and JS pages correctly: <script type="text/javascript" src="<?php echo $base; ?>jgrowl/jgrowl.js"></script> <link type="text/css" rel="stylesheet" media="all" href="<?php echo $base; ?>css/jgrowl.css"/> And I am trying two different methods to get it working, the first method is the method that I actually want, which is when an if statement is run it should show the jGrowl window like below: if ($flag == "OK") { ?> <script type="text/javascript"> $(function() { $.jGrowl("HELLO"); } ); </script> <?php } But this gives me no luck, so I am also trying an onclick version: <p><a href="javascript:void(0);" onclick="$.jGrowl('One more message...');">Click here.</a></p> This also give me no luck, but what does happen with this on is in Google Chrome's console it gives me this error: Uncaught TypeError: Object function (a,b){return new e.fn.init(a,b,h)} has no method 'jGrowl' I have tried to find help based around this error but have had no luck, hope someone can help! Thanks guys. ---------------- UPDATE ------------------ I have been playing around a bit and I a little more information out of the error in the Google Chrome Console... Uncaught TypeError: Object function (a,b){return new e.fn.init(a,b,h)} has no method 'jGrowl' (anonymous function) index.php:572 f.extend._Deferred.e.resolveWith jquery-latest.min.js:2 e.extend.ready jquery-latest.min.js:2 c.addEventListener.C jquery-latest.min.js:2 Im not 100% sure but I think jquery-latest.min.js is referring to: <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script> Which I use to enable facebook commenting within the website. Could this be an issue? ---------------- UPDATE ------------------ If I comment out <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script> Then my jGrowl works, any idea how I can get around this? otherwise I cant have both jGrowl and facebook commenting. ---------------- UPDATE ------------------ I now understand what is going wrong, I had both: <script type="text/javascript" src="<?php echo $base; ?>js/jquery-1.4.2.js"></script> and <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script> I was not aware the the second one of these two is also getting the main jQuery library therefore causing the problems with my jQuery. All is fixed an sorted now. ------------ PROBLEM SOLVED ------------- A: I realised that I was linking to the jQuery libary twice by accident, all fixed now. @Brad there are 3 ways of doing it: Link to file <script type="text/javascript" src="<?php echo $base; ?>js/jquery-1.4.2.js"></script> Link to latest-min <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script> Link to google <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js" type="text/javascript"></script> But you can only have 1 of these, if you have more than 1 your jQuery/JavaScript will fail
{ "language": "en", "url": "https://stackoverflow.com/questions/7595510", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: solr synonyms not being parsed I'm making an auto-suggest feature using past searches in solr. Synonyms.txt contains a list of common typos / misspellings etc. It's setup to run on index and using the anaysis tool in the admin I can see it's working correctly - however it doesn't seem to be applied to live data. Field type : <field name="suggest_ngrams" type="text_ngram" indexed="true" stored="false" multiValued="true" /> Schema: <fieldType name="text_ngram" class="solr.TextField" positionIncrementGap="100"> <analyzer type="index"> <tokenizer class="solr.KeywordTokenizerFactory"/> <filter class="solr.LowerCaseFilterFactory"/> <filter class="solr.StopFilterFactory" ignoreCase="true" words="stopwords_en.txt" enablePositionIncrement="true"/> <filter class="solr.SynonymFilterFactory" synonyms="synonyms.txt" ignoreCase="true" expand="false"/> <filter class="solr.EdgeNGramFilterFactory" minGramSize="2" maxGramSize="15" side="front"/> </analyzer> <analyzer type="query"> <tokenizer class="solr.KeywordTokenizerFactory"/> <filter class="solr.LowerCaseFilterFactory"/> <filter class="solr.StopFilterFactory" ignoreCase="true" words="stopwords_en.txt" enablePositionIncrement="true"/> </analyzer> and an example of synonyms.txt watch, watches, watche, watchs => watch So at index time I would expect "watche" to be replaced with "watch" - this doesn't seem to be the case (even though the analysis tool says that's what it's doing. To be clear if I query solr (?q=watc) the phrase "watche" appears in the results Any ideas or insight would be appreciated as I think everything is setup correctly Thanks A: If I got the issue right :- The synonyms are used only during index time and do not affect the stored values. So what you see in the analysis is the index time values, which seem to work fine. When you query solr and it matches this result, the results would return "watche" only, as this is the original value stored. The stored values are never modified and are stored as is and returned in the response. Please clarify if i got it wrong. A: As @Jayendra described solr doesn't change stored value. Therefore you should find another way of handling this obstacle. In my case I come up with a solution using facet. If you facet on that field you receive the indexed value(Mapped). Another solution is You can apply the filters to the data in a separate process prior to loading the data into Solr
{ "language": "en", "url": "https://stackoverflow.com/questions/7595514", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: xCode Is there a way to create a relation between back button and tabbar? Hi I am a new bee to iPad development. I have created a Tabbar application in xcode and created 5 tabs. I am able to load 5 different views. Each view consists of a navigation bar cont and tabbar by default. I have added a back button to navigation bar to the four tabs. When in the detail pages i.e., Tab 2 I am tapping on the back button it returns to the Home page(First Tab View). and I go to other tabs and when I return to the 2nd tab home page is displayed. To my understanding when I am clicking on the back button a new layer is been created. if this so then how can I reload the view in the tabs when I revisit the tab Can anybody let me know what could be the problem. Thanks in advance, Kris A: Difficult to understand your exact problem from your description, but reading between the lines it sounds like you've set the tab bar / view controller structure up wrong to me. I have created a similar app in the past where I have a tabbar in the root view controller and then 3 navigation view controllers each assigned to a tab of the tab bar (but there's only one instance of the tab bar - reading your message it seems like you have one for each navigation view controller?) Thinking about this more, if you are creating a new tab bar with each navigation view controller, then when you tap on another tab you are creating yet another view controller and before long you would have a massive number of view controllers and tab bars active. You should only have one tab bar in your app. If you have it set up correctly when you switch tabs you should return to whatever level of pushed view controllers you previously had within each tab. Are you by any chance having to recreate the view controllers when the tab switch somehow?
{ "language": "en", "url": "https://stackoverflow.com/questions/7595516", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Visual Studio 2010 VSTO Excel 2007 multilanguage? I have to add multilanguage support to several existing VSTO Excel AddIns. Adding this to the user controls etc. was relatively easy, but now I have to add multilanguage support for existing entries in Excel Files. These files are used as templates. Does anybody know how to do this, without replacing the cell-entries by code but with resources files or anything like that?
{ "language": "en", "url": "https://stackoverflow.com/questions/7595518", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: I tried to use the syntax $inf_ to get value for checkut attributes I am getting the value but the problem is that the value gets wrapped in span tag. For example 2 get the subtotl, I used var subtotal=$inf_cartAmt(chkCartSubtlAmt); Output for above syntax is var subtotal=<span class="cartAmt_chkCartSubtlAmt"> $94.93 </span>; Note how the val $94.93 is wrapped in span tag. Do we have any other syntax which can just give the value. A: It's hard to tell what $inf_cartAmt is from your code, but you could try - $inf_cartAmt(chkCartSubtlAmt).text(); Failing that, you could use jQuery to remove the span tag from your string - subtotal = $(subtotal).text()
{ "language": "en", "url": "https://stackoverflow.com/questions/7595524", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Postcript: maximum array size? Is there a maximum size for a postscript array ? I wrote a PS document containing containing an array that is displayed in ghostview without any problem. But when the number of items in this array increases, ghostview raises the following exception: ERROR: /stackoverflow in -file- Operand stack: --nostringval-- Execution stack: %interp_exit .runexec2 --nostringval-- --nostringval-- --nostringval-- 2 %stopped_push --nostringval-- --nostringval-- --nostringval-- false 1 %stopped_push 1 3 %oparray_pop 1 3 %oparray_pop 1 3 %oparray_pop 1 3 %oparray_pop .runexec2 --nostringval-- --nostringval-- --nostringval-- 2 %stopped_push Dictionary stack: --dict:1122/1686(ro)(G)-- --dict:0/20(G)-- --dict:122/200(L)-- Current allocation mode is local Last OS error: 2 Current file position is 301163 ESP Ghostscript 815.02: Unrecoverable error, exit code 1 A: There is a maximum array length: 65535. This is also the maximum string length. But that doesn't appear to be the problem here. Postscript Level 2 removed the limit on stack size, so it should automatically expand to whatever size the virtual memory system can manage. If you're getting a /stackoverflow error; you need to upgrade your interpreter to at least the Level 2 (1991) standard. Edit: That said, there are ways to work around the problem if upgrading isn't an option. The limit most likely occurs because the stack is being statically allocated. If you have access to the source code, you can simply increase the size and recompile the interpreter. The limit quoted in the PLRM 1ed is 500. Another option is to change the way you work with the stack (harder). If you cannot construct a 1000 element array using [] or {} you can still allocate the array (1000 array) and fill it with slices constructed normally (dup dup 0 [ 0 1 .. 450 ] putinterval dup dup 450 [ 451 452 .. 900 ] putinterval dup dup 900 [ 901 902 .. 999 ] putinterval). Remember, marks take up space on the stack too; and certain operators are really procedures and they will need stack space to operate. Edit: If the arrays are truly huge, array slices may run you up against total memory limits; because if you don't have growing stacks, you probably don't have garbage collection either. The above method leaves 1000 arrays elements used and inaccessible in VM. Using packedarray for the slices might forstall this problem somewhat. The next step would be to write a procedure that works like a hybrid of putinterval and packedarray that can load data into an array without creating temporary arrays. This may run slower since we're reimplementing low-level functionality at a higher level. Here's a first stab. It reads ahead (using currentfile token) and puts each element into subsequent positions of the array. arrayfill must be the last word on the source line (like image) so currentfile can find the first element (the remainder of the source line is in an internal scanner buffer). % array index count arrayfill(NL) array % elem_0 elem_1 .. % elem_count-1 /arrayfill { %a i c 1 index add 1 sub %a ini fin 1 exch { %a i 2 copy %a i a i currentfile token pop %a i a i el put %a i pop %a } for } def %example 5 array 0 5 arrayfill (0) (1) (2) (3) (4) {=} forall
{ "language": "en", "url": "https://stackoverflow.com/questions/7595532", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Generating a time series with a specific start and end date I want to generate a time series with all business dates in the range: startDate = "1990-01-01" endDate = "1990-12-31" For example "1990-01-01", "1990-01-02", ... A: You can just use the seq command. For example, ##Specify you want 10 dates starting on 1990-01-01 R> seq(as.Date("1990-01-01"), length.out=10, by="1 day") [1] "1990-01-01" "1990-01-02" "1990-01-03" "1990-01-04" "1990-01-05" [6] "1990-01-06" "1990-01-07" "1990-01-08" "1990-01-09" "1990-01-10" or ##Specify the start and end with increment R> seq(as.Date("1990-01-01"), as.Date("1990-01-10"), by="1 day") [1] "1990-01-01" "1990-01-02" "1990-01-03" "1990-01-04" "1990-01-05" [6] "1990-01-06" "1990-01-07" "1990-01-08" "1990-01-09" "1990-01-10" To just get business days, you can use the chron library: days = seq(as.Date("1990-01-01"), as.Date("1990-12-31"), by="1 day") library(chron) weekDays = days[!is.weekend(days)] A: There is a base function called ?weekdays. startDate = "1990-01-01" endDate = "1990-12-31" x <- seq(as.Date(startDate), to = as.Date(endDate), by="1 day") x[!weekdays(x) %in% c("Sunday", "Saturday")] But, since the actual names of the days will be locale-specific, be sure to set those correctly. Note that weekdays is just a wrapper on format(x, "%A"). See ?strptime for the details on the format codes. A: @csgillespie: chron provides the function is.weekend: days = seq(as.Date("1990-01-01"), as.Date("1990-12-31"), by="1 day") library(chron) weekDays = days[!is.weekend(days)] ## let's check the result with the function weekdays weekdays(weekDays) Besides, you can get the same results without chron using format: isWeekend <- function(x) {format(x, '%w') %in% c(0, 6)} weekDays2 = days[!isWeekend(days)]
{ "language": "en", "url": "https://stackoverflow.com/questions/7595533", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Scretch image in web browser component c# is there any way to stretch image to size of webbrowser in webbrowser component? (winforms, c#) Thanks!
{ "language": "en", "url": "https://stackoverflow.com/questions/7595536", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to solve a Mercurial case-folding collision? I use Mercurial as source control with the main repository managed on KILN. At one point in time I changed my iOS project name from WeatherTimeMachine to weathertimemachine. This resulted in a case change of several files and folders: * *WeatherTimeMachine.xcode *WeatherTimeMachine_Prefix.pch *WeatherTimeMachine-Info.plist In the meantime I've added a tag to a revision in KILN... So I now have: * *a head in KILN *a head on my local repo with case changes When trying to merge I get the following error message: "Mercurial case-folding collision" How can I fix this? A: I have found some information here: FixingCaseCollisions, but somehow this did not work for me. Here is how I managed to solve this issue: Make a copy of your existing repository folder (for safety). For example: * *cp -r WeatherTimeMachine WeatherTimeMachineCopy Fool mercurial into thinking the problematic revision is the current tip: * *hg debugsetparents <bad revision> *hg debugrebuildstate Remove the files which are causing the problem (-f is required to force the removal). Here is an example: * *hg rm -A -f WeatherTimeMachine-Info.plist Once all problematic files have been removed, commit the changes * *hg ci -m "fixed collision-folding issue" -u michael Then restore mercurial to the proper revision * *hg debugsetparents tip *hg debugrebuildstate After this the merge is possible and the problem is gone. And now I can happily resume working with MacHg to manage my Mercurial repository and push my change sets to KILN. A: If you're on Mac OS X, you don't need to export your repository to Linux or another foreign case-sensitive file system as suggested by the Mercurial documentation. Just use Disk Utility to create a case-sensitive, journaled disk image slightly bigger than your repository, copy your repo there, then remove the conflicting files and commit. A: This is a no-programming no-hg answer, but it solved my mercurial case-folding problems once and for all! For now anyway.. I gave up trying to avoid and "fix" the case-collision problems. That just looks ugly and you can never really "solve" the problem, only can do a workaround. The only way (that I can think of) to really solve the problem is to have a case-sensitive filesystem. No need to reformat your entire disk, a single partition will do the job nicely. I used the Disk Utility app that comes with the os, pretty straightforward, just remember to select Mac OS Extended (Case-sensitive, Journaled) when creating new partition. Also, note that the Disk Utility can resize partitions only by moving the end (not the beginning) of partition. You can probably create a symlink to where your old source code lived, so no need to change the IDE settings and stuff (but I haven't tried this, just happy with the new partition). A: We resolved this without resorting to a case-sensitive filesystem by issuing HG rename commands. Say you are having trouble because "Foo.txt" needs to be called "foo.txt": > hg rename Foo.txt Foo.txt.renamed > hg rename Foo.txt.renamed foo.txt We encountered this problem when a file was deleted and then later re-created in the main repository with the same name, but different case. A branch repository that was created before these changes could not then be merged in, despite the changesets from the main repository having been pulled. A: For Mac OS X, what worked for me is to simply copy the folder (duplicate works - cmd-D) and continue working on it, from the new path. A: OSX same I wanted to clone a repo and I had case-folding error preventing me top clone. If the repository has multiple commit simply clone an earlier revision with this command: hg clone -r 7 Then add anything conflicting to the .hgignore file and update.
{ "language": "en", "url": "https://stackoverflow.com/questions/7595538", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: const qualification conversion From (4.4/1 ) It reads An rvalue of type “pointer to cv1 T” can be converted to an rvalue of type “pointer to cv2 T” if “cv2 T” is more cv-qualified than “cv1 T.” I don't know where the standard defines 'more cv-qualifield' type but as I understood a declarator with const is more cv-qualified than than a non-const. For following conversions, how does the quote from standard fits in or how you know which one is less or more cv-qualifed? int *const c1 = 0; int const* c2 = 0; const int *const c3 = 0; c1 = c2; // allowed c1 = c3; // allowed Update: c2 = c1; c2 = c3; A: Table 6 in 3.9.3/4 gives the partial ordering of cv-qualifiers and 3.9.3/4 also gives the definition of more cv-qualified. * *no cv-qualifier < const *no cv-qualifier < volatile *no cv-qualifier < const volatile *const < const volatile *volatile < const volatile A: Since c1 is a const pointer variable (which is different to a pointer to constant data), it cannot be modified. Therefore, both assignments are illegal. What the standard refers to is this case: int *d1 = 0; const int* d2 = d1; // d2 is more cv-qualified than d1 const volatile int* d3 = d1; // d3 is more cv-qualified than d2 A: I don't know where the standard defines 'more cv-qualifield' type It is §3.9.3/4 There is a (partial) ordering on cv-qualifiers, so that a type can be said to be more cv-qualified than another. Table 6 shows the relations that constitute this ordering. Table 6—relations on const and volatile no cv-qualifier < const no cv-qualifier < volatile no cv-qualifier < const volatile const < const volatile volatile < const volatile That is, * *const T is more cv-qualified than T. *volatile T is more cv-qualified than T. *const volatile T is more cv-qualified than T. *const volatile T is more cv-qualified than const T. *const volatile T is more cv-qualified than volatile T.
{ "language": "en", "url": "https://stackoverflow.com/questions/7595541", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Can't remove records from DataGrid when it binded to Dictionary<,> I have some Dictionary with data. I use it as an ItemsSource for my WPF DataGrid. Dictionary<string, string> dic = new Dictionary<string, string>(); dic.Add("1st", "entry"); dic.Add("2nd", "entry 2"); dic.Add("3rd", "entry 3"); dataGrid1.ItemsSource = dic; <DataGrid Name="dataGrid1" CanUserDeleteRows="True" AutoGenerateColumns="True"> <DataGrid.Columns> <DataGridTextColumn Binding="{Binding Path=Key}"/> <DataGridTextColumn Binding="{Binding Path=Value}"/> </DataGrid.Columns> </DataGrid> Why is it not letting me delete rows? :( A: it does not work because Dictionary do not implement IEditableCollectionView. here is a nice overview for the editing features of the datagrid. but you can do the deleting by your self. Create a command with parameter selected items from your datagrid and delete the items from your dictionary by your self. at this time you should think about using a ObservableCollection as an intemssource because of notifying the view.
{ "language": "en", "url": "https://stackoverflow.com/questions/7595548", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Google place page is not shown in Android webview I am trying to show http://www.google.co.jp/m/place#ipd:mode=home website thru WebView in Android emulator but I am not seeing the web site and seeing only blank space under the place tag of the page. I am able to see other sites like www.google.com. Do I need to enable more settings for the google place page? Permission in the manifest <uses-permission android:name="android.permission.INTERNET" /> Code WebView view= (WebView) findViewById(R.id.view1); View.getSettings().setJavaScriptEnabled(true); View.getSettings().setBuiltInZoomControls(true); View.getSettings().setSupportZoom(true); View.loadUrl(" http://www.google.co.jp/m/place#ipd:mode=home"); A: You need to do view.getSettings().setAppCacheEnabled(true); view.getSettings().setDomStorageEnabled(true); on the setting object. That fixed the problem for me.
{ "language": "en", "url": "https://stackoverflow.com/questions/7595550", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to print screen of a SWT window from a SWT based application I would like to allow a user to print an application window she or he interacts with. I am looking for examples how to implement such a print screen functionality for SWT based GUI. A: SWT's StyledText widget directly supports printing its contents. Otherwise, you'll have to build your own print function using the org.eclipse.swt.printing classes Printer, PrinterData, and PrintDialog. The standard pattern for printing involves the following steps: * *Create a Printer object *Start a print job *Create a GC *Start a page *Draw on the page *End the page *Repeat the start, draw, and end cycle for as many pages as you need to print *End the print job *Clean up A: A very simple method is (which we use in our product) to take the screenshot of the window and then print it using SWT printer api. See the below code for taking screen capture of a window. >> Orignal Window >>Screen capture >>Code The code tells only about the screen capturing of a particular window. Check the printer api usage here SWT Printer Usage. In this code I am creating a GC for the display and then copying the area in which the shell is present. import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StyleRange; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.events.PaintEvent; import org.eclipse.swt.events.PaintListener; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Canvas; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.TableItem; public class ScreenCaptureTest { public static void main(String[] args) { String[] names = {"Harry", "Sally", "Jhon", "Tim", "Scott"}; String[] msg = {"Hello World!", "Today is a nice day to walk", "I am bored", "This is how you take widget capture", "Ha Ha Ha!! That's funny !"}; final Display display = new Display(); final Shell shell = new Shell(display); shell.setText("Screen Capture"); shell.setLayout(new GridLayout(1, true)); final Composite composite = new Composite(shell, SWT.BORDER); composite.setLayout(new GridLayout(2, true)); composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); /* * Create Table Widget */ Table table = new Table(composite, SWT.BORDER|SWT.V_SCROLL|SWT.H_SCROLL|SWT.FULL_SELECTION); table.setLinesVisible(true); table.setHeaderVisible(true); table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); TableColumn columnName = new TableColumn(table, SWT.LEFT); columnName.setText("Name"); columnName.setWidth(100); TableColumn columnMsg = new TableColumn(table, SWT.LEFT); columnMsg.setText("Message"); columnMsg.setWidth(200); for (int i = 0; i < 5; i++) { TableItem item = new TableItem(table, SWT.NONE, 0); item.setText(0, names[i]); item.setText(1, msg[i]); } /* * Create StyledText Widget */ StyledText text = new StyledText (composite, SWT.BORDER); text.setText("0123456789 ABCDEFGHIJKLM NOPQRSTUVWXYZ"); text.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); StyleRange style1 = new StyleRange(); style1.start = 0; style1.length = 10; style1.fontStyle = SWT.BOLD; text.setStyleRange(style1); StyleRange style2 = new StyleRange(); style2.start = 11; style2.length = 13; style2.foreground = display.getSystemColor(SWT.COLOR_RED); text.setStyleRange(style2); StyleRange style3 = new StyleRange(); style3.start = 25; style3.length = 13; style3.background = display.getSystemColor(SWT.COLOR_BLUE); text.setStyleRange(style3); /* * Create Button */ Button button = new Button(shell, SWT.PUSH); button.setText("Capture"); button.pack(); button.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { /* * Widget capturing logic */ GC gc = new GC(display); final Image image = new Image(display, shell.getBounds()); gc.copyArea(image, shell.getBounds().x, shell.getBounds().y); gc.dispose(); Shell popup = new Shell(shell); popup.setText("Captured Image"); popup.addListener(SWT.Close, new Listener() { public void handleEvent(Event e) { image.dispose(); } }); Canvas canvas = new Canvas(popup, SWT.NONE); canvas.setBounds(0,0,image.getImageData().width, image.getImageData().height); canvas.addPaintListener(new PaintListener() { public void paintControl(PaintEvent e) { e.gc.drawImage(image, 0, 0); } }); popup.pack(); popup.open(); } }); shell.pack(); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } display.dispose(); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7595552", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Selecting a random HTML element using JavaScript only I'm trying to select an element from my HTML code, to then use it in JavaScript (it needs to be highlighted). The HTML consists of a table with 36 td's. My code so far: var box; function getRandom() { return (Math.floor(Math.random()*37)) } function highlight() { box = document.getElementById(getRandom()); box.style.backgroundColor = "yellow"; } If anyone can give me any pointers, it'd be appreciated. I know it would be easy using jQuery, but I haven't begun learning that yet. Edit: excerpt of the HTML code, this goes up to name="36". <table id="reflexTable"> <tbody> <tr> <td name="1"></td> <td name="2"></td> <td name="3"></td> <td name="4"></td> <td name="5"></td> <td name="6"></td> </tr> A: A nicer way that does not involve setting element ids: function highlight() { // get all TDs that are descendants of table#reflexTable: var tds = document.getElementById('reflexTable').getElementsByTagName('td'); // get a random int between 0 (inclusive) and tds.length (exclusive) var rand = Math.floor( Math.random() * tds.length ); // highlight td at that index tds[rand].style.backgroundColor = "yellow"; } The big advantage of this method is that you can add/remove as many TDs as you please without needing to edit your JS to generate a valid random number. A: getElementById gets the element which has the matching id. Your table data cells don't have an id at all. They have a name, but HTML doesn't allow that. Switch to id. HTML 4 doesn't allow an id to start with a number. Prefix the id with a common string. Then: document.getElementById("foo" + getRandom()); A: You're not setting the id attribute, you're setting the name attribute, change it to: <td id="1"></td> ...etc A: Several things: * *You should declare the box variable inside the highlight function. *You have to convert that random number to a string. *Quentin mentioned something important--you should give each table element an id of something like "s0","s1","s2", etc... *Start the naming at 0 because your getRandom function will sometimes return it. function highlight(){ var number; number = getRandom().toString(); var box; box = document.getElementById("s" + number); box.style.backgroundColor = "yellow"; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7595557", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: what if broswer does-not allow cookie I am working on a web based application with JSP and servlets. I am using the Cookie class and response.getCookie method to set cookies in the browser. But I have a doubt as to how will the behavior be when the browser does-not allow cookies, through browser setting. In this case, will the servlet code like getCookie throw any exception? How will be the behavior ? A: In this case, will the servlet code like getCookie throw any exception? No. It will merely return null. How will be the behavior ? Exactly the same as if the user had never visited your site before and directly opened that page.
{ "language": "en", "url": "https://stackoverflow.com/questions/7595558", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can I disable the Facebook login button on certain conditions? I want to allow the user to click the 'fb:login-button' (which I'm using for registration as well) only if they've entered valid input in a text box on my page. Is there a way to do this? A: One simple way would be to position a div directly on top of the button. If the div is transparent, the user will see the button but not be able to click on it; if the div is the color of the background, it will make the button "hidden"; or you could even have a semi-opaque div to give the button a "dimmed" effect. In each case just move the div or set display:none to return the button to normal operation. A: Why not use the registration plugin and do validation of your custom field yourself?
{ "language": "en", "url": "https://stackoverflow.com/questions/7595567", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: what the function that I can use in Javascript to convert from one character encoding to another? what the built-in or user-defined function that I can use in Javascript or jQuery to convert from one character encoding to another? For Example, FROM "utf-8" TO "windows-1256" OR FROM "windows-1256" TO "utf-8" A practical use of that is if you have a php page with specific character encoding like "windows-1256" that you could not change it according to the business needs and when you use ajax to send a block data from database using json which uses "utf-8" encoding only so you need to convert the ouput of json to this encoding so that the characters and the strings will be displayed well Thanks in advance ..... A: From the standpoint of a JavaScript runtime environment, there's really no such thing as character encodings – the messiness of encodings is abstracted away from you. By spec, all JS source text is interpreted as Unicode characters, and all Strings are Unicode. As such, there's no way in JavaScript to represent characters in anything other than Unicode. Look at the methods available on a String instance – you'll see there's nothing related to character encoding. Because JavaScript runs in Unicode, and all JavaScript strings are stored in Unicode, all AJAX calls will be transmitted over the wire in Unicode. From the jQuery AJAX docs: Data will always be transmitted to the server using UTF-8 charset; you must decode this appropriately on the server side. Your PHP script is going to have to cope with Unicode input from AJAX calls.
{ "language": "en", "url": "https://stackoverflow.com/questions/7595569", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to check is not null and greater than in android sqlite query I am using db query, how to check one value is not null and greater than other value in a query. db.query(DB_TAB, new String[] { KEY_ROWID, stemp, dtemp },stemp + "!=" + null, null, null, null, null, null); I want to check both stemp and dtemp is not null and also dtemp is greater than stemp. A: Also, different in sqlite is "<>" not "!=".
{ "language": "en", "url": "https://stackoverflow.com/questions/7595572", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: URL encoding in javascript I have this parameter user@ampliflex.co.in in my url. I want to encode it using javascript, I dont want . in my url. A: Even if you encode . in JavaScript, the browser is allowed to unencode it before sending it to a server. RFC 3986 section 6.2.2.2. Percent-Encoding Normalization says The percent-encoding mechanism (Section 2.1) is a frequent source of variance among otherwise identical URIs. In addition to the case normalization issue noted above, some URI producers percent-encode octets that do not require percent-encoding, resulting in URIs that are equivalent to their non-encoded counterparts. These URIs should be normalized by decoding any percent-encoded octet that corresponds to an unreserved character, as described in Section 2.3. '.' is an unreserved character in URLs. unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
{ "language": "en", "url": "https://stackoverflow.com/questions/7595573", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: drop down menus on tablet pcs Hi is there a good way to implement drop downs so that they're functional on tablet pc's, either with css or javascript. Obviously there are workarounds such as including alternative navigation areas, I just wondered if there was a way to get them working. A: Here is an idea for jQuery solution for iPads and iPhones based on detecting userAgent (uses click instead on mouseover): if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) ||(navigator.userAgent.match(/iPad/i))) { $(".link").click(function(){ $(".submenu").show(); //you can insert other stuff here return false; }); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7595577", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: JSR-303 and JPA overlapping Aloha hey! I already use JPA annotations, now I'd like to use JSR-303 annotations to validate attributes as well. My questions is, how well do they interact with each other? If I use @Basic(optional=false) or @NotNull, will I still have to use nullable=false etc.? I haven't decided which validator implementation to use, e.g. hibernate-validator or oVal (You may also suggest others. I know that oVal is not a JSR-303 implementation, but it maps most annotations). oVal manual (see above) states that certain JPA annotations will be translated into oVal annotations as well. Hibernate-validator has a similar mechanism. Some search results claim that Bean Validation and JPA do officially overlap, but I have not figured in which exact way. A: They are both run time checks . There is some difference though JPA specification states @Basic(optional = false) can be use as schema hint i.e if you are updating your database schema by JPA (generally not a good practice though) you can use it to indicate that this column value can not be null and must have a value. Section 9.1.18 Basic Annotation of JPA1 specification and Section 11.1.6 Basic Annotation of JPA2 specification Clearly indicate that. Other than that both will do a runtime check in other words before the sql is send to database. Generally for validation prior to sending SQL to server if you are using JSR 303 which includes many other checks as well you will use @NotNull however you may not be using JSR 303 in which case you can use @Basic(optional = false) which has been out even before JSR 303 however is not preferred over JSR303. You might now want to know @Column(nullable = false) is purely used on database side. Should you ever use both - Yes only if you are allowing JPA to update schema otherwise JSR-303 is preferred over the other. A: After reading both specifications almost entirely, this is what I found. I'll thusly answer my question myself; As of now; * *JPA and BV annotations do often share the same meaning. The usage of BV constraints however does not influence the created DDL schema constraints of the JPA implementation. *The JPA implementation will, if configured so, check BV constraints at pre-persist, pre-update, and pre-remove. This is done by delegating the work to the BV implementation. The BV implementation on the other hand will not use JPA constraints. *Using BV constrains such as @NotNull to automatically cause JPA constraints such as @Column(nullable=false) is recommended to the JPA implementation in the BV specification, but not part of the official specification and thus not reliable behaviour. As a result I will have to use both BV and JPA annotations, even though they may have the same meaning. References * *Section 3.6 Bean Validation - JPA2 specification. *Appendix D Java Persistence 2.0 integration - Bean validation specification. P.S.: I will wait whether someone has any corrections or additions to this, then set is as the preferred answer.
{ "language": "en", "url": "https://stackoverflow.com/questions/7595578", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Designing Regular Expressions in C# I've run into a bit of an issue designing RegEx in C#. I have to parse a text document that has multiple urls embedded in it, and I have to extract those ...url=http://www.cnn.com?id=abc,def&system=2&mode=2&quality=ade,url=http://www.bbc.com... (^ I've added ellipsis to show that its part of content, ... won't actually be in the text) The begining part is easy as I can start regex with 'url=', however, I can't come up with a way of ending the match RegEx = (?<IgnoreFirst>[,]url=)(?<Url>[^,]+) This regex stop at first comma - so just after 'abc' and doesn't return the entire url RegEx = (?<IgnoreFirst>[,]url=)(?<Url>[^,]+)(?<IgnoreSecond>url) This doesn't work either because the match stops at first comma and then looks for 'url', which it couldn't find. From some of the reading I've done it seems like its an issue of backtracking etc, so if anyone can help me out with the correct regex, that'd be great! PS. while we're at it, if I wanted to extract url just before &quality, how would I do that? A: How about using something like this: RegEx = url=(?<Url>.+?)(?=,url|$) The lookahead at the end will force matching to stop either at the next ",url" or at the end of the string or line.
{ "language": "en", "url": "https://stackoverflow.com/questions/7595580", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Force WPF DataGrid to regenerate itself I have a custom control which inherits from DataGrid and is basically a 2D DataGrid (accepts an ItemsSource with two dimensions, such as double[,] ). I added a specific DependencyProperty which is ColumnHeaders and RowHeaders so I can define them. Here is how it works right now: * *I bind a 2D ItemsSource to the DataGrid *A wrapper method will take this source to transform it to a classic IEnumerable bindable to the actual datagrid's ItemsSource *Each row / column auto-generated is done using the events AutoGeneratingColumn & AutoGeneratingRow in order to define their header The problem here: When I initialize the DataGrid, everything works fine. After that, one of the use-cases of my application defines that only the column headers can change (by modifying the DependencyProperty ColumnHeaders And, whatever I do here, the DataGrid won't re-autogenerate its columns (and therefore, headers won't be changed in any way). So, is there a way to ask the DataGrid something like "Hey, I want you to restart from scratch and regenerate your columns" ? Because for now, I can't reach the AutoGeneratingColumn event, and calling a method such as InvalidateVisual will just redraw the grid (and not regenerate columns). Any ideas here? I'm not sure that we need some code but... I'll put some so nobody asks for it :D /// <summary> /// IList of String containing column headers /// </summary> public static readonly DependencyProperty ColumnHeadersProperty = DependencyProperty.Register("ColumnHeaders", typeof(IEnumerable), typeof(FormattedDataGrid2D), new PropertyMetadata(HeadersChanged)); /// <summary> /// Handler called when the binding on ItemsSource2D changed /// </summary> /// <param name="source"></param> /// <param name="e"></param> private static void ItemsSource2DPropertyChanged(DependencyObject source, DependencyPropertyChangedEventArgs e) { FormattedDataGrid2D @this = source as FormattedDataGrid2D; @this.OnItemsSource2DChanged(e.OldValue as IEnumerable, e.NewValue as IEnumerable); } // (in the constructor) AutoGeneratingColumn += new EventHandler<DataGridAutoGeneratingColumnEventArgs>(DataGrid2D_AutoGeneratingColumn); void DataGrid2D_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e) { DataGridTextColumn column = e.Column as DataGridTextColumn; column.Header = (ColumnHeaders == null) ? columnIndex++ : (ColumnHeaders as IList)[columnIndex++]; //Header will be the defined header OR the column number column.Width = new DataGridLength(1.0, DataGridLengthUnitType.Auto); Binding binding = column.Binding as Binding; binding.Path = new PropertyPath(binding.Path.Path + ".Value"); // Workaround to get a good value to display, do not take care of that } A: Reset your ItemsSource and it should redraw your DataGrid void ResetDataGrid() { var temp = myDataGrid.ItemsSource; myDataGrid.ItemsSource = null; myDataGrid.ItemsSource = temp; } You might also be able to refresh the binding, but I haven't tested it to see if this will actually regenerate the DataGrid: void ResetDataGrid() { myDataGrid.GetBindingExpression(DataGrid.ItemsSourceProperty).UpdateTarget(); } A: Toggling AutogeneratedColumns off and then on will cause the columns to be automatically generated again. dataGrid.AutoGenerateColumns = false; dataGrid.AutoGenerateColumns = true;
{ "language": "en", "url": "https://stackoverflow.com/questions/7595583", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: As a working-traveler, is there a way to get around port 80 blockage without touching the router? I work while traveling at the moment. I'm at the point where I want to start setting up the paypal integration, but I can't because I can't open port 80 up so that paypal sandbox can communicate with my computer. I've tried getting my own USB modem w/ sim card (data plan) but it seems they are really aggressive with blocking ports on those also. So, i can't get to the routers in the hotels since it would be wrong (and i don't have the passwords). Is there some kind of trick that I can use so I can mess with paypal sandbox integration? I've tried using hosting (godaddy) but it's awful slow to keep uploading changes to a host just to see if what you did worked (not to mention problems with debugging). A: Looks like i didn't get any help this time, but i found a way around it! I created a VPN in Windows 7 in my home network (so my work laptop can connect back home). I checked the setting that allows remote vpn connections to pick their own IP address so my work laptop would have a static ip. I then simply opened up port 80, and forwarded it to the static IP set for my laptop. I can't believe it, but it works!
{ "language": "en", "url": "https://stackoverflow.com/questions/7595584", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Threading in CLR in SQL Server 2008 I have a CLR process which runs under SQL Server2008. It builds a cache of several tables data to hold in a static class for use later by other calls. My question is could I improve the process of loading this cache by spawning threads to load each data set/ table in my cache? I've steared clear of this in the past as various posts have suggested leave the thread management to SQL Server. However I could really do with speeding up this process. Currently its a sequential process to load each data set. If I could run these concurrently it would be very handy. A process I've done many atime outside of the CLR cover to get some extra performance gains. Any ideas help tips very much appreciated. A: You can use threads, but they must behave. Otherwise you'll lose the benefits of using them. From the CLR Host Environment How SQL Server and the CLR Work Together This section discusses how SQL Server integrates the threading, scheduling, synchronization, and memory management models of SQL Server and the CLR. In particular, this section examines the integration in light of scalability, reliability, and security goals. SQL Server essentially acts as the operating system for the CLR when it is hosted inside SQL Server. The CLR calls low-level routines implemented by SQL Server for threading, scheduling, synchronization, and memory management. These are the same primitives that the rest of the SQL Server engine uses. This approach provides several scalability, reliability, and security benefits. Scalability: Common threading, scheduling, and synchronization CLR calls SQL Server APIs for creating threads, both for running user code and for its own internal use. In order to synchronize between multiple threads, the CLR calls SQL Server synchronization objects. This allows the SQL Server scheduler to schedule other tasks when a thread is waiting on a synchronization object. For example, when the CLR initiates garbage collection, all of its threads wait for garbage collection to finish. Because the CLR threads and the synchronization objects they are waiting on are known to the SQL Server scheduler, SQL Server can schedule threads that are running other database tasks not involving the CLR. This also enables SQL Server to detect deadlocks that involve locks taken by CLR synchronization objects and employ traditional techniques for deadlock removal. Managed code runs preemptively in SQL Server. The SQL Server scheduler has the ability to detect and stop threads that have not yielded for a significant amount of time. The ability to hook CLR threads to SQL Server threads implies that the SQL Server scheduler can identify "runaway" threads in the CLR and manage their priority. Such runaway threads are suspended and put back in the queue. Threads that are repeatedly identified as runaway threads are not allowed to run for a given period of time so that other executing workers can run. A: Static data shared across invocations - not a good plan for CLR calls: SQL Server documentation Programming Model Restrictions The programming model for managed code in SQL Server involves writing functions, procedures, and types which typically do not require the use of state held across multiple invocations or the sharing of state across multiple user sessions. Further, as described earlier, the presence of shared state can cause critical exceptions that impact the scalability and the reliability of the application. Given these considerations, we discourage the use of static variables and static data members of classes used in SQL Server. For SAFE and EXTERNAL_ACCESS assemblies, SQL Server examines the metadata of the assembly at CREATE ASSEMBLY time and fails the creation of such assemblies if it finds the use of static data members and variables.
{ "language": "en", "url": "https://stackoverflow.com/questions/7595586", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Flipping textviews issue suppose i have 3 textviews set in horizontal LinearLayout which is in one screen.I know i can flip textviews with help of ViewFlipper.But is there anyway to flip portion means if i will flip then one textview will be gone and two textviews will remain. Just see this link. A: See this for ViewFlipper animation http://android-pro.blogspot.com/2010/09/using-view-flipper-in-android.html or you can use HorozontalPager also link https://github.com/ysamlan/horizontalpager
{ "language": "en", "url": "https://stackoverflow.com/questions/7595587", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to include the md5 value of a file into itself Supposed that you want to create a file which contains the md5 digest of itself. How to do that? Before you include the md5 value into the file, you have to calculate the value, but if and only if the md5 digest has been included into the file, you can calculate the value. It's kind o a dilemma. Any Idea? A: The short answer is that unless you use MD5 vulnerabilities you can't do that. I believe that even using MD5 vulnerabilities building such collision is impractical. A solution would be to either attach the digest at the end of the file or ship it separately. A: You have to avoid that cyclic dependency, so you can't checksum the checksum. To work around that, you could reserver space for the checksum in your file, but set that space to zeroes. Then calculate the checksum and embed it. In order to check it later, you'd have to read it in, and set those bytes in the file to zero again.
{ "language": "en", "url": "https://stackoverflow.com/questions/7595588", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Centering an absolutely positioned item I have the following text: <p>This is the text</p> p { position: absolute; top: 300px; } I want it to be 300px from the top, but centered in the browser (no matter the width), how would I do this? Thank you. A: If you set the width to 100%, you can use text-align: p { position: absolute; top: 300px; width: 100%; text-align: center; } A: <div id="outer"> <p>This is the text</p> </div> p { position: absolute; top: 300px; left: 400px; /* or whatever half the width is */ } #outer { position: relative; } A: There are a many ways to center something horizontally. But every way is for different conditions. Here, I've added a fiddle with three versions of centering: http://jsfiddle.net/kizu/5WMNE/ * *Just centering of text: cheap, but not fair. *For modern browsers you can use transform: translate(-50%,0) to align blocks, 'cause the percents in transforms are calculated from the elements' dimensions, not from the parents' ones. But it won't work in IE, however it's possible to write expressions that would emulate it. *And if you'd add en extra wrapper, you can use inline-block to center in truly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7595589", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I link external files to eclipse in php and force it to copy to my project folder? I use ecplise for my php projects. I want to have an external location for all my plugins and link specific plugins to each of my projects. I found how to link folders etc, but the actual files aren't copied in the folder, resulting in errors in the website because the files are missing. They are only inside my project. How can I link an actual folder to my eclipse project, that is being updated automatically from the source? In Visual Studio there is an option to copy specific resources to the output folder. I am looking for something similar here. A: Some things come to mind: * *I don't know if such an option exists. You could achieve that with build tools, that just to the copy on build. You wouldn't then need to reference the files in eclipse any longer then however. *You can configure the PHP include path in your project. Then you can configure the include in your application the same. Might not solve all your issues, but would work cross compatible.
{ "language": "en", "url": "https://stackoverflow.com/questions/7595596", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: cocos2d director flow control: replace scene after push scene. What happens to the pushed scene? // TRY TO AVOID A BIG STACK OF PUSHED SCENES -(void) mainMenu() { // etc [[CCDirector sharedDirector] pushScene: gameScene]; } // stack: // . game <-- running scene // . mainMenu -(void) game { [[CCDirector sharedDirector] pushScene: gameOverScene]; } // stack: // . gameOver <-- running scene // . game // . mainMenu -(void) showGameOver { [[CCDirector sharedDirector] pushScene: hiScoreScene]; } // stack: // . scores <-- running scene (4 pushed scenes... expensive) // . gameOver // . game // . mainMenu -(void) toMainMenu { [CCDirector sharedDirector] replaceScene: mainScene]; } // stack: // I don't know... I want to kill all the scenes in the stack after replaceScene: call. But I don't know if it happens. A: I was just biten by this (cocos2d-x, but same concept). My rule of thumb now is - only push a scene if the only way to exit that screen is to pop the scene. If you want to go to another scene from the one you pushed, you should use replaceScene instead. A: Just use replaceScene throughout. Pushing & popping scenes only makes sense for quick intermissions, ie showing the settings screen. You will want to avoid any scenario where you push a scene, where it might potentially be followed by a call to replaceScene. It gets very complicated and inconvenient to keep track of the current scene stack (Director exposes no convenience methods to let you manage the scene stack). It's very easy to accidentally keep growing the stack of pushed scenes until you run out of memory. The short answer is: avoid popping and pushing scenes whenever possible. If you need to keep state, create a Singleton class that stores the values that need to be persisted when replacing scenes.
{ "language": "en", "url": "https://stackoverflow.com/questions/7595597", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Android - Terminate process while in another Activity I'm having my main activity starting another activity which will render the UI. When I try to stop the process from Eclipse while in the second activity, the process just instantly gets restarted! I have to press "Back" once before I can manually stop the process without it being restarted What am I missing? Main activity: package org.test; import android.app.ActivityGroup; import android.content.Intent; import android.os.Bundle; import android.view.Window; public class main extends ActivityGroup { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); Intent intent = new Intent(this, ScreenMain.class); startActivity(intent); } @Override public void onDestroy() { finish(); } } Second activity: package org.test; import android.app.Activity; import android.os.Bundle; import android.view.Window; import android.widget.GridView; public class ScreenMain extends Activity { private GridView mGridView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.screen_main); } @Override protected void onDestroy() { super.onDestroy(); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7595599", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Regarding ajaxStart/ajaxStop jquery i have seen that ajaxStart/ajaxStop always used against a DIV. Consider the following: $("#lbl_ajaxInProgress").ajaxStart(function() { // update labels $(this).text('Yes'); }); $("#lbl_ajaxInProgress").ajaxStop(function() { // update labels $(this).text('No'); }); Why do we need to bind ajaxstart/stop against a div? can't we use like $ajaxStart(function() { // update labels $(this).text('Yes'); }); $ajaxStop(function() { // update labels $(this).text('No'); }); That when ajax request will be made then ajaxStart function will be invoked and ajaxStop will be invoked when ajax request completed. Please elaborate on this requirement. after changing bit now it is wokking here the working version $("#imgHolder").ajaxStart(function () { $(document).ajaxStart(function () { $('div#content').block({ message: '<table><tr><td><img src="../images/ajax-loader.gif" border="0"/></td><td><h3>Processing...</h3></td></tr><table>', css: { border: '1px solid #a00' } }); $('#imgHolder').empty(); $("#btnPrint").hide(); }); $("#imgHolder").ajaxStop(function () { $(document).ajaxStop(function () { $("#btnPrint").show(); $('div#content').unblock(); }); A: Maybe a stupid question, but why do you use ajaxStart and ajaxStop when you can do the start stuff right before your .ajax( call and the stop when the function succeeds or fails (succes, error) /* ajaxStart stuff here */ $('div#content').block({ message: '<table><tr><td><img src="../images/ajax-loader.gif" border="0"/></td><td><h3>Processing...</h3></td></tr><table>', css: { border: '1px solid #a00' } }); $('#imgHolder').empty(); $("#btnPrint").hide(); /* end start */ $.ajax({ type: "POST", url: "myAjax.asmx/Sample", data: dataString, cache: false, contentType: "application/json; charset=utf-8", dataType: "json", success: function (msg) { $("#btnPrint").show(); $('div#content').unblock(); }, error:function(xhr,err){ $('div#content').fadeOut(); alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status); alert("responseText: " + xhr.responseText); } }); Then you do not have the <div> requirement.
{ "language": "en", "url": "https://stackoverflow.com/questions/7595601", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Schema XSD: Element Unique inside a node, not repeated values I would like to validate a XML file with a schema for that values in the same node can't be repeated. It's important the order of the signatures. My invalid XML is: <person> <name>Peter Petrelli</name> <subject1>Mathematics</subject1> <note1>8.5</note1> <subject2>Natural Science</subject2> <note2>4.5</note2> <subject3>Mathematics</subject3> <note3>7</note3> </person> </school> It's not possible Mathematics is more than once. How can i validate this with a XSD schema? Thank you very much A: With a more sensible design there would be no problem: <person> <name>Peter Petrelli</name> <subject> <name>Mathematics</name> <note>2</note> </subject> <subject> <name>Natural Sciences</name> <note>2.5</note> </subject> <subject> <name>Mathematics</name> <note>4</note> </subject> then the <unique> definition inside the <person> element could be: <unique name="su"> <selector xpath="subject" /> <field xpath="name"/> </unique>
{ "language": "en", "url": "https://stackoverflow.com/questions/7595603", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Json error on jQuery's load method I get the following error when playing with JSON request: Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property. This is the jQuery code: //load partial view contain grid $('#rptProductsRates').load('@Url.Action("ProductsRatesFlipPagination", "Reports")', { flipPagination: true }, function (data) { if (data.toString().substr(0, 15) == "<!DOCTYPE html>") { window.location = '@Url.Action("ProductsRates", "Reports")'; } else { debugger; var resultError = data.toString().substr(0, 9); if (resultError == "<!DOCTYPE") { var exceptionURL='@Url.Content("~/Reports/Exception?controller=Reports&action=ProductsRates")'; window.location = exceptionURL; //unblock the UI $.unblockUI(); } else { $('#contentDiv').show(); //unblock the UI $.unblockUI(); var bottomMarginFirst = (screen.height * .29) var bottomMargin = (screen.height * .42) if ($('.renderBody').height() <= ($(document).height() - bottomMarginFirst)) { $('.renderBody').css({ 'height': ($(document).height() - bottomMargin + @System.Configuration.ConfigurationManager.AppSettings["GridHeight"] - 100) }) } } } What's the cause and a possible solution to this error? A: Looks like you're throwing an AJAX request back to a an ASP.NET MVC3 back-end. AFAIK, the native Javascript serializer used by MVC3 has a default maximum parsed JSON length of 4MB (correct me if I'm mistaken). If you're passing in a JSON string larger than that, you'll have to slap on a workaround (by breaking up the request, optimizing your objects, or tweaking your server-side settings).
{ "language": "en", "url": "https://stackoverflow.com/questions/7595607", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Unable to create .Net 4.0 application pools in IIS I have installed ASP.NET 4 using the Web Platform installer of a Windows 2008 SP2 Server with IIS7. The MVC sites work fine, when I set a default (created at an install time) ASP.NET 4.0 application pool to it. But when I want my site to have it's own application pool, I am unable to create a new pool with .Net Framework 4 support - only .Net 2.0. Is it a correct behaviour of IIS7? Do ASP.NET 4 apps all have to be hosted in the same default ASP.NET 4.0 app pool? A: In command prompt type cd C:\Windows\Microsoft.NET\Framework\v4.0.30319\ and run aspnet_regiis.exe -ir. That should help you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7595612", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Binding custom entity collection to an ADF table I create a method on the session facade, that returns a custom entity collection. I publish it in the local interface. I bind corresponding data control iterator to an ADF table. When run, it shows "No data to display". There are no exceptions in the weblogic console. public List<Users> getCollection() { List<Users> l = new ArrayList<Users>(); Users u = em.find(Users.class, new BigDecimal(999)); System.out.println(u.getName()); l.add(u); return l; } When I invoke this method via another method, bound to a ADF button, all is fine though. User name is printed to the weblogic console. public int printCollectionSize() { return getCollection().size(); } When I bind to an ADF table a data control iterator created from (autogenerated) method getUsersFindAll, all is fine too. public List<Users> getUsersFindAll() { return em.createNamedQuery("Users.findAll").getResultList(); } I am completely lost. Is my method never gets executed by the data binding system? What is wrong with it? A: In ADF all of the code and bindings in the JSP page are simply properties values used for ADF when it begins auto-generating code to link between JSP and the backing bean. So first and foremost I'm not sure (though I'm no expert) as to whether you can easily bind ADF components to just any collection. Best bet to start with is to find a way to call a method directly early on that ensures the collection has been initialized, then refresh the table. Perhaps use a command button with full refresh so you don't have to worry about any PPR oddities.
{ "language": "en", "url": "https://stackoverflow.com/questions/7595618", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Need ideas and testing a new encryption method I developed I developed a new method of encrypting information. It does not comply with standard methods of encryption and was custom made to encrypt info stored in session cookies. It basically works like this: -It takes a standard 72 char string as it's IDENTITY or password. There could be more than a million variations of this. It then uses a pre-defined set of randomly generated variations of text and uses that to hide the actual content. However, it has special chars hidden in each enrypted line to help identify how to decrypt it. My reason for posting here is to see if anyone here could (a) crack it or (b) give me some advice on how to make it better. I am not too reluctant to give too much info yet as this is still in aplha stage and not the finished project. Here is an example. It is the 50 US states in random order. Please note that even if I keep the same order, each time it will look different. To prove that, I will run it twice with the same order used: First Run: H39pwxMnczu+#u!?:IeQAAeSPrjJFRZ84#zma-XbMaU7#F|Bm!6o3qgnJ3 cFIoTYNS|dAfVa ibes!zd!O-e4sxx8yOo!?hTvK-f6htqlRxT?pV3CT--l4vU#7TInYV-WXNFil-t3+tG+:9b5X ?9#2Ncfn8AUim!3LZw#s5YRqF5Xfwm1:sCO?B90ViBQkmW?MlHn1h4Pd5AU8Lw QYwzr8IxhB 0r!mccmccmffmRzbapQ_dSjm+9#5jRR_IlqvWjY:Z9RfiABL_Rp#Dp!DyP?HiAB#9+HXRp?1x SHjCpl+lvLvKVECH#bY+jn?T_-:1T7M#x?4uQ!bsJglVmc5dHN79HUF58|sTVDIp#jN__8tIk ?5ErfVd2N9TgcR3pWE#Dw98FYnUT9BHlBolV:mPFYnHw5P69BmJhWo|fYYL25P?rguINWY+f4 P?6QBXUxyYg3iWNpVL2FoBd-s UaqyAaOc M#2xd6ewglq??MZe4nD-#UnW3H6Fa?TIAdegkd ERM?yyKtW_IydIOm77ia:9ao8 o#RcB8u_G3Jwox-K?0IC#S22GG0wQH-hfbptWSCCKo0Noaj SRnCpwIzQv2CwvtH_Qt2RUT9ms#TDY9#Jb9J88m_V5xmQL_Gnj_9kO5JiRYVN0pY?YW_RnI9g rDVUGkUuEg76dDXVawq|SImE8MyKKDDmar+|vHh93?y88SwmFwtYvzCNEA52n:eCfu1PGgH k RO6ZAV7VO3S:3WWz+1LGzlb+o#!+:xyL3BKA1jIHArAd+K#4:5k2 Oi2Og2F|:DI+fxXL|f7G DmqBiMZv2277kCjE# 6JPAorUURxk+xNB p?ew!cnuTz?GMqO8v63tJ7Mu TGoENfSN6Q4C7Y !VMBYFY5YLadz0!TnjMrVA8Sr2rFdML-zR45:9m59i5e zg8dx0+T x?1LP79cFTnj:mc93w S#?vL+v+i+mNXmV:W4ckvwjGMJRcQKAntLxgIH9KMWJQFTVb!Vxhlp9ELJ_7FVBU2YD:gJbAL omUd_SFpmR_dXC RwigvHF67DObZdOZ-O_f6#egP4lMfP?BHzJZEiMj!bdEZQSfTsRBbWrzm: 09!mIINcG-n??B1-jQfdA#_lp|tG++M9jpedAJ_mpzd+P 7Ws5MD4Y#+p4dP97n0?HYR4!0Z+ cEtiKjA:6hfp+#D2ClS-2eH9e1dDsNZ7mN5vwR- a:EZ6j|3Py#I3ivk0hfp1|KIglp-Jz-d |c9O:#Ue5Mk575P004EY 9QKC!5 cQ0ysIGgp46Z-r0 ZQyEIPLVo-HZXLN0RRiYbAYV0S_ZV xXY#8SAwW ZB?Sr4OcL!ncpl+#m_W?iL5HAJ3 Z0Jol9|DyC-A80UgCm7zmr_8QMOpDmHE4XF :r7:LlgSvzJuKm6oXy8r#XRMaJvNsnydX?N-rtt4Y73YsrwIXsf6nKoYf7Zc be:dj0ppKKh# G-f8w8PPb-Z-oHp:BPAVDj-MHvSZyp0_E8k mwZvLLp?30AaFCUO!DUZ+h:#OS637Am6UXKUu TcWQAUyQ:VJKv94zus2X9tn88p3vD34tgr2iupAwD+INKoMQuc?mXeZoouyKDohTm6 JoveXP dP27Gb4iLdZ51w7YDr8#XTdisjQGrYII#BnX6P532?KH2r0LtS?D:nN6Q:2-_2lGDcZU3THX3 wAt9|j:9:OyvSwM8GmuFAN0zbg:eGXTUaknggG!bAgcqU62PgrkaxGCTXCtGlrF|lGq:XdUT1 np1lj08kyIC-qNcOpxAwjxS9Y|#A6g-dNJgxiDx+K6W?vp3jqpplpSDvTI:49N|16NHZNs :i qA_92j6!YML9jMMF mv|b5NSS K97Seq|8JXS+5b2 zvmzf c+BCc qMmr|vyhVgc+xLhn_Oh 3O!9IS|9Vj9BY_G J-0: !zf!ZIGLjuq|Reqq9q4fuPt8vm0y5G0#H0p78zeYE6eGd3O sO+5 4KxCIUCRCe614E_K 5aI72VD297P BMP76eD|1VqjmRP uXjdF3jP|NiCBPoVUKmx1QT_skiB rD_IvYESiE::6th4CKM67?:hNStD1:g _xH_jdY54#+y8YK+snh2|zyf0:we UtwCKHhcI:jc j4vbZ0hkYSkr2!Vq5ua+rxT4mHUxGtLYEEXXxeTAmzsyG_vL4hX:xeArSKJq8ldm4ij2qklrx 848Tf?I76s?TZVDsSW7NW M6om3j+E6|jiIbOR_+5uD4US?14G|Nb9dD 961hLBj1zsb!0bZo QefvLrM!sP:OmqqRRsHuCNV_BPG0O83RXsHCapIbJ75#N8czeJx5as7LxiFv#5cVydKyrsPL3 gJxaabTzbY!7LSCNsZ-XhBFrl1dbtleLgsPmrHP7tK2VStDTs qsJ07ckxwul2mwXg_Xrr8nw glo3YkbTQnzTQJ5evtzc8gDulM0o qF_std?h TFlgqwTrKm_Fd-74j73gJwzrK0gloYJteVS aHDL7A+ZHlFLIygly8nkKBqQjNUQF8 sC48pgqJDq|?FV+ih-nsjh#Bw#NN1AhGL+Jm78BqAw H-U8Jyg7n:6ei#af:qF?erI6l?As8iefonU9nwI-l7As!IrRm-ajd3F|0NVM-sccAbZIMC6VF JqWhZczdLcpfqn_5kNwuKe30yKP6e8|ZeqXO3k8Vn3CFkDB_ke??9qDMr8tfqpRvqkGhMe2XF AAx7JTdlXYYSdVMdA1!NjHgS1RNdUI2AxCDcaJuS8iiwm#NuxeJcNK7jSuiDA2ZAj!lj+n7D_ -FQf::fvo9:1MM:YVuA0VxX-+yuhn+61y 4vyVddlx aIupDxQFMxyPtaVcX1!mhmZAmLxT5W CC603Xv0n:CqhLd 9:1g3yFpS2CYaaOf8L2gtSFLjWTC2ay1:v1T0kTQ?WyRNn14Qv_zy5|6l qSU9E92MC9hstXhHAA+Ssy 5-aSKejShBLyHdfFDC:C1WCRSpOvAx8|4zwjcV|M18b:PnBqmN pGWHgmJUU3:sBt|6lSB+2?9tUMGCXG?mk?1_2MufcGW1XdiMDY7Td3#HckI!h+Qsp?SjNB3 ? p97lhhHvpl7#E93wDTkoWeiCtCB6Ca9lMN:rjvVugE?IvmBjht_|wUQ1|XS#Xp9_agWo2gd5R Ua9QU!j|UQ|G:tdALda+OaP-bthr|dmPLW9tc01_WBJj|OHIU9:Qk8o:kHm3CE95BP?W6ptd3 usPh|dRWdWftqwqtZ21#4R5O4+ 4#T2C?nkCjbSZMM#Ml5YqO-?q:HL?J|sT3h-#rQ9#gB09P j4ehkYokoQUs2Gvb5GS?xv_Tmmis?wO1TrHY1r_txSAJG+C04nza5xZ:dH93a!C0G56X4#fAx us:1SdYdh14#T2C?nkCjbSZMM#Ml5YqO-?q:HL?J|sT3h-#rQ9#gB09P5t4QK_wb3XZiO|ZFS p4sHcceZElZvE+Nh:gUlQqEUQIWBswi931xdjFMGBpaCqrTM#1x9GXZdRJwBBjU3IUcpG!sHG jmQbkkb??bb9aO4Chq4HvXq_jG:iZh5Uux5VWYxwa2+uT1n#iLmKCjmf6oGlwssJE0qHP+qtd gJ-mTnvc?VoJrCXtG-fSg78_B!wfPCXJSactZKuggGNr5NT7S0MzS1J 0QQrhDvlxH?t 3V Second Run: GAG58FX0vFXjbXH-S#Np6aEPC6ekzwQvpbP0 3F8AihC9UdZ0+2of_70kfqv?KH-SQo5kyEAM hjLKSsOShgSjjH3Grh|YMjqC6fwRji hY9v?aJZDunghjC FYvd#x8nxCm#theeFMuXMrhTlC :dZNv3gLrJMp04uYXAL 5z3v#nkrCjDa c:oPi6 pPVY?fIsduoUp7T#mb9rYCUN2AvIr:epy p1rJJrJJrhhr4HM!mtC6AQiYq 50jSC!Gt?6QcrfEjfGorwCll?s0UsnCdhG34 EY5sj0I7F kxATb4J4aBae!wHoXJx0WnZdLl0pdP V_s9m17E:ex5b#3ok83maad-2pXIwxUXvNUEnnyLXH AoRZTCJ2!T#4-c::ZcokDSyFgo#9TTlncSKkMCstgolM jnvB4sibSNV!O1Xdj884jdEpwRI7 hM1S#R|RM1GKrJlMx7uChoIdYQnZYMSSem96piXhBpqGB7EE3fpxv9Zjn|BOfB#FxLVShoI6h Dz3ivvRAodwv4wlgZZrQm73U8BLYANr8dJQ0p!Lus76Cwj#SxJII!JxDKTnktxm#j27FCTFY7 RK#iHq4tlVDiqV3Mr73+VVhWnz6f2|#6yq#gFFBU61en7OrZ#DU#_T1KIV|CHz||N|3UaQcki qSKpX6p:MgXacPBTjDqRS1|MytVmc??jcmdLh5r6m tywS8|h8_Sh apmSLq1AMaC+9bh Yv+ QJdvgr#rdpm76yyoGd8Zb#JVv7zG7uR8-LrN!OaNNXNiGEM?53CJoI8JHUJPf5za:BWa809sZ CFg3J2sndTYYBTdm5Oh9WdFqlDC wO NCOF|SdC5aLf0|:1sAOFpu1Rt1LOfpkbjAVNQI1Ttn PdjcQ1QWQy-wUagFcNgxQxV#G_x6_g3bHF3m8Jjfmgmp0ZaVTAA4OeAR 3RqJTgjc??jb2?v0 xL+B? B m3gyOgBCnPy:me40_ZZyiYBCM|zl7DA00nH8v EC4ozl7hDr|H:irBmLv9rCl?DB| jSWhZYRNSoZh6Tko5ePqx8d+x9jOwJ9q9HyXm_YGGt!RGUsxUVOYqw622w8I2#y45KkjCzS++ ! vpssP#mwYBBcVoY1t:TnLqPzzv5mu#F1 QTnLxqy:5wVyYd9uKy1nsqY:wSyji79D-8diOs XCV34ukN|9|WzyBUU0+ZU!i6!JbB:LS88L238 |CXRNP-lxppoMipVK6A9EpJx#r20jXCQkfC u!e1W0uHKh2KRKdD-HW59Zf84MQ_CwD0qCdt?HVC94R_dw0XCl!T?:znt!rR44gLCb5|R9aft s7RcsundeK|Y8u1xE7|gg7VUgLt2kQ8W?Pw--aO0-N!S3lq-hwizVe9k2yrI2iBEEVurPbz3k cEXHAQK:TEdT-ZCkdpv:hT0n5d+r!ZxRb-rs:vvgNdW4l:pai-3CZfkNpdfoIDPu6Z-15aaxS AcH!Y!JJCpCbHJOosE2NF+bc:MJSd!TAtkjoNIj2eewlovAdRTcAjFljX1SwAJdoyuNsW2wc9 Nd4brngbG+DCb+1NL1U-+BBAxDXbHX1cm1qzyWcwCXFiH1v30r4P-U3:CXXgS?dVPdM9pUU-Q X+Qnb_IduieZkrnWkUAd4XQ?zC6Jzv22p8CgXA 4:Xz#8zylUpXkAC5|6VRvp:+JkUoF4X#iN q7fgCpMgMH7rt7+?RCrn9HV5T7xUEw_bP1Uv9HHKgBmYbm A211PJLS_|S+Lj1ne2EYxwSW_s ipqEg:X?!c-pYtxIgbtVG-VFMNct?xpiXTSLQcbfw?NPJgtGW4p#4zTJLZ-UFmPTvEt8mdb-Q kuXTnNQz|asTNayvWFXJK v7TmmVBMp|Jp9un K!s0Xb0esN 5EnW|yF0UXotdAN#x+t9mtl -Eb1J#-1|:18ylTE+ hZ!pmyIF6TxSr2lQWY+CY:Zrp8Vj-RSZo1lGRtIVmPyzdWV+?Dn4D5Z !zupeZpspY0j?zc37puAR+LM+BRQg c34d1!8yziP94:2ntqeVJD8ynp1szKB6VXe_9gyZil5 hrp|wESsOSh6JjB8BGCBH?9:vxjxnhM1fO6naExgQCAu8RrA7Fx7iMCH16h9K|M8EsLrVY6:y Zf#puO9hDFNPUqwJW0:SGmp2woALX-ufvV:SL8WhGt_1f ub2NScmQOPoYzJ4TlG2RcUJIhPS _ObYH2 Jk72YU-LG1S+O-DkURITg547tg#NU#8GTe1OLyHhG4kzZt0VOnpJ1QMiVxW+aGJtcC Fm7|tY1feJyc5ngtpeFPM6kjG54cQUzp!TNX_sv1m3:Y6UD!amHM_px mCMYp::vhNZMqex9j VQ0qqPuIPYwuQeD2UDjGpKlrHZqXGwVY?QJWrtMIl|CdW8-RcGIQ_6u1e9hoQz#HGD1Prrn!H WLqm:eKU2jtUkDEwAf1L2?I7xbe:gShmzfo2CgcUxL|jgqUmLhhetInURV|a_LSKVxjtDNna4 Qp73OmWkpry3wuxrveKyM-PLia5A3Hd#giIXzFe3PJqxEsTm+P2rNe6Euaa9_N0wvefCJiFCr 7:x!sRIUtHyZXI#:Gx4D97prCQ89mXZMD+?d+VesF:vPDblFyytLF6UdSI!84EBl9yIFKA4O 9F+3I6B#e65AEKQhDPrEDcbIVW9scy BcEnR?2ywFbhC2vpt2c:lf?HDudzNE0P-E2UiTnk46 GKir5CGmzJfE7FEBly6nQXfiH6PPv_6j5FsWa YK?HCPW6+dYc4#U+fK??FQVi+nyGnH1aFY wc!:aa:PzUae88aBrc2zrAkqGXc|gOF5XwVfXr umGylJ4jxAL3TAX9+8k7e:yfPfIh:qAe10 2RIPO7LP|09zfg66O7gpSbDQ20?GEfW6Qg+B?TqUa+9GEEbrPz+RcCRfI2b?pD+rP4nNcdRj3 gJMzaz73_zlK2VlSALg qshMb7t5!UtlTQnZBm3qVcVrO3NtmwaeHA7BFJuJ2uLGezg4aXrs1 f mS+!RNg:xZ3OvGhIiLOARNN0j!8OK+ Kg620GbuOj!QDB+nKmcD0t44O|kAvBM?KIcL00TK fK6QTTSc_QIMHA0?nU|w2!VqNq3R!hA2PExBz_w9KCKyC+ZxSOXEL3:i4 u+uDG6nKjN2KDWg F_CF1GhM1FMvkGm4XmpGjdEZHA-xhmN4JQsgjdUVQPPx8zmU96pgRp5Vc|PidU6Jqpkf ylKs gJ17?3TY3YHN?s5BurGPLhsVAl0AcgrHkJFKk3SdX MTYsJaVhR5wtlRmgDC? 5c8fG1US4!v UW1j|o+|+jOHMrE68LsyYE33e4cOyS5k8xkWYnK3usy5r0kTpo:gt6yPu_55N0DdItdam+yy6 gJBma3L37mAcgrHkJFKk3SdX MTYsJaVhR5wtlRmgDC? 5c8fG1US4!vsBefg1n3ht7QlZOXS bCYjqq#b?tbN?p FN-cyocxVu#HSLF-EncXQ?_290F3SJ--Gn5z69zAkwFF0S?Zn8Z aYzcBw UahK||KUUKKUa5LDOTH_WkTK31PcyH!qt6Y4druSa8gt3Yo+OWnGkMw?da1LSppnBdQkWgG3k R:rZbqHTDa:6Azhrq8Md OeBI::jAac!dc|xVOO Bq3A73+-yczUVq-fY3gnec5S7iorx|:4Y As you can see, it looked different for the same order of 50 lines of text. So, any ideas? A: Any encryption method which relies on the secrecy of the algorithm is flawed. The attacker will always know the algorithm. See Kerckhoff's Principle for a longer explanation. It is absurdly easy to write an algorithm that you yourself cannot break, anyone can do it. However, unless you are a professional cryptographer, a professional cryptographer will find it easy to break. Have you tested your algorithm against differential cryptanalysis? Do you even know what differential cryptanalysis is? There are many excellent cyphers available already, suitable for many different purposes and with varying levels of complexity and security. Don't reinvent the wheel; use an existing cypher.
{ "language": "en", "url": "https://stackoverflow.com/questions/7595623", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why this popup fail on IE? I have this code : <a id="bookingLink" href="javascript.void(0);">Link</a> $('#bookingLink').click(function(e) { e.preventDefault(); window.open("http://www.google.com", "Booking Daniela", "width=950,height=680"); }); and it fails (no popup is showed; also, the link in the bottom is /javascript.void(0);) Why? And how can I fix it? P.S. Popup are enabled on the browser :) A: the name attribute must have no space. Try "BookingDaniela" A: Microsoft does not support "name" attribute, so if you delete "Booking Daniela", it will work window.open('http://www.google.com', '', 'width=950,height=680'); Check the following MS documentation page, http://msdn.microsoft.com/en-us/library/ms536651%28v=vs.85%29.aspx. sName "Optional. String that specifies the name of the window. This name is used as the value for the TARGET attribute on a form or an anchor element." A: You wrote: <a id="bookingLink" href="javascript.void(0);">Link</a> $('#bookingLink').click(function(e) { e.preventDefault(); window.open("http://www.google.com", "Booking Daniela", "width=950,height=680"); }); Let's rewrite this to work: <a id="bookinglink">Link</a> $('#bookinglink').click(function(e){ e.preventDefault(); window.open("http://www.google.com","Booking Daniela", "width="950,height=680"); }); If you wanted to pass the data in (e.g. if you have multiple #bookinglink elements), you could do this: <a id="bookinglink" pagename="link1">Link</a> <a id="bookinglink" pagename="link2">Link</a> <a id="bookinglink" pagename="link3">Link</a> $('#bookinglink').click(function(e){ e.preventDefault(); var opage = "http://www.google.com"; var pname = $(this).attr('pagename'); window.open(opage,pname,"width=950,height=680"); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7595625", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to setup multidatabase in symfony doctrine i am using symfony for my project where i have two database, but i know only to setup symfony for single database, like below code database.yml all:doctrine: class: sfDoctrineDatabase param: dsn: mysql:host=localhost;dbname=gapi username: root password: so, please help me about to setup two or more database for symfony doctrine. A: The structure of the databases.yml is like this: all: # <-- Environment doctrine: # <-- Name of connection class: sfDoctrineDatabase # <-- Connection class param: # <-- Parameters for the class dsn: mysql:host=localhost;dbname=gapi username: root password: So if you want to add an extra database connection (the databases.yml specifies the connections, not the databases itself). You can copy the block fromdoctrine` on, and give it a new name. Something like this: all: # <-- Environment doctrine: # <-- Name of connection class: sfDoctrineDatabase # <-- Connection class param: # <-- Parameters for the class dsn: mysql:host=localhost;dbname=gapi username: root password: # Extra connection: connection2: # <-- Name of connection class: sfDoctrineDatabase # <-- Connection class param: # <-- Parameters for the class dsn: mysql:host=localhost;dbname=database2 username: root password: But be warned: working with multiple connections requires a lot of understanding of Symfony and Doctrine, and you have think and test very good, to know for sure you're executing queries on the correct connection.
{ "language": "en", "url": "https://stackoverflow.com/questions/7595627", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Maven properties in multi-module project are reset to default I have a question regarding properties in a multi-module project. Consider the following 3-level project struture: project +- pom.xml (packaging: pom) //referred to as super-pom +- module_group +- pom.xml (packaging: pom) //referred to as group-pom +- module +-pom.xml (packaging: jar) //referred to as module-pom In the super-pom I define a property revision which gets the default value "unknown". Additionally I declare and use the buildnumber-maven-plugin which is configured to get the svn revision and put it into property revision. Next I configure the maven-jar-plugin to write that property into the manifest. In th module-pom I declare usage of the buildnumber-maven-plugin so that is actually executed. This all works when building the module directly, i.e. executing the module-pom only. The manifest contains the revision that is reported by the buildnumber-maven-plugin as is printed in the console. However, if I execute the super-pom or group-pom the default value for revision is written to the manifest, although the buildnumber-maven-plugin gets executed and it retrieves the correct revision (it prints it to the console before the maven-jar-plugin runs). So I have the feeling that I am missing something on property inheritance in multi-module projects. Does anyone have an idea what could be wrong here? Or could anyone point me to a description of how properties are actually handled in those cases (unfortunately I didn't manage to find a good description yet)? Update I did some research and a few test runs with debug output (-X option) and from what I found so far, I assume my problem is the following: 1) During pom parsing the properties used in the pom are replaced with their values. Consider this partial pom: <!-- declare the property default value --> <properties> <revision>default</revision> </properties> ... <!-- use the property --> <someconfig>${revision}</someconfig> After the pom is evaluated, it seems to result in a state that would correspond to this: <properties> <revision>default</revision> </properties> ... <!-- The property seems to be "statically" replaced --> <someconfig>default</someconfig> 2) The plugin that sets the actual property value runs afterwards, even if during the validate phase. Thus the property itself is correctly set to the new value, but it is not read anymore. 3) The plugin that uses <someconfig> (in my case it would be the maven-jar-plugin) now runs with <someconfig>default</someconfig> and thus it doesn't read revision at all. Can anyone confirm this? A: I can only say that declaring buildnumber-maven-plugin and maven-jar-plugin in a super-pom works well for me, no matter whether it is a group build or a targeted build. Here's a part of this super-pom (a parent for all projects): <!-- Generate build number --> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>buildnumber-maven-plugin</artifactId> <version>1.0</version> <executions> <execution> <phase>validate</phase> <goals> <goal>create</goal> </goals> </execution> </executions> <configuration> <doCheck>false</doCheck> <doUpdate>false</doUpdate> </configuration> </plugin> <!-- Attach build number to all jars --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <version>2.1</version> <configuration> <archive> <manifest> <addDefaultImplementationEntries>true</addDefaultImplementationEntries> </manifest> <manifestEntries> <Implementation-Build>${buildNumber}</Implementation-Build> <Implementation-Build-Timestamp>${maven.build.timestamp}</Implementation-Build-Timestamp> </manifestEntries> </archive> </configuration> </plugin>
{ "language": "en", "url": "https://stackoverflow.com/questions/7595630", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: VS11 Dev Preview Unit Test Explorer doesn’t show Unit Tests I wonder has anyone come across with this issue where the MSTest Unit Test doesn’t show up in the new Unit Test Explorer. I’m running Windows 7 (32bit). I downloaded the VS11 Developer Preview from the link below. http://www.microsoft.com/download/en/details.aspx?id=27543 I created a sample C# Console App, and add the Test Library from the MSTest project template. Then I created a sample Unit Test, and rebuild the solution. When I open the Test Explorer (View->OtherWindows->UnitTest Explorer) I do not see any tests loaded. I only see a message saying… “No test discovered. Please build your project and ensure the appropriate test framework adapter is installed”. I assume the MSTest adapter is automatically installed. If not I’m not even sure how to install an adapter. I could be missing something here but I cannot figure it out. Has anyone experiencing this issue? A: Found out that at this only works with Windows8. (At this stage) More info http://jerssoft.blogspot.com/2011/09/vs11-unit-test-explorer-acercamientos.html#more (you need to translate to English) "Of course, all this work the right way if we have properly configured and in the final version , since according to understand, if you want to try this plugin, you need to be working with Windows 8 :) " http://geekswithblogs.net/lbugnion/archive/2011/09/24/running-unit-tests-in-visual-studio-2011-and-windows-8.aspx A: If you are using VS Ultimate version of VS 11 developer preview, then it support MStest based unittesting for Windows7 style apps/projects if that is what you were trying out. It is possible that you are hitting a bug. Will it possible for you to share your repro steps? Thanks, Abhishek Agrawal Program Manager, Visual Studio, Microsoft Corp A: This wasn't working for me using Visual Studio Express 2012 Web RC, but I got it going eventually. I added the reference to Microsoft.VisualStudio.QualityTools.UnitTestFramework which I found in C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\PublicAssemblies I made sure this was set to Copy Local but probably not required. Then I tried cleaning and rebuilding but with no effect. I made sure I didn't have any testsettings selected (Test Menu > Test Settings > Untick the testrunconfig if selected), then changed my Test > Test Settings > Default Processor Architecture to x64 (my machine is x64). Then I cleaned and rebuilt the solution and my Test Explorer was populated when I click Run All.
{ "language": "en", "url": "https://stackoverflow.com/questions/7595632", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to convert polygon data into line segments using PostGIS I have a polygon data table in PostgreSQL/PostGIS. Now I need to convert this Polygon data into its corresponding line segments. Can anybody tell me how to convert it using PostGIS queries. Thanks in Advance A: Generally, converting polygon to line may be not straightforward because there is no one-to-one mapping and various elements of polygon map to different linestring (exterior ring, interior rings, etc.). Considering that, you will need to split each of those separately following possible approach like this: SELECT ST_AsText( ST_MakeLine(sp,ep) ) FROM -- extract the endpoints for every 2-point line segment for each linestring (SELECT ST_PointN(geom, generate_series(1, ST_NPoints(geom)-1)) as sp, ST_PointN(geom, generate_series(2, ST_NPoints(geom) )) as ep FROM -- extract the individual linestrings (SELECT (ST_Dump(ST_Boundary(geom))).geom FROM mypolygontable ) AS linestrings ) AS segments; depending on what polygon data are stored in mypolygontable, you may want to dump not only the boundary (as above using ST_Boundary) but also other elements. The code above with more detailed overview is taken from the postgis-users list: Split a polygon to N linestrings There is also a generic approach to the problem explained in Exploding a linestring or polygon into individual vectors in PostGIS A: This is the first hit on google when you search this problem. I don't know if so much time has passed a function has been created since, but for future googlers ST_ExteriorRings(geom) worked great for me. http://postgis.net/docs/ST_ExteriorRing.html SELECT ST_ExteriorRing(ST_Dump(geom)).geom) FROM foo
{ "language": "en", "url": "https://stackoverflow.com/questions/7595635", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: Android cannot access textView component from activity I have the following actvity. package org.dewsworld.ui; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.widget.TextView; public class DetailList extends Activity { TextView title = (TextView) findViewById(R.id.title) ; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.detail_list); title.setText("hello world"); } } Which manipulate detail_list.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:weightSum="1"> <TextView android:id="@+id/title" android:textAppearance="?android:attr/textAppearanceMedium" android:layout_height="wrap_content" android:layout_width="match_parent" android:text="@string/headline" /> <ListView android:id="@+id/listView1" android:layout_width="match_parent" android:layout_height="match_parent"></ListView> </LinearLayout> But, when I run this, I get a runtime error. LogCat is, A: try like this public class DetailList extends Activity { TextView title; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.detail_list); title = (TextView) findViewById(R.id.title) ; title.setText("hello world"); } } A: package org.dewsworld.ui; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.widget.TextView; public class DetailList extends Activity { TextView title; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.detail_list); title = (TextView) findViewById(R.id.title) ;; title.setText("hello world"); } } its complaining because you are trying to get the value of textView using an Activity method which is not been created yet (Since its Oncreate() is yet to run)
{ "language": "en", "url": "https://stackoverflow.com/questions/7595636", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Buffers per tab in vim Is there a way I can configure vim to remember buffers based on their tab? I am currently working on two projects, and I have each project in its own tab, with its own local directory. To navigate through files I'm using FuzzyFinder. The problem is that when I want to search through buffers, I get all the buffers from both projects. Can I limit it to show only buffers from the current tab? It may very well be that I am using a wrong approach here. If this is the case, what would be a better one? A: Vim's tabs are not like most other editors tabs: they don't represent specific files or groups of files. They are just "views" allowing you to arrange buffers visually. Vim's buffers are global and AFAIK there is no native way to bind them to specific tabs but I saw a "per-tab" fork of NERDTreee on Github the other day so it might be possible with some effort. I use tabs only for quick edits and have usually one or two dozens buffers open. Most of them are hidden (:help hidden) and I rarely have more than 3 splits (only one file visible, most of the time). Buffer switching and file opening are done with LustyExplorer. If I must work on two project I use two instances of GVim or two separate "GUI" windows in MacVim. So yes, your approach is wrong (mine is most probably not perfect, either) but the culprit is the person or commity which decided to call Vim's tabs "tabs". As a side note I find the "Rolodex Vim" idea quite enjoyable, there are two implementations on this page.
{ "language": "en", "url": "https://stackoverflow.com/questions/7595642", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How to count dynamically added table rows with jQuery? How can I count the table rows that is added dynamically with jQuery? I have tried with $('#mytbody').children().length; but it doesn't work with rows that are added dynamically. Here is my code, also runnable in JsFiddle <!DOCTYPE html> <html> <head> <script src="jquery-1.6.2.min.js"> <script> $(function() { $('#add').bind('click', function() { $('#mytbody').after('<tr><td>'+ new Date() +'</td></tr>'); var count = $('#mytbody').children().length; $('#counter').html(count); }); }); </script> </head> <body> <button id="add">Add row</button> <table> <tbody id="mytbody"> </tbody> </table> Number of rows: <span id="counter"></span> </body> </html> A: http://jsfiddle.net/H8sBr/2/ you need to use .append() not .after(). After adds a element After your tbody but you count elements Inside your tbody. If you use append, you add them at the end of the tbody. Alternately you could use .prepend() to add entries on top of the table. PS: This is a commun misconception because of the css selector .after() that adds content after the content of the selected element not after the element. A: Try altering count to var count = $('table tr').length; This seems to work - not sure why acting on the tbody doesn't. Edit: jsFiddle A: You are adding rows outside of tbody. Change after to prepend will work.. or change count to var count = $('table tr').length; http://jsfiddle.net/H8sBr/442/ A: Just use a counter,it has less dom lookups : $(function() { $('#counter').html(0); var count = 1; $('#add').bind('click', function() { $('#mytbody').after('<tr><td>'+ new Date() +'</td></tr>'); $('#counter').html(count); count++ }); }); A: It looks there is some bug (not sure) in jQuery; row length is not getting updated if you add table row dynamically. var rowCount = $("#tableId > tbody > tr").length; will not return correct count if you add row dynamically. Simple solution is to use: var rowCount = document.getElementById("tableId").rows.length; Yes, you can use jQuery with javascript.
{ "language": "en", "url": "https://stackoverflow.com/questions/7595645", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: More regex tweaking advice required I'm getting through adding delimiters to a large references file thanks to help from SO. Almost there now. I have a regex which I received from an SO member which allowed me to add the "|" between the author and year. I know need to add "|" between the article and publication. The rule I cam up with is that I want to add the "|" after the last period(dot) that precedes the ":" in the publication name. I tried editing my positive look ahead for this but it does not seem to work. I would appreciate your input on this as always. Thanks in advance. Actually I probably don't need even to specify the after 3 "|" rule. The main thing would be to match to the last period that precedes the ":". Would that be correct. Even so my regex does not seem to be working. ^((?:[^|]+\|){3}.*?\.)(?=\:) 122| Ryan, T.N. |2002. |Some article name here. Publication name 2: 101-105. A: Okay 2 problems: * *You forgot that there is stuff between the period and the colon for the lookahead! :) *You did not have a greedy match before the period, so it was matching the first period instead of the last Try: '^((?:[^|]+\|){3}.*\.)(?=[^:]*?\:)' See the difference? (Removed a ?, added a [^:]*)
{ "language": "en", "url": "https://stackoverflow.com/questions/7595646", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Sort array by its content I have an array looking like this: markerArray[i] = [i, title, cat]; this array is within a for loop adding the content dynamic so the result could be something like this: markerArray[0] = [0, A title, A]; markerArray[1] = [1, A title new, B]; markerArray[3] = [3, A title, E]; markerArray[4] = [4, A title, A]; So my question is how can I or is it possible to sort the array so that the output would be based on A,B C etc or title or whatever taken from inside the array like this, note that the last (category) is in alphabetic order now: markerArray[0] = [0, A title, A]; markerArray[1] = [4, A title, A]; markerArray[2] = [1, A title new, B]; markerArray[3] = [3, A title, E]; Is this even possible? A: try - var markerArray = new Array(); markerArray[0] = [0, "A title", "A"]; markerArray[1] = [1, "A title new", "B"]; markerArray[3] = [3, "A title", "E"]; markerArray[4] = [4, "A title", "Z"]; markerArray[5] = [5, "A title", "A"]; markerArray.sort(function(a, b) { var comp1 = a[2]; var comp2 = b[2]; return (comp1 < comp2) ? -1 : (comp1 > comp2) ? 1 : 0; }) alert(markerArray); A: You have to use the sort function, available in the Array object. This function/method accepts a custom user function to determine how the elements have to be sorted. function customSorter( a, b ) { var comp1 = a[2]; var comp2 = b[2]; return (comp1 < comp2) ? -1 : (comp1 > comp2) ? 1 : 0; } var markerArray = new Array(); markerArray[0] = [0, "A title", "A"]; markerArray[1] = [1, "A title new", "B"]; markerArray[3] = [3, "A title", "E"]; markerArray[4] = [4, "A title", "Z"]; markerArray[5] = [5, "A title", "A"]; markerArray.sort( customSorter ); Useful info: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort A: Use a custom sort function. Read a documentation how to do it. A: You can pass the compare function as a parameter to Array.sort method and write your comparison logic inside the compare function. See here https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort A: You could try this kind of stuff: markerArray.sort(function(a,b){ for (i = 0; i <= 3 ; i++) { if (a[i] <> b[i]) { if (a[i] < b[i]) return -1; if (a[i] > b[i]) return 1; } } return 0; }); This will try to sort with the first element, if they are identical, it tries to sort with the second one, and so on with the third one. [EDIT] Adding some interesting links (see other answers too): * *What is the easiest way to order a <UL>/<OL> in jQuery? *How may I sort a list alphabetically using jQuery? *http://hungred.com/how-to/tutorial-sort-array-javascript/
{ "language": "en", "url": "https://stackoverflow.com/questions/7595648", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C# - list to store nullable types In C# we can declare a list to store int, like List myList = new List {1,1,2}; I want to store null values as well (nullable type) hence I want to create a list of nullable types. Something like this List<?int> myList = new List<int> {1,1,2}; Above code does not compile. Does .Net supports list of nullable types? Atul Sureka A: Sure, you need List<int?> myList = new List<int?> {1,1,2}; * *It's int? not ?int *You need the nullable int when you construct it as well as in the variable definition. As a side note, you can't actually declare a list like List myList = new List {1, 1, 2}; as there's no non-generic List. A: You shouldn't use ?int but int?. A: Try List<int?> myList= new List<int?>(); A: Did you try List<int?> myList = new List<int?> {1,1,2};? A: this compiles List<int?> ints = new List<int?> { 1, 2, 3 };
{ "language": "en", "url": "https://stackoverflow.com/questions/7595649", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: get vector between 2 rectangles suppose I have 2 rectangles as follows: * *one encloses the other *they share at least 2 sides (3 or all 4 also possible) how do I get the vector that describes the displacement required for the inner rectangle to move upto the non-shared side(s)? A: If i understood you correctly, then you you should follow those steps: * *Find corner that both sides are shared. *Get oposit corner from inner and outer rectangles. *vector = outerRecCorner - innerRecCorner A: It's more like a math than programming question :) Lets assume you have two rectangles: A (inside) and B (outside). They have 4 corners: Point [] GetCorners (Rectangle rect) { Point [] corners = new Point[4]; Point corners[0] = new Point(rect.X, rect.Y); Point corners[1] = new Point(rect.X + rect.Width, rect.Y); Point corners[2] = new Point(rect.X, rect.Y + rect.Height); Point corners[3] = new Point(rect.X + rect.Width + rect.Width, rect.Y); return corners; } First find the first shared corner: Point [] cornersListA = GetCorners(A); Point [] cornersListB = GetCorners(B); int sharedCornerIndex = 0; for (int i=0; i<4; i++) { if(cornersListA[i].X==cornersListB[i].X && cornersListA[i].Y==cornersListB[i].Y) { sharedCornerIndex = i; break; } } Then find the corner oposite of it: int oppositeCornerIndex = 0; if(sharedCornerIndex ==0) oppositeCornerIndex = 3; if(sharedCornerIndex ==3) oppositeCornerIndex = 0; if(sharedCornerIndex ==1) oppositeCornerIndex = 2; if(sharedCornerIndex ==2) oppositeCornerIndex = 1; Finally, get vector (I didn't check this part of the code, but it should work): Vector v = new Vector(); v.X = cornersListB[oppositeCornerIndex].X - cornersListA[oppositeCornerIndex].X; v.Y = cornersListB[oppositeCornerIndex].Y - cornersListA[oppositeCornerIndex].Y;
{ "language": "en", "url": "https://stackoverflow.com/questions/7595651", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: C# Deserialization - Is it safe to catch TargetInvocationException? I am using BinaryFormatter to serialize and deserialize some objects. The structure of those object is as follows: [Serializable()] public class SerializableObject : ISerializable { public void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("SomeProperty", SomeProperty); // similar for other properties } public SerializableObject(SerializationInfo info, StreamingContext context) { this.SomeProperty = (SomePropertyClass)info.GetValue("SomeProperty", typeof(SomePropertyClass)); // similar for other properties } } I have noticed that when I try to deserialize an object, a TargetInvocation exception is thrown if the "SomeProperty" entry cannot be found (for example, because it was renamed or deleted). Since I intend to change the properties of SerializableObject class in future, I was thinking of catching the exception and setting the value of the problematic property to some default value instead of crashing my application, like this: public SerializableObject(SerializationInfo info, StreamingContext context) { try { this.SomeProperty = (SomePropertyClass)info.GetValue("SomeProperty", typeof(SomePropertyClass)); } catch (TargetInvocationException) { this.SomeProperty = SomePropertyClass.DefaultValue; } } As we all know, catching exceptions that you don't know how or cannot handle is a bad practice, so I'm asking whether it's safe to catch it in this place? Can the same exception be thrown for any other reason (that I don't know and therefore shouldn't handle)? A: A TargetInvokationException should have an InnerException which will give you more information. I'd suggest that you check the inner in the catch block and rethrow if the situation is simply a missing property. A: Since TargetInvocationException is not listed in the set of exceptions you should expect from that method (see MSDN) I would say it is wrong to try to handle that. A better approach is to loop on the names it does have, and pick the ones you expected: foreach(SerializationEntry entry in info) { switch(entry.Name) { case "Foo": //... case "Bar": //... } } Or... use a less fussy serializer ;p (btw, the above uses the alternative foreach handling based on a typed enumerator and GetEnumerator() method; it doesn't implement IEnumerable/IEnumerable<T>, but... it doesn't have to; you can use foreach without that)
{ "language": "en", "url": "https://stackoverflow.com/questions/7595653", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: SecKeychainItemDelete returns -67701 (errSecInvalidRecord) on Mac OS X 10.7 I have a program built with Xcode 3.2.5 on a Mac 10.6 system, the program needs to add to and remove items from the system keychain. It runs well on Mac OS X 10.6 but on 10.7, The call to SecKeychainItemDelete returned error code -67701 which is not defined in 10.6 SDK. After some googling I found -67701 (errSecInvalidRecord) is newly added in 10.7 SDK. Does anyone know how to fix this? A: I ran into the same problem. This happens because the keychain api caches SecKeychainItemRef object every time one of SecKeychainFindInternetPassword and SecKeychainFindGenericPassword methods is called. So, whenever you have called any of these two methods be sure to clear the api cache using the method SecKeychainItemFreeAttributesAndData. Also release the SecKeychainItemRef object using CFRelease. A: To answer a super old question: I think this is because of the new sandboxing features in OS X Lion. I think the solution is to sign your app and add enablements for the Keychain. Source: TunnelBlick - an OSS VPN tunnel - suggests this is the problem
{ "language": "en", "url": "https://stackoverflow.com/questions/7595656", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Retrieve "Clean" Image Out Of ImageView I've Image stored in ImageView and after several processes (flip, rotate, fix color, etc) it's saved back as new file. However, I just realize that when I just load into ImageView and soon after that directly save the result, I got different result. Take a look at attached image for reference. image source image result Here's how I extract image from ImageView: String filePath = Environment.getExternalStorageDirectory() + File.separator + bufferPath; ByteArrayOutputStream bytes = new ByteArrayOutputStream(); selectedImage.setDrawingCacheEnabled(true); Bitmap bitmap = Bitmap.createBitmap(selectedImage.getDrawingCache()); selectedImage.setDrawingCacheEnabled(false); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes); imageFile = new File( filePath ); //write the bytes in file FileOutputStream fo = new FileOutputStream(imageFile); fo.write(bytes.toByteArray()); Is there any workaround to make resulting image the same as source? different component, maybe? A: Hold a backing Bitmap (originally the source) that you carry out your manipulations on. Use the ImageView just to show this Bitmap - do not manipulate the post-scaled version that is held in the ImageView's drawing cache.
{ "language": "en", "url": "https://stackoverflow.com/questions/7595660", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Couchdb list api - can't seem to return plain/text I am trying to return text/plain from a couchdb list but it is not working. The content is returned correctly but the content type seems to be forced to application/json. Code snippet is start({ "headers" : {"Content-type" : "text/plain"}}); send("Nono, you can't do this"); Before this code there is one getRow invoked. If I remove that the text/plain content type is returned as expected. Not sure what is going wrong here and I can't really avoid the getRow as the result of that determines the content type to return. Any guidance warmly welcomed! A: CouchDB starts the response (including sending the default Content-Type header) when you first call getRow(), so what you are seeing is expected behaviour. Submit a ticket to our JIRA (http://issues.apache.org/jira/browse/COUCHDB), though, and perhaps it can be delayed, allowing the useful effect you are attempting.
{ "language": "en", "url": "https://stackoverflow.com/questions/7595662", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: SVN Commit error (SVN on window server) I am trying to upload around 828 MB data on SVN server but it throws following error. ................................................................................ ....svn: Commit failed (details follow): svn: PUT of '/svn/interborosrc/!svn/wrk/bd7fee70-765a-e141-88fb-f99591db3db4/tru nk/Archived/CAS_BASE/Code_Base/DB_Objects/Procedures/get_tot_outstanding_reserve .sql': timed out waiting for server What could be the issue , I have uploaded data in GB's but not encounter such issues before Regards Prashant A: edit the servers config file (%APPDATA%\Subversion\servers). In there, you can find the option http-timeout = 60 Just increase that value.
{ "language": "en", "url": "https://stackoverflow.com/questions/7595668", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How to make the default text in a select field grey like the placeholder for textfields? I have the following select field in a form: { xtype: 'selectfield', name: 'minprice', label: 'Min Price', valueField: 'No min', placeHolder: 'No min', useClearIcon: true, options: [{ text: 'No Min', value: 'Test' }, { text: 'Test2', value: 'Test2' }, { text: 'Test3', value: 'Test3' }] } I would like the first option 'No min' to look like a place holder (so it's light grey). The reason for this is that the rest of the form has placeholders in light grey and having a select field with black text doesn't fit the style of the form. I've tried specifying a placeholder and the the valueField with no success. Thanks. A: You can use the placeHolder property but then you shouldn't specify the options property. For example: { id:'theSelect', name: 'fieldId', xtype: 'selectfield', displayField: 'text', valueField: 'value', placeHolder :'No min' } And then have this or load it from a store to load the options: Ext.getCmp('theSelect').setOptions( [ {text: 'First Option', value: 'first'}, {text: 'Second Option', value: 'second'}, {text: 'Third Option', value: 'third'} ]); See the whole working code here http://jsfiddle.net/p5K4q/16/ A: You can do this with -webkit-text-fill-color. The easiest way to target a specific field is like this: { xtype: 'datepickerfield', placeHolder : 'Date', cls: 'your-class' } .your-class .x-form-field { -webkit-text-fill-color: red; } A: You can use the placeholder and set the AutoComplete as false, since it is set to true by default.. This works fine for me.
{ "language": "en", "url": "https://stackoverflow.com/questions/7595669", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to stop an NSTimer that I don't know is released or not Sorry to ask this question, but it's now day 3 I try to solve this problem and have no progress so far. The problem is this: during a game there is a pause between the user answered a question and the next question. Also in several other cases there are such pauses in gameplay. For this I use one NSTimer. In .h I have: @property(nonatomic,retain) NSTimer *scheduleTimer; and in the .m @synthesize scheduleTimer; scheduleTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target: self selector: @selector(playFeedbackSound) userInfo: nil repeats: NO]; now this works just fine. But when the user exits the ViewController I need to invalidate the timer. Otherwise the timer will fire and then crash the app or pops up stuff that does not belong in the other view etc. Therefore I write: - (void)viewWillDisappear:(BOOL)animated { [scheduleTimer invalidate]; } now this does the job if the timer is actually set. But if there is no such timer scheduled, the app just crashes. I tried probably everything there is, including @try (which crashes the app too, Zombie says "* -[CFRunLoopTimer invalidate]: message sent to deallocated instance 0x567640"). Since the timer gets released after it is done, a [scheduleTimer isValid] will just crash the app as well. Now I'm already pretty desperate, and as a last resort I'm thinking of replacing the timer with UIView animateWithDuration that does nothing visible. However, I think this should be a pretty standard situation. I just don't know why I can't find an answer to this very obvious task. Can you help? Thank you A: I think the problem is that the NSTimer gets autoreleased before you invalidate it. So you should do: scheduleTimer = [[NSTimer scheduledTimerWithTimeInterval:1.0 target: self selector: @selector(playFeedbackSound) userInfo: nil repeats: NO] retain]; And you should also release the timer in viewWillDisappear: [scheduleTimer release]; But an even better solution is probably to use the dot property syntax to care of retain/release: self.scheduleTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target: self selector: @selector(playFeedbackSound) userInfo: nil repeats: NO]; And then: - (void)viewWillDisappear:(BOOL)animated { if (self.scheduleTimer != nil) { [self.scheduleTimer invalidate]; self.scheduleTimer = nil; } } A: Create a method to invalidate the timer that also sets the property to nil: - (void) invalidateTimer { if (self.scheduleTimer) { [self.scheduleTimer invalidate]; self.scheduleTimer = nil; } } ... and then call that method whenever you invalidate the timer. For example: - (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear: animated]; [self invalidateTimer]; } Make sure your timer is retained by using: self.scheduleTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target: self selector: @selector(playFeedbackSound) userInfo: nil repeats: NO];
{ "language": "en", "url": "https://stackoverflow.com/questions/7595685", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is Ajax called this method? I have created one web service that will may called from web using jQuery ajax call or may call from desktop application that I have created I want to know in that webservice method.. Is this ajax call or not?.. Is that possible? A: If the HTTP_X_REQUESTED_WITH server variable is set and equals to 'XMLHttpRequest', you can assume that the request was made via jQuery AJAX. A: As @Tatu Ulmanen answered you can check the HTTP_X_REQUESTED_WITH server variable is set and equals to 'XMLHttpRequest' to know that the request is ajax. For this to work it is important that the correct header is set by you or the javascript library you are using. Otherwise there is no way to differentiate because ajax requests are normal GET or POST requests
{ "language": "en", "url": "https://stackoverflow.com/questions/7595688", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Where is the source code for the UIComponent in FLEX 4.5? All the methods in UIComponent, LayoutManager (and I suppose more) are unimplemented. Why? and how to find it? I use the lastest version of flashDeveloper. The flex package is downloaded by the app itself, and I saw is version 4.5 A: FlashDevelop has a keyboard shortcut that will take you to the class definition. I think it's something like F4, but I don't use it on a daily basis. UIComponent has a lot of unimplemented methods because it's sort of like a smucky abstract class-ish thing.
{ "language": "en", "url": "https://stackoverflow.com/questions/7595690", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Convert certificate in BIN format to X509 format I have read this good article on running tomcat in https and implemented it. http://techtracer.com/2007/09/12/setting-up-ssl-on-tomcat-in-3-easy-steps/ It is working fine and my tomcat is running in https mode. But the problem is i got the certificate in BIN format. I need it in X509 format so that i can use it as an raw resource for my Android project I have used java keytool to create it.Can i use OpenSSL to convert it into X509 Format or java keytool is sufficient? I am new to this securities stuff. Please point me in the right direction and clear my doubts. A: I think keytool already handles certificates in X509 format only. You should have generated .keystore file. You can export certificate from it using command: keytool -export -alias mycert -keystore mykeystore.bin -file certificatefile.cer A: Yes of course, you can use OpenSSL to convert the certificate and keys to and from the following formats * *Standard PEM *DER / Binary *PKCS#7 (aka P7B) *PKCS#12 (aka PFX) In your case, given a private key file and digital certificate in standard PEM, convert them both to pkcs12 format using the following steps: Step 1: Convert the PEMs to a single PKCS12 file OpenSSL> pkcs12 -export -in CE_cert.cer -inkey CE_prv_key_PEM.key -out pkcs12_KeyStore.p12 -name ce_cert_prv_key Heres the doc for OpenSSL PKCS12 command. Step 2: Import the PKCS12 file created in step 1 into the new JKS C:\>keytool -importkeystore -srckeystore pkcs12_KeyStore.p12 -srcstoretype pkcs12 -srcstorepass somepass -srcalias ce_cert_prv_key -destk eystore path/to/JavaKeyStore_KS.jks -deststoretype jks -deststorepass somepass -destkeypass somepass Now after having the certificate and private key in the JKS format, you can use this JSK key store in Tomcat.
{ "language": "en", "url": "https://stackoverflow.com/questions/7595692", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Code Contract, inheritance and Liskov Principle I have in my code the concept of command : public abstract class BaseCommand { public BaseCommand() { this.CommandId = Guid.NewGuid(); this.State = CommandState.Ready; } public Guid CommandId { get; private set; } public CommandState State {get; private set; } protected abstract void OnExecute(); public void Execute() { OnExecute(); State = CommandState.Executed; } } And some concrete implementation like this one : public class DeleteItemCommand { public int ItemId {get; set;} protected override void OnExecute() { var if = AnyKindOfFactory.GetItemRepository(); if.DeleteItem(ItemId); } } Now I want to add some validation. The first thing I can do is add a if/throw check: public class DeleteItemCommand { public int ItemId {get; set;} protected override void Execute() { if(ItemId == default(int)) throw new VeryBadThingHappendException("ItemId is not set, cannot delete the void"); var if = AnyKindOfFactory.GetItemRepository(); if.DeleteItem(ItemId); } } Now, I'm trying to use Code Contracts, because I'm quite convinced of its usefulness to reduce bug risk. If I rewrote the method like this : public class DeleteItemCommand { public int ItemId {get; set;} public void Execute() { Contract.Requires<VeryBadThingHappendException>(ItemId != default(int)); var if = AnyKindOfFactory.GetItemRepository(); if.DeleteItem(ItemId); } } The method compiles, the check is done at run-time. However, I got warning : warning CC1032: CodeContracts: Method 'MyProject.DeleteItemCommand.Execute' overrides 'MyProject.BaseCommand.Execute', thus cannot add Requires. I understand this warning is issued because I'm breaking the Liskov Principle. However, in my case, conditions are different from one concrete class to another. My BaseCommand class is actually defining some common attributes like CommandIdentifier, state, and other ultimate features I removed here to keep the question simple. While I understand the concepts of this principle, I don't know what are the step I have to do to remove the warning properly (don't tell me about the #pragma warning remove). * *Should I stop using code contracts in this case, where concrete implementations have specific requirements ? *Should I rewrite my commanding mechanism to have, for example, separation between the Command "arguments" and the Command "execution" ? (having one CommandeExecutor<TCommand> per concrete class). This would result in a lot more classes in my project. *Any other suggestion ? *[Edit] As suggested by adrianm, convert properties to readonly, add constructor parameters to populate the properties and check properties in the contructor A: I don't think you can use code contracts in this case. I think, you cannot add preconditions in overridden methods, only invariants and postconditions are possible there. Your best bet might be be to refactor from inheritance to composition: ICommandExecutor { Execute(BaseCommand source); } public abstract class BaseCommand { public ICommandExecutor Executor { get; private set; } public void Execute() { this.Executor.Execute(this); State = CommandState.Executed; } } public class DeleteCommandExecutor : ICommandExecutor { public void Execute(BaseCommand source) { Contract.Requires<VeryBadThingHappendException>(source.ItemId != default(int)); var if = AnyKindOfFactory.GetItemRepository(); if.DeleteItem(source.ItemId); } } A: You could change the code to perform the execution in a different method: public class DeleteItemCommand: BaseCommand { public int ItemId {get; set;} public override void Execute() { PrivateExecute(ItemId); } private void PrivateExecute(int itemId) { Contract.Requires<VeryBadThingHappendException>(itemId != default(int)); var rep = AnyKindOfFactory.GetItemRepository(); rep.DeleteItem(itemId); } } A: In this case the code contracts are directing your attention to a design error in your class structure, and you would be wise to heed this warning. To see the problem, consider how the classes may be used. protected void executeButton_Click(object sender, EventArgs args) { BaseCommand command = GetCurrenctlySelectedCommand(); command.Execute(); } If the variable command happens to hold an object of the type DeleteItemCommand, then that object has preconditions that must be met or an exception will be thrown. We would like to avoid this exception, so how can we verify that the precondition is met? Unfortunately, there is no simple way to do this. We cannot reason about all the possible preconditions about every type of derived object that may inhabit that variable. In fact, that variable may contain a type of object that was not invented when this code was written. In fact, the type for that object may not even be in the accessibility domain of this method, if it was provided by a factory in another assembly. Since there is no way to verify that preconditions are met for this object, we cannot ensure the correctness of this code. We can either conclude from this that code contracts are useless, or that the code is designed incorrectly. I understand this warning is issued because I'm breaking the Liskov Principle. So you admit it! However, in my case, conditions are different from one concrete class to another. My BaseCommand class is actually defining some common attributes like CommandIdentifier, state, and other ultimate features I removed here to keep the question simple. Your analysis itself suggests the proper alternative. Instead of a BaseCommand abstract class, you should create a CommandAttributes concrete sealed class. Then include an instance of this class within all of your command objects. By using composition rather than inheritence, each of your command classes get the functionality they need, and they can define whatever sorts of preconditions or postconditions they need. And any methods that use those classes can verify those preconditions are met and take advantage of the postconditions. A: I would use the constructor to set all the correct values, instead of public property setters. public class DeleteItemCommand { public DeleteItemCommand(int itemId) { Contract.Requires<VeryBadThingHappendException>(itemId!= default(int)); ItemId = itemId; } public int ItemId {get; private set;} public void Execute() { var if = AnyKindOfFactory.GetItemRepository(); if.DeleteItem(ItemId); } } A: Apparently, Code Contracts work best on Domain Objects. I am guessing your Command class is not a domain object.
{ "language": "en", "url": "https://stackoverflow.com/questions/7595697", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Two asterisks before variable name While digging in some C source code I found that fragment of code char **words I know that single asterisk before variable name "points" to pointer, but what is the purpose of those two asterisks ? A: // your imagination is the limit char letter; char *word; // sequence of letters char **sentence; // sequence of words char ***paragraph; // sequence of sentences char ****book; // sequence of paragraphs char *****library; // sequence of books The data structure is probably not the best to represent the concept: this is just an illustration. A: It is a pointer to a pointer. It is used primarily when you use an array of character strings. For example: you have char sample[5][5]; - this can store 5 strings of length 4; If you need to pass it to a function, func(sample); And the function definition of such a function would be func(char **temp); A: simple dude! it points to the pointer thats it **a points to the pointer *a thats it. For more information you can google it
{ "language": "en", "url": "https://stackoverflow.com/questions/7595698", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: Sitefinity RadGrid not working in backend page I have a RadGrid on a sitefinity page, I am using it to create a module to proform CRUD on a database table in the backend. If I put the RadGrid on a aspx page and view in browser, it works fine, However when I add it to a site finity back end page, Only the refresh and delete work, the add and update dont save to the database. I can only assume something in the sitefinity backend if conflicting with the RadGrid Ajax here is my code: <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="newsArticleAdmin.ascx.cs" Inherits="SitefinityWebApp.Modules.newsArticles.admin.newsArticleAdmin" %> <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %> <div style="clear:both;"></div> <div id="adminContents"> <h2>News Articles</h2> <p>These articles appear on the home page</p> <br /> <telerik:RadScriptManager ID="RadScriptManager1" Runat="server"> </telerik:RadScriptManager> <telerik:RadAjaxManager ID="RadAjaxManager1" runat="server"> <AjaxSettings> <telerik:AjaxSetting AjaxControlID="RadGrid1"> <UpdatedControls> <telerik:AjaxUpdatedControl ControlID="RadGrid1" /> <telerik:AjaxUpdatedControl ControlID="SqlDataSource1" /> </UpdatedControls> </telerik:AjaxSetting> </AjaxSettings> </telerik:RadAjaxManager> <telerik:RadGrid ID="RadGrid1" runat="server" AllowAutomaticDeletes="True" AllowAutomaticInserts="True" AllowAutomaticUpdates="True" AutoGenerateDeleteColumn="True" AutoGenerateEditColumn="True" CellSpacing="0" DataSourceID="SqlDataSource1" GridLines="None" Skin="Telerik"> <MasterTableView AutoGenerateColumns="False" CommandItemDisplay="TopAndBottom" DataKeyNames="fld_blogPostId" DataSourceID="SqlDataSource1" EditMode="InPlace"> <CommandItemSettings ExportToPdfText="Export to PDF" AddNewRecordText="Add new article"></CommandItemSettings> <RowIndicatorColumn FilterControlAltText="Filter RowIndicator column"> </RowIndicatorColumn> <ExpandCollapseColumn FilterControlAltText="Filter ExpandColumn column"> </ExpandCollapseColumn> <Columns> <telerik:GridBoundColumn DataField="fld_blogPostId" DataType="System.Int32" FilterControlAltText="Filter fld_blogPostId column" HeaderText="fld_blogPostId" ReadOnly="True" SortExpression="fld_blogPostId" UniqueName="fld_blogPostId"> </telerik:GridBoundColumn> <telerik:GridBoundColumn DataField="fld_blogTitle" FilterControlAltText="Filter fld_blogTitle column" HeaderText="fld_blogTitle" SortExpression="fld_blogTitle" UniqueName="fld_blogTitle"> </telerik:GridBoundColumn> <telerik:GridBoundColumn DataField="fld_blogContents" FilterControlAltText="Filter fld_blogContents column" HeaderText="fld_blogContents" SortExpression="fld_blogContents" UniqueName="fld_blogContents"> </telerik:GridBoundColumn> <telerik:GridBoundColumn DataField="fld_blogDate" FilterControlAltText="Filter fld_blogDate column" HeaderText="fld_blogDate" SortExpression="fld_blogDate" UniqueName="fld_blogDate"> </telerik:GridBoundColumn> <telerik:GridBoundColumn DataField="fld_blogImage" FilterControlAltText="Filter fld_blogImage column" HeaderText="fld_blogImage" SortExpression="fld_blogImage" UniqueName="fld_blogImage"> </telerik:GridBoundColumn> </Columns> <EditFormSettings> <EditColumn FilterControlAltText="Filter EditCommandColumn column"></EditColumn> </EditFormSettings> </MasterTableView> <StatusBarSettings LoadingText="Loading articles..." ReadyText="Articles ready" /> <FilterMenu EnableImageSprites="False"></FilterMenu> <HeaderContextMenu CssClass="GridContextMenu GridContextMenu_Default"></HeaderContextMenu> </telerik:RadGrid> <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NewsArticlesConnectionString %>" DeleteCommand="DELETE FROM [tbl_newsArticles] WHERE [fld_blogPostId] = @fld_blogPostId" InsertCommand="INSERT INTO [tbl_newsArticles] ([fld_blogTitle], [fld_blogContents], [fld_blogDate], [fld_blogImage]) VALUES(@fld_blogTitle, @fld_blogContents, @fld_blogDate, @fld_blogImage)" SelectCommand="SELECT * FROM tbl_newsArticles" UpdateCommand="UPDATE [tbl_newsArticles] SET [fld_blogTitle] = @fld_blogTitle, [fld_blogContents] = @fld_blogContents, [fld_blogDate] = @fld_blogDate, [fld_blogImage] = @fld_blogImage WHERE fld_blogPostId = @fld_blogPostId"> <DeleteParameters> <asp:Parameter Name="fld_blogPostId" /> </DeleteParameters> <InsertParameters> <asp:Parameter Name="fld_blogTitle" /> <asp:Parameter Name="fld_blogContents" /> <asp:Parameter Name="fld_blogDate" /> <asp:Parameter Name="fld_blogImage" /> </InsertParameters> <UpdateParameters> <asp:Parameter Name="fld_blogTitle" /> <asp:Parameter Name="fld_blogContents" /> <asp:Parameter Name="fld_blogDate" /> <asp:Parameter Name="fld_blogImage" /> <asp:Parameter Name="fld_blogPostId" /> </UpdateParameters> </asp:SqlDataSource> </div> Anyone seen this before and know of a fix? Cheers Andrew @atmd83 A: try opening the page in the backend page editor and make sure that "enable view state" is set to true. by default, backend pages in Sitefinity are usually set with this disabled, as most of the backend uses AJAX. hope this is helpful!
{ "language": "en", "url": "https://stackoverflow.com/questions/7595700", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to remove a flag in Java Hi I need to remove a flag in Java. I have the following constants: public final static int OPTION_A = 0x0001; public final static int OPTION_B = 0x0002; public final static int OPTION_C = 0x0004; public final static int OPTION_D = 0x0008; public final static int OPTION_E = 0x0010; public final static int DEFAULT_OPTIONS = OPTION_A | OPTION_B | OPTION_C | OPTION_D | OPTION_E; I want to remove, for example OPTION_E from default options. Why is not the following code correct? // remove option E from defaul options: int result = DEFATUL_OPTIONS; result |= ~OPTION_E; A: You should use the and operator instead of or: result &= ~OPTION_E; One way to think about it is that |= sets bits whereas &= clears bits: result |= 1; // set the least-significant bit result &= ~1; // clear the least-significant bit A: |= performs a bitwise or, so you're effectively "adding" all the flags other than OPTION_E. You want &= (bitwise and) to say you want to retain all the flags other than OPTION_E: result &= ~OPTION_E; However, a better approach would be to use enums and EnumSet to start with: EnumSet<Option> options = EnumSet.of(Option.A, Option.B, Option.C, Option.D, Option.E); options.remove(Option.E); A: You must write result &= ~OPTION_E; Longer explanation: You must think in bits: ~OPTION_E // 0x0010 -> 0xFFEF DEFATUL_OPTIONS // -> 0x001F 0xFFEF | 0x001F // -> 0xFFFF 0XFFEF & 0x001F // -> 0x000F The OR will never clear 1 bits, it will at most set some more. AND on the other hand will clear bits.
{ "language": "en", "url": "https://stackoverflow.com/questions/7595701", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "29" }
Q: IOS process internals - how to get information? I am looking for an API to monitor the tasks running on a plain iPhone (no jailbreak). Those are about: * *look for CPU usage (my main concern). *look for memory usage. *look for disk usage (how many read/write) *look for network usage (how many bytes sent and received by network: 3G, Wifi, GSM). *is it possible to rely on the IOS simulator running on a Mac (or should I test my application directly on the device)? I think I can look into the system C libraries (sigint, etc.) but I am not sure to be able to retrieve this information except for the current applications running. I know some monitor applications run on the global usage but I would like to be able to find the information process by process. If someone can provide some links or something useful, I will start a deeper investigation then. A: CPU usage can be found by looking at the code from this related question: iOS - Get CPU usage from application Memory usage: Available memory for iPhone OS app And here are a couple threads that talk about how to find out about the applications or tasks currently running: Can we retrieve the applications currently running in iPhone and iPad How to get information about free memory and running processes in an App Store approved app? (Yes, there is one!) How to get the active processes running in iOS The answers to these questions may point you in the direction you'd like to head towards. Good luck! A: The Activity Monitor should get you what you're looking for. You should be able to observe RAM, CPU, and VRAM usage for each iOS process. This is a default tool installed with xCode. Very handy.
{ "language": "en", "url": "https://stackoverflow.com/questions/7595702", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: access the same database from two different applications (read/write and read-only) I know that there's lot of documentation about, but i'm totally newbie on this argument and I would like to have some simple advices about that. I'm working with spring hibernate and jpa. I'm going to have two different applications on the same server. Both of them communicate with the same database, but one just read and the other read and write. Which is the best way to afford this? Looking aorund i understand that should be necessary a second-level cache like EHCache, but there are some stupid things that i can't understand. For example, should I create exactly the same entities in both applications? How can read-only application associate its entities with the ones created by the other application? A: Well, here's some remarks on your question * *Theoretically, you're not at all forced to have the same Java Classes mapped to the database tables. You could make different ones and annotate them such that both sets map to the same tables. That being said, this is not too good a practice. What you should do is have a data-access-module where you have your set of JPA Entity beans mapped to the tables, as well as the classes that allow you to do basic operations on these (at least CRUD), then have separate service classes in each of your two projects that use the data-access-module classes to implement the specific business logic *Since you're having 2 applications accessing the same database, you'll be dealing with two separate JPA Contexts, which will flush and synchronize separately. Because of this, some data inconsistencies may appear, if you don't make sure to manually flush the modifications each time you need to. This could be further an issue if you use a 2nd level cache on top of it all (like EHCache). However, in your current setup, only the application that reads AND writes should adhere to these restrictions, the other one (the one that's read only) can, and indeed it is advised, to use a second level cache to speed up its operations. Just make sure that said cache is refreshed/expired such that you'll get the desired data when it's written by the first app (i.e., if you makes writes often, your cache should also expire often. If you do writes once a month you can configure a longer expire time on the read-only application's 2nd level cache) A: I would just create two users, one of which has only read access (if that's supported by your DB engine).
{ "language": "en", "url": "https://stackoverflow.com/questions/7595703", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Tab links using only the page and app_id has stopped working, is there an alternative beyond querying Facebook each time? A few days ago these type of links worked: http://www.facebook.com/pages/132456789?sk=app_132465798465 but now they give 404's. The alternative is link to the namespace of the page like so: http://www.facebook.com/pages/foo/1456798324564?sk=app_134654689794 however to find out the link I'd need to ask Facebook for it, and it seem like since the namespace can change I can't just ask for it once. Is there another way to use page and app id's to link to tabs without needing the roundtrip to Facebook? A: I don't think that first format was ever used on Facebook, i'm surprised it worked. As far as I can tell the 'name' part of a page URL is arbitrary, so just filling in something there will work, e.g. http://www.facebook.com/pages/Tea/194040780316?sk=info will also work as http://www.facebook.com/pages/some_random_text/194040780316?sk=info
{ "language": "en", "url": "https://stackoverflow.com/questions/7595706", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: DLL in sub folder rather than in application folder have created a dynamic python file (pyd) using VC++. Using cx_freeze, I have created an exe. In order for this program to work on other computers, I need to have a file msvcr100.dll in the applications folder. And I do get the desired output. However the distribution license for Microsoft clearly states that the dll files should be in a sub folder within the application folder. The sub folder should be named "Microsoft.VC100.CRT". I have tried playing around with the settings in MS VC++ by changing the project properties. Its proving to be very tricky as the only thing I used MSVC++ was for my python program to use some c option and return some output which I can use again in my python program. I have played around with manifest files (embedding and without embedding), also set the Additional Libraries Directory in VC++ Any one got any ideas as to what I can do to make my pyd file look into the Microsoft.VC100.CRT. A: I'm not sure when in your script the DLL is loaded, but assuming it's delayed to the point you can do something about it, then you can have a go at loading the library yourself: import os import ctypes try: here = os.path.dirname(__file__) except NameError: here = os.getcwd() dll = ctypes.CDLL(os.path.join(here, 'Microsoft.VC100.CRT', 'msvcr100.dll')) del here or with pywin32 import os import win32api try: dll = win32api.LoadLibrary('msvcr100.dll') #Never hurts to try except win32api.error: try: here = os.path.dirname(__file__) except NameError: here = os.getcwd() #Just to prove messing with PATH does something. os.environ['PATH'] = os.environ['PATH'] + os.pathsep + os.path.join(here, 'Microsoft.VC100.CRT') dll = win32api.LoadLibrary('msvcr100.dll') #Give it another crank of the handle. #Or alternatively without messing with PATH dll = win32api.LoadLibrary(os.path.join(here, 'Microsoft.VC100.CRT', 'msvcr100.dll')) #Give it another alternative crank of the handle. del here A: The dynamic python file I had created was compiled using Visual C++ 2010. Hence in order for it to work, the MSVCR100.dll files were needed. However as I had also created an application (.exe) of my final program, it depended on MSVCR90.dll. As Microsoft insist that these dlls should be in a folder with a particular name, I couldn't just place these files in the application folder. Hence what I did was compiled the pyd file using Visual C++ 2008. Then added the MSVCR90.dll file along with the corresponding manifests and MSVCP90.dll and MSVCM90.dll files. This solved the problem. My guess is that before my program in order to work needed two generations of C run time files. By compiling the pyd file using VC++2008, I effectively reduced that dependancy to one generation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7595709", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why use (function(){})() or !function(){}()? I was reading In JavaScript, what is the advantage of !function(){}() over (function () {})()? then it hit me, why use : (function(){})() or !function(){}() instead of just function(){}()? Is there any specific reason? A: It depends on where you write this. function(){}() by itself will generate a syntax error as it is evaluated as function declaration and those need names. By using parenthesis or the not operator, you enforce it to be interpreted as function expression, which don't need names. In case where it would be treated as expression anyway, you can omit the parenthesis or the operator. A: I guess you are asking why use: var fn = (function(){}()); versus: var fn = function(){}(); The simple answer for me is that often the function on the RHS is long and it's not until I get to the bottom and see the closing () that I realise I've been reading a function expression and not a function assignment. A full explanation is in Peter Michaux's An Important Pair of Parens. A: A slight variation on RobG's answer. Many scripts encompass the entire program in one function to ensure proper scoping. This function is then immediately run using the double parentheses at the end. However, this is slightly different then programs which define a function that can be used in the page but not run initially. The only difference between these two scenarios is the last two characters (the addition of the double parentheses). Since these could be very long programs, the initial parenthesis is there to indicate that "this will be run immediately." Is it necessary for the program to run? No. Is it helpful for someone looking at the code and trying to understand it? Yes.
{ "language": "en", "url": "https://stackoverflow.com/questions/7595712", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to write a trigger to abort delete in MYSQL? I read this article but it seems not work for delete. I got this error when tried to create a trigger: Executing SQL script in server ERROR: Error 1363: There is no NEW row in on DELETE trigger CREATE TRIGGER DeviceCatalog_PreventDeletion BEFORE DELETE on DeviceCatalog FOR EACH ROW BEGIN DECLARE dummy INT; IF old.id = 1 or old.id =2 THEN SELECT * FROM DeviceCatalog WHERE DeviceCatalog.id=NEW.id; END IF; END; SQL script execution finished: statements: 4 succeeded, 1 failed A: Well, the error messages tells you quite clearly: in a DELETE trigger there is no NEW. * *In an INSERT trigger you can access the new values with NEW.. *In an UPDATE trigger you can access the new values with NEW., the old ones with - you guessed it - OLD. *In a DELETE trigger you can acces the old values with OLD.. It simply makes no sense to have NEW in a DELETE, just as OLD in an INSERT makes no sense. A: Improving @Devart's (accepted) answer with @MathewFoscarini's comment about MySQL SIGNAL Command, instead of raising an error by calling an inexistent procedure you could signal your custom error message. DELIMITER $$ CREATE TRIGGER DeviceCatalog_PreventDeletion BEFORE DELETE ON DeviceCatalog FOR EACH ROW BEGIN IF old.id IN (1,2) THEN -- Will only abort deletion for specified IDs SIGNAL SQLSTATE '45000' -- "unhandled user-defined exception" -- Here comes your custom error message that will be returned by MySQL SET MESSAGE_TEXT = 'This record is sacred! You are not allowed to remove it!!'; END IF; END $$ DELIMITER ; The SQLSTATE 45000 was chosen as MySQL's Reference Manual suggests: To signal a generic SQLSTATE value, use '45000', which means “unhandled user-defined exception.” This way your custom message will be shown to the user whenever it tries to delete records ID 1 or 2. Also, if no records should be deleted from the table, you could just remove the IF .. THEN and END IF; lines. This would prevent ANY records from being deleted on the table. A: Try something like this - DELIMITER $$ CREATE TRIGGER trigger1 BEFORE DELETE ON table1 FOR EACH ROW BEGIN IF OLD.id = 1 THEN -- Abort when trying to remove this record CALL cannot_delete_error; -- raise an error to prevent deleting from the table END IF; END $$ DELIMITER ; A: As the error says: There is no NEW variable on delete. you can use new.id only on insert and update. Use old.id instead. SELECT * FROM DeviceCatalog WHERE DeviceCatalog.id=old.id;
{ "language": "en", "url": "https://stackoverflow.com/questions/7595714", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: Javascript Regular Expression Works on OSx NOT on Windows I have been developing a javascript application on OSx with Safari as the main browser, I am trying to migrate this application to a windows system with WAMP as my server. The code has not changed, however it will no longer work correctly and when carrying out the find within an array using the regular expression. I receive the return value as false which should not be the case. If anyone can take a brief look at this code and give me some opinions I would be very grateful. Array.prototype.find = function(searchStr) { var returnArray = false; for (index=0; index<this.length; index++) { if (typeof(searchStr) == 'function') { if (searchStr.test(this[index])) { if (!returnArray) { returnArray = [] } returnArray.push(index); } } else { if (this[index]===searchStr) { if (!returnArray) { returnArray = [] } returnArray.push(index); } } } return returnArray; } var newIndexTargetID = window.indexTargetID; var searchStr =RegExp(newIndexTargetID,'i'); var regexp1=mytool_array.find(searchStr); alert ("2" + mytool_array[regexp1]) var previousProperty = mytool_array[regexp1]; mytool_array[regexp1] = "[[" + timeLimitID + "," + '"' + l[j].sourceId + '"' + "," + timeLimitProperty + "]]" + "(" + previousProperty + ")"; finalResult = mytool_array.join(' '); A: The type of a regular expression object is not function but object. At least in Internet Explorer and Firefox. I suggest that you swap the code in the if statement and check if the type is string, as the type of the RegExp object seems to differ between browsers.
{ "language": "en", "url": "https://stackoverflow.com/questions/7595722", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I delete variable in Template Toolkit? Looking at Template::Manual::VMethods section of the Template Toolkit manual I don't see any method doing this. Also assigning undef to variable doesn't work - variable.defined returns true after the fact. A: Well, googling "delete variable" site:mail.template-toolkit.org/pipermail/templates/ brought the question [Templates] Can I “DELETE some_var”? from Felipe Gasper with two answers from Petr Danihlik. Petr suggests: [% SET foo = 1 %] [% IF foo.defined %] defined1 [% END %] [% PERL %] delete($stash->{foo}); [% END %] [% IF foo.defined %] defined2 [% END %] A: I looked at Catalyst::View:TT code, in order to understand variables context. The following subroutine, which I summarized a little bit does the rendering work: sub render { my ( $self, $c, $template, $args ) = @_; # [...] my $output; # Template rendering will end here # Variables interpolated by TT process() are passed inside an hashref # as copies. my $vars = { ( ref $args eq 'HASH' ? %$args : %{ $c->stash() } ), $self->template_vars( $c ) }; # [...] unless ( $self->template->process( $template, $vars, \$output ) ) { # [ ... ] } # [ ... ] return $output; } TT process() is called with copies of variables in $c->stash, so why do we need to mess with $c->stash to get rid of a local copy? Maybe we don't. Moreover, TT define() VMethod, like other methods, seem to have been built for lists. Scalars are auto-promoted to single element list when a VMethod is called on them: maybe for this reason the IF test returns always true. I did some tests with variables carrying references to DBIx::Class::ResultSet objects, and this seems to work while testing for a variable: [%- resultset_rs = undef %] [%- IF ( resultset_rs ) %] <h3>defined</h3> [%- END %] The first line deletes the variable, and the second does proper test. UPDATE If you can add EVAL_PERL => 1 flag in your Catalyst View, inside config() argumets, __PACKAGE__->config({ # ... EVAL_PERL => 1 }); then you can use [% RAWPERL %] directive in templates, which gives you direct access to the Template::Context object: then you can delete vars and .defined() VMethod does the right thing. [%- RAWPERL %] delete $context->stash->{ 'resultset_rs' }; [%- END %] [%- IF ( resultset_rs.defined ) %] <h3>defined: [% resultset_rs %]<h3> [%- ELSE %] <h3>undefined: [% resultset_rs %]<h3> [%- END %]
{ "language": "en", "url": "https://stackoverflow.com/questions/7595723", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: warning in the PageControl sample code: Using the result of an assignment as a condition without parentheses I'm trying to understand the way UIPageControl works. SO I downloaded this sample code from Apple UIPageControlSampleCode It runs fine but there is a warning (Using the result of an assignment as a condition without parentheses) at the if-statement in the following code: - (id)initWithPageNumber:(int)page { if (self = [super initWithNibName:@"MainView" bundle:nil]) { pageNumber = page; } return self; } Now my question is: why would the developer do something like this? making an assignment inside of an if-statement condition? Is it a mistake? A: An assignment operator (=), except for performing the assignment, also returns the assigned value. This is so you can do stuff like a = b = 1; Which for the compiler is the same as writing a = (b = 1); This means that when doing self = <some init function>; You can check if the init succeeded by putting the assignment in an if statement. If it succeeded it returns a valid pointer, which is not zero which means the condition of the if statement is true. If the init fails, it returns nil which is actually zero, so there is no point in continuing the rest of the initialization. The reason for the warning is that it's easy to accidentally use (=) in an if statement instead of (==): if ( a = 1 ) // Should be a == 1 { // Do important stuff } So the compiler is trying to protect you from this mistake. For this reason I prefer making the condition explicit, in your example: if ((self = [super initWithNibName:@"MainView" bundle:nil]) != nil) A: This warning is because since the sample code have been created by Apple, the version of the compiler and the default compiler options have changed. Especially, this warning -- that tells you that you may mean "==" instead of "=" (because the statement is in a "if" condition and you generally test for equality instead of assignation) -- is quite logic; but the warning wasn't activated by default in previous versions of the compiler and of Xcode, which explains why such code may still be present in old sample codes (nobody's perfect, even Apple developpers ;)). The correct normal usage/convention is then: * *Either to explicitly test for equality in the "if" condition, to be explicit to the compiler so that it is sure of what you mean: if (nil != (self = [super initWithNibName:@"MainView" bundle:nil])) *Or a notation that is also accepted by the compiler is to double the parenthesis to mention that making a condition with simple assignation and not "==" is not a mistake. Thus writing if ((self = [super initWithNibName:@"MainView" bundle:nil])) will work too and remove the warning. I would suggest to adopt the first solution. If you explicitly test that, after the assignation, the result of the assignation (thus the value in self) is not nil, then when you read the code (even if it is not yours), you are sure of what was intended. Even if the code will work if you keep the code this way (and keep the warning), this warning ensures that you didn't mistype '=' instead of '==' in your code, as this may be a common mistake (for newbies but also for experienced programmers that may have typed too fast ;)) so I consider it being a good thing that it is now activated, and a good practice to explicitly make the comparison with nil for the sake of clarity
{ "language": "en", "url": "https://stackoverflow.com/questions/7595727", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Every time i click a button it exits? (action listener) here is my code import java.awt.event.*; import javax.swing.*; import java.awt.*; import java.applet.Applet; class Panell implements ActionListener { JButton button; JButton buttonTwo; JButton buttonThree; JButton buttonFour; JButton buttonFive; JTextArea textArea; public static void main(String[] args) { Panell gui = new Panell (); gui.go(); } void go() { JFrame frame = new JFrame(); JPanel panel = new JPanel(); panel.setBackground(Color.darkGray); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); button = new JButton("Monday"); buttonTwo = new JButton("Tuesday"); buttonThree = new JButton("Wednesday"); buttonFour = new JButton("Thursday"); buttonFive = new JButton("Friday"); textArea = new JTextArea(); button.addActionListener(this); buttonTwo.addActionListener(this); buttonThree.addActionListener(this); buttonFour.addActionListener(this); buttonFive.addActionListener(this); panel.add(button); panel.add(buttonTwo); panel.add(buttonThree); panel.add(buttonFour); panel.add(buttonFive); frame.add(BorderLayout.CENTER, textArea); frame.getContentPane().add(BorderLayout.WEST, panel); frame.setSize(300,300); frame.setVisible(true); } public void actionPerformed(ActionEvent event) { if(event.getSource() == button) { textArea.setText("I've been clicked!"); } else { System.exit(1); } { if(event.getSource() == buttonTwo) { textArea.setText("herro"); } else { System.exit(1); } } } } It keeps on exiting when i press a button? any ideas? and also how can i add more action listeners? A: You should exit (should you?) only if all of the conditions (buttons pressed) failed. Not one of them. You can use something like: if(event.getSource() == button) { textArea.setText("I've been clicked!"); } else if(event.getSource() == buttonTwo) { textArea.setText("herro"); } else if(... ...//any other check } else { System.exit(1); //button not found :( } A: Your application closes due to your "System.exit(1)". The comparison "==" is ok in this case, since you compare object-references. But you have always to be sure if you compare references or objects. So it is more safe for you to change your code: event.getSource() == button to this event.getSource().equals(button) In addition you should check your if's: if the event source is not "button" (Monday), your "else" quits your application. The next comparison (to buttonTwo) will never be reached. If the first comparison fits, the next comparison will fail and again the next "else" (of the second comparison) quits your application. Change your code to something like this: public void actionPerformed(ActionEvent event) { if (event.getSource().equals(button)) { textArea.setText("I've been clicked!"); } else if (event.getSource().equals(buttonTwo)) { textArea.setText("herro"); } else { System.exit(1); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7595732", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: HTTPS and 500 Internal Server Error I Just installed SSL on my server, I can access to all my folder with and without https. Now, I put a php file on a folder. I can access to it without https, but when I want to open a secure connexion with httpS I have : 500 Internal Server Error. Only if the content of this folder is a php project, if not (e.g.: html project) it will open very well with https I have any .htaccess on this folder. How can I fix that? Thanks in advance. A: This sounds like the Virtual Host directive within the httpd-ssl.conf isn't properly configured to handle PHP files. My guess would be a user/permission issue or the lack of a handler directive that would tell Apache how to handle .php files. Regards A: You have to configure you htaccess properly, by that i mean to get it on.
{ "language": "en", "url": "https://stackoverflow.com/questions/7595734", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: memset error in iPad app Hi Im currently building an iPad app. I was using the memset() as below but every tine it runs I get a bad access error? arrayPointer = malloc(sizeof(int) * size); memset(arrayPointer, 0, sizeof(int)* size); //sets all the values in the array to 0 Cheers A: You could use calloc() it basically does the same as malloc() but also sets all bits to 0 in the allocated memory. It is also suited well for array initializations. For your example: arrayPointer = calloc(sizeof(int), size); EDIT: You should consider inspecting the returned pointer. NULL will be returned, when your memory allocation was erroneous.
{ "language": "en", "url": "https://stackoverflow.com/questions/7595736", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ruby years hash generate I want to create hash with years to send it to form How to create {2011 => 2011, 2010 => 2010 ... 1990 => 1990} I tried like @years = [2011..1990].each { |y| @year.push(y => y) } How to write this correct? A: Here is your answer forwards: Hash[(1990..2011).map{|y| [y,y]}] and backwards: Hash[(1990..2011).map{|y| [y,y]}.reverse] A: @Carl Zulauf answer is correct. I was thinking about using zip: 1.9.2 (main):0 > range=1990..2000 => 1990..2000 1.9.2 (main):0 > Hash[range.zip(range)] => {1990=>1990, 1991=>1991, 1992=>1992, 1993=>1993, 1994=>1994, 1995=>1995, 1996=>1996, 1997=>1997, 1998=>1998, 1999=>1999, 2000=>2000}
{ "language": "en", "url": "https://stackoverflow.com/questions/7595742", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Jqgrid rowlist Selection box I have a pager inside of my jqgrid, on the pager i have rowList option, where people can choose if they want to have 10/20 or more rows showed up at one time. The problem is that selection box is not viewed fully. example : http://imageshack.us/photo/my-images/849/unledevx.png/ Are there any way to show it completely? I have tryed to find CSS options for this item, but couldnt find it. A: The CSS setting from the line 58 of the ui.jqgrid.css .ui-jqgrid .ui-pg-selbox { font-size:.8em; line-height:18px; display:block; height:18px; margin: 0em; } is responsible for the font size. One sees another problem with very wide pager input field (ui-pg-input). The reason can be the following: * *no or wrong <!DOCTYPE html ...> at the beginning of HTML file (see here) *add input.ui-pg-input { width: auto; } to fix the pager input field. See this post additionally if you use ASP.NET MVC. *the usage of "compatibility view" of IE (see here inclusive comments). You can solve the problem (if it exists) with adding of <meta http-equiv="X-UA-Compatible" content="IE=edge" /> in the <head> of the page. In any way you have CSS problem. You can use IE developer tools (press F12 to start) to examine the styles.
{ "language": "en", "url": "https://stackoverflow.com/questions/7595743", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Determine if system wide backup is enabled programmatically I was wondering if it possible to determine if the user has enabled the option to backup application data to the cloud from within my android app. I can determine this from the command line, from adb shell by calling: bmgr enabled Does android provide an API to do so from code? A: According to http://developer.android.com/guide/developing/tools/bmgr.html there is no API to do what you ask - only interfaces an app can implement to interact with the BackupManager regarding its data backup/restore.. A: try { int backups_enabled = Settings.Secure.getInt(getApplicationContext().getContentResolver(), "backup_enabled"); Log.i("TAG", "Backups are "+(backups_enabled == 1 ? "enabled" : "disabled")); } catch (Settings.SettingNotFoundException e) { Log.e("TAG", "Setting not found", e); } Note: In order for backups to work, the device also needs to be provisioned (Settings.Global.DEVICE_PROVISIONED).
{ "language": "en", "url": "https://stackoverflow.com/questions/7595748", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Compute pixels geographical coordinates of a callibrated map I have some calibrated maps (using MapCalibrator), for which I need to find out the corresponding OSM style tiles. While I have found some algorithms to calculate the tiles from geographical coordinates (lat/lon), I am stuck at finding out the pixels location (in lat/lon), based on the few calibrated points I have. For Ex I have a image 3758/5751 pixels, and following calibrated points: - x y lon lat - 1897 2224 26.3256 46.2311 - 3303 2708 26.43678 46.20419 - 2297 306 26.3577 46.3365 - 2135 4648 26.3423 46.0967 - 1885 1764 26.3236 46.2561 - 2091 2806 26.3386 46.1995 - 3613 2922 26.4604 46.1921 How can I compute the loat/lon for an arbitrary pixel? PS1. The map is a touristic one, from a small enough region (no idea what projection type uses). PS2. I am coding in Java.. but any hint would be appreciated. What I have tried is some linear transformation between the calibrated points and each pixel, but the tiles come out somehow a little shifted to the NW (by a few Km judging by the map scale), and depending on which 2 calibrated points I use, the offset is bigger or smaller. A: I figured it out. The linear transformation was good enough. The problem was that the geographical coordinates have the origin in the lower left corner, while the pixels in the upper left corner. (I'd messed up the Y coordinates, and after a sign reversal in another point, the result seemed almost good... but somehow shifted :D )
{ "language": "en", "url": "https://stackoverflow.com/questions/7595751", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do implement Event Tracking on a site built with Classic ASP I need to implement Google Analytics Event Tracking on a website built in classic asp. As I am n00b I assumed this would be achievable with a few simple includes. e.g. onClick="_gaq.push(['_trackEvent', '<% =category %>', '<% =action %>']);" I have been skooled. Unfortunately I have no idea what to do next, beyond moving away from ASP (which is not possible). Any suggestions or advice would be gratefully received. A: That code should work, provided you've set category and action; be mindful though that you escape single quotes ('): onClick="_gaq.push(['_trackEvent', '<%=Replace(category, "'", "\'") %>', '<%=Replace(action, "'", "\'") %>']);"
{ "language": "en", "url": "https://stackoverflow.com/questions/7595753", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Converting dynamic values list from XML to XSLT IN XMl multiple dynamic values i need to display in XSLT XML FOrmat: <?xml version="1.0" encoding="ISO-8859-1" ?> - <TreatySeries> - <AnnexTitle Number="A"> <EngAnnexNumber /> <FrAnnexNumber /> <Footer>Volume 150</Footer> <Topofpage /> </AnnexTitle> - <AnnexEntry> - <Footnote> <EngFootNote>United Nations, Treaty Series, vol. 123, I-1654.</EngFootNote> <FrnFootNote>Nations Unies, Recueil des Traités, vol. 123, I-1654.</FrnFootNote> </Footnote> - <AnnexEntryHeader> - <EngAnnexHeader> <TreatyNumber>1654</TreatyNumber> - <Participants> <Participant>Advisory Centre on WTO Law</Participant> <Participant>Afghanistan</Participant> <Participant>Agency for the Safety of Air Navigation in Africa and Madagascar</Participant> <Participant>Finland</Participant> </Participants> IN XML multiple i need to display those dynamic participants in XSLT. in this format <......> kindly in XSLT how to display dynamic multiple values in a specified format No. 1654. <participant1><participant2><participant3><participant4><......>No. 1654. Centre consultatif sur la législation de l'OMC CONVENTION BETWEEN THE KINGDOM OF BELGIUM, THE GRAND DUCHY OF LUXEMBOURG AND THE KINGDOM OF THE NETHERLANDS RELATING TO THE UNIFICATION OF EXCISE DUTIES AND OF FEES FOR THE WARRANTY OF ARTICLES OF PRECIOUS METALS. THE HAGUE, 18 FEBRUARY 1950 [United Nations, Treaty Series, vol. 123, I-1654.] XSLT CODE: <xsl:value-of select="$AnnexEntry/AnnexEntryHeader/EngAnnexHeader/Participants/Participant[1]"/> </w:t> <xsl:if test="count($AnnexEntry/AnnexEntryHeader/EngAnnexHeader/Participants/Participant) = 2"> <xsl:variable name="participant2Eng" select="$AnnexEntry/AnnexEntryHeader/EngAnnexHeader/Participants/Participant[2]"/> <w:t><xsl:value-of select="concat('',$stringAndEng,' ',$participant2Eng)"/></w:t> </xsl:if> but i need to display dynamic values. A: If I understand well, you are trying to display all tags within your output, try something like <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="/Participants"> <xsl:for-each select='Participant'> <xsl:value-of select='.'> </xsl:for-each> </xsl:template> </xsl:stylesheet> I need to display multiple participant values in my output like <participant1><participant2><participant3>.......<participantN> in XSL how to write the code
{ "language": "en", "url": "https://stackoverflow.com/questions/7595756", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Insert XML data SQL Server - Encoding issue I serialize some data before inserting it into the DB. Dim insertString As String = "INSERT INTO GP_SELECTION(SOCIETE, NAME, OBJECT_TYPE, DATA) VALUES ('{0}','{1}',{2},'{3}')" Dim xmlData As String = .XmlFromFilters() insertString = String.Format(insertString, societe, .Name, CInt(.ObjectType), xmlData) Now, when I do the insert, the sql is like INSERT INTO GP_SELECTION(SOCIETE, NAME, OBJECT_TYPE, DATA) VALUES ('01','hello world!!!',0, '<?xml version="1.0" encoding="utf-16"?> <ArrayOfPropertyFilter xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <PropertyFilter> <AndOr>SOME DATA</AndOr> <Value xsi:type="xsd:string" /> </PropertyFilter> </ArrayOfPropertyFilter>') and the SQl server gives me: XML parsing: line 1, character 38, unable to switch the encoding I wonder how to avoid it... Should I convert the Unicode(UTF) insertString ? How? Or maybe I should use a SQL method for conversion? Maybe a solution will be to remove from the serialized string the "encoding="utf-16"" (then the insert works without problems)...? PS. To prevent unusual comments, actually, I don't use stored procedures and I use the direct INSERT code. I recognize this is not the best way to do, but however this is my choice at this time. A: I don't know why this makes a difference :-) but if you cast your XML to NVARCHAR(MAX) and then back to XML it seems to work (at least in my test case): DECLARE @tmp TABLE (ID INT, XmlCol XML) INSERT INTO @tmp VALUES (1, CAST(CAST('<?xml version="1.0" encoding="utf-16"?> <ArrayOfPropertyFilter xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <PropertyFilter> <AndOr>SOME DATA</AndOr> <Value xsi:type="xsd:string" /> </PropertyFilter> </ArrayOfPropertyFilter>' AS NVARCHAR(MAX)) AS XML)) Your bigger problem however is that your approach is open to SQL injection - you should use a parametrized query instead of concatenating together your SQL statement as a string! Use something like: INSERT INTO GP_SELECTION(SOCIETE, NAME, OBJECT_TYPE, DATA) VALUES (@Societe, @Name, @ObjectType, @Data) and then define SQL parameters for your query and fill those with values. Much safer!!
{ "language": "en", "url": "https://stackoverflow.com/questions/7595757", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is it possible to customize invisible's characters in xcode4? I'm using xcode 4 and I would like to see special characters (spaces, tabs, etc.) all time. I could toggle showing them by "Editor"->"Show Invisibles". But the way how it's showing in xcode doesn't satisfy me: Is it possible to customize this characters? Thanks. A: i do it by customize the key binding set a key shortcut for the show invisible character in the xcode->preferences->key binding enter invisibles in search box "invisibles" option 'show invisible' appear set a shortcut for it of your choice then use it for on/off the show invisible characters http://i1144.photobucket.com/albums/o483/saqibzaidi/ABC.jpg
{ "language": "en", "url": "https://stackoverflow.com/questions/7595759", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: XAML UserControl - Set Background based on Trigger I have a UserControl that contains an Expander : <UserControl x:Class="Client.DevicesExpander" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="300" x:Name="devicesExpander" > <Expander Margin="1" Name="expander" FontSize="11" BorderThickness="1" BorderBrush="DarkRed" Foreground="Black" Header="{Binding ElementName=devicesExpander, Path=Header}" FontWeight="Bold" MouseDoubleClick="Expander_MouseDoubleClick" Expanded="Expander_Expanded" IsExpanded="{Binding ElementName=devicesExpander, Path=IsExpanded}" Background="{Binding ElementName=devicesExpander, Path=Background}"> <StackPanel Name="_devicesPanel"> <ListBox BorderThickness="0,1,0,0" Name="_devicesList" FontWeight="Normal" MouseDoubleClick="DevicesList_MouseDoubleClick" Background="{Binding ElementName=devicesExpander, Path=Background}" /> </StackPanel> <Expander.Style> <Style TargetType="{x:Type Expander}"> <Style.Triggers> <DataTrigger Binding="{Binding ElementName=devicesExpander, Path=IsExpanded}" Value="True"> <Setter Property="Background" Value="White" /> </DataTrigger> </Style.Triggers> </Style> </Expander.Style> </Expander> </UserControl> Ans basically all I'd like to do is change the Expander and StackPanel's Background color based on the IsExpanded of the UserControl (or Expander). I've added three Dependancy Properties to the control : public static readonly DependencyProperty HeaderProperty = DependencyProperty.Register("Header", typeof(string), typeof(DevicesExpander)); public static readonly DependencyProperty IsExpandedProperty = DependencyProperty.Register("IsExpanded", typeof(bool), typeof(DevicesExpander)); public static readonly DependencyProperty BackgroundProperty = DependencyProperty.Register("Background", typeof(System.Windows.Media.Brush), typeof(DevicesExpander)); But my code does not work. The IsExpanded property from the usercontrol does work as the property changes accordingly (when the expander expands) when checked from within the window where the usercontrol is placed. How can I change the background color of the Expander based on the UserControl.IsExpanded property ? Thanks ! EDIT: I have in the meanwhile done the following: <UserControl.Resources> <Style TargetType="{x:Type UserControl}"> <Style.Triggers> <DataTrigger Binding="{Binding ElementName=devicesExpander, Path=IsExpanded}" Value="True"> <Setter Property="Background" Value="White" /> </DataTrigger> </Style.Triggers> </Style> </UserControl.Resources> <Expander Margin="1" Name="expander" FontSize="11" BorderThickness="1" BorderBrush="DarkRed" Foreground="Black" Header="{Binding ElementName=devicesExpander, Path=Header}" FontWeight="Bold" MouseDoubleClick="Expander_MouseDoubleClick" Expanded="Expander_Expanded" IsExpanded="{Binding ElementName=devicesExpander, Path=IsExpanded}" Background="Transparent"> <StackPanel Name="_devicesPanel"> <ListBox BorderThickness="0,1,0,0" Name="_devicesList" FontWeight="Normal" MouseDoubleClick="DevicesList_MouseDoubleClick" Background="Transparent" /> </StackPanel> </Expander> and removed the BackgroundProperty dependancy property. I actually thought this could work, but alas ... A: I have managed to solve my problem. Herewith the solution (showing only the essential code) ... My Dependancy Property is created as follows: public static readonly DependencyProperty IsExpandedProperty = DependencyProperty.Register("IsExpanded", typeof(bool), typeof(DevicesExpander)); public bool IsExpanded { get { return (bool)GetValue(IsExpandedProperty); } set { SetValue(IsExpandedProperty, value); } } and my XAML is : <UserControl x:Class="TestApp.DevicesExpander" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Name="devicesExpander"> <Expander> <Expander.Style> <Style TargetType="Expander"> <Style.Triggers> <DataTrigger Binding="{Binding ElementName=devicesExpander, Path=IsExpanded}" Value="True"> <Setter Property="Background" Value="Black" /> </DataTrigger> <DataTrigger Binding="{Binding ElementName=devicesExpander, Path=IsExpanded}" Value="False"> <Setter Property="Background" Value="Red" /> </DataTrigger> </Style.Triggers> </Style> </Expander.Style> </Expander> </UserControl> The solution in the end was to remove the Backgroud property from the element and specify a DataTrigger for IsExpanded=True and IsExpanded=False. It thus seems like the Background property when specified in the element properties overrides anything that the triggers tried to set. Hope this helps someone ! A: Herewith another solution to the same problem, this time using a IValueConverter ... My XAML: <UserControl.Resources> <local:BackgroundConverter x:Key="backgroundConvertor" /> </UserControl.Resources> <Expander> <Expander.Style> <Style TargetType="Expander"> <Setter Property="Background" Value="{Binding ElementName=devicesEntry, Path=IsExpanded, Converter={StaticResource backgroundConvertor}}" /> </Style> </Expander.Style> </Expander> and my code for the value convertor : public class BackgroundConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { return (bool)value ? "White" : "Transparent"; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { string color = value as string; if (color == "White") return true; return false; } } I think though that I prefer the XAML only solution, although the IValueConverter option does make for slightly better reading of the XAML ... (The DependancyProperty is still created exactly the same way)
{ "language": "en", "url": "https://stackoverflow.com/questions/7595762", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Javascript delegate I have the following the code function createDelegate(object, method) { var shim = function() { method.apply(object, arguments); } return shim; } this.test = 3; var pAction = {to: this.test} this.tmp = createDelegate(this, function() { print("in: " + pAction.to); return pAction.to; }); print("out: " + this.tmp()); But for some reason I get the following result in: 3 out: undefined Anyone knows the reason for this? A: When you create the delegated function you must return the result of the old function: function createDelegate(object, method) { var shim = function() { return method.apply(object, arguments); } return shim; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7595768", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: is it possible in java-lucene to map multifield values? i have a single document in lucene index with multiple fields and some of the fields are multivalued for example Document{ field1: field2: field3: .... field9:} and fields are like field1:some string value field2:some int value . . . field8:(string values that are space separated and each is a token )//uid for some items field9:(value or items whose uid is in field8 and both field8 and field9 are one to one map) With this i am able to search and index a multivalued field in a flat document structure now i have an other field say field10: in which i have multiple values against a single uid in field8 then how can i index and search this new field in this structure using lucene i want to index and then map the field10 values against field8, for example field8: { uid1 | uid2 | uid3} field10:{id1,id2,id3 | id1,id7 | id1 } help required regards A: Here's what I think you're asking. Suppose you have a document like: field8: { 1 | 2 | 3 } field10: { foo,bar | baz,foo | bar,baz } You want to have the query +field8:1 +field10:foo return this document, but +field8:3 +field10:foo shouldn't return the document. This is a relational data model, and it's not something Lucene tries to be good at. Your best bet is to use a relational database. If you want to stick with Lucene, you should split each one of these fields into its own document. So one doc would be field8:1, field10: foo,bar etc. Alternatively you could have your own tokenizer which used payloads or term positions to handle this. I don't know that it would be particularly easy or fast. There are many questions on this site regarding your problem, e.g. Storing relational data in a Lucene.NET index
{ "language": "en", "url": "https://stackoverflow.com/questions/7595769", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SQL Server 2005 Auditing Background I have a production SQL Server 2005 server to which 4 different applications connect and make changes. There are no foreign keys and in some cases no primary keys. Unfortunately throwing the whole thing out and starting from scratch is not an option. So my solution is to start migrating each of the applications to a service layer approach so that there is only one application directly connecting to the database. However there are problems that need to be fixed before that service layer is written and all the applications are migrated over. So rather than make changes and hope they don't break any one of the 4 badly written applications (with no way of quickly testing all functionality) my solution is to start auditing the database Problem How do I audit what stored procedures, tables, columns, views are being accessed/updated/called by each user on SQL Server 2005. I can find out which tables are being updated but I have no idea which columns and by what users. I also don't know if certain tables are being accessed only through stored procedures/views. I know that SQL Server 2008 has better auditing features but if I could do this without spending money that would be great. That said if the best solution is to upgrade or buy software that's also an option. A: Check out SQL Server 2008's CDC feature. You can't use this directly in 2005 but you can write a trigger for each table to log all data changes to a new audit table. i.e. you'd have an audit table for each table in your db, with all the same columns plus some additional columns saying what the operation was and when it occurred. If the nature of your applications means you can get user information and/or application information from CURRENT_USER and APP_NAME() you could include that information in the audit table too. And check out this answer for more goodness.
{ "language": "en", "url": "https://stackoverflow.com/questions/7595781", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: IIS Rewrite Rule how to check requesturl + .php file is exists or not in rule i want to check that file with requestedurl + .php is exists or not. in apache i can do this with RewriteCond %{REQUEST_FILENAME}.php -f so that it can rewrite my request test.com/login to test.com/login.php i want to do same with iis rewrite rule. i have tried with following. <rewrite> <rules> <rule name="Imported Rule 1" stopProcessing="true"> <match url="^(.*)$" /> <conditions> <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" /> <add input="{REQUEST_FILENAME}\.php" matchType="IsFile" /> </conditions> <action type="Rewrite" url="{R:1}.php" /> </rule> <rule name="Imported Rule 2"> <match url="^(.*)$" /> <conditions> <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" /> <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" /> </conditions> <action type="Rewrite" url="allpages.php" /> </rule> </rules> </rewrite> but it doesnt works. thanks in advance for help A: Change {REQUEST_FILENAME}\.php to {REQUEST_FILENAME}.php in first rule. Further there is no need to check if requested URL exists as directory. To rewrite 'test.com/login' to 'test.com/login.php' only if login.php exits, use: <rule name="Rewrite to PHP"> <match url="^(.*)$" /> <conditions> <add input="{REQUEST_FILENAME}.php" matchType="IsFile" /> </conditions> <action type="Rewrite" url="{R:0}.php" /> </rule> Tested
{ "language": "en", "url": "https://stackoverflow.com/questions/7595782", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Timeout only when connecting through Management console I'm using SQL server 2008r2 on a windows 2003 server and connecting to it from a vista machine. The database itself is part of an application that uses ODBC to connect and that connects perfectly 100% of the time. But as I'm making some changes to the application and database I'm working through the management console. The first time I try and connect to the db in the morning it times out. I have a work around for it that involves remote desktoping to the server and connecting to the db using the mamangement console on the same server. Once I have connected locally I can close the remote session and then I'll be able to connect to the server from the management console on my pc. This connection will stay open all day but if I close the management console for a while (10+ mins, I havent fully tested how long) it will timeout again. This happens from other client pcs as well so I'm thinking that I need to change something on the server... does anyone have any pointers as to what settings could cause this login timeout? and what I can do to fix it as its becoming a serious annoyance! A: It sounds like you need to enable TCP/IP protocol. You can do this via SSCM (SQL Server Configuration Manager). A: I think I have got it figured out now. The solution that seems to work is linked to TCP/IP protocol, as the above poster mentions. I needed to go into the protocol and update the ports used from dynamic to fixed and put them on 1433 (why this isn't default I dont know, and I presume theres good reason for it!) Answer found on the post below https://serverfault.com/questions/179898/sql-server-timeout-on-first-attempt
{ "language": "en", "url": "https://stackoverflow.com/questions/7595787", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Client-side technology for big web application I get order to develop web application (as SAAS). Something like ZohoCRM. It's my first so complicated app. Key requirements are: * *One page app (no page refresh) *Easy features adding *Modularity *UPD: Real time data exchange: users-server-users (sockets or long-polling) So I'm struggle to cope with Javascript (jQuery) and Flash (Flex). Thoughts about Javascript: Pros: pluginless, supporting by tablets and smartphones browsers, lightweight (loading faster). Cons: a lot of job on cross-browsing issues, viewable sources. Thoughts about Flash: Pros: no need to fudge with cross-browsing, rich components customization. Cons: require plugin, not clear situation with Apple products. So which way I have to go? Thanks in advance. UPD#1: It will be a web based application for business. First part is basic CRM functionality. Later step-by-step it'll get ERP features. Main data operations will be with tables and trees with filtering. Must work just in browsers so far. But I'm sure that later will appear requirements for tablets and smartphones support. P.S. After thinking and googling I more and more inclining to Javascript stack (jQuery, backbone and underscore). A: The Pro's you mention for JavaScript is the reason you should use JavaScript. Mobile is getting more and more important on the web. Flash is slow, (compared to JavaScript) and there's enough functionality on JavaScript. Using jQuery for example takes care of cross-browser issues.
{ "language": "en", "url": "https://stackoverflow.com/questions/7595790", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: boost::interprocess::message_queue permission denied So I have the following code with boost 1.47: try { m_messageQueue = boost::shared_ptr<boost::interprocess::message_queue>( new boost::interprocess::message_queue ( boost::interprocess::open_or_create ,name.c_str() //name ,numElements //max message number ,sizeof(Message) //max message size )); } catch(boost::interprocess::interprocess_exception &e) { cerr << e.what(); } where name="test_queue", numElements=100, and sizeof(Message)=256. The output is: Permission denied If I run as user root, it will pass. I can't figure out where it is trying to write to where it would have a permission error. Looking at the boost code, shouldn't it just be in /tmp/boost_interprocess which any user would have access to create and write to? Also, I noticed https://svn.boost.org/trac/boost/ticket/4250, but this should be fixed now. Any help would be appreciated. A: I am on Centos 5.5. For me it was the need to set umask for the user running the queue to 022. After I set this in .bashrc all works as intended.
{ "language": "en", "url": "https://stackoverflow.com/questions/7595792", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }