text
stringlengths
8
267k
meta
dict
Q: asp:DataPager onclick event I am working with the .Net List view along with a data pager to enable pagination for a list view. I am able to set the pagination working perfectly for the list view but I wish to have a method being called when ever the user clicks on any of the page numbers in the data pager. I want to perform some operation whenever the page number is called. I guess there is no onclick event, so is there any other way by which this is possible. Thanks A: you can set it as imagebutton or linkbutton. I have piece of code.. you just need to implement it. you can set link and click event. foreach (DataPagerFieldItem dpfItem in dtpPaging.Controls) { foreach (Control cPagerControls in dpfItem.Controls) { if (cPagerControls is ImageButton) { ImageButton imgNavigation = cPagerControls as ImageButton; imgNavigation.PostBackUrl = CommonLogic.GetFormattedURL(strPageUrl); imgNavigation.Click += new ImageClickEventHandler(imgNavigation_Click); } if (cPagerControls is LinkButton) { LinkButton lnkNumbers = cPagerControls as LinkButton; lnkNumbers.PostBackUrl = CommonLogic.GetFormattedURL(strPageUrl); lnkNumbers.Click += new EventHandler(lnkNumbers_Click); } } } A: You can bind a handler to the OnPagePropertiesChanging Event of the List View. A PagePropertiesChangingEventArgs object is passed to the handler as argument which contains MaximumRows and StartRowIndex properties. You can use these to calculate the current page number. It is very easy and requires no code-behind event binding as the solution proposed by sikender.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551650", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: WSDL WebService I need comunicating using java with a WebService that uses the WSDL technology. I tried some libraries but with no success, thus, I decided to do it manually. My plan is getting a .xml which uses the comunication (filtering with fiddler for example) and copy it manually building a string. So the .xml will be ok. Do I need to take care of anything else? Do I have to do any more? Http request, response? I wouldn't like to create all the structure for the xml and after that, find that I can't continue the comunication. Thanks A: Java comes with a complete API for XML Web Services, this is JAX-WS. (lot of documentation available with a simple serach with google) it allows developers to build a working client with very little effort starting from a WSDL file (seems your case) I really discourage you to build the client by yourself. You should care about SOAP message building, message sending, response parsing and so on.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551651", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why i got the Error like Package file was not sign correctly? I have Uploade the App on android market few days ago. Now i have make another version of that application. I have Sign that Application with the same keystore and with the same package and Application name. The Only things i have change is the version code of that application. After that, On Android market i got the option of the upadte of the application. But if i am going to update that file, the error is generate like the Package file was not sign correctly. . . So where is the problem ??? Please let me know about it. . . Please I realy need help. . . A: Have you changed the version name also. make sure you had done that and again try to sign the app using the same keystore and password. the problem will get solved. also make sure you have the same base package name and before. A: It sounds like you uploaded a debug build, rather than a release build. A: I am totally agree with @Sean Owen answer that you may have tried to upload the debug build. Still, let me provide you additional information if you forgot to prepare release build and yes dont forget to sign this APK with the same keystore that you have signed with previously.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551654", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to join 2 images in google app engine in Java I saw python codes to join two images in google app engine with 'composite'. But I need java codes to use 'composite' to merge two images. Showing an actual code would be very helpful. A: This is my first reply, so hopefully I won't be hammered too badly. Since nobody else answered this, and I spent a bit of time on this today, I thought I'd provide some code. The main reason this took way too much time for me, is that for whatever reason, the devserver simulation of the Images API doesn't work right and the composite images are not correct when using the devserver. I was spending forever fiddling with the values in the devserver, until I just uploaded the test code to AppEngine, and it worked as expected. Argg! Anyway, the code below assumes you have two 300x300 images, one in aImage and other in bImage, that you want to paste side-by-side into a 600x300 new canvas, which is created in the resulting Image newImage: List<Composite> listComposites=new ArrayList<Composite>(); Composite aPaste = ImagesServiceFactory.makeComposite(aImage, 0, 0, 1f, Composite.Anchor.TOP_LEFT); listComposites.add( aPaste ); Composite bPaste = ImagesServiceFactory.makeComposite(bImage, 300, 0, 1f, Composite.Anchor.TOP_LEFT); listComposites.add( bPaste ); Image newImage = imagesService.composite(listComposites, 600, 300, 0xff333333L, ImagesService.OutputEncoding.JPEG); The first makeComposite places the first image at location 0,0 relative to TOP_LEFT. The second makeComposite places the second image at 300,0. Both are pasted with opacity 1.0. Hope this helps. This code saves the result in JPEG format. And, again, for me, this DOES NOT WORK in the devserver, but works as expected on the real App Engine platform.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551656", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Grails Calendar plugin throws stack / recursion error Calendar plugin version :CURRENT RELEASE 1.2.1 I followed steps as mentioned in the grails plugin documentation, I get the following error in all types of browser Chrome 14.0835: Uncaught RangeError: Maximum Callstack size exceeded. Firefox 6.02: Too much recursion calendar.js line 1851 IE 9: Out of stack space calendar.js line 1850 A: The offending jscalendar code is this: Date.prototype.__msh_oldSetFullYear = Date.prototype.setFullYear; Date.prototype.setFullYear = function(y) { var d = new Date(this); d.__msh_oldSetFullYear(y); if (d.getMonth() != this.getMonth()) this.setDate(28); this.__msh_oldSetFullYear(y); }; Which redefines Date.setFullYear(). Have a look at comments #124 and #125 on this "old jscalendar" page. Comment #124 (by Chris Lively) Suggests updating calendar.js (near the bottom, ~line 1850). For those getting the recursion error. You just need to comment a few lines. See below. //Date.prototype.msh_oldSetFullYear = Date.prototype.setFullYear; Date.prototype.setFullYear = function(y) { var d = new Date(this); //d.msh_oldSetFullYear(y); if (d.getMonth() != this.getMonth()) this.setDate(28); //this._msholdSetFullYear(y); }; Comment #125 (reply by larisa) The problem with recursion occurs due to multiple includes of calendar JavaScript on a page. As a result Date patch redefines setFullYear function twice and causes infinite loop when it gets executed. We fixed it by making sure that function is redefined only once: if(Date.prototype.msh_oldSetFullYear == null) { Date.prototype.msh_oldSetFullYear = Date.prototype.setFullYear; } Both of these suggest updates to calendar.js, which isn't ideal since it's delivered with the plugin. Two suggestions: * *Make sure you're not importing the calendar resources twice. Do you have a <calendar:resources/> in your main layout and your view GSP? If so, remove one of them. *If that doesn't work, perhaps use a different plugin. The calendar plugin looks like it hasn't been updated in a while (it's using an older version of jscalendar). If you're feeling ambitious, you could go update the plugin yourself! A: This works for me: if (Date.prototype.__msh_oldSetFullYear == null) { Date.prototype.__msh_oldSetFullYear = Date.prototype.setFullYear; } Date.prototype.setFullYear = function(y) { var d = new Date(this); Date.prototype.__msh_oldSetFullYear.apply(d, arguments); if (d.getMonth() != this.getMonth()) this.setDate(28); Date.prototype.__msh_oldSetFullYear.apply(this, arguments); }; A: The way I resolved this issue is 1) Downloaded the source of the plugin 2) Created a plugin with the same name locally. 3) Copied the original source files to the local plugin I created 4) Changed the javascript file as suggested above 5) Compile and package the plugin 6) Removed the old plugin in my main project 7) Installed the newly created plugin from the zip file created from step 5. It worked like a charm. Thanks Rob Hruska for pointing me where to comment in the javascript file A: I was facing same issue, I had placed <calendar:resources/> in my main jsp as well as in the template which was rendered in the jsp. Removing one of them solved the issue.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551662", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to find the date of the first commit of files in git Would there be a way to see the date of the first commit of a list of files, such that I could order them by that list? For context, I'm playing around with Node.JS, using it to create a simple blog where the "database" is actually a git repository. What I thought I'd try is to list out all the files in a particular directory, and then call something like this on each: git log --format="format:%ci" --reverse [my file here] This would output something like this: 2010-09-01 11:42:56 -0700 2010-09-22 12:17:19 -0700 2010-09-22 13:18:11 -0700 2011-03-05 00:11:19 -0800 2011-08-26 08:50:02 -0700 2011-08-26 08:51:50 -0700 Then, grab the first result and use that for ordering. Is there a better way? A: I think you can get what you want using the --diff-filter option to git log, selecting only files that have been added. For example, you could parse the output of: git log --format="format:%ci" --name-only --diff-filter=A See the documentation for git log for more on the different states understood by --diff-filter.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551664", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: check element has a class starting with string using jquery I am getting the last element from a form which has a value like this: var lastOne =$(':text[name^=distanceSlab][value!=""]').last(); now I want to find the element which has a class that begins with the string "limit". I have tried something like: if(lastOne.is("class^='limit'")){ console.log('BEGINNING WITH LIMIT') } but it didn't work. How do I do this? A: if(lastOne.is("[class^='limit']")){ console.log('BEGINNING WITH LIMIT'); } You forgot to put [] around the selector. A: if(lastOne.attr('class').match(/^limit.+/)) ...
{ "language": "en", "url": "https://stackoverflow.com/questions/7551665", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: why the result is not in my expectation? #include <iostream> using namespace std; typedef void (*pFun)(void); class A { private: int a; int b; virtual void outPrint() { cout << b << endl; } public: A() { a = 3; b = 4; } }; int main() { A obj; cout << *((int*)(&obj)+1) << endl; pFun pFunc; pFunc = (pFun)*((int*)*(int*)(&obj)); pFunc(); system("pause"); return 0; } when i call pFunc(), the result i think should be 4,but actually it's a random number. and i debug the program, finding that pFunc points to the outPrint function. i don't know why,plz help me A: Seems that you assume that the address of the object obj can be interpreted as an address of a function of the type you defined. It cannot. I'm not entirely sure why would you have such an assumption to begin with. You're probably assuming things about the internal implementation of the dynamic dispatch. But do take a note: A::outPrint that you expect to be called, accepts 1 parameter (this, that is not explicitly defined), whereas your typedef assumes no parameters. So even if the address casting works fine and the address you get is that of the member function (which is a stretch to begin with), your call is incorrect. If you change the typedef to: typedef void (*pFun)(A*); and the call to pFunc(&obj); That might work. Yet, the behavior per spec is undefined, to the best of my understanding. A: Adding 1 to a int* only has defined behaviour in the case of traversing an int[]. Every other cases, there are no definition of what should happen. It is implementation defined since the final memory position of the members are not defined. Try solving the problem in a way that does not exploit compiler details but the standard. Also, in the case you get the function address following this way, calling it as a static method (without an object), only can provide you several headaches. A: I'm not quite sure what exactly it is you're trying to do. It looks like you're trying to directly manipulate the pointer in order to get the address of a method, but that's a very bad idea for about 6 different reasons. It is possible to get a pointer to a class method, but it's not bound to the object so you need to be careful. I'd suggest you have a fundamental misunderstanding of pointers and C++ classes, which must be corrected before you can manage any of this safely. Most people don't need function pointers, and almost nobody needs method pointers. A: You are relying on various "undefined behavior", hence the result depends on what compiler and platform you are running on. (int*)&obj+1 (better if you write ((int*)&obj)+1 to avoid misinterpretations) is not necessarily the b member. There may be padding between members, and &obj may be not the same as &(obj.a) being obj a polymorphic object (so may be it has a vtable pointer in top of it). If this is the case, *(int*)&obj is the vtable address treated as an int. Converting it to an int* (supposing int and pointer having same sizes) it points to the first vtable entry (most likely the address of outPrint), hence the "random number".
{ "language": "en", "url": "https://stackoverflow.com/questions/7551667", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: libgdx SpriteBatch render to texture Is it possible to render to texture using SpriteBatch in libGdx (Java engine for Android/Desktop)? If so, how do it? Basically I want to render everything to 320 x 240 region of 512 x 256 texture and than scale region to fit screen (in landscape mode). This way I want to eliminate artifacts which happen when I scale alpha blended textures independently. If there is any other way to remove such artifacts, please point them out :) And is there any online documentation for libGdx? A: This snippet was given to me on the LibGDX forum and it works flawlessly. private float m_fboScaler = 1.5f; private boolean m_fboEnabled = true; private FrameBuffer m_fbo = null; private TextureRegion m_fboRegion = null; public void render(SpriteBatch spriteBatch) { int width = Gdx.graphics.getWidth(); int height = Gdx.graphics.getHeight(); if(m_fboEnabled) // enable or disable the supersampling { if(m_fbo == null) { // m_fboScaler increase or decrease the antialiasing quality m_fbo = new FrameBuffer(Format.RGB565, (int)(width * m_fboScaler), (int)(height * m_fboScaler), false); m_fboRegion = new TextureRegion(m_fbo.getColorBufferTexture()); m_fboRegion.flip(false, true); } m_fbo.begin(); } // this is the main render function my_render_impl(); if(m_fbo != null) { m_fbo.end(); spriteBatch.begin(); spriteBatch.draw(m_fboRegion, 0, 0, width, height); spriteBatch.end(); } } A: For the moment, I would recommend you to use Pixmaps. You see, there are not many functions written for them, but apparently you can write a Pixmap (with alpha channel) to another one (pm1.drawPixmap(pm2, srcx, srcy, w, h, ...)), providing that you don't want to scale it (you may scale the composition later, but the proportion the pictures used in the composition won't be resized... unless you write a resizing function). If you want to do more complex stuff (like writing a string using a BitmapFont into a Texture for later manipulation, or writing it into a Pixmap and then uploading it to the video memory), then... then tell me if you succeed (as I want to go into that direction to optimize). I think that the best would be to add the needed functions to libgdx... Anyway, don't take anything I wrote here as an undeniable truth- if I get further, I will update. The documentation I found is somewhat limited -I'm sure you've gone through it already. There's information in the badlogic's blog and in the googlecode project page -and also there's a relatively good book written by Mario, "Beginning Android Games". Also, there are a few (very basic) videos. And don't forget that you can consult source and the beautiful examples... Also, you can always ask in the forum: http://badlogicgames.com/forum/ UPDATE: Your answer using the FrameBuffer and TextureRegion is undeniably much better. I leave this one just because it mentions the documentation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551669", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "37" }
Q: Is it possible to protect our documents from getting copied using HTML 5 or general Web technologies? I want to develop a Web App for Mobile users, which will provide users with documents for users to view. I want to ensure that the documents once downloaded to temp folder needs to be deleted once user closes the window. Is there any option for this in HTML 5? Is there any provision to disable copy/paste options for when browser shows the specific pdf documents or MS office documents? UPDATE1: Two things I need to know if possible: * *Ability to delete files through an API *Disable copy, paste option through Browser for Documents. (might seem like a fantasy) A: I don't believe you can delete user cache/temp folder via web, but you can protect your pdf and doc files with password and disable copy/paste and print function. A: you can make your document flash .swf then use google swiify to convert it to html5 !
{ "language": "en", "url": "https://stackoverflow.com/questions/7551675", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jQuery: How to focus on input text field such that the cursor is placed at the end of the text? Consider the following example: (demo here) HTML: <input type="text" /> <div>Click here to set focus</div> JS: $(function() { $("input").val("Hello"); $("div").click(function() { $("input").focus(); }); }); When the div is clicked, the cursor positioned at the beginning of the text: |Hello. How could I set the cursor at the end of the text: Hello| ? A: Use this plugin: http://plugins.jquery.com/project/PutCursorAtEnd A: I think you are looking for selectionStart.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551679", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Trying to force some kind of IEnumerable.Each-method I have the following snipped inside a Razor-file: <td>@item.Mottakere.All(q => { @q.Epost <br /> })</td> Where @item is a object from a foreach ... Model.ToList() and @item.Mottaker is a List inside this object. I know this doesn't work, mostly because All expects a bool, and also because I can't inline razor in a lambda this way... But is there any way I could force this kind of functionality? Or should I just do a normal nested foreach ? A: I invite you to checkout Templated Razor Delegates. A: All doesn't expect bool, but it returns true when the given lambda is true for every item in the list - for example Are all apples in the list red? In your case, when you want to output the elements in Mottakere, you'll have to use another foreach or use some helper method. For example see this.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551684", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Proximity 'Hit tests' from multiple arrays (Action Script 3) I know this should be possible and Im pretty confident with my code. I have two arrays that are dynamically filled from another function. When two sprites from each array interact they should trigger a function, but at the moment they just glide right past each other. public function mixGender ():void { for (var gi:int = 0; gi < firstSpriteArray.length; gi++) { var sprite1 = firstSpriteArray[gi]; for (var pi:uint = 0; pi < secondSpriteArray.length; pi++) { var sprite2:pinkSprite = secondSpriteArray[pi]; var dist = getDistance(sprite1.x,sprite1.y,sprite2.x,sprite2.y); if (dist < 28) { /*and if they are within touching range calls a function.*/ function (); } } } } There must be something obvious Im missing. Any hints? A: Give this a whirl: public function mixGender():void { // Method constants var radius:int = 28; // Collisions for each(var a:Sprite in firstSpriteArray) { for each(var b:Sprite in secondSpriteArray) { // Measure distance var d:Number = Point.distance( new Point(a.x, a.y), new Point(b.x, b.y) ); if(d < radius) { trace('collision'); } } } } Bit of testing with this code on the timeline: var firstSpriteArray:Array = [new Sprite()]; var secondSpriteArray:Array = [new Sprite()]; mixGender(); // collision firstSpriteArray[0].x = 29; mixGender(); // nothing
{ "language": "en", "url": "https://stackoverflow.com/questions/7551685", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Jquery form validation plugin - temporarily disable and then enable I'm using Jquery form validation plugin. http://docs.jquery.com/Plugins/validation All I want is to temporarily disable the form validation while am performing some other operation and after that re-enable the validation on that form. I used unbind..but then am not able to reenable the validation on that form. I have 25-30 forms.. so enabling each form again using the rules not possible..Any Suggestion??
{ "language": "en", "url": "https://stackoverflow.com/questions/7551689", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: XNA: NullReferenceException when playing SoundEffect from another class I'm both a C# and XNA noob, and I'm a bit stuck. In my Game1 class, I have added a SoundEffect object. From within this class, I can then play the sound by using [objectname].Play();. E.g. public SoundEffect newSound; newSound.Play(); However, I have another class which represents a sprite. If I try to ply the sound from within that class, I get a nullreference exception error. For example (within my sprite class): Game1 newGame = new Game1(); newGame.newSound.Play(); I know this is a common error. I know thatit has something to do with initializing the object instance. My problem is that, while I have researched this extensively, and have found other solutions to this error, I don't understand why I'm receiving it. That's why I haven't pasted my full code. What I'm wondering is, can anyone point me in the direction of a tutorial or article that can explain to me how this should work? I'd rather not just make this error disappear without fully understanding what the problem is. Any help would be most appreciated. Thanks A: The problem is, your sprite needs access to the instance of Game1 that is running the game loop, and that has initialised the SoundEffect. new Game1() is giving you a different instance, which isn't in the right state to do anything. What would normally be done here is to have a constructor argument or a settable property on your Sprite class. I assume your Game1 class create your sprite at some point: Sprite s = new Sprite(); And instead, you want to be able to pass the instance of Game1 to it: Sprite s = new Sprite(this); And you'll need to modify your sprite class so that it a) takes this new argument in its constructor, and b) stores this value into a field, so that you can access it later. I'd be able to flesh this out a bit more if I could see your whole Sprite class, but I can appreciate it may be a little large to post here. A: This it's going to be like assuming a lot of things.... You have Game1 class, that it's the main class that is running in the Update/Draw infinite loop to keep the game... Then you have another class that let's call it Enemy, and in in the Update method of Game1 you make a call like Enemy.PlaySound() In Enemy::PlaySound you want to play the sound that you initialized in the LoadContent of Game1 something like public void PlaySound() { Game1 newGame; //like assuming that with this you are pointing to the instance of Game1 that it's running and since it's not the instance of that class and it's not even initialized there is the NullReferenceException.....(I think) newGame.NewSound.Play(); //Assuming againt that we have a property to access the NewSound } A lot of long shots here.....but it's kinda of unclear the question.... EDIT - After First Comment That won't work either It will work like this public class Enemy { .... public void PlaySound(Game1 newGame) { newGame.NewSound.Play(); } .... } But passing the Game1 as a parameter to the Enemy Methods is not a good practice...IMO There are a lot of good books, tutorials and frameworks that can guide you.... * *http://www.flatredball.com/ *http://nuclexframework.codeplex.com/ *http://create.msdn.com/en-US/education/gamedevelopment
{ "language": "en", "url": "https://stackoverflow.com/questions/7551690", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to show more than one textview title in a list view? I have a list view and i'm trying to show more than one textview in a listview? How to achieve it? any example code ? thanks in advance... A: You need to create a custom list adapter. There are many examples online. Google for "android custom list" and u will find enough examples. The idea is that you create a row.xml that reaembles what a single row should look like. Could be 2 textviews could be 10. In the adapter you tell the rows in the listview to use row.xml instead of standard rows. For the custom adapter you will probably want to extend arrayadapter. I am using my phone so i can't link examples. Goodluck on your search. Its actually not so hard when u understand the proces.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551691", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Working with directories - Python I have the following piece of python code. The code is supposed to get a source, a temporary and an final output path from the user and extract some header files. When the full paths are specified from the terminal, the program works perfectly but when the terminal command is as so : Python Get-iOS-Private-SDKs.py -p /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.3.sdk/System/Library/PrivateFrameworks/ -t ./tmp -f ./Test.txt, then the header files, instead of getting generated in a tmp folder in the current directory, they go into a recursive loop. Each folder in-turn has a tmp folder and it goes on and on. Can anyone tell me why ? import optparse,os,subprocess from glob import glob parser = optparse.OptionParser() parser.add_option("-p","--path", help = "Source path", dest = "Input_Path", metavar = "PATH") parser.add_option("-t","--temp",help = "Temporary Folder Path", dest = "Temp_Path", metavar = "PATH") parser.add_option("-f","--file",help = "Destination Path",dest ="Output_Path",metavar = "PATH") (opts,args) =parser.parse_args() if (opts.Input_Path is None or opts.Output_Path is None or opts.Temp_Path is None): print "Error: Please specify the necessary paths" else: os.makedirs(opts.Temp_Path + "Private_SDK") dest = opts.Temp_Path + "Private_SDK/" for root,subFolders,files in os.walk(opts.Input_Path): for file in files: os.makedirs(dest + file) os.chdir(dest + file) command = ['/opt/local/bin/class-dump','-H',os.path.join(root,file)] subprocess.call(command) The folder also does not get created as Private_SDK, it gets created as tmpPrivate_SDK. Basically if I am able to get the full path from the terminal when ./tmp is mentioned, I can make the program run ! A: os.makedirs gets a relative path (based on ./tmp) and gets called after calls to chdir (see dest initialisation and usage) A: As already said, the loop for file in files: os.makedirs(dest + file) os.chdir(dest + file) command = ['/opt/local/bin/class-dump','-H',os.path.join(root,file)] subprocess.call(command) is the source of this. Instead, you should * *either work with absolute paths - that requires fetching the current working directory before the said loop with wd = os.getcwd() and modifying dest in that way that you have a absdest = os.path.join(wd, dest) and work with this. (Besides, you should better work more with os.path.join() instead of dest + file). *or go always back to the "old" working directory after a subprocess call. Here, you need the wd = os.getcwd() part as well and need to os.chdir(wd) afterwards.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551706", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: maven plugin to call or invoke a rest web service Is there any maven plugin which will be invoking already existing rest web service? or else is there any way to invoke a web service in pom.xml. like we have for invoking a external command org.codehaus.mojo exec-maven-plugin 1.2 please help me A: If you need invoke a REST service using a POST method, you can use a groovy script <project> <modelVersion>4.0.0</modelVersion> <groupId>com.myspotontheweb.demo</groupId> <artifactId>maven-rest</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <dependency> <groupId>org.codehaus.groovy.modules.http-builder</groupId> <artifactId>http-builder</artifactId> <version>0.5.1</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.codehaus.groovy.maven</groupId> <artifactId>gmaven-plugin</artifactId> <version>1.0</version> <executions> <execution> <phase>generate-resources</phase> <goals> <goal>execute</goal> </goals> <configuration> <source> import groovyx.net.http.RESTClient import groovy.util.slurpersupport.GPathResult import static groovyx.net.http.ContentType.XML solr = new RESTClient('http://localhost:8080/solr/update') def response = solr.post( contentType: XML, requestContentType: XML, body: { add { doc { field(name:"id", "SOLR1000") field(name:"name", "Solr, the Enterprise Search Server") field(name:"manu", "Apache Software Foundation") field(name:"cat", "software") field(name:"cat", "search") field(name:"features", "Advanced Full-Text Search Capabilities using Lucene") field(name:"features", "Optimized for High Volume Web Traffic") field(name:"features", "Standards Based Open Interfaces - XML and HTTP") field(name:"features", "Comprehensive HTML Administration Interfaces") field(name:"features", "Scalability - Efficient Replication to other Solr Search Servers") field(name:"features", "Flexible and Adaptable with XML configuration and Schema") field(name:"features", "Good unicode support: héllo (hello with an accent over the e)") field(name:"price", "0") field(name:"popularity", "10") field(name:"inStock", "true") field(name:"incubationdate_dt", "2006-01-17T00:00:00.000Z") } } } ) log.info "Solr response status: ${response.status}" </source> </configuration> </execution> </executions> </plugin> </plugins> </build> </project> The REST API example was taken from Hubert Klein Ikkink's blog: http://mrhaki.blogspot.com/ A: You can call REST web service using Ant's Get task (though it's limited to only GET method). And use Maven's Antrun plugin to call your Ant script. A: You can use the rest-maven-plugin to perform either a POST or a GET (and other methods such as PATCH or PUT would probably work as well). The plugin can POST a file and also save the results returned from the REST request to a file, with normal maven support for filesets and remapping the resulting filenames relative to the POSTed file. It will also support pure GET request with the results stored to a specific file. Standard REST query properties are supported, such as setting Query parameters, Header parameters, and Request/Response media types. See for the code. The latest release version of the maven plugin is also published and available via normal Sonatype Nexus repository. Here's an example where JSON Schema document is submitted to a NodeJS REST service which will return JSON sample data generated by the Faker module. It will upload all the files in the ./target/classes/json/faker directory which match '*.json' and deposit the results into the ./target/classes/json/examples directory. Check out the example below. <properties> <rest-maven-plugin.version>1.4</rest-maven-plugin.version> </properties> <plugins> <plugin> <groupId>com.github.cjnygard</groupId> <artifactId>rest-maven-plugin</artifactId> <version>${rest-maven-plugin.version}</version> <executions> <execution> <id>fake-json-data</id> <phase>process-classes</phase> <goals> <goal>rest-request</goal> </goals> <configuration> <endpoint>${json-data-server.url}</endpoint> <resource>schema/v1/api</resource> <queryParams> <addRequired>1</addRequired> </queryParams> <fileset> <directory>${project.build.resourcepath}/json/faker</directory> <includes> <include>*.json</include> </includes> </fileset> <requestType> <type>application</type> <subtype>json</subtype> </requestType> <responseType> <type>application</type> <subtype>json</subtype> </responseType> <outputDir>${project.build.resourcepath}/md/json/examples</outputDir> </configuration> </execution> </executions> </plugin> </plugins> A: To give an example of the Antrun Maven Plugin solution: <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-antrun-plugin</artifactId> <version>1.8</version> <executions> <execution> <id>notify</id> <phase>compile</phase> <goals><goal>run</goal></goals> <configuration> <target> <get dest="target/counter" usetimestamp="false" src="https://c1.navrcholu.cz/hit?site=144925;t=lb14;ref=;jss=0" verbose="off" quiet="true" ignoreerrors="true"/> </target> <failOnError>false</failOnError> </configuration> </execution> </executions> </plugin> A: I needed support for an untrusted HTTPs connection and none of the above approaches was supporting this easily. I found the Java curl library. Ant's Get task is nice but does not support this. The Java curl library is also offering a wider range of options and HTTP methods. For my purposes I have used this solution together with the Groovy Maven plugin: <plugin> <groupId>org.codehaus.gmaven</groupId> <artifactId>groovy-maven-plugin</artifactId> <version>2.2-SNAPSHOT</version> <executions> <execution> <phase>integration-test</phase> <goals> <goal>execute</goal> </goals> <configuration> <source> import static org.toilelibre.libe.curl.Curl.$; try { $("curl -k " + "-o target/openapi.json https://localhost:1234/openapi"); } catch (Exception e) { System.err.println(e) } </source> </configuration> </execution> </executions> <dependencies> <dependency> <groupId>org.toile-libre.libe</groupId> <artifactId>curl</artifactId> <version>0.0.29</version> </dependency> </dependencies> </plugin>
{ "language": "en", "url": "https://stackoverflow.com/questions/7551711", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: SQL Server database sync with another database table I have 2 tables. The 1st table is just a normal table in a database inside SQL Server. The 2nd table is also a table in a database except that it belong to SharePoint 2007 and is not known even though one can go to the SharePoint site to see that it belong to a SharePoint Form library. My question is how to auto-sync these two tables together? (At anytime, the two table must contain the same information.) A: You can synchronize databases with SQL Server Replication. Best Regards
{ "language": "en", "url": "https://stackoverflow.com/questions/7551715", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Special Character in UserName for iPhone app Have some special character in username like tüser, when i try to add it into NSMutableDictionary it is adding in a different format. Let me know how to resolve this issue. A: What do you mean with different format? If you are using NSLog to print the content of dictionary, you might see it escape some special characters, but you'll still be able to access the value using that key. NSMutableDictionary * dictionary = [NSMutableDictionary dictionary]; [dictionary setObject: @"hello" forKey: @"tüser"]; NSLog(@"Dictionary: %@", dictionary); NSLog(@"Value: %@", [dictionary objectForKey: @"tüser"]); Output: Dictionary: { "t\U00fcser" = hello; } Value: hello
{ "language": "en", "url": "https://stackoverflow.com/questions/7551719", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Howto get javascript value in HTML form I've got jquery using the sortable plug in. I'm using the following function to get the values. $(function() { $( "#sortable" ).sortable({ placeholder: "ui-state-highlight" }); }); function overzicht(){ var regel = ''; $('ul#sortable li').each(function(index) { regel += $(this).attr('id').replace(/ /g, "") + ','; }); } <ul id="sortable"> <xsl:for-each select="//regels/item"> <li style="list-style:none; vertical-align:middle; min-height:50px" id="{veld[3]}" class="ui-state-default"> </li> </xsl:for-each> </ul> How do I get the "regel" value in a HTML form like this? <form name="cartForm" method="post" action="edit_bestellijst.asp"> <input type="hidden" name="act" value="update" /> <input type="hidden" name="artNr" value="***regel values***)" /> </form> I'm using a bit XSL. Can someone please help me? A: after the each loop you should write : $("input[name='artNr']").val(regel);
{ "language": "en", "url": "https://stackoverflow.com/questions/7551722", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP - Accessing SPAN values I'm new to PHP but I'm working on an email script for an order form. I have all the values and what not in a form, with a text element that is span-ned for javascript access client side. What I need to do is also access these span values when I POST. HTML: <form name="myform" action="submit.php" method="post"> <strong>Price:</strong> $<span id="SMP">11.99</span> <strong>Price:</strong> $<span id="SDP">11.99</span> <strong>Price:</strong> $<span id="YTP">11.99</span> <strong>Price:</strong> $<span id="SDP">11.99</span> //bunch of input form code i truncated for readabilty </form> A: You can't do that. The POST array will only contain what you post via input fields. Easiest thing for you to do would be to have some hidden inputs with your values in them <input type="hidden" name="prices[0]" value ="11.99"> <input type="hidden" name="prices[1]" value ="11.99"> <input type="hidden" name="prices[2]" value ="11.99"> This will be available in your $_POST array. You can access it like $value1 = $_POST['prices'][0]; Or just iterate it through as an array A: You can't. You'll have to add some hidden inputs, and modify them from Javascript, to get them server-side. PHP can't access to the HTML, and only inputs elements are posted.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551724", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Text Positioning with IText for Java I need to position different text before I generate the pdf using IText. I've been thinking of using Chunks, but I don't know how to position them separately. I also tried using PdfContentByte but it doesn't generate any PDF File. A: Why don't you use tables combined with Chunks for your layout. ex: PdfPTable headerTable = new PdfPTable(2); float[] headerTableWidths = { 80f, 20f }; headerTable.setWidthPercentage(100f); headerTable.setWidths(headerTableWidths); headerTable.getDefaultCell().setBorderWidth(0); headerTable.getDefaultCell().setPadding(2); headerTable.getDefaultCell().setBorderColor(BaseColor.BLACK); headerTable.getDefaultCell().setFixedHeight(90f); PdfPCell infoCell = new PdfPCell(); infoCell.setHorizontalAlignment(Element.ALIGN_CENTER); infoCell.setVerticalAlignment(Element.ALIGN_TOP); infoCell.addElement("test"); infoCell.addElement("text"); table.addCell(infoCell);
{ "language": "en", "url": "https://stackoverflow.com/questions/7551728", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to avoid the page reload while using javascript I am using javascript in a jsp page to make some changes [adding a row in the table] to the current HTML page. The addition is happening successfully, but when i am about to exit from the function the page is getting reloaded. How to avoid the page reloading and, show the page without any change in the scroll. A: Add return false at the end of the function if it's an event handler. I've seen people usually recommend event.preventDefault() but I've personally had it fail on some browsers for me. So not quite sure if that will work just as well. A: This is a bit vague, we don't know exactly what you are trying to do. However, I think it's better to use jQuery. Or AJAX. Learn jQuery and try to implement your code in jQuery, it's easy, efficient. jQuery tutorial: http://www.w3schools.com/jquery/default.asp and AJAX tutorial: http://www.w3schools.com/ajax/default.asp
{ "language": "en", "url": "https://stackoverflow.com/questions/7551730", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: HTML in Symfony2 form labels instead of plain text I am trying to implement something like this: <div> <input type="checkbox" name="checkbox" id="checkbox_id" /> <label for="checkbox_id">I agree to the <a href="/tos">Terms of Service</a></label> </div> The closest I've come to implement this is through: <div> {{ form_widget(form.agreeWithTos) }} <label for="{{ form.agreeWithTos.vars.id }}">I agree to the <a href="#">Terms of Service</a></label> </div> Is there a better way? Having to specify {{ form.agreeWithTos.vars.id }} is inelegant. :) A: I've been beating my head over this then had a eureka moment. The easiest way to do this–BY FAR–is to create a Twig extension. Here's my Twig code: {# twig example #} {% block form_label %} {% set label = parent() %} {{ label|unescape|raw }} {% endblock %} and PHP: <?php new Twig_SimpleFilter('unescape', function($value) { return html_entity_decode($value); }); A couple notes: * *This unescapes all previously escaped code. You should definitely re-escape afterwards as necessary. *This requires an extends tag for your target form theme in your own custom form theme which you can use in your subsequent forms. Put the twig code in a custom form theme and replace references to your other form theme/themes with this one. Overall this is the fewest lines of code for the biggest and best outcome that I've been able to find. It's also ultra-portable and DRY: You can extend any form theme and the label will change without you changing the rest of your code. A: Another very simple approach is to override the form theme directly in the template which renders the form. Using {% form_theme form _self %} it is as simple as this: {% form_theme form _self %} {% block form_label %} {{ label | raw }} {% endblock %} {{ form_start(form) }} See the corresponding section in the docs: https://symfony.com/doc/current/form/form_customization.html#method-1-inside-the-same-template-as-the-form The easiest way to customize the [...] block is to customize it directly in the template that's actually rendering the form. By using the special {% form_theme form _self %} tag, Twig looks inside the same template for any overridden form blocks. [...] The disadvantage of this method is that the customized form block can't be reused when rendering other forms in other templates. In other words, this method is most useful when making form customizations that are specific to a single form in your application. If you want to reuse a form customization across several (or all) forms in your application, read on to the next section. A: Another approach is to use a simple Twig replacement: {% set formHtml %} {{ form(oForm) }} {% endset %} {{ formHtml|replace({'[link]': '<a href=" ... ">', '[/link]': '</a>'})|raw }} In your form, you have something like this in order to make it work: $formBuilder->add('conditions', CheckboxType::class, [ 'label' => 'Yes, I agree with the [link]terms and conditions[/link].' ] ); Of course, you may change [link] to anything else. Please note that you do not use HTML tags ;-) A: Solved this problem using the following code in my form-theme: {# ---- form-theme.html.twig #} {% block checkbox_row %} {% spaceless %} <div> {{ form_errors(form) }} <label class="checkbox" for="{{ form.vars.id }}"> {{ form_widget(form) }} {{ label|default(form_label(form)) | raw }} </label> </div> {% endspaceless %} {% endblock %} in your Form-Template you can then use: {% form_theme form '::form-theme.html.twig' %} {{form_row(form.termsOfServiceAccepted, { 'label' : 'I have read and agree to the <a href="#">Terms and conditions</a>' }) }} this way, the block from the form-theme would apply to any checkbox on the page. If you need to also use the default-theme, you can add a parameter to enable special-rendering: {# ---- form-theme.html.twig #} {% block checkbox_row %} {% spaceless %} {% if not useTosStyle %} {{ parent() }} {% else %} {# ... special rendering ... #} {% endif %} {% endspaceless %} {% endblock %} which would be used like this: {% form_theme form '::form-theme.html.twig' %} {{form_row(form.termsOfServiceAccepted, { 'useTosStyle' : true, 'label' : 'I have read and agree to the <a href="#">Terms and conditions</a>' }) }} A: Thanks to a recent commit to Symfony, you can use label_html from Symfony 5.1 onward: {{ form_label( form.privacy, 'I accept the <a href="' ~ path('privacy') ~ '">privacy terms</a>.', { 'label_html': true, }, ) }} A: I think you are looking for form theming. That way you are able to style each part of form, in an independent file, anyway you want and then just render it in "elegant" way, row by row with {{ form_row(form) }} or simply with {{ form_widget(form) }}. It's really up to you how you set it up. A: Symfony 4.2 TWIG: {% block main %} .... {% form_theme form _self %} ... {{ form_row(form.policy, {'label': 'security.newPassword.policy'|trans({"%policyLink%":policyLink, "%termsLink%":termsLink})}) }} ... {% endblock %} {% block checkbox_radio_label %} <label{% with { attr: label_attr } %}{{ block('attributes') }}{% endwith %}> {{- widget|raw }} {{ label|unescape|raw }} </label> {% endblock checkbox_radio_label %} PHP: use Twig\Extension\AbstractExtension; use Twig\TwigFilter; class AppExtension extends AbstractExtension { public function getFilters() { return [ new TwigFilter('unescape', function ($value) { return html_entity_decode($value); }), ]; } } A: So form theming is pretty complicated. The easiest thing I've found is to just suppress the field's label ('label'=> false in Symfony form class) and then just add the html label in the twig html. A: You could leverage form theming in another way: you could move the <label> tag outside the form_label() function. Create a custom form theme, and for checkboxes only move the <label> tag outside the form_label function: {% block checkbox_row %} <label>{{ form_label(form) }}</label> {{ form_errors(form) }} {{ form_widget(form) }} {% endblock checkbox_row %} {% block checkbox_label %} {{ label }} {% endblock checkbox_label %} Now, in your teplate, override the label of your checkbox, and thus effectively inject HTML into the label function: {% form_theme form 'yourtheme.html.twig' _self %} {% block _your_TOS_checkbox_label %} I agree with <a href="#" target="_blank">terms and conditions</a> {% endblock _your_TOS_checkbox_label %}
{ "language": "en", "url": "https://stackoverflow.com/questions/7551735", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "18" }
Q: No module named _core when using mailer.py on Windows/Python 2.7 I'm trying to configure and run SVN post-commit hook sending mails. I've downloaded class mailer.py, installed Python 2.7 and svn-win32 bindings for svn. The machine is Windows-7 64 bit, the Python is 32 bit. Now the mailer.py ends with error, which is caused by import problem. When I in python console type "import svn.core" I have following error: >>> import svn.core Traceback (most recent call last): File "<stdin>", line 1, in <module> File "c:\tools\Python27\lib\site-packages\svn\core.py", line 19, in <module> from libsvn.core import * File "c:\tools\Python27\lib\site-packages\libsvn\core.py", line 5, in <module> import _core ImportError: No module named _core while in directory site-packages/libsvn are files such as: _core.dll I've installed other bindings, pysvn, that was installed correctly, but as far as I've noticed, it's the totally other API so I can't use that for python.py Does someone had similar problem and knows how to deal with it? A: The Python bindings need to load the native Subversion libraries (DLL's). If your Python is 32-bit then you would need 32-bit versions of the native Subversion libraries on PATH. A: I have problem like this. Trouble was that python just can not import this library (svn.core and other). I just make: import sys sys.path.append("C:\csvn\lib\svn-python"). My file core.pyc was in C:\csvn\lib\svn-python\svn. Hope it helps somebody. Such behacior for me is strange because there is no "init.py" or "init.pyc" file in svn-python directory. But it works.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551738", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Find value between array values I have a large array and would like to find between which array values the search value would appear. A simplified version of this array is as follows: [0] => Array ( [min] => 0 [max] => 4.999 [val] => low ) [1] => Array ( [min] => 5 [max] => 9.999 [val] => med ) [2] => Array ( [min] => 10 [max] => 14.999 [val] => high ) So if I was to search for 6.2 the returned result would be the array value 'med' Is there a built in function that can easily walk over the array to make this calculation or would I need to set up a foreach loop Thanks in advance A: I think a simple foreach would be fast enough, with some precaution in floating point comparisons : see it here : http://codepad.org/sZkDJJQb <?php $rangeArray = array( array( 'min' => 0, 'max' => 4.999, 'val' => 'low'), array( 'min' => 5, 'max' => 9.999, 'val' => 'med'), array( 'min' => 10, 'max' => 14.999, 'val' => 'high'), ); $input = 6.2; $precision = 0.00001 ; foreach($rangeArray as $current) { if( ($input - $current['min']) > $precision and ($input - $current['max']) <= $precision ) { echo $current['val']; break; } } ?>
{ "language": "en", "url": "https://stackoverflow.com/questions/7551742", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Regex Text Field Validator for iPhone I have the following behavior of a desktop version of a software: * *a text field is validated with a regex abc|xyz *this means that a user is allowed to type a, ab, x, xy, abc, xyz, other symbols will not be shown in a text field I have to port such behavior to iphone. Strings a, ab, x, xy does not match to regex abc|xyz that's why matching user input will restrict typing any char to a text filed. Is there any way to match a user input as a beginning of a regex string? Initial regex should not be modified (^$ could be added). The desktop version uses QRegExpValidator class from Qt. QRegExpValidator has Intermediate state that is a, ab, x, xy in my case. It uses matchedLength() to determine Intermediate state Also I had a look through NSRegularExpression and RegexKitLite A: Have a look at PCRE - Perl Compatible Regular Expressions. It is rumored to be used in Apple products.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551745", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Get Attribute model by attribute_code in Magento How could I get Attribute model (from: eav_attribute table) by attribute_code in Magento? Notice: - I don't care what is entity_type. Thank you so much. A: You have to know entity_type because you can have the same attribute_code for different entities. So to get attribute model: $attributeModel = Mage::getModel('eav/entity_attribute')->loadByCode($entity_type, $attributeCode); $entity_type parameter can be numeric (id directly), string (for example 'catalog_product' or Mage_Catalog_Model_Product::ENTITY) or it can be instance of model Mage_Eav_Model_Entity_Type A: Perhaps you can read the attributes by filter the collection Mage::getModel('eav/entity_attribute')->getCollection()->addFieldToFilter('attribute_code', array('in' => $codes) ) Since I need the attributes from the Product by code, I do it like this: $codes = (array) $codes; $res = array_intersect_key($this->getAttributes(), array_flip($codes)); $codes is an attribute_code-array Scope: extended Mage_Catalog_Model_Product A: $attribute_code = "flat_printing_quantity"; $attribute_details = Mage::getSingleton("eav/config")->getAttribute(Mage_Catalog_Model_Product::ENTITY, $attribute_code); $attribute = $attribute_details->getData(); echo $attribute['attribute_id']; A: $attributeModel = Mage::getModel('eav/entity_attribute')->loadByCode(1, 'is_approved'); echo $attributeModel->getAttributeId();
{ "language": "en", "url": "https://stackoverflow.com/questions/7551750", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "20" }
Q: Facebook Send button causing horizontal scroll I'm working on Ruby On Rails, and just integrated Facebook Send button in a project. When Clicked on the "Send" button, the popup window is going out of the screen and causing horizontal scrollbar. I tried a few solutions on some blog-sites and stackoverflow, but could not resolve the issue. Here are some screen shots: * *before clicking Send button http://imgur.com/wv2HZ *after clicking Send button http://imgur.com/BRUeT The code in View: fbsend.html.erb (using HTML5 code) <div class="right"> <script>(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) {return;} js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/all.js#xfbml=1"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk'));</script> <div class="fb-send" data-href="MY_SITE_URL"></div> </div> application.html.erb <div id="fb-root"></div> <script src="http://connect.facebook.net/en_US/all.js"></script> <script src="http://connect.facebook.net/en_US/all.js#appId=MY_APP_ID&amp;xfbml=1"></script> <script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script> <script> FB.init({ appId: "MY_APP_ID", cookie: true, xfbml: true }); </script> How can I fix the issue, so the popup will fit in screen and won't cause horizontal scrollbar? Thanks A: I believe the comment box is placed into its own iframe, so you should be able to re-position it in your own CSS independently from the button/etc. One issue with that approach is that the small comment "pointer" triangle on the top of the comment box will no longer aim at the triggering button. Maybe an overflow:hidden on a parent container could allow you to hide that part from view. Good luck! A: Adding display:none to #fb-root worked for me: <div id="fb-root" style="display:none;"></div> A: well, in the picture it appears the send box, upon click, is extending the width of the window with a scroll bar so you can scroll to the box. That's normal. Your choices: a. Move the send button further left so upon click, it doesn't go past the window border, so no need for scroll bars. b. Add a overflow-x:hidden; styling property to your <body> element's css. This way, users just won't be able to see the whole box.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551752", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to see the source code of a particular html tag by onClick() javascript without showing its css? Hi everyone, here am trying to display the source code of a particular div by onclick javascript function. But the result am getting is , when i click on the div, am seeing the whole source code though am trying to make only the particular source code of a div to get displayed. anyone please highlight me what am doing wrong here..! and what to do to make it work in the way its expected. <html> <head> <title></title> <script type="text/javascript"> function viewsource(){ var oldHTML = document.getElementById('para').innerHTML; var newHTML = "" + oldHTML + ""; var newHTML = newHTML.replace(/</g,"&lt;"); var newHTML = newHTML.replace(/>/g,"&gt;"); var newHTML = newHTML.replace(/\t/g,"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"); document.getElementById('para').innerHTML = newHTML; } </script> </head> <body> <p id='para'><strong>This is my <span style="border: 1px solid #ccc;">test text</span> to check if it works</strong></p> <input type='button' onclick='viewsource()' value='View Source'/> </body> </html> Additional notes: In the above code, when the button is clicked, the paragraph tag with the id of para will display...but it shows its css too. I want to display only the html tag without the css style attribute. I don't want the content using innerHTML but i want the whole div including with the div id.(eg.)<div id='softros'><img src='/images/bgrade.jpg' /></div> A: have you considered to just use inside your java script handler : document.getElementById(YOUR_DIV_ID_GOES_HERE).innerHTML A: You can get the HTML of the div using .innerHTML or .outerHTML but you need the encode it before you can display it. Otherwise the html gets renderd by the browser. In PHP you could use htmlencode javascript has no function for this but you could use this htmlencode.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551754", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to store data , and add button in firefox / chrome javascript plugin im beginner to java script / XUL development and c++ if needed . i have 2 basic questions and i need some directions . background : i like to build simple plugin that schedule by date actions to preform. 1. can i store data ( dates + ids ) so the plug in could read and write to it , what is the limitations ? 2. what is the best way to add button to gmail , or you tube , is Grease monkey is the only way ? Thanks for helping . <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> A: To perform automatic date operations, you need your own Date()function & these links wil help you: https://developer.mozilla.org/en/CSS/Getting_Started/XUL_user_interfaces https://wiki.mozilla.org/XUL:Specs:DateTimePickers Regarding read & write to any files in XUL javaScript is pretty simple: https://developer.mozilla.org/en/Code_snippets/File_I%2F%2FO http://puna.net.nz/archives/Code/Mozilla%20XUL%20LOG%20-%20read%20local%20files%20and%20write%20local%20files.htm The above links explained very clearly to read & write any type of files in any bit format in a directory or in a local machine, there is no limitation. I have no idea baout Grease Monkey but in XUL use ca use DOM function to create buttons & elements dynamically. https://developer.mozilla.org/en/XUL/button http://www.borngeek.com/firefox/toolbar-tutorial/chapter-6/
{ "language": "en", "url": "https://stackoverflow.com/questions/7551755", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Sinatra with Warden & Omniauth Need some high level advice before putting the pieces of an app together.. I'm not entirely sure how these three pieces should fit together. My understanding: I have the user log in using omniauth and get redirected to a callback, where I can get information provided by the API and use it to build a user in the database. Then, I use warden to "store" the user, and authenticate whether actions are valid or not. * *It looks as if I'll have to create my own "strategy" for warden? *How should I store the user's identity? A: Somebody's already done the hard work for you. On github: https://github.com/hassox/warden_omniauth
{ "language": "en", "url": "https://stackoverflow.com/questions/7551763", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using class to call jQuery UI date-picker doesn't work I'm using jQuery UI datepicker - the range version. I have a form and in the input field (text) of the "from date" I call the datepicker. It works fine. The problem is that I also have in that field an image (of a calendar) that I set it's class to be the same one as the field's. BUT, while the field open the datepicker without problems, clicking the image seems do do nothing. I know there are some questions regarding this issue, but nothing helps ;) <input type="text" id="fromDate" value="Enter date" name="fromDate" class="fromDatePicker"/> <img class="fromDatePicker" src="images/calender_icon_a1.jpg" id="ci1"/> The js code: $(function() { $( ".fromDatePicker" ).datepicker({ defaultDate: "+1w", dateFormat: 'dd/mm/yy', altFormat: 'yymmdd', altField: "#fromDateFormatted", numberOfMonths: 2, onSelect: function( selectedDate ) { $('#toDate').datepicker( "option", "minDate", selectedDate ); } }); A: Apparently you can't bind a datepicker to an image. If we look at the datepicker source, we see this: if (nodeName == 'input') { this._connectDatepicker(target, inst); } else if (inline) { this._inlineDatepicker(target, inst); } and inline is true if and only if nodeName is div or span. So when you try to bind the datepicker to an <img>, you get ignored without so much as a warning in the console. If you look at the Icon Trigger example on the jQuery-UI demos page, you'll see the approved way of activating the datepicker using an icon: $('.fromDatePicker').datepicker({ // existing options showOn: "both", buttonImage: "images/calendar_icon_a1.jpg", buttonImageOnly: true }); and then remove your img.fromDatePicker element entirely.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551770", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to Protect Base Field's Public/Private If i have a ClassA public class ClassA { public string name; } Where Attribute Name is Public ,and it can be modified from Anywhere . Than i have a ClassB public class ClassB : ClassA { private string name;//But it's not Woking ,name is still public } ...which Inherit's ClassA ,but i need at ClassB to make name as Private Field. So if i create an Object of Type ClassB than ClassB.name cannot be modified . A: just don't publish the field but accessors: public class ClassA { private string _name; public string Name { get { return _name; } protected set { _name = value; } } } public class ClassB : ClassA { /* nothing left to do - you can set Name in here but not from outside */ } A: This is not possible. You can not change visibility of base class's field. A: Assuming you cannot change A, do not use inheritance, but aggregation and delegation: public class A { public string name; public int f() { return 42; } } public class B { private A a; public int f() { return a.f(); } public string getName() { return a.name; } } A: Carsten Konig's method is a good way, and here is an alternative. public class ClassA { public virtual string Name { get; private set; } } public class ClassB : ClassA { public override string Name { get { return base.Name; } } } A: Hm. There is a pair of tricks for this. But none of them is what you really want. One is: public class ClassA { protected string name; public string Name { get { return name; } public set { name = value; } } } public class ClassB : ClassA { public new string Name { get { return base.name; } } } A: If you don't have control over ClassA, you can do this: void Main() { var b = new ClassB(); var a = (ClassA)b; a.name = "hello"; b.PrintName(); } class ClassA { public string name; } class ClassB : ClassA { private new string name; public void PrintName() { Console.WriteLine(base.name); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7551771", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Fixed positioning in Android 2.3 browser should work... shouldn't it? From looking around on the net, my understanding is that fixed positioning should work in Android 2.3 if one has the right meta tags set. This is what my current viewport settings are. <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no" /> On my Galaxy S2, the div with fixed position (basically it's a thin header at the top of the page) does not stay in place when scrolling down the page. It moves with the page. However, when you stop scrolling, it will jump to the top of the page again. Is that the expected fixed position behaviour for Android 2.3? Is there a better way to do this (which hopefully doesn't involve the massive complexity of addiong iScroll)? A: I've just been having a look into this issue myself as part of a project we are doing: the S2 does not appear to fully support position:fixed, instead it emulates it by snapping the object back in place once the scrolling is completed (which is how we are handling it, with JS, for handsets which do not support position:fixed). I've no idea why this is, as all the other Android 2.3 devices we have tested do support it fully with no issues, but you're not the only one having problems! A: Here is another thing that breaks position:fixed on Android 2.3 anything{ -webkit-transition:none !important; } It only breaks when you use !important. Which sucks because anything{ -webkit-transition:anything; } Makes elements invisible. Hope this helps! A: There is an excellent comparison and discussion by Brad Frost of fixed positioning for Android, iOS, Firefox Mobile, Opera Mobile, Blackberry, Windows phone and more here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551778", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Jquery accessing appended element id with another js script Im trying to call a js function on a HTML element which I have appended to the page using JQUERY. <body> <div id='father'> </div> <input type="submit" value="choice one" onclick='choice_one()'/> <input type="submit" value="choice two" onclick='choice_two()'/> <input type="submit" value="choice three" onclick='choice_three()'/> </body> My jQuery is in a js function.. <script> function choice_one(){ var container = "<div id='field'> <form> <input type="text" id='choice_one_answer' value="" /> <input type="submit" value="submit" onclick='answer_one()'/> </form> </div>"; $('ul#field').remove(); $("div#father").append(container); } function choice_two(){ var container = "<div id='field'> <form> <input type="text" id='choice_two_answer1' value="" /> <input type="text" id='choice_two_answer3' value="" /> <input type="submit" value="submit" onclick='answer_two()'/> </form> </div>"; $('ul#field').remove(); $("div#father").append(container); } </script> So the third part is using the answers and with js then reloading anther field. Then loading another function --> new answer field. <script> function answer_one(){ var answer = document.getElementById('choice_one_answer'); do something with answer... choice_two(); } function answer_two(){ var answer_one = document.getElementById('choice_two_answer1'); var answer_two = document.getElementById('choice_two_answer2'); do something with answer... choice_one(); } other functions.... </script> So when I try to call the js functions eg answer_one()/ answer_two() the function cannot grab the variable from the input Id's ---> i presume their is because the element were not loaded when the page loaded! Is there a jQuery/ js workaround for this... any thoughts?? Is there a work around for something like this?? A: I think it's a good practice to append html in one line, like this: var container = "<div id='field'><form><input type="text" id='choice_one_answer' value="" /><input type="submit" value="submit" onclick='answer_one()'/></form></div>"; Don't have the time to test anything, but the jQuery workaround for accessing inserted code is .live() A: Why are you using jQuery but not using $()/jQuery() selector for selecting the element? Try to comment out the //$('ul#id').remove() line and dupm $('ul#id').size() to console in order to know that your element exists.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551787", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is it good to pass CamelCase controller name in Cakephp URL? Sorry for this basic question I have a controller named "UserProfiles" it contain a function named "view". But when a user login i redirecting to that view method. I using the following code : 1.) $this->redirect('/UserProfiles/view'); and i have other option 2.) $this->redirect('/user_profiles/view'); My Output: http://www.sample.com/UserProfiles/view Or http://www.sample.com/user_profiles/view My doubt is which is correct standard to use in cakephp, and which of these 2 option will helpful for SEO friendly url ? A: The CakePHP convention is that you use underscored and lowercase in your urls. See: http://book.cakephp.org/view/904/Controller-Conventions#URL-Considerations-for-Controller-Names-905
{ "language": "en", "url": "https://stackoverflow.com/questions/7551790", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to run Selenium tests parallelly in one machine I have two test suites configured in build.gradle and i am using selenium-server-standalone-2.1.0.jar. How can i make use of selenium-grid to run selenium tests parallel. Is it possible to run two different test suites at a time?
{ "language": "en", "url": "https://stackoverflow.com/questions/7551793", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Displaying a google map in google closure How can I display a map in Google Closure. There seems to be many UI widgets but none for showing a map A: I'm confused. Since Google Closure is a javascript library, can't you just use the Google Maps Javascript API? Something like: <script type="text/javascript" src="http://maps.googleapis.com/maps/ap/js?sensor=set_to_true_or_false"> </script> <script type="text/javascript"> function initialize() { var latlng = new google.maps.LatLng(-34.397, 150.644); var myOptions = { zoom: 8, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); } And then you can just change the document.getElementById() to whatever you need. Reference: Google Maps Javascript API
{ "language": "en", "url": "https://stackoverflow.com/questions/7551794", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Collection usage in BackboneJS Which is better to use the collection: * *Collection contain the total list of data, and include a function to select the the part of data show in view. Lots of data should be loaded in client side. *Collection only contain the data to show in view. In this way, require to fetch data from server more frequently. And the data to show in view is selected on server side. Any suggestion? A: It depends on the size and sensitivity of the collection, but in general I preference proxying requests to the server-side, and storing only the view/cache data locally. It will serve better in the long-run. A: If you have tonnes of data, best solution will be to load it on demand.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551798", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Rails and sqlite 3 in different locations - problem? I'm working with an Agile Web Development book to learn Rails, and it's using sqlite 3 for a database. On my Mac Snowleopard system sqlite3 is installed in /opt/local/bin/sqlite3 whereas the other necessary components are all /usr/bin/ruby /usr/bin/irb /usr/bin/gem /usr/bin/rake Will this create a problem? If so, how can I fix the problem in advance? If it involves doing something with the PATH variable, can you please provide detailed instructions how to fix it. Thanks from a newbie... UPDATE This is my current bash profile export PATH="/usr/local/bin:/usr/local/sbin:/usr/local/mysql/bin:$PATH" MacPorts Installer addition on 2011-09-20_at_01:30:15: adding an appropriate PATH variable for use with MacPorts. export PATH=/opt/local/bin:/opt/local/sbin:$PATH Finished adapting your PATH environment variable for use with MacPorts. A: As long as everything's in the PATH, it will be fine.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551802", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: closing the current popup window on button click in apex using salesforce i am in a strange situation I have an apex page inside that page there is a button on the click of which i call a a javascript method. From this method i call window.open(url) and open a new popup window. Now this new window is also an apex page. This window contains a button.on the click of this button i want to close the current popup window using javascript. can anybody suggest me what should i do? i have tried: ** window.close(); self.close(); ** I have tried with apex command button as well as with the HTML button. but still window cant be closed. A: Perhaps same issue as this: In Visualforce pages, is it possible to use the command line in the Firebug console? So try disabling development mode on your user. Søren
{ "language": "en", "url": "https://stackoverflow.com/questions/7551803", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: How to access res/drawable/"folder" On my application I have many pictures which I have grouped in folder under res/drawable. But Android dosen't let me access them trough "R". Is there a way to access those folders. This is the Code im using for. ImageView iv = new ImageView(conext); iv.setImageResource(R.drawable.**smiley.666**); I marked the part which I can't access. Thx in Advance safari A: R.drawable.xxx is just a reference that the Android SDK generates in your R.java file. You are trying to make a sub-folder in your res-folder. The SDK can't generate a reference to any of your sub-folders, you have to put it in the predefined folders drawable-hdpi, -ldpi and -mdpi. If you dont know how this works. I'll sum up. Android runs on a lot of different devices with a lot of different screen resolutions. With these three folders, you can have the same picture in three resolutions and depending on the device you are running your app on, one of these three folders will be used. You can read more here: http://developer.android.com/guide/practices/screens_support.html A: You can't create folders in res/drawable the system doesn't recognize those. A: No, Android does not allow subfolders under /res/drawable: Can the Android drawable directory contain subdirectories? You can however, add all image files under /drawable and then access them programmatically via: int drawableID = context.getResources().getIdentifier("drawableName", "drawable", getPackageName()); iv.setImageResource(drawableID); Where drawableName is a name of the drawable file, i.e. myimage if image file is myimage.jpg. The code above will get image resource with id R.drawable.drawableName. A: you need to save your image first and then make a xml for them so you can access it through R.your_pics A: context.getResources().getDrawable(R.drawable.progressbar1); Android - Open resource from @drawable String
{ "language": "en", "url": "https://stackoverflow.com/questions/7551810", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Eclipse: Autocompletion for Spring beans in Spring WebFlow? I am using Spring Web Flow 1.0 and Spring 2.0 (beans are defined in XMLs). In eclipse (Indigo 3.7), I'd like to enable autocompletion for my beans when writing web flows. I am already using Spring IDE plugin. Example (I'd like to prompt autocompletion for action - bean and method): <action-state id="doDeleteSelection"> <action bean="pm.TypoController" method="doDeleteElement" /> <transition to="elements" /> </action-state> Is this possible? A: Yes. This behavior is available in the Spring WebFlow editor. SpringIDE provides basic WebFlow editing using this editor. If you want a more sophisticated graphical editor, then you should download SpringSource Tool Suite: http://www.springsource.com/developer/sts It is possible to install STS into an existing Eclipse instance. I must say that I am a little surprised that you are not finding this feature since the use of the webflow editor should be default for all webflow files. Perhaps there is another problem going on.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551820", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Android OverlayItem on View class I am searching for a solution that will place an OverlayItem on a simple class extends View. All tutorials about OverlayItems are showing only how to set them up on MapView. I know, there's that method, getOverlays() or something, which returns ArrayList of OverlayItems. All is clear here. The problem starts when I am using normal view which is needed, because I am drawing things and showing them to user using that view. My target is to put OverlayItems that will act like those on map (with balloons). Any ideas or workarounds? I'm in a dead point.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551821", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Changing the text / content using properties files at runtime I'm using ResourceBundle.getBundle() to load property file in our portlet But If any user wants to change contents of that property file at runtime without deploying that portlet again. How can it reflect in UI[get latest value from property file] without deploying portlet? Thanks in Advance, Mayur Patel A: If I understand the question correct you can use portletPreferences instead of that propertyfile... See if you can find the table portletpreferences in your liferay database and see if that is anything for you. /Björn A: There's no such functionality in Liferay. You'd have to change Liferay code to make this work the way you want. To understand where in Liferay code .properties files are loaded into ResourceBundle-s see com.liferay.portlet.PortletConfigImpl class getResourceBundle(Locale locale)� method and com.liferay.portal.language.LanguageResources _loadLocale(Locale locale)� method.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551822", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java private method override I came across this scenario. We have a class lets say Main having a private method print. There is another class Main1 which extends Main class and redefines the print method. Since main1 is an object of Main1 class, I expect main1 print method to get called... public class Main { public static void main(String[] args) { Main main1 = new Main1(); List<String> list = new ArrayList<String>(); main1.print(list); } private void print(List<String> string) { System.out.println("main"); } } class Main1 extends Main { public void print(List<String> string) { System.out.println("main1"); } } In this case, when we run the program, it print "main". It really confuses me as that method is private and is not even part of Main1 class. A: The answer is not too hard: * *the type of the main1 variable is Main (not Main1) *so you can only call methods of that type *the only possible method called print that accepts a List<String> on Main is the private one *the calling code is inside the class Main so it can call a private method in that class Therefore Main.print(List<String>) will be called. Note that changing the type of main1 to Main1 will result in the other print(List<String>) method being called. A: If you want to be able to override your print method you have to declare it public: public class Main { public void print(List<String> string) { } } Otherwise it will call your private method without looking for the implementation in a derived class . A: Private method is not inherited and method overriding does not happened in your code. You can see this by putting @Override annotation in Main1.print() method. If you put that annotation, compile error generated. Main.java:17: method does not override or implement a method from a supertype @Override ^ 1 error In your case, Main1.print() and Main.print() are different and not related each other(no overriding, no overloading). So if you specify main1 as Main, Main.print() will be called. And if you specify main1 as Main1, Main1.print() will be called. A: Your main1 is a type of Main but instantiated with as Main1! It's OK since it is a subclass for Main. However, when you call the print method (BTW, it should be main1.print(list);) it will call the private method in the Main class! If you change the visibility of your method to protected or public, in this case print method in the Main1 class will be called because of polymorphic behavior of your instantiated object (remember, it is after all a Main1 object based on the code that you've provided!)
{ "language": "en", "url": "https://stackoverflow.com/questions/7551828", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to set invisible false only a charator of a string using js or JQuery I am having a string "Custormer1#-#Project1". I want to invisible the two #s in the string? Can I do this without replacing the character using javascript or JQuery? A: The only option you have is to wrap them in a <span>-element and hide that span with CSS. Check this fiddle for an example: http://jsfiddle.net/CJefw/ and note that the text() method in jquery still returns the right content, without the added spans. A: you can use jquery with map the original string array and in the map you can ignore the char. so the original string wont be affected that way - you wont replace the chars....
{ "language": "en", "url": "https://stackoverflow.com/questions/7551841", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Redrawing screen in cocos2d Is there a way to force a redraw in cocos2d? I have this code: CGSize s = [CCDirector sharedDirector].winSize; glLineWidth( 5.0f ); glEnable(GL_LINE_SMOOTH); glColor4ub(255,0,0,255); ccDrawLine( ccp(0, s.height), ccp(s.width, 0) ); which draws a red line. However it only works if I overload the draw method of a class. How can I get cocos2d or opengl to refresh? A: What do you mean by refreshing? Is it like clearing the screen and drawing again? The draw function in open Gl es is called at every frame. I will explain. Consider you want to draw line from p1 to p2. call ccDrawLine(p1,p2); in draw function. you can declare the points p1 and p2 global. Changing values of p1 and p2 will change the line accordingly. This is because the draw function is called and refreshed everytime a frame is drawn. the refresh rate = frame rate
{ "language": "en", "url": "https://stackoverflow.com/questions/7551843", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Measuring "total bytes sent" from web service with nettcpbinding using perfmon I have a web service (WCF) exposing both http endpoints and a tcp endpoint (using the nettcpbinding). I am trying to measure the difference in "total bytes sent" using the different endpoints. I have tried using perfmon and looked at the performance counter: web service > total bytes sent. However it looks like that this only measures http traffic - can any of you confirm this? It doesn't look like tcp traffic increments the number. There is also a TCP category in perfmon, but there is not a "total bytes sent". Is perfmon the wrong tool for the job? A: Solved. I measured bytes received on the client by using code something similar to: NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces(); NetworkInterface lan = null; foreach (NetworkInterface networkInterface in interfaces) { if (networkInterface.Name.Equals("Local Area Connection")) { lan = networkInterface; } } IPv4InterfaceStatistics stats = lan.GetIPv4Statistics(); Console.WriteLine("bytes received: " + stats.BytesReceived); Do this before and after the web service call and diff the 2 values. Obviously you need to be aware that any other traffic on the client does not interfere.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551847", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Reflect WF4 System.Activities Possible Duplicate: Reflector Not Decompiling 'System.Data.Entity.dll' .NET 4.0 I want to reflect the WF4 System.Activities assembly. The problem is when i open it in the reflector all the methods are empty! I can reflect the WF3 System.Activities... Does any one know if i can reflect it? A: Not sure what your problem is but it's certainly possible. I use Reflector all the time to check on the WF4 activities internals.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551849", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to calculate distance and time between two CLLocation throughout the whole ride with CloudMade maps? In my iPhone application I allow the user to choose a destination on the map, then when he starts driving toward the destination I want to give him information like: how long until he reaches the destination and what its current distance from the destination. I'm using CloudMade maps SDK for iPhone and i know there is an API method to get a path between two point that returns also the time and distance between them. Is it OK to call this method every time i get a new location from the CLLocationManager to get the updated time and distance? I assume this method query the CloudMade servers so i don't know if calling it a lot of time is the best way to do this.. A: For distance /* * distanceFromLocation: * * Discussion: * Returns the lateral distance between two locations. */ - (CLLocationDistance)distanceFromLocation:(const CLLocation *)location __OSX_AVAILABLE_STARTING(__MAC_10_6,__IPHONE_3_2); For getting the time needed, you could calculate it yourself. CLLocation has a speed parameter. Use the distance and the speed to calculate time. A: Swift version would be: var startLocation:CLLocation! var lastLocation: CLLocation! let distance = startLocation.distanceFromLocation(lastLocation)
{ "language": "en", "url": "https://stackoverflow.com/questions/7551856", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android ViewHolder in CursorAdapter causing listView to get screwed I've been struggeling in the past few days trying to figure this out, I hope you can help me... I have an Activity that shows a list of Players by setting a listadapter like this: PlayerCursorAdapter playerAdapter = new PlayerCursorAdapter(this, R.layout.players_row, c, columns, to); setListAdapter(playerAdapter); When clicking an item in the list, this code will be executed showing a dialog with an "Edit" and "Delete" option for editing and removing players: private class OnPlayerItemClickListener implements OnItemClickListener { public void onItemClick(AdapterView<?> parent, View view, int position, long rowId) { Toast.makeText(view.getContext(), "Clicked Item [" + position + "], rowId [" + rowId + "]", Toast.LENGTH_SHORT).show(); // Prepare Dialog with "Edit" and "Delete" option final CharSequence[] choices = { view.getContext().getString(R.string.buttonEdit), view.getContext().getString(R.string.buttonDelete) }; AlertDialog.Builder builder = new AlertDialog.Builder( view.getContext()); builder.setTitle(R.string.title_edit_delete_player); builder.setItems(choices, new EditOrDeleteDialogOnClickListener( view, rowId)); AlertDialog alert = builder.create(); // Show Dialog alert.show(); } Based on your choice (Edit or delete player), the following listener will be executed: private class EditOrDeleteDialogOnClickListener implements DialogInterface.OnClickListener { private View view; private long rowId; public EditOrDeleteDialogOnClickListener(View view, long rowId) { this.view = view; this.rowId = rowId; } public void onClick(DialogInterface dialog, int item) { if (item == 0) { // Edit showDialog(PlayGameActivity.DIALOG_EDIT_PLAYER_ID); } else if (item == 1) { // Delete from database DatabaseHelper databaseHelper = new DatabaseHelper( view.getContext()); databaseHelper.deletePlayer(rowId); // Requery to update view. ((PlayerCursorAdapter) getListAdapter()).getCursor().requery(); Toast.makeText( view.getContext(), view.getContext().getString( R.string.message_player_removed) + " " + rowId, Toast.LENGTH_SHORT).show(); } } } The code for the adapter is here: public class PlayerCursorAdapter extends SimpleCursorAdapter { private LayoutInflater layoutInflater; private int layout; public PlayerCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to) { super(context, layout, c, from, to); this.layout = layout; layoutInflater = LayoutInflater.from(context); } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { Cursor c = getCursor(); View view = layoutInflater.inflate(layout, parent, false); // Get Data int nameCol = c.getColumnIndex(Player.COLUMN_PLAYER_NAME); String name = c.getString(nameCol); int gamesPlayedCol = c.getColumnIndex(Player.COLUMN_GAMES_PLAYED); String gamesPlayed = c.getString(gamesPlayedCol); int gamesWonCol = c.getColumnIndex(Player.COLUMN_GAMES_WON); String gamesWon = c.getString(gamesWonCol); // Set data on fields TextView topText = (TextView) view.findViewById(R.id.topText); if (name != null) topText.setText(name); TextView bottomText = (TextView) view.findViewById(R.id.bottomText); if (gamesPlayed != null && gamesWon != null) bottomText.setText(view.getContext().getString( R.string.info_played_won) + gamesPlayed + "/" + gamesWon); CheckBox checkBox = (CheckBox) view.findViewById(R.id.checkBox); // Set up PlayerViewHolder PlayerViewHolder playerViewHolder = new PlayerViewHolder(); playerViewHolder.playerName = name; playerViewHolder.gamesPlayed = gamesPlayed; playerViewHolder.gamesWon = gamesWon; playerViewHolder.isChecked = checkBox.isChecked(); view.setTag(playerViewHolder); return view; } private class PlayerViewHolder { String playerName; String gamesPlayed; String gamesWon; boolean isChecked; } @Override public void bindView(View view, Context context, Cursor c) { PlayerViewHolder playerViewHolder = (PlayerViewHolder) view.getTag(); TextView topText = (TextView) view.findViewById(R.id.topText); topText.setText(playerViewHolder.playerName); TextView bottomText = (TextView) view.findViewById(R.id.bottomText); bottomText.setText(view.getContext() .getString(R.string.info_played_won) + playerViewHolder.gamesPlayed + "/" + playerViewHolder.gamesWon); CheckBox checkBox = (CheckBox) view.findViewById(R.id.checkBox); checkBox.setChecked(playerViewHolder.isChecked); } } Now, the problem is that after removing a few of the players in the list, the list gets screwed up, eg. it shows something different than what is actually available. I've experimented a little and if I stop using the PlayerViewHolder in bindView and instead read the text from the cursor and assign it directly to the text fields, then it works.... So question is, why is my ViewHolder screwing up things??? Any help will be greatly appreciated! Thanks! * *Zyb3r A: Found a solution... Basically I reinitialize the Cursor and ListAdapter plus assigns the ListAdapter to the ListView all over again when I change the data in the database. I'm not entirely sure why this is nessasary, but notifyDataSetChanged(), notifyDataSetInvalidated() and all the other things I tried didn't work, so now I'm using this approach. :o) * *Zyb3r
{ "language": "en", "url": "https://stackoverflow.com/questions/7551858", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: target to a div without reloading the page in javascript i wrote a web page that included some stuff. There, i need to create a input text box after clicking on a button, but it will be at the bottom due to existing stuff and i can't see the input box as it is in the out of visible area.there i'v to scroll down to find that.I tried with focus method , it focuses to the input box, it is unable to take the input box to visible area.in the top , i'v some javascript stuff .so i need to do this without refreshing.Here is the code snippet i'v tried. <script> function create(){ var inputBox=document.createElement('input'); inputBox.setAttribute('id','myInput'); var body=document.getElementsByTagName('body')[0]; body.appendChild(inputBox); document.getElementById('myInput').focus(); } </script> <body> <button onclick="create()">Click me</button> </body> Can anyone help me ! A: Yes, you are inserting the text input as the last element in body. If you want it to appear at a specific place, create a placeholder for it. For instance: <script> function create(){ var inputBox=document.createElement('input'); inputBox.setAttribute('id','myInput'); var wrapper=document.getElementById('wrapper'); wrapper.appendChild(inputBox); inputBox.focus(); } </script> <body> <button onclick="create()">Click me</button> <div id="wrapper"></div> </body> A: You need a anker: <a name="button"></a> <button onclick="create()">Click me</button> Then you can jump to it location.href = 'http://yourpage#button' The page will not reload if you jump to an anker on the same page. A: Well you can always have the input in the HTML markup , and make it visible when clicking the button . Also replacing the body.appendChild with body.insertBefore(inputBox,body.firstChild); should do what you want .
{ "language": "en", "url": "https://stackoverflow.com/questions/7551859", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Write an array on.plist I have a problem. I have this file dictionary .plist: <plist version="1.0"> <dict> <key>2</key> <array> <string>a</string> <string>b</string> <string>c</string> </array> </dict> </plist> So now I read this file in this way: NSString* plistPath = [[NSBundle mainBundle] pathForResource:@"dictionary" ofType:@"plist"]; NSMutableDictionary *contentArray = [NSMutableDictionary dictionaryWithContentsOfFile:plistPath]; NSMutableArray *dic = [contentArray objectForKey:@"2"]; NSLog(@"Numero di elementi del dictionary corrispondente a 2: %i", [dic count]); for (int i = 0; i < [dic count]; ++i) { NSString *temp = [dic objectAtIndex:i]; NSLog(@"Stringa = %@\n", temp); } Now I want to modify the array: [dic replaceObjectAtIndex:0 withObject:@"ok"]; and I want to write it on the dictionary.plist and I try this: [contentArray writeToFile:plistPath atomically:YES]; [contentArray release]; But this code doesn't work, and I receive an error, how can I do this? Thanks A: Since you didn't provide the error, I assume the problem might be that NSMutableDictionary * contentArray = [NSMutableDictionary dictionaryWithContentsOfFile: plistPath]; only creates a mutable container (you can change the content of contentArray, but not the objects (leaves) inside of it. If you want mutable leaves, use NSPropertyListSerialization instead: NSMutableDictionary * contentArray = [NSPropertyListSerialization propertyListFromData: [NSData dataWithContentsOfFile: plistPath] mutabilityOption: NSPropertyListMutableContainersAndLeaves format: nil errorDescription: nil];
{ "language": "en", "url": "https://stackoverflow.com/questions/7551861", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Create a method applicable to a String object I would like to create a method applicable to a String object, that will return a modified String: String s = "blabla"; String result = s.MyNewMethod(); I have tried to create a new class String but keyword this seems unknown: class String { public String MyNewMethod() { String s = this.Replace(',', '.'); // Replace method is unknown here // ... } } A: You need to define an extension method: public static class StringExtensions { public static string MyNewMethod(this string s) { // do something and return a string } } Note that extension methods are static and are defined in a static top-level class. A: I think this needs a bit more explanation. * *String is a sealed class in .NET as in most OO typesafe languages. This means you can't subclass string. Here's some great info about strings: http://www.yoda.arachsys.com/csharp/strings.html. And why they can't be subclassed. *To make a subclass in .net you have to use the following syntax: // here "Test is a subclass of Test2" public class Test : Test2 { } *Extension methods as mentioned by Jason are great for adding functionality to sealed classes. Extension methods can never override a function that already exists in a class. At compile time they have a lower priority then instance methods. Since extension methods do not live within the class they cannot access internal and private fields.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551863", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Ruby file is in search path but can't be found by 'require' I have a Rails app that's trying to use the gnuplot gem, but Rails won't bother to load it. It's in my Gemfile and I installed it with bundle install. Bundle knows about it: vp117025:src tim$ bundle show gnuplot /Users/tim/.rvm/gems/ruby-1.9.2-p290/gems/gnuplot-2.3.6 But it doesn't appear in the Rails console (and isn't accessible from my app), even after an explicit require, which shouldn't be necessary. vp117025:src tim$ rails console Loading development environment (Rails 3.1.0) ruby-1.9.2-p290 :001 > require 'gnuplot' => false ruby-1.9.2-p290 :002 > require 'gnuplot.rb' => false Now, check to see whether the name of the module is in the constants table: ruby-1.9.2-p290 :003 > Module.constants.include? :Gnuplot => false It isn't! The module must not really be accessible. This is happening even though the require search path contains the directory that holds gnuplot.rb. ruby-1.9.2-p290 :004 > $:.include? "/Users/tim/.rvm/gems/ruby-1.9.2-p290/gems/gnuplot-2.3.6/lib" => true If I include the file explicitly by its full path, it works! ruby-1.9.2-p290 :005 > require "/Users/tim/.rvm/gems/ruby-1.9.2-p290/gems/gnuplot-2.3.6/lib/gnuplot.rb" => true ruby-1.9.2-p290 :006 > Module.constants.include? :Gnuplot => true The module is now visible to the interpreter. It works just fine from outside Rails. vp117025:src tim$ irb -rubygems -r gnuplot ruby-1.9.2-p290 :001 > Module.constants.include? :Gnuplot => true Why can't the Rails environment load gnuplot.rb, even though its parent directory is in the search path? A: It is loading. The return value of a require statement will be false if the library was already loaded. When you start the Rails console, it requires all the gems in your bundle, so requiring it again will give you false as you see here. Require treats every path passed to it fairly literally, so you can require a file by both its relative and absolute paths, and it will load both times. That's why you get a true result when using the full path – Ruby is treating it as a different file.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551864", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Grails not printing messages to log file using custom appender My Grails application is going to mirgate an existing database to a new database. I got some unformatted email addresses from the existing database which do not pass validation with my Grails application because of a constraint (email:true), so I get a field error. I want write these field errors in a log file. How can I do that? I tried a Appender in log4J. It will somehow create a log file so-call "migration.log", but it does not write any field error into this log file. log4j = { // Example of changing the log pattern for the default console // appender: // appenders { // console name:'stdout', layout:pattern(conversionPattern: '%c{2} %m%n') appender new FileAppender( name: "migrationAppender",file : "migration.log", layout: pattern(conversionPattern: "%c{2} %m%n") ) } This is configration. I define a FileAppender. In my service. I just call the following: def foundation = new Foundation(name: name, foundationName: foundationName).addToAddresses(address).addToCommunicationMedia(email) foundation.validate() if (!foundation.hasErrors()) { foundation.save(flush: true) } else { log.error "${foundation.errors}" } In the console, the errors occur and I saw a "migration.log" has been created, but somehow the file in empty. Error 2011-09-26 09:00:29,543 [main] ERROR service.MasterDataMigrationService - org.springframework.validation.BeanPropertyBindingResult: 1 errors Field error in object 'de.rvgmbh.nemesis.migration.domain.partner.participant.IndividualPerson' on field 'communicationMedia[0].address': rejected value [erbelrechtsanwalt-eberl.de]; A: log4j = { appenders { rollingFile name:"file", maxFileSize:(1024*1024), file:"migration.log", maxBackupIndex:10 environments { development { console name:'stdout' } } } error 'org.codehaus.groovy.grails.web.servlet', // controllers 'org.codehaus.groovy.grails.web.pages', // GSP 'org.codehaus.groovy.grails.web.sitemesh', // layouts 'org.codehaus.groovy.grails.web.mapping.filter', // URL mapping 'org.codehaus.groovy.grails.web.mapping', // URL mapping 'org.codehaus.groovy.grails.commons', // core / classloading 'org.codehaus.groovy.grails.plugins', // plugins 'org.codehaus.groovy.grails.orm.hibernate', // hibernate integration 'org.springframework', 'org.hibernate', 'net.sf.ehcache.hibernate' warn 'org.mortbay.log' environments { development { root { info 'file', 'stdout' } debug 'grails.app' }//development test { root { info 'file' } info 'grails.app' } production { root { info 'file' } info 'grails.app' } } } dev: logs to console and file from debug level test: logs to file from info level prod: logs to file from info level
{ "language": "en", "url": "https://stackoverflow.com/questions/7551868", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: MVC Testing actions that rely on HTTPContext I have a project where I need to provide action tests. My approuch has been to ensure actions do not rely on anything they do not receive as parameters, maing use of ValueProviders and ModelBinders. As such I would pass in HTTPContextBase etc. However, I now have an action which uses a static class that is a wrapper around HTTPContext to accesses Session and Identity. Thus it seems I have to mock out HTTPContext to test this action. Not too complicated, I guess, but it just feels wrong. My gut feeling is that the static class should be redeveloped to be instantiated with HTTPSessionStateBase and IPrinicple and use them as internal stores. Then I could instantiate this wrapper in my action, from action parameters, making the action and the wrapper class much more testing friendly. Would this be a recommended approuch or does anyone have any other ideas, were I would not have to change my static class to instance ? A: I think that using Moq to mock a HttpContext is just the way you might want to try it out. [TestMethod] public void Test() { var context = new Mock<HttpContextBase>(); var request = new Mock<HttpRequestBase>(); context.Setup(c => c.Request).Returns(request.Object); HomeController controller = new HomeController(); controller.ControllerContext = new ControllerContext( context , new RouteData(), controller ); .... ........... } Updated: In the case if you want to mock HttpSession(as gdoron mentioned in comment). It is not really complicated since you are MOCKING something doesn't means you have to build entire, real object and all of its properties. Suppose that your controller will * *Checks whether user is authenticated. *Gets identity name. *Gets a value from Session["key"]. *manipulates cookie. The code could be like that: [TestMethod] public void Test() { ...... ......... var mockedControllerContext = new Mock<ControllerContext> (); mockedControllerContext.SetupGet(p => p.HttpContext.Session["key"]).Returns("A value in session"); mockedControllerContext.SetupGet(p => p.HttpContext.Request.IsAuthenticated).Returns(true); mockedControllerContext.SetupGet(p => p.HttpContext.User.Identity.Name).Returns("An identity name"); mockedControllerContext.SetupGet(p => p.HttpContext.Response.Cookies).Returns(new HttpCookieCollection ()); HomeController controller = new HomeController(); controller.ControllerContext = mockedControllerContext.Object; ..... ...... } A: I strongly recommend using MvcContrib - testhelpers Learn how to use from CodePlex You can download it from nuget or directly from CodePlex Good luck!
{ "language": "en", "url": "https://stackoverflow.com/questions/7551878", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: symfony plugin installation failing [bhLDAPAuthPlugin] I'm working on a symfony project and I need a user access conected to an LDAP server. So I searched for something already done to add to my app and found this plugin that has all I wanted. So I tried to install with the command $ php symfony plugin:install bhLDAPAuthPlugin for some reason it throws me this error: No release avaiable for plugin "bhLDAPAuthPlugin" I don't really understand what that message means. I've checked the spell of the command (also copied the command given in the page of the plugin) and same error appears. If I had no all requeriments for instalation, other errors would be thrown, right? PS: If you know some easy way to implement by myself the comunication with LDAP (Microsoft Active Directory) will also be appreciated. A: No exactly sure how to solve the error message, perhaps it helps is specifically specify which version you wish to install. Otherwise there's an easy workaround: Just download the tgz file from here: http://www.symfony-project.org/plugins/bhLDAPAuthPlugin/6_0_0 and do php symfony plugin:install bhLDAPAuthPlugin-etc-etc.tgz
{ "language": "en", "url": "https://stackoverflow.com/questions/7551883", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to Integrate non supported fonts in WP7 I am creating a English to Mangolean Dictionary app; So i need to display mangolean word corresponding to my english word; i read from a blog that wp7 only supports limited language set. So how can i over come my issue. Please help me to solve this issue. A: There's a tutorial on embedding fonts in Silverlight here: http://paulyanez.com/interactive/index.php/2009/12/embedding-fonts-in-silverlight/ The implementation for Windows Phone is exactly the same. The tutorial uses Expression Blend (which is part of the developer tools download and also free for Windows Phone), which is the simplest, quickest, and easiest way to embed fonts for Silverlight. A: Apart from the supported Fonts you can add your on fonts to you project. For example create a folder named Fonts in you project and add you *.TTF files(Font Files). By referring this font files you can resolve your issues.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551889", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to create a folder in network drive To create a dynamic folder in local drive it was generating, if suppose we need to create a folder in network path means error say that cannot access to the path is denied, how to resolve this issue , i m working on vb.net A: Same as creating a directory on a local drive, via Directory.CreateDirectory - Of course, the share needs to be set up to allow directory creations, and the user that your application (and specifically the thread) needs to have sufficient permissions as well.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551891", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to pass a generic object as a methods parameter This may be a very basic question, but it still gets me confused (and Google can't help) ;-) How can I pass a generic object as a parameter to a function? For example I have a class CoolGeneric<T> Now I need a method DoSomethingWithAGeneric(CoolGeneric g). Here the compiler keeps on complaining that a concrete type parameter is necessary. But the method should work with all kinds of type parameters! How can I do this? Thanks! A: Simply : DoSomethingWithAGeneric<T>(CoolGeneric<T> g) Or if the method is within a class declaring the generic type : class MyClass<T> { DoSomethingWithAGeneric(CoolGeneric<T> g) } A: You want: DoSomethingWithAGeneric<T>(CoolGeneric<T> g) the compiler will usually detect the T automatically (generic type inference), so the caller doesn't normally have to specify it; i.e. CoolGeneric<int> foo = ... DoSomethingWithAGeneric(foo); which is (usually) identical to: DoSomethingWithAGeneric<int>(foo);
{ "language": "en", "url": "https://stackoverflow.com/questions/7551893", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Porting XmlTextReader to XmlReader with same behaviour I want to port some C# code with the full .NET Framework as target into Silverlight-compatible code. One of the problems I've encountered is that in the original code, an instance of XmlTextReader is used: var xmlReader = new XmlTextReader(streamReader) { WhitespaceHandling = WhitespaceHandling.None, xmlResolver = null }; However, in Silverlight, only XmlReader is available. Therefore, I'm wondering how to convert from the original XmlTextReader. In the documentation of XmlTextReader, it's stated that In the .NET Framework version 2.0 release, the recommended practice is to create XmlReader instances using the XmlReader.Create method. This allows you to take full advantage of the new features introduced in this release. For more information, see Creating XML Readers. This supports the theory that a port should be possible. How does the initialization of a XmlReader has to look like to process the XML files exactly the same as the XmlTextReader instance mentioned above? var settings = new XmlReaderSettings { ... } var xmlReader = XmlReader.Create(streamReader, settings); A: Its not possible to replicate this entirely. Silverlight XmlReader does not support ignoring significant whitespace. This therefore is close:- var settings = new XmlReaderSettings { IgnoreWhitespace = true, XmlResolver = null }; I think you should just go with that and see what happens.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551898", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Predicting Dictionary<> size and speed I need to accurately calculate the size of a Dictionary for different sizes. I've tried doing some memory monitoring while running my application, but I am doing a lot of other stuff at the same time that affects the result. How can I calculate (aprox) expected size of a Dictionary with n items? I need to know how much RAM I need in different scenarious. By what factor does lookup time increase? O(1) ALWAYS? I'm planning to use dictionaries for 10M+ entries, probably more. Already consideret question for Size of a dictionary A: To answer my own question I created a small test program. Here are the results: * *100 000 random lookups in a table consisting of 10 000 000 random entries takes 0,02 seconds, the table uses 200MB of RAM. *Memory used by a dictionary seems to be around 20-22 times for Int32 index once you get above 100 items. The ratio goes down as the dictionary gets larger. *Pre-allocating memory seems to cut down noticeable on insert time. Details of the test and results at http://blog.tedd.no/2011/09/26/net-dictionary-speed-and-memory/
{ "language": "en", "url": "https://stackoverflow.com/questions/7551901", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is it OK to use Monitor.TryEnter in event handler method? I have EventHandler method which is called pretty often and it's body processing takes some time. Is it OK, to lock operations inside this handler it via Monitor? The purpose is that meanwhile locker locks the object other events and processing of the object are simply skipped. public void MyEventHandler(object sender, EventArgs e) { if (!Monitor.TryEnter(locker)) return; // skipping meanwhile processing // do some stuff here Monitor.Exit(locker) } A: it looks like it would be cleaner/more performant to * *(a) prevent the events from being raised *(b) use a condition variable. Regardless, always put the Monitor.Exit into a finally block A: It's not horrible, as long as: * *You're doing this on a background thread (or, to the point, you're not doing this on the event handling thread). *You're synchronizing all access to whatever your //do some stuff code needs. *You wrap everything after the TryEnter in a try/finally, like so: . public void MyEventHandler(object sender, EventArgs e) { if (!Monitor.TryEnter(locker)) return; try { // do some stuff here } finally { Monitor.Exit(locker); } } It'd be nicer if you could prevent firing the event at all (and thus avoid starting a thread to potentially do nothing -- cause of course you're not doing this time-consuming processing on the event handling thread...) Alternatively, if you don't really need to lock for the whole duration (that is, if the event handler won't be doing anything that requires synchronization with other code), you could lock just long enough to set a flag, like private Object condition_lock = new Object(); private bool handlingEvent = false; public void MyEventHandler(object sender, EventArgs e) { lock (condition_lock) { if (handlingEvent) return; handlingEvent = true; } try { // do some stuff here } finally { handlingEvent = false; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7551904", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jQuery popup form? I have a form which is currently sitting in a division on a php page. I would like it to do the following: * *User clicks link to bring up form in pop-up division in center of screen *User fills out the form *User hits the submit button *Form closes and brings up another small division with a thank you message which shows for 5 seconds then disappears What's going to be the easiest way to achieve this? I currently have jQuery and jQuery Tools scripts on the site in question. EDIT: I'can't use jquery-ui as that conflicts with jQuery tools accordion. A: For similar task, I used JQuery UI Dialog http://jqueryui.com/demos/dialog/#modal-form A: You should have a look at this documentation about jQuery UI Dialogs: http://jqueryui.com/demos/dialog/ Have also a look at Modal Forms (look at the navigation menu at the right of the page). Basically, you only set up a form inside of a dialog. Having that thank you -Dialog show up for a few seconds is also easy by using jquery Dialogs and something like setTimeout to close it. Don't forget to include the jQuery and jQuery UI libraries into your source code. Have a look at some jQuery tutorial first, if you don't know jQuery.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551906", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Erroneous value for commit options in params hash I'm using a submit_tag form helper in one of my apps. The value of this submit button should change dynamically. The two possible values for this submit button are Save and Update. So, in the view, I have done something like the following: <% temp = 0 %> <% text = '' %> <% temp = ActivityLog.find_by_sql("SELECT COUNT(id) AS cnt FROM logs WHERE id > 0")%> <% text = temp[0][:count].to_i > 0 ? 'Update' : 'Save' %> <!-- other html contents --> <%= submit_tag text, :id=>"submitBtn"+i.to_s, :onclick=>"submit_button_clicked(this)"%> Now, when I run the view inside a browser, I can see the desired effect. But the rails controller receives the erroneous value for the commit options in the params hash. For instance, when the value of text is evaluated to Save, I get the following in the Firebug: <input type="submit" value="Save" style="" onclick="submit_button_clicked(this)" name="commit" id="submitBtn3"> But raise params.inspect in the associated controller shows the follwing: {"commit"=>"Update", "authenticity_token"=>"", "time"=>{"292"=>"3.0", "2"=>"1.0", "456"=>"4.0"}, "date"=>"2011-09-20"} See, although the value of the Submit button is shown as Save in the HTML, the rails controller shows the value of commit as Update. What's wrong in here? A: If you are using Rails helpers, it provides a simple way to choose text on button with according to type of form: <%= form_for @activity do |f| %> <%= f.label :title %>: <%= f.text_field :title %><br /> <%= f.submit %> <% end %> When no value is given, it checks if the object is a new resource or not to create the proper label. In the example above, if @activity is a new record, it will use "Create Activity" as submit button label, otherwise, it uses "Update Activity". P.S. please do not use SQL in your views
{ "language": "en", "url": "https://stackoverflow.com/questions/7551908", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android development - Users updating app question I've written a program that, when completed, I plan to add to the Android Marketplace. I have given many files as features for users to store information and reload later, and while debugging, I've noticed the files tend to get deleted when I update the code after a long while (like a few days spread apart--for some reason, it doesn't happen when I update the code often, like every hour when I'm adding new features and testing them out). Note that I use a real phone for testing and not the emulator. What I'm wondering is, will the files get deleted after each release of the app? I really don't want users to lose their stored information on every update or bug fix I provide, so if that is the case, is there a way around this? A: Nope the files doesn't get deleted automatically, but it depends upon where you are storing the files. If the user deletes the app the files associated with it will get deleted too. But in case of an upgrade, No! normally it won't. In case you are using SQLite for storing data, there is a proper way to handle upgrade there.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551909", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jQuery Force set src attribute for iframe I have a main page (actually a JSP) with an iframe inside it as; <iframe name="abc_frame" id="abc_frame" src="about:blank" frameborder="0" scrolling="no"></iframe> Now there are multiple links on the main page (rendered dynamically via JSP) which can try to set the src to some URL... Now my question is,using jQuery (may be live()), can I override that in such a way that the "src" attribute for abc_frame would always have some particular value (e.g. "somefixedURL") I cannot capture the link clicking, as it is completely dynamically created via some Java code and hence I am trying to override the iframe src ? A: While generating the links set the target to the iframes name property and you probably wont have to deal with jquery at all. <a href="inventory.aspx" target="contentframe" title="Title Inventory"> <iframe id="iframe1" name="contentframe" ></iframe> A: $(document).ready(function() { $('#abc_frame').attr('src',url); }) A: Setting src attribute didn't work for me. The iframe didn't display the url. What worked for me was: window.open(url, "nameof_iframe"); Hope it helps someone. A: <script type="text/javascript"> document.write( "<iframe id='myframe' src='http://www.example.com/" + window.location.search + "' height='100' width='100%' >" ) </script> This code takes the url-parameters (?a=1&b=2) from the page containing the iframe and attaches them to the base url of the iframe. It works for my purposes. A: if you are using jQuery 1.6 and up, you want to use .prop() rather than .attr(): $('#abc_frame').prop('src', url) See this question for an explanation of the differences. A: Use attr $('#abc_frame').attr('src', url) This way you can get and set every HTML tag attribute. Note that there is also .prop(). See .prop() vs .attr() about the differences. Short version: .attr() is used for attributes as they are written in HTML source code and .prop() is for all that JavaScript attached to the DOM element. A: You cannot set FIX iframe's src or prevent javascript/form submit to change its location. However you can put script to onload of the page and change action of each dynamic link. A: $(".excel").click(function () { var t = $(this).closest(".tblGrid").attr("id"); window.frames["Iframe" + t].document.location.href = pagename + "?tbl=" + t; }); this is what i use, no jquery needed for this. in this particular scenario for each table i have with an excel export icon this forces the iframe attached to that table to load the same page with a variable in the Query String that the page looks for, and if found response writes out a stream with an excel mimetype and includes the data for that table.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551912", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "90" }
Q: How to change the radius of the circle around the marker in Google Map API I am trying to change the circle radius by changing the value of combo-menu. So I wrote the a function for onchange as below. function changeRadius(){ var selectedRadius = (document.getElementById("circle_radius").value)*1000; var circle = new google.maps.Circle({ map: map, radius: selectedRadius // radius unit is meter. }); var marker2 = new google.maps.Marker({ map: map, position: new google.maps.LatLng(40,-90), draggable: true, title: 'Drag me!' }); circle1.bindTo('center', marker2, 'position'); } But It doesn't work. Any idea? A: You'll have to do something like this: google.maps.event.addDomListener( document.getElementById('circle_radius'), 'change', function() { circle.setRadius(document.getElementById('circle_radius').value) }); with this function you'll set up a function as listener for the circle_radius combo value change event. The function will update the radius of your circle with the value of the combo.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551914", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Android Web request content format I want to format the content I get from a specific website to show it on my device . For example , from this page I need only the program titles and the description of each one . I get the html code for this page with this function : private String getPage() { String str = "***"; try { HttpClient hc = new DefaultHttpClient(); HttpPost post = new HttpPost("http://golfnews.no/golfpaatv.php"); HttpResponse rp = hc.execute(post); if(rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { str = EntityUtils.toString(rp.getEntity()); } }catch(IOException e){ e.printStackTrace(); } return str; } It returns a string which contains the html code. Now I want to have some strings containing the titles and other strings containing the description . I tried a few methods but I can't figure out what to do ! I am a beginner and I don't know much in android . Could you please help me ? Thanks. A: Instead of that URL, you just fetch RSS by using this link, and now parse the RSS either by using SAX Parser, DOM Parser or Pull Parser.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551916", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How get the values of a text field with mootools? Hi i have in my form a text field like this <input type="text" name="optionsArray[]" class="pollOptionInput"> and i want to get those values they can be value 1 = 123 value 2= foo value 3= bar etc the list can go on. i want to get those values so i can pass them to my controller via ajax. A: not sure if I read this correctly - are all the fields going to have the same name? if so, this works: var vals = document.getElements("input.pollOptionInput[name='optionsArray[]']").get("value"); console.log(vals); on markup <input type="text" value="foo" name="optionsArray[]" class="pollOptionInput"> <input type="text" value="boo" name="optionsArray[]" class="pollOptionInput"> <input type="text" value="bar" name="optionsArray[]" class="pollOptionInput"> results in: ["foo", "boo", "bar"] you need mootools 1.2+ to be guaranteed parsing of the name property as is, it will fail in 1.11/1.12 update: new Request.JSON({ 'method': 'post', 'url': en4.core.baseUrl + 'wall/createpoll/', 'data': { 'poll_title': poll_title, 'poll_description': poll_description, 'poll_privacy': poll_privacy, 'poll_comment': poll_comment, 'options': vals } }).send(); new Request.JSON({ 'method': 'post', 'url': en4.core.baseUrl + 'wall/createpoll/', 'data': document.id("formName") // serialize all input fields of a form. }).send();
{ "language": "en", "url": "https://stackoverflow.com/questions/7551917", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: package folder already used in project netbeans I am trying to create a new project in netbeans. But when I add folder in the projects it always throws error: "package folder already used in project netbeans". I deleted all folders in c:/users/../.netbeans/6.9/var/. Still I am getting the same issue. The error mentions a folder already packaged as some old package name, but that old package name is not available in my system folders. Can anyone please help me? A: I found the solution: Actually my folder already contained a pom.xml file. Due to that it was not taking the new projects. I found this solution from this link. A: If your existing project folder contains a sub folder called "nbproject" . Delete the folder and then add it .The folder contains files regarding previous net-beans related project settings. I am importing in Net-beans 7.2 from an earlier version. A: I had this problem and used all of the mentioned way but could not solve it. I change the name of folder that want to add and now it work properly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551921", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Error in getting row count using javascript I am trying to get the row count of grid view using javascript. Javascript is called but some how I am not getting row count. This is the code for my javascript <script language="javascript" type="text/javascript"> function CheckSites() { var Grid = document.getElementByID(<%=grdSiteInformation.ClientID%>); var row = Grid.rows.length; alert(grid); if(length=0) alert('Enter atleast one site'); } </script> This is how I am calling that function... <asp:Button ID="btnAdd" runat="server" Text="Save" OnClick="btnAdd_Click" OnClientClick="CheckSites()"/> This is the definition of my gridview <asp:GridView ID="grdSiteInformation" runat="server" AutoGenerateColumns="False" OnRowCommand="grdSiteInformation_RowCommand"> <Columns> <asp:BoundField DataField="TableRowIndex" HeaderText="Sr.No" /> <asp:BoundField DataField="SiteID" HeaderText="SiteID" /> <asp:BoundField DataField="POrderID" HeaderText="POrderID" /> <asp:BoundField DataField="SiteName" HeaderText="SiteName" /> <asp:BoundField DataField="Location" HeaderText="Location" /> <asp:BoundField DataField="SiteAddress" HeaderText="SiteAddress" /> <asp:BoundField DataField="Cluster" HeaderText="Cluster" /> <asp:BoundField DataField="SubVendorName" HeaderText="SubVendorName" /> <asp:TemplateField> <ItemTemplate> <asp:Button ID="btnEdit" runat="server" CommandArgument='<%# Eval("SiteID") %>' CommandName="Edt" Text="Edit" /> </ItemTemplate> <HeaderTemplate> Edit </HeaderTemplate> </asp:TemplateField> </Columns> </asp:GridView> Please guide me where/what I am making mistake mistake... Thanks A: Try var rowCount = document.getElementById('<%=grdSiteInformation.ClientID%>') .getElementsByTagName("TR").length; alert(rowCount); Edit Try jQuery var totalRows = $("#<%=GridView1.ClientID %> tr").length; A: If you are using Asp.Net's GridView and you just want row count then you can change your js function as: function CheckSites() { var row = <%=grdSiteInformation.Rows.Count %> if(row=0) alert('Enter at least one site'); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7551927", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Sorting an array once in a function which is called many times Is this possible? I have a function which accepts a user string and then splits into an array of words. I'm going to sort the array and de-duplicate it. However, it will be used in a function which is called in an iterative step. It actually iterates over a database and checks for each word in the user defines string in each field. I would like to only sort and de-dup the array once but call the function many for that particular instance of the class. Should I just store the sorted array in a static instance variable? Thanks for your time My code is something like this (pseudo-code): public class searchAssistant{ private float mScores[][]; private Cursor mCursor; public searchAssistant(Cursor c){ mCursor = c; } private float scoreType1(String typeFromCursor, String typeFromUser){ if (typeFromCursor == typeFromUser) {return 1} else {return 0} } //similar method for type scoreType2 but sorting an array private int[] scoreAll(){ int 1 = 0; do { mScores = ScoreType1(mCursor.getString(), smomeString) + scoreType2(...); itr++; } while(cursor.moveToNext) return mScores; } } is this the wrong way to be doing things? A: No. Change the signature of the method called multiple times to make it accept the array, and compute the array before calling the method: Instead of String s = "..."; while (someCondition) { someMethodCalledMultipleTimes(s); } Use something like this: String s = "..."; String[] array = computeTheArrayFormTheString(s); while (someCondition) { someMethodCalledMultipleTimes(array); } A: If all of this is happening in the same Thread, you can use a ThreadLocal to save the sort state: private static final ThreadLocal<Boolean> SORT_STATE = new ThreadLocal<Boolean>(){ protected Boolean initialValue(){return Boolean.FALSE;} }; public void doSomething(String[] array) { if(!SORT_STATE.get().booleanValue()){ // then sort the array here SORT_STATE.set(Boolean.TRUE); } // now do everything else } A: Should I just store the sorted array in a static instance variable "Static instance variable" is an oxymoron. You almost certainly shouldn't store it in a static variable. It might make sense to store it in an instance variable. This may have consequences for thread safety (don't know if that's relevant to your situation). If the iteration is performed by a function defined in the same class, it might make sense to do the sorting inside that outer function and simply pass the sorted array to the inner function every time you call it. A: You would store it in a non-static instance variable (there is no such thing as static instance variable - these are opposite things). If your application is not multithreaded you can do the sorting and dedupping the first time and than store the result. (Same if it's multithreaded, but then you need to use locking of some sort).
{ "language": "en", "url": "https://stackoverflow.com/questions/7551928", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: preg_match question, how to do this? Say I have the following: $var = "127.0.0.1 (127.0.0.1) 56(84) bytes of data. 64 bytes from 127.0.0.1: icmp_seq=1 ttl=57 time=19.5 ms --- 127.0.0.1 ping statistics --- 1 packets transmitted, 1 received, 0% packet loss, time 0ms rtt min/avg/max/mdev = 19.548/19.548/19.548/0.000 ms "; How can I return so it just says $var2 = "19.5"; So it basically grabs whats in this part: time=19.5 ms --- Thank you EDIT I think I have figured it out myself: $var = "127.0.0.1 (127.0.0.1) 56(84) bytes of data. 64 bytes from 127.0.0.1: icmp_seq=1 ttl=57 time=19.5 ms --- 127.0.0.1 ping statistics --- 1 packets transmitted, 1 received, 0% packet loss, time 0ms rtt min/avg/max/mdev = 19.548/19.548/19.548/0.000 ms"; $var2 = preg_match("/time=(.*) ms ---/", $var, $matches); print_r($matches[1]); I don't know if this is the right way to do it, but it seems to work? A: Try this: $var = "127.0.0.1 (127.0.0.1) 56(84) bytes of data. 64 bytes from 127.0.0.1: icmp_seq=1 ttl=57 time=19.5 ms --- 127.0.0.1 ping statistics --- 1 packets transmitted, 1 received, 0% packet loss, time 0ms rtt min/avg/max/mdev = 19.548/19.548/19.548/0.000 ms "; if(preg_match('/time=(\d+\.\d+)/', $var, $match)) { $var2 = $match[1]; echo $var2; } which will echo: 19.5 $match[1] will contain the entire match (time=19.5), in your case, and $match[1] contains match group 1 from the pattern: which is the number 19.5. A: preg_match("/time=([\d.]+).ms/",$var,$matches); //var_dump($matches) //$match[1] now holds the 19.5 ?> Enjoy A: This could do it with preg_match: if (preg_match("/time=(.*?) ms/", $line, $m)) { $time = (float) $m[1]; } Or with explode: $fields = explode("=", $line); $time = (float) $fields[4]; A: You could retrieve this with the following pattern: preg_match('/time=([^ ]+) /',$matches); echo $matches[1]; // 19.5 Matches after time= at least one character (+) that isn't a space ([^ ]). A: Use this regex in your preg_match call time=([\d\.]+) A: <?php $var="127.0.0.1 (127.0.0.1) 56(84) bytes of data. 64 bytes from 127.0.0.1: icmp_seq=1 ttl=57 time=19.5 ms --- 127.0.0.1 ping statistics --- 1 packets transmitted, 1 received, 0% packet loss, time 0ms rtt min/avg/max/mdev = 19.548/19.548/19.548/0.000 ms "; preg_match("/time=([0-9.]+)/", $var, $matches); $var2 = $matches[1]; echo $var2; ?> Edit: Or you can edit the regex to: preg_match("/time\s*=\s*([0-9.]+)/", $var, $matches); So that it matches "time=xx.x" or "time = xx.x".
{ "language": "en", "url": "https://stackoverflow.com/questions/7551934", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I resize the size of the cell.textLabel? I want to resize the default textLabel of a UITableViewCell because I display a image at the right of the rows. I Tryed with this code but it doesn't works, and I don't understand why. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { //... cell.textLabel.frame = CGRectMake(5, 5, 100, 50); //... } A: u should used custom label UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease]; UILabel *Lbl = [[UILabel alloc]initWithFrame:CGRectMake(75.0f, 4.5f, 360.0f, 20.0f)]; [cell.contentView addSubview:Lbl]; [Lbl release]; } A: I think that is impossible. Make custom cell. UILabel myTextLabel; //Set Frame and do something. [cell.contentView addSubview:myTextLabel]; A: textLabel is readonly property so we can't set frame.. @property(nonatomic,readonly,retain) UILabel *textLabel __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_3_0); // default is nil. label will be created if necessary. @property(nonatomic,readonly,retain) UILabel *detailTextLabel __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_3_0); // default is nil. label will be created if necessary (and the current style supports a detail label). use custom cell ... A: You can not change a cell's textLabel's frame except or you go with custom cell and use UILabel, UIImageView as a subview of the cell.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551940", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Getting certificate chain to a private root I'm trying to verify that the certificate from a signature chains back to a particular root certificate, which is not trusted by Windows (it's a private certificate for the app). My current attempt to do this involves creating a chaining engine which only trusts the specific certificate I want as the root, so that no other chains can be generated. HCERTSTORE hPrivateRootStore = CertOpenStore(CERT_STORE_PROV_FILENAME, dwEncoding, NULL, CERT_STORE_OPEN_EXISTING_FLAG | CERT_STORE_READONLY_FLAG, _T("C:\\Test\\PrivateRoot.cer")); CERT_CHAIN_ENGINE_CONFIG config; memset(&config, 0, sizeof(config)); config.cbSize = sizeof(config); config.hRestrictedTrust = hPrivateRootStore; config.dwFlags = CERT_CHAIN_CACHE_ONLY_URL_RETRIEVAL | CERT_CHAIN_ENABLE_SHARE_STORE; HCERTCHAINENGINE hEngine; CertCreateCertificateChainEngine(&config, &hEngine); CERT_CHAIN_PARA params; memset(&params, 0, sizeof(params)); params.cbSize = sizeof(params); PCCERT_CHAIN_CONTEXT chains = NULL; if (CertGetCertificateChain(hEngine, pCertContext, NULL, hStore, &params, 0, NULL, &chains)) ... (error checking omitted for clarity; pCertContext and hStore came from CryptQueryObject extracting the signature and related certificates from a signed binary file.) Unfortunately, this doesn't seem to work; despite using a custom chaining engine it still seems to be searching the OS store, and either doesn't find a chain or finds one to a different root (which is trusted by the OS). I can only get the chain I want by adding my private root certificate to the OS trusted store. I've also tried setting config.hRestrictedOther to an empty memory store, since the docs suggest that having hRestrictedTrust non-NULL will bring in the system stores again, but that doesn't make any difference. Is there something I'm missing, or a better way to do this? Edit: just to give a bit more context, I'm trying to do something similar to the driver signing certificates, where the signing certificate chains back to two different roots: one standard CA root trusted by the OS and one internal root (which in drivers is also trusted by the OS but in my case will only be trusted by my app). The cross occurs somewhere mid-way up the "main" chain; there could potentially be a number of different files all signed with different "real" CAs but still chained back to my internal certificate. A: I've found a half-baked workaround now; it's a little ugly but it does kinda work. I got the basic idea from Chromium's test suite; it involves installing a hook into Crypt32 such that when it tries to open the system stores to build the chain it gets my custom store instead, containing only my desired certificate. The good is that this seems to force CertGetCertificateChain to go "past" the real CA certificate and chain all the way to my custom certificate, instead of stopping at the CA certificate (which is what it usually does when that is trusted). The bad is that it doesn't seem to stop it from building chains to and trusting any other CA certificate. I can work around that by explicitly verifying that the root of the chain is the certificate I wanted, but it's less than ideal, and I'm not sure if there are situations which will trip it up. Still looking for any better solutions; I'm definitely getting the impression that I'm taking the wrong path somewhere. Ok, new plan. I'm now just walking the chain manually (since I know that all of the certificates I care about will be in the hStore extracted from the signed .exe), with basic structure like this: * *Use WinVerifyTrust to do basic "is it not tampered" authentication. *Use CryptQueryObject to obtain certificate store hStore from the .exe *Use CryptMsgGetParam and CertFindCertificateInStore to find the signing certificate from hStore. *Starting from the signing certificate, use CertFindCertificateInStore with CERT_FIND_SUBJECT_NAME in a loop to find the potential issuer certificates; keep walking back until I hit a self-signed certificate or find my desired root (checking for a match via CertComparePublicKeyInfo). *Abandon a particular branch if CertVerifySubjectCertificateContext says that the signatures don't match. Seems cleaner than the previous approaches I was trying. Thoughts/comments/alternatives? (Something which in some ways does seem to make more sense would be to add an additional custom countersignature [similar to the timestamping] instead of trying to chain certificates like this, but I can't find any information on doing that, or what the pros/cons are.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7551942", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How do I compare the performance of Node.js to that of PHP on Apache this might have been asked many times but, I want the specific performance testing methodology. I am having second thoughts on porting my application from PHP to Node.js since it involves some realtime data. If the performance tests that I make are satisfactory, then I think I will introduce some new modules which include realtime data. Please can anyone help me with the task of how to test the performance. Thanks. A: I think this question has been asked already. But since you ask "how" it's done, you might want to use Apache Utilities which can be used to benchmark the performance. This article walks through how one person used 'ab' to generate traffic, and dstat to monitor cpu and memory.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551946", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Frontend ajax framework work with Grails I have some knowledge about Flex and Java EE, they are good for web application development. Anyway when I try to write a typical web page that is based on HTML/CSS/Javascript, I think I should take a look at some new program language/framework. I heard much good news about grails and finally decided to learn it instead of python, ruby, scale… But I still don’t have an overview of the whole structure. Grails is a backend framework like php, jsp, jsf right? So that probably means, it’s a replacement of Java EE in backend, then how about the frontend (need ajax functionality), what are people using with grails? thanks A: Grails is not a replacement, it is an abstraction around the tradition Java EE stack and some extremely popular libraries like Spring and Hibernate, that allows you to go faster by using "convention over configuration". One component of Grails is GSPs, groovy server pages, which is a front end technology, the V in the MVC (Model View Controller) paradigm. You also have Domain Objects, which are the M (Model), and Controllers, which are the C. Grails also has Services which are best put into the M category (IMHO) of the MVC paradigm. So the Model arrangement in Grails gives you relatively easy persistence (using hibernate under the covers), the Services give you great reusability in your business and transactional logic, and the Controller simply invoke the right logic for a given request, and return the response. One part of that response is what gets displayed on the screen. In a simple webapp, GSPs fill that role -- the controller tells the browser to render a specific GSP which has data bound to it from the service method that was invoked in the controller. However, it is easy to have the controller return json, so if the endpoint bound to the controller is an ajax request, the client can handle the response itself. You can use any front end technology you want in a grails app. The default is GSPs, which is an extension of JSPs, which are part of the traditional java stack, but you can use jQuery, Sencha, Sproutcore, Backbone, anything you want. You would have one GSP in that case which bootstraps your javascript code, and the rest would be handled by the client application. A: Grails is a web framework and is not just a backend framework. It supports both JSP and GSP ( Groovy Server Pages) for views. If you plan to use Ajax functionality, you can make use of one of many javascript frameworks available. You can also go ahead with Flex (since you already know it) or use a javascript framework like ExtJs, Dojo, YUI etc...
{ "language": "en", "url": "https://stackoverflow.com/questions/7551959", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using REST as Business Logic Layer ,Con and Pro I am thinking of creating an Application as i shown in the figure, i am creating the presentation layer in PHP, where JAX-RS REST Service is working as Business Layer and JPA as Data Object Layer My Question is 1)Is this arch secure? 2)Is this arch Scale? 3)IS there any other problem in my Arch? A: This is a quite generic question (e.g. like "I am going to by a car. 1) is it fast 2.) is it secure") However, there are some things to say here: * *The question is not, if the "architecture" is secure, but if you can make the services that you are using secure. If you are using e.g. Tomcat for the rest services, they will be as secure as you can make tomcat secure. *Since there is (or should be) no state in REST-services, this should scale well, provided you find the right granularity for your services and do not introduce artificial state-handling. If you attach a load-balancer in front of the REST-Services, each call could be sent to another machine (or process). This will most likely lead to the database being your bottleneck. *Yes and no. What you describe as architecture is very generic. Basically there is no problem in it if you do it right. But you can produce a lot of problems with it if you do it wrong. Conclusion: Security and scale will depend on the details and the components you are using. Basically an architecture-type like the on you chose should provide a good basis for a scalable architecture (and implementation).
{ "language": "en", "url": "https://stackoverflow.com/questions/7551961", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Working with DatePicker with some restrictions on Date and Time I am working with DatePicker and I want to set specific restrictions on the selection of Date Picker by user,I want the start day of the week - tuesday end day of the week - saturday start time - 16:00:00 end time - 19:00:00 So friends please share your thoughts on this. Whether we should use NSDateComponents. A: You can use next properties of UIDatePicker: The minimum date that a date picker can show: @property(nonatomic, retain) NSDate *minimumDate The maximum date that a date picker can show: @property(nonatomic, retain) NSDate *maximumDate A: You can set maximum and minimum limit to UIDatePicker as given, NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"MM-dd-yyyy HH:mm:ss"]; NSDate *startDate = [dateFormatter dateFromString:@"04-16-1983 20:30:15"]; NSDate *endDate = [dateFormatter dateFromString:@"10-16-1983 10:20:30"]; UIDatePicker *datePicker = [[UIDatePicker alloc] init]; [datePicker setMinimumDate:startDate]; [datePicker setMaximumDate:endDate]; Hope this will help you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551970", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Should an object "load" another object on its own, or have the other passed to it? Is it a good practice to load another object from within an original object, like so: Class parent() { $child; function loadChild() { $child = new Child(); $this->child = $child; } } or, should the child object always be passed in separately? Class parent() { $child; function setChild(child $child) { $this->child = $child; } } $parent = new Parent(); $child = new Child(); $parent->setChild($child); Which is the better option, more flexible etc? A: The second option is more appropriate. It's called Dependency Injection. One of the main reasons to it is that you can pass any object that implements child interface (including mock object, which is important for TDD) without need to modify your class. A: It depends on the situation. The name of the second object suggests that * *the Child instance will only be used by the Parent instance *does not need to live longer than the Parent instance If this is the case, than the first pattern (Object composition pattern) is the better one. If the Child instance is needed/used at other places in you code, the second pattern (Dependency injection) is more appropriate. Dependency Injection is a more flexible pattern, if you are unsure about your use case, you should generally use the Dependency Injection. A: Depence on what you want. If you are sure you do not need to change child ever you can create it in the object. Less code => less errors. But if you might want to have different Childs later this would be bad.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551971", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Convert this linq code to expression Can an expert in C# helps me to convert this linq code into Expression trees ? var settingViewModels = from l in settingsByEnvironment["Localhost"] from d in settingsByEnvironment["Dev"] from p in settingsByEnvironment["Prod"] where l.Key == d.Key && p.Key == d.Key select new MyKeyValue { Key = p.Key, LocalhostValue = l.Value, DevValue = d.Value, ProdValue = p.Value }; Thanks ! A: var settingViewModels = from l in settingsByEnvironment["Localhost"].AsQueryable() from d in settingsByEnvironment["Dev"].AsQueryable() from p in settingsByEnvironment["Prod"].AsQueryable() where l.Key == d.Key && p.Key == d.Key select new MyKeyValue { Key = p.Key, LocalhostValue = l.Value, DevValue = d.Value, ProdValue = p.Value }; var expression = settingsViewModels.Expression;
{ "language": "en", "url": "https://stackoverflow.com/questions/7551972", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to scroll images vertically in blackberry All the screens I've designed for BlackBerry so far I set the position coordinates statically, without the need of a vertical scroll. I do not understand how to use this vertical manager to scroll and see the list. A: We have to create vertical field manager as follow VerticalFieldManager manager= new VerticalFieldManager( Manager.VERTICAL_SCROLL | Manager.VERTICAL_SCROLLBAR ); to scroll fields in vertical field manager. The following link will also help you. How to set a ScrollBar to the VerticalFieldManager in Blackberry?
{ "language": "en", "url": "https://stackoverflow.com/questions/7551973", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Split a string (that contains tags) by spaces without breaking the tags or tag inner html in Javascript I'm attempting to split a string by spaces into an array of words. If the string contains HTML tags, I would like the full tag (including content) to be treated as a single word. For example, I like to eat <a href="http://www.waffles.com/">tasty delicious waffles</a> for breakfast should split into I like to eat <a href="http://www.waffles.com/">tasty delicious waffles</a> for breakfast I've seen a couple related threads on Stack Overflow but I'm having trouble adapting anything to Javascript because they were written for languages that I'm not quite familiar with. Is there a regex expression that could easily do this or will the solution require multiple regex splits and iteration? Thanks. A: result = subject.match(/<\s*(\w+\b)(?:(?!<\s*\/\s*\1\b)[\s\S])*<\s*\/\s*\1\s*>|\S+/g); will work if your tags can't be nested, if all tags are properly closed, and if current tag names don't occur in comments, strings etc. Explanation: <\s* # Either match a < (+ optional whitespace) (\w+\b) # tag name (?: # Then match... (?! # (as long as it's impossible to match... <\s*\/\s*\1\b # the closing tag here ) # End of negative lookahead) [\s\S] # ...any character )* # zero or more times. <\s*\/\s*\1\s*> # Then match the closing tag. | # OR: \S+ # Match a run of non-whitespace characters. A: This is hard or impossible to do with regexp alone (depending on the complexity of HTML that you want/need to allow). Instead, iterate over the children of the parent node and split them if they are text nodes or print them unmodified if they are non-text nodes.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551974", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to generate an identity column in hyperion interactive reporting? I want to display an auto-incremented series (basically the row number) in a new column. How do I go about doing this in Hyperion Interactive Reporting ? A: Create a new computed column and assign it a value of 1. Then, create another computed column which will have a cumulative sum of the previous computed column. The function to be used is Cume().
{ "language": "en", "url": "https://stackoverflow.com/questions/7551983", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Geocoding Requests problem? http://code.google.com/apis/maps/documentation/geocoding/ I learned from here sending a request. First time when I am sending request it's fine I am receiving the responce. But when I am sending the second requst the reponce is "REQUEST_DENIED" indicates that your request was denied, generally because of lack of a sensor parameter. What's that mean? Is there any way that I can send requests and receive all responses? A: If you develop for Android you should take a look at GeoCoder class. It presumably uses the same background service, but it's all nicely packed, so you do not need to bother with details. One note: this is only available if the device is a "Google" device, i.e. if it has Market on it: Why is Android Geocoder throwing a "Service not Available" exception?
{ "language": "en", "url": "https://stackoverflow.com/questions/7551985", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Questions about duplicating last object of a NSArray I've a NSArray of MyObjects. I want to duplicate the last object of my array. In other terms, I want to add a new object to the array that's exactly the same of the last one. I tried with: id object = [[self arrangedObjects] lastObject]; id newObject = [object copy]; But I've realized that I can't use copy method, because it is not implemented in NSObject. Should I implement the copy method in MyObject class, returning a new instance of MyObject and change the code as follows: MyObject object = [[self arrangedObjects] lastObject]; MyObject newObject = [object copy]; Or are there other solutoins ? UPDATE From NSObject documentation NSObject does not itself support the NSCopying protocol. Subclasses must support the protocol and implement the copyWithZone: method. A subclass version of the copyWithZone: method should send the message to super first, to incorporate its implementation, unless the subclass descends directly from NSObject. A: If your objects are NSObject, you can make a new NSObject category that implements the NSCopying Protocol. Be sure to iterate through all keys and copy their value to your new object. For deep copying you should also call 'copy' on each of its value objects. If your object is custom, implement the protocol in it's class. If you have mixed objects in the array, all of them must implement NSCopying protocol therefor you can use id<NSCopying> when you declare them to avoid a compile time warning/error. A: As far as I know, if you want to copy an object, implement the NSCopying protocol, which lets you use NSObject - (id)copy method. In the - (id)copyWithZone:(NSZone *)zone method, allocate a new object using + (id)allocWithZone:(NSZone *)zone then copy its members, update its states, and so on
{ "language": "en", "url": "https://stackoverflow.com/questions/7551987", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Entity Framework 4: Many to Many relationship IQueryable instead of ICollection Good morning everyone, I am trying to tackle a problem I run into with EF code first. My schema is the following public class Article : IUrlNode { [Key] public Guid ArticleID { get; set; } public string Title { get; set; } public DateTime DateCreated { get; set; } public DateTime DateUpdated { get; set; } public string Summary { get; set; } [System.ComponentModel.DataAnnotations.InverseProperty("CategoryArticles")] public virtual IQueryable<Category> ArticleCategories { get; set; } public string FriendlyUrl { get; set; } } [RouteChild("CategoryArticles")] public class Category : ContentNode { public Guid ServiceId { get; set; } [System.ComponentModel.DataAnnotations.InverseProperty("ArticleCategories")] public virtual IQueryable<Article> CategoryArticles { get; set; } } I have written code with which I am able to retrieve a category from the database without actually knowing that its a category. From then on I must retrieve a single article of that category again without knowing that its an article. For categories I am relying on the ContentNode base class and for Articles on the IUrlNode interface. Category retrieval works fine and with a single query but after I actually get the category I have to use reflection to get the navigation property pointed by the RouteChild attribute to find that single article that matches my criteria. Problem is that the navigation property type is ICollection which means that it will at best use lazy loading and will bring all the articles from the database and will find the one I am looking for in memory. My problem is also described in this previous post (not by me): Entity Framework Code First IQueryable Is there a way to have that navigation property as IQueryable or some other design that can go around this limitation? A: No there is no way to have navigation property as IQueryable but you can change the collection to IQueryable by using: IQueryable<Article> query = context.Entry(category).Collection(c => c.articles).Query(); query.Where(...).Load(); Generally your "algorithm" looks pretty strange. You want to work with base class but in the same time you want to access child properties. That sounds wrong and it can most probably be solved in better way (non "generic" way is also better).
{ "language": "en", "url": "https://stackoverflow.com/questions/7551988", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Add a new column to the file How can I add a new column to a file using awk? original.file F1 F2 F3 ..F10 add F11 to original.file F1 F2 F3 ..F10 F11 A: awk '{print $0, "F11"}' original.file A: If you want to add a column to a file, you can do the following. remark: We assume that the field separator FS equals to the string "fs". You can replace this by anything, or if you just use <blanks> as field separator, you can remove the BEGIN{FS=OFS="fs"} part in any of the following solutions. add a column at the beginning: awk 'BEGIN{FS=OFS="fs"}{print value OFS $0}' file add a column at the end: awk 'BEGIN{FS=OFS="fs"}{print $0 OFS value}' file add a column before column n: awk 'BEGIN{FS=OFS="fs"}{$n = value OFS $n}1' file add column after column n: awk 'BEGIN{FS=OFS="fs"}{$n = $n OFS value}1' file add a column before each of column n1 < n2 < ... < nm: (start at the back) awk 'BEGIN{FS=OFS="fs"; split("n1,n2,n3,...,nm",a,",")} {for(i=m;i>0;--i) $(a[i]) = value OFS $(a[i])}1' file or for different values awk 'BEGIN{FS=OFS="fs"; split("n1,n2,n3,...,nm",a,","); split("value1,value2,...,valuem",v,",")} {for(i=m;i>0;--i) $(a[i]) = v[i] OFS $(a[i])}1' file add a column after each of column n1 < n2 < ... < nm: (start at the back) awk 'BEGIN{FS=OFS="fs"; split("n1,n2,n3,...,nm",a,",")} {for(i=m;i>0;--i) $(a[i]) = $(a[i]) OFS value}1' file or for different values awk 'BEGIN{FS=OFS="fs"; split("n1,n2,n3,...,nm",a,","); split("value1,value2,...,valuem",v,",")} {for(i=m;i>0;--i) $(a[i]) = $(a[i]) OFS v[i]}1' file A: try: awk 'BEGIN{getline to_add < "f3"}{print $0,to_add}' f Reads the column to add from file "f3" and saves it in the variable to_add. After that it adds the column to each line of file f. HTH Chris
{ "language": "en", "url": "https://stackoverflow.com/questions/7551991", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "21" }
Q: Pass POST data via raw HTTP For testing purposes, I need to send some raw POST data to a page I set up on my web server. The page is working fine. I have tested sending data to via another web page as well as a C# application. However, I want to try passing raw HTTP data to it as well. How can I do that? What client will enable me to do that? I'm looking to pass data to the page in the following form: POST /login.jsp HTTP/1.1 Host: www.mysite.com User-Agent: Mozilla/4.0 Content-Length: 27 Content-Type: application/x-www-form-urlencoded userid=joe&password=guessme A: If you want it real raw, use telnet. If you want something more high-level — you can use curl. A: You could use a Javascript Ajax library, both jQuery and Prototype JS allow you to easily modify headers and Post data.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551997", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How can this SQL be improved? (MySQL database) SELECT * FROM inventory WHERE inventory.zip IN (93650,93750,93765,93729,93710,93740,93711,93720,93704,93741,93705,93755,93791,93790,93794,93793,93726,93792) AND inventory.price >= 1000 AND inventory.year BETWEEN 1977 AND 2011 ORDER BY price ASC LIMIT 0, 25 The database is MySQL InnoDB tables (switching to MyISAM to see how it works). The table has about 500,000 records and the fields searched are indexed. It takes very long until I get the results and sometimes I get Internal Server Error. How can the query be improved? A: Study the execution plan for the query. In MySql this is done using the explain command EXPLAIN SELECT * FROM inventory WHERE inventory.zip IN (93650,93750,93765,93729,93710,93740,93711,93720,93704,93741,93705,93755,93791,93790,93794,93793,93726,93792) AND inventory.price >= 1000 AND inventory.year BETWEEN 1977 AND 2011 ORDER BY price ASC LIMIT 0, 25 This should give you the execution plan. With that, you can see if it's properly using indexes or if one of your conditions is provoking a full table scan. If it does, either you need another index or you might need to modify the query itself.
{ "language": "en", "url": "https://stackoverflow.com/questions/7552005", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Xcode for distance between two locations in google maps Possible Duplicate: Calculate distance between two locations using google map in iphone I just want to complete xcode for calculate distance between two location . In which user can enter both the location's addresses, and from that addresses I want to calculate the distance between them b,coz am new to xcode. Please send a link/code as soon as possible Thank you A: From addresses you have to take the latitude and longitudes. like this NSString *urlString = [NSString stringWithFormat:@"http://maps.google.com/maps/geo?q=%@&output=csv", theAddress]; NSString *locationString = [[[NSString alloc] initWithContentsOfURL:[NSURL URLWithString:urlString]] autorelease]; NSArray *splitArray = [[[NSArray alloc] initWithArray:[locationString componentsSeparatedByString:@","]] autorelease]; if([splitArray count]!=0) { MKCoordinateRegion region; region.center.latitude = [[splitArray objectAtIndex:2] doubleValue]; region.center.longitude = [[splitArray objectAtIndex:3] doubleValue]; region.span.latitudeDelta = 0.01; // Add a little extra space on the sides region.span.longitudeDelta = 0.01; // Add a little extra space on the sides region = [mapView regionThatFits:region]; [mapView setRegion:region animated:YES]; CLLocation *firstLocation= [[CLLocation alloc]initWithLatitude:[[splitArray objectAtIndex:2] doubleValue] longitude:[[splitArray objectAtIndex:3] doubleValue]]; //in the sameway for secondlocation also CLLocationDistance distance = [firstLocation distanceFromLocation:secondLocation];
{ "language": "en", "url": "https://stackoverflow.com/questions/7552010", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-4" }
Q: Flex RSL Error: the loaded file did not have a valid signature I'm using Flex SDK 4.5 to create swf files, recently I got the following error when try to open my swf file: [trace] Warning: Ignoring 'secure' attribute in policy file from http://fpdownload.adobe.com/pub/swz/crossdomain.xml. The 'secure' attribute is only permitted in HTTPS and socket policy files. See http://www.adobe.com/go/strict_policy_files for details. [trace] Error #2046: The loaded file did not have a valid signature. [trace] Failed to load RSL http://fpdownload.adobe.com/pub/swz/flex/4.5.1.21328/framework_4.5.1.21328.swz [trace] Failing over to RSL framework_4.5.1.21328.swz I totally have no idea whats going on with rsl loading step. Any idea how to solve this without have to statically linking rsl into swf file ? A: Please check your mime-type setup for .swz, at least in my case trying to load signed Adobe framework SDK libraries 4.5.1 from application folder rather than from Adobe was achieved by adding mime type in Apache http.conf as follows AddType application/x-shockwave-flash .swz A: This error normally pops up because the compiled application is using a different framework version than the one you're trying to load through RSLs. Flash Player verifies the filesize digest of the RSLs before being loaded because if a different framework is being loaded in than the one specified by the application, it can cause erratic behavior. I would imagine you're trying to do this through Flash Builder. If that's the case, you should download the flex sdk of the same version number and build on that for it to work. If not, you'll have to make sure the RSL points to the same version as what you're compiling with. A: Another cause of this problem can be when the clock on the user's computer is set to the wrong time/date. I know this sounds weird, but it has something to do with how the signatures on the swz files are interpreted. This was the solution for one of our customers.
{ "language": "en", "url": "https://stackoverflow.com/questions/7552013", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: JPA monitor for persistence context How convinion debug state of persistence context, watch result of queries, monitor all entities? Is some JPA monitor for this? A: If you are using EclipseLink, there is a performance monitor option, see, http://wiki.eclipse.org/EclipseLink/UserGuide/JPA/Advanced_JPA_Development/Performance/Performance_Monitoring_and_Profiling/Performance_Monitoring You can also configure logging, http://wiki.eclipse.org/EclipseLink/Examples/JPA/Logging
{ "language": "en", "url": "https://stackoverflow.com/questions/7552014", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to addAttributeToFilter? I am trying to get Collection of all available products in Magento & Filter that collection Here is my code: $searcher = Mage::getModel('catalog/product')->getCollection(); $searcher->addAttributeToSelect('name'); echo count($searcher); $searcher->addAttributeToFilter('name',array('like' => 'paper')); $searcher->load(); echo count($searcher); Now first time it gives count 745(FOR ALL PRODUCTS) but after filtering it still shows 745. A: EDIT: This works for me: $searcher = Mage::getModel('catalog/product')->getCollection() ->addAttributeToSelect('name') ->addAttributeToFilter('name',array('eq' => 'paper')); $searcher->load(); echo count($searcher);
{ "language": "en", "url": "https://stackoverflow.com/questions/7552018", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to execute UNION without sorting? (SQL) UNION joins two results and remove duplicates, while UNION ALL does not remove duplicates. UNION also sort the final output. What I want is the UNION ALL without duplicates and without the sort. Is that possible? The reason for this is that I want the result of the first query to be on top of the final result, and the second query at the bottom (and each sorted as if they where run individually). A: I notice this question gets quite a lot of views so I'll first address a question you didn't ask! Regarding the title. To achieve a "Sql Union All with “distinct”" then simply replace UNION ALL with UNION. This has the effect of removing duplicates. For your specific question, given the clarification "The first query should have "priority", so duplicates should be removed from bottom" you can use SELECT col1, col2, MIN(grp) AS source_group FROM (SELECT 1 AS grp, col1, col2 FROM t1 UNION ALL SELECT 2 AS grp, col1, col2 FROM t2) AS t GROUP BY col1, col2 ORDER BY MIN(grp), col1 A: SELECT *, 1 AS sort_order FROM table1 EXCEPT SELECT *, 1 AS sort_order FROM table2 UNION SELECT *, 1 AS sort_order FROM table1 INTERSECT SELECT *, 1 AS sort_order FROM table2 UNION SELECT *, 2 AS sort_order FROM table2 EXCEPT SELECT *, 2 AS sort_order FROM table1 ORDER BY sort_order; But the real answer is: other than the ORDER BY clause, the sort order will by arbitrary and not guaranteed. A: Consider these tables (Standard SQL code, runs on SQL Server 2008): WITH A AS ( SELECT * FROM ( VALUES (1), (2), (3), (4), (5), (6) ) AS T (col) ), B AS ( SELECT * FROM ( VALUES (9), (8), (7), (6), (5), (4) ) AS T (col) ), ... The desired effect is this to sort table A by col ascending, sort table B by col descending then unioning the two, removing duplicates, retaining order before the union and leaving table A results on the "top" with table B on the "bottom" e.g. (pesudo code) ( SELECT * FROM A ORDER BY col ) UNION ( SELECT * FROM B ORDER BY col DESC ); Of course, this won't work in SQL because there can only be one ORDER BY clause and it can only be applied to the top level table expression (or whatever the output of a SELECT query is known as; I call it the "resultset"). The first thing to address is the intersection between the two tables, in this case the values 4, 5 and 6. How the intersection should be sorted needs to be specified in SQL code, therefore it is desirable that the designer specifies this too! (i.e. the person asking the question, in this case). The implication in this case would seem to be that the intersection ("duplicates") should be sorted within the results for table A. Therefore, the sorted resultset should look like this: VALUES (1), -- A including intersection, ascending (2), -- A including intersection, ascending (3), -- A including intersection, ascending (4), -- A including intersection, ascending (5), -- A including intersection, ascending (6), -- A including intersection, ascending (9), -- B only, descending (8), -- B only, descending (7), -- B only, descending Note in SQL "top" and "bottom" has no inferent meaning and a table (other than a resultset) has no inherent ordering. Also (to cut a long story short) consider that UNION removes duplicate rows by implication and must be applied before ORDER BY. The conclusion has to be that each table's sort order must be explicitly defined by exposing a sort order column(s) before being unioned. For this we can use the ROW_NUMBER() windowed function e.g. ... A_ranked AS ( SELECT col, ROW_NUMBER() OVER (ORDER BY col) AS sort_order_1 FROM A -- include the intersection ), B_ranked AS ( SELECT *, ROW_NUMBER() OVER (ORDER BY col DESC) AS sort_order_1 FROM B WHERE NOT EXISTS ( -- exclude the intersection SELECT * FROM A WHERE A.col = B.col ) ) SELECT *, 1 AS sort_order_0 FROM A_ranked UNION SELECT *, 2 AS sort_order_0 FROM B_ranked ORDER BY sort_order_0, sort_order_1; A: "UNION also sort the final output" - only as an implementation artifact. It is by no means guaranteed to perform the sort, and if you need a particular sort order, you should specify it with an ORDER BY clause. Otherwise, the output order is whatever is most convenient for the server to provide. As such, your request for a function that performs a UNION ALL but that removes duplicates is easy - it's called UNION. From your clarification, you also appear to believe that a UNION ALL will return all of the results from the first query before the results of the subsequent queries. This is also not guaranteed. Again, the only way to achieve a particular order is to specify it using an ORDER BY clause. A: select T.Col1, T.Col2, T.Sort from ( select T.Col1, T.Col2, T.Sort, rank() over(partition by T.Col1, T.Col2 order by T.Sort) as rn from ( select Col1, Col2, 1 as Sort from Table1 union all select Col1, Col2, 2 from Table2 ) as T ) as T where T.rn = 1 order by T.Sort A: Try this: SELECT DISTINCT * FROM ( SELECT column1, column2 FROM Table1 UNION ALL SELECT column1, column2 FROM Table2 UNION ALL SELECT column1, column2 FROM Table3 ) X ORDER BY Column1 A: The sort is used to eliminate the duplicates, and is implicit for DISTINCT and UNION queries (but not UNION ALL) - you could still specify the columns you'd prefer to order by if you need them sorted by specific columns. For example, if you wanted to sort by the result sets, you could introduce an additional column, and sort by that first: SELECT foo, bar, 1 as ResultSet FROM Foo WHERE bar = 1 UNION SELECT foo, bar, 2 as ResultSet FROM Foo WHERE bar = 3 UNION SELECT foo, bar, 3 as ResultSet FROM Foo WHERE bar = 2 ORDER BY ResultSet A: I assume your tables are table1 and table2 respectively, and your solution is; (select * from table1 MINUS select * from table2) UNION ALL (select * from table2 MINUS select * from table1) A: 1,1: select 1 from dual union all select 1 from dual 1: select 1 from dual union select 1 from dual A: You can do something like this. Select distinct name from (SELECT r.name FROM outsider_role_mapping orm1 union all SELECT r.name FROM user_role_mapping orm2 ) tmp;
{ "language": "en", "url": "https://stackoverflow.com/questions/7552019", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "36" }