text
stringlengths
8
267k
meta
dict
Q: Is there a way to get all controllers in an ExtJS 4.0 application I'm building an app using ExtJS 4.0's new MVC architecture. I'm looking for a way to iterate over all the controllers in the app. below I've put some sample code to give an idea of what I'm trying to do. Ext.application({ name: 'MyApp', appFolder: '/App', controllers: [ 'HdMenuItemsController' ], launch: function () { //This works: this.getController('HdMenuItemsController') //I want to do something like this: this.controllers.each(myFunction); //or this: this.getAllControllers().each(myFunction); //or this: Ext.getControllersForApp(this).each(myFunction); } }); A: No built in way that I know of (and I am kinda curious why you would need to do this), but you can accomplish this as follows (place this in your launch() function as you have in your example): this.controllers.each(function(item, index, length){ var myController = this.getController(item.id); //now do something with myController! //OR: this.getController(item.id).someFunction(); //where someFunction() is defined in all of your controllers });
{ "language": "en", "url": "https://stackoverflow.com/questions/7503761", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Fix for unreadable ghostscript font I'm using the ruby Scruffy gem to create some graphs. It relies on RMagick to render the text and create the pngs. When I run my ruby script I get this error. sh: gs: command not found sh: gs: command not found /Users/natebird/.rvm/gems/ree-1.8.7-2011.03/gems/scruffy-0.2.6/lib/scruffy/rasterizers/rmagick_rasterizer.rb:15:in `from_blob': unable to read font `/usr/local/share/ghostscript/fonts/n019003l.pfb' @ error/annotate.c/RenderFreetype/1128: `(null)' (Magick::ImageMagickError) from /Users/natebird/.rvm/gems/ree-1.8.7-2011.03/gems/scruffy-0.2.6/lib/scruffy/rasterizers/rmagick_rasterizer.rb:15:in `rasterize' from /Users/natebird/.rvm/gems/ree-1.8.7-2011.03/gems/scruffy-0.2.6/lib/scruffy/graph.rb:164:in `render' from autobench_grapher.rb:61:in `generate_graph' from autobench_grapher.rb:30:in `run' from autobench_grapher.rb:15:in `run' from autobench_grapher.rb:91 A: You need to install ghostscript (see: gs: command not found). How you do this depends on what platform you are on.
{ "language": "en", "url": "https://stackoverflow.com/questions/7503764", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: How to send the browser to an error page if part of the response has been sent (chunked) This is typical scenario: a page is evaluated, and there's a buffer - once the buffer is full, the part of the page that is evaluated is sent to the browser. This uses the HTTP 1.1 chunked encoding. However, an error can occur in one of the chunks (after the first one is already sent). In that case: * *you can't redirect (send a Location header), because the headers and the response status were already sent *you can't do server-side redirect (forward), because the new page will have to be rendered after the part that is already sent - it will look ugly for sure. So what should you do in this case? I asked a question whether you can send a Location header in the chunked trailer, but this is low-level http and the abstraction of languages may not allow it, even if it is possible (and it is likely not to be supported across browsers) Another option is to send a <script>window.href.location="errorPage"</script> and thus force the client to redirect, but that's ugly. Plus you have to put </script> to close any potential unclosed <script> tag in the partial page. (I'm tagging major web languages/frameworks, because this is an universal issue) A: You cannot redirect from the server in a chunked encoding because the headers have already been sent. The only way to perform a redirect is to send a <script> tag from the server and perform a client side redirect. Just out of curiosity are you trying to implement a COMET server? If this is the case HTML5 WebSockets seem better way (if the browsers you are targeting support them of course) compared to the hidden iframe technique.
{ "language": "en", "url": "https://stackoverflow.com/questions/7503765", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: JQTouch execute javascript when External page is loaded with Ajax I'm using the built in JQtouch method of loading an external php page like this: <li class="arrow"><a href="get_products.php?eId='.$classCode_id.'&sName='.$sectionName.'">'.$sectionName.'</a> </li> This is working great. However I need to have some javascript run when get_product.php loads. I tried including it in the php page itself but it doesn't get executed. Any ideas?
{ "language": "en", "url": "https://stackoverflow.com/questions/7503768", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Drawing shapes in textboxes Is it possible to draw a shape in a textbox(not rich)? I tried the below, but nothing seems to happen. Protected Overloads Sub OnPaintBackground(ByVal pevent As System.Windows.Forms.PaintEventArgs) pevent.Graphics.DrawEllipse(Pens.Black, pevent.ClipRectangle) End Sub The future hope is to make a textbox with a watermark type image on the side. A: If you put a breakpoint in the debugger do you reach this line? I believe you need to use SetStyle(ControlStyles.UserPaint, True) before your control will call OnPaintBackground. You may want to look at this SO answer about custom backgrounds in WinForm textboxes: Can a background image be set on a Winforms TextBox? The short answer, is it looks like this is not easily possible due. You may want to look at this article, as it offers some interesting approaches to custom drawn text box controls.
{ "language": "en", "url": "https://stackoverflow.com/questions/7503770", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: MDX query Count() return null when we put [Account].[Account Number].&[1] in WHERE clause In our Adventure Works cube, if we run the following query, we will get two null cells back, and it will only happen for some members in Account Number. Does anyone know why? Query that will return two cells with null value: WITH MEMBER count1 AS 'Count(Crossjoin([Measures].[Amount], [Date].[Calendar Year].[Calendar Year]))' MEMBER count2 AS 'Count(DrilldownLevel([Department].[Departments]))' SELECT {count1, count2} ON 0 FROM [Adventure Works] WHERE [Account].[Account Number].&[1] Query that will return two cells with correct number: WITH MEMBER count1 AS 'Count(Crossjoin([Measures].[Amount], [Date].[Calendar Year].[Calendar Year]))' MEMBER count2 AS 'Count(DrilldownLevel([Department].[Departments]))' SELECT {count1, count2} ON 0 FROM [Adventure Works] WHERE [Account].[Account Number].&[4] Does anyone know why adding "[Account].[Account Number].&[1]" in the WHERE clause will cause the Count() to return cell with null value? Also, if we change the query to the following, it seems to give us the correct result. Does anyone know whether using Crossjoin is a right way to fix the problem? WITH MEMBER count1 AS 'Count(Crossjoin(Crossjoin([Measures].[Amount], [Date].[Calendar Year].[Calendar Year]), [Account].[Account Number].&[1]))' MEMBER count2 AS 'Count(Crossjoin(DrilldownLevel([Department].[Departments]), [Account].[Account Number].&[1]))' SELECT {count1, count2} ON 0 FROM [Adventure Works] Thanks, Vivien A: Try: WITH MEMBER [Measures].[count1] AS Count(NonEmpty([Date].[Calendar Year].[Calendar Year],[Measures].[Amount])) MEMBER [Measures].[count2] AS Count(NonEmpty([Department].[Departments].[Departments].Members,[Measures].[Amount])) SELECT { [Measures].[count1], [Measures].[count2] } ON 0 FROM [Adventure Works] WHERE [Account].[Account Number].&[1]
{ "language": "en", "url": "https://stackoverflow.com/questions/7503773", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to convert PDF to low-resolution (but good quality) JPEG? When I use the following ghostscript command to generate jpg thumbnails from PDFs, the image quality is often very poor: gs -q -dNOPAUSE -dBATCH -sDEVICE=jpeggray -g465x600 -dUseCropBox -dPDFFitPage -sOutputFile=pdf_to_lowres.jpg test.pdf By contrast, if I use ghostscript to generate a high-resolution png, and then use mogrify to convert the high-res png to a low-res jpg, I get pretty good results. gs -q -dNOPAUSE -dBATCH -sDEVICE=pnggray -g2550x3300 -dUseCropBox -dPDFFitPage -sOutputFile=pdf_to_highres.png test.pdf mogrify -thumbnail 465x600 -format jpg -write pdf_to_highres_to_lowres.jpg pdf_to_highres.png Is there any way to achieve good results while bypassing the intermediate pdf -> high-res png step? I need to do this for a large number of pdfs, so I'm trying to minimize the compute time. Here are links to the images referenced above: * *test.pdf *pdf_to_lowres.jpg *pdf_to_highres.png *pdf_to_highres_to_lowres.jpg A: One option that seems to improve the output a lot: -dDOINTERPOLATE. Here's what I got by running the same command as you but with the -dDOINTERPOLATE option: I'm not sure what interpolation method this uses but it seems pretty good, especially in comparison to the results without it. P.S. Consider outputting PNG images (-sDEVICE=pnggray) instead of JPEG. For most PDF documents (which tend to have just a few solid colors) it's a more appropriate choice. A: Your PDF looks like it is just a wrapper around a jpeg already. Try using the pdfimages program from xpdf to extract the actual image rather than rendering to a file.
{ "language": "en", "url": "https://stackoverflow.com/questions/7503780", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Buttons in a Visual Studios form application Sorry if this is a dumb question, I'm taking an intro to programming class and need a bit of help with this project I'm working on. I'm trying to write an application that has about 30 buttons. One common thing I want is for all the buttons to turn yellow when clicked. If they're clicked a second time, they change back to the default color. right now I use the code: private void btn_1_Click(object sender, EventArgs e) { btn_1.BackColor = Color.Yellow; } But that only turns the buttons yellow, I can't turn them "off" by clicking it a second time. Also, when I'm creating these button events in VS2010, I end up with 30 different event handlers for each button..Is there a way to get them all to do the same thing without having to write all the repetitive code? I'm guessing that I would have to write my own buttons class? How would I go about doing that? Do i need to create a class library which inherits Buttons? Sorry for the noob questions. THanks A: If every button has a specific action that needs to be performed, then yes, you need to have a click handler for each; however, you can encapsulate the common behavior in a single method. For example: private void btn_1_Click(object sender, EventArgs e) { ToggleColor((Button)sender); //rest of the code specific to this button } private void ToggleColor (Button button) { if(button.Color==Color.Yellow; button.Color=Color.Black; else button.Color=Color.Yellow; } Note that above code is not tested. Now, if all the buttons do the same thing, you can just set the on click handlers for all of them to be btn_1_Click; for example. A: private void btn_1_Click(object sender, EventArgs e) { if (btn_1.BackColor != Color.Yellow) { btn_1.BackColor = Color.Yellow } else { btn_1.BackColor = Color.Control; } } this is switching default and yellow A: If all buttons do the exact same thing you can assign the same event handler to all buttons (instead of btn_1_Click, btn_2_Click etc... you'd have btton_click) - you can select this handler in the properties of each button. A: You don't have to write your own class. You can simply assign all your buttons to the same event handler, like this: button1.Click += new EventHandler(myEventHandler); button2.Click += new EventHandler(myEventHandler); button3.Click += new EventHandler(myEventHandler); button4.Click += new EventHandler(myEventHandler); Just keep in mind that your event handler has this signature: private void myEventHandler(object sender, EventArgs e) By doing that, all your buttons, when clicked, will trigger the same method. Now to control the color, what you can do is create a simple property on your form which would hold the last color applied. It could be an enum, then you could simply check its value and apply the other one to the buttons, like this: // Declare your enum: private enum Colors { Yellow, Default } private Colors ActualColor = Colors.Default; // Write your custom event handler: private void myEventHandler(object sender, EventArgs e) { if (ActualColor == Colors.Default) { // Apply yellow to buttons ActualColor = Colors.Yellow; } else { // Apply default ActualColor = Colors.Default; } } A: In order to keep track whether it is the 'second time' you press the button, you should declare a variable OUTSIDE the method, which indicates whether you already pressed the button or not. For example: public bool IsButtonYellow; private void btn_1_Click(object sender, EventArgs e) { if(!IsButtonYellow) { btn.BackColor = Color.Yellow; IsButtonYellow = true; } else { btn.BackColor = Control.DefaultBackColor; IsButtonYellow = false; } } A: Yes: * *Create your own button class *Inherit from Button *Implement the handler in your button class and you're done You can do something simple like this: public class MyButton : Button { private bool _buttonState; protected override void OnClick(EventArgs e) { base.OnClick(e); if (_buttonState) { BackColor = Color.Yellow; } else { BackColor = Color.White; } } } Then in your code you can just create as many of these "MyButton" objects as you need, with no code repetition. A: To make all buttons use the same event handler in VS2010: Click once on a button to select it. In the “properties” window: click on the “lightning” (=events). Paste the first button’s event name (btn_1_Click) next to “Click”. Do the same for every button. As for changing the color: See answer by killie01. Good luck.
{ "language": "en", "url": "https://stackoverflow.com/questions/7503782", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Compile all .rb files of a Ruby on Rails app to .class using JRuby, pack it into a .war and deploy into a Java appserver Is it possible to compile all .rb source files files (including the configuration source file files) of Ruby on Rails to .class files using JRuby, pack it into a .war file and deploy to JBoss or another Java appserver? A: Check out warbler for this purpose. From the main page: Warbler is a gem that makes a .war file out of a Rails, Merb, or Rack-based application. The intent is to provide a minimal, flexible, ruby-like way to bundle all your application files for deployment to a Java application server. A: the following command should compile all .rb to .class warble compiled in the warble.rb file you can uncomment the line to compile only some Ruby files # config.compiled_ruby_files = FileList['app/**/*.rb']
{ "language": "en", "url": "https://stackoverflow.com/questions/7503787", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Intersection points of line bisector with rectangle I've been trying to wrap my head around this the whole day... Basically, I have the coordinates of two points that will always be inside a rectangle. I also know the position of the corners of the rectangle. Those two entry points are given at runtime. I need an algorithm to find the 2 points where the bisector line made by the line segment between the given points intersects that rectangle. Some details: In the above image, A and B are given by their coordinates: A(x1, y1) and B(x2, y2). Basically, I'll need to find position of C and D. Red X is the center of the AB segment. This point (let's call it center) will have to be on the CD line. What I've did: * *found the center: center.x = (A.x+B.x)/2; center.y = (A.y+B.y)/2; *found CD slope: AB_slope = A.y - B.y / A.x - B.x; CD_slope = -1/AB_slope; Knowing the center and CD slope gave me the equation of CD and such, I've attempted to find a solution by trying the position of the points on all the 4 borders of the rectangle. However, for some reason it doesn't work: every time I have a solution let's say for C, D is plotted outside or vice-versa. Here are the equations I'm using: * *knowing x: y = (CD_slope * (x - center.x)) + center.y; if y > 0 && y < 512: #=> solution found! *knowing y: x = (y - center.y + CD_slope*center.x)/CD_slope; if x > 0 && x < 512: #=> solution found! From this, I could also end up with another segment (let's say I've found C and I know the center), but geometry failed on me to find the extension of this segment till it intersects the other side of the rectangle. Updated to include coding snippet (see comments in main function) typedef struct { double x; double y; } Point; Point calculate_center(Point p1, Point p2) { Point point; point.x = (p1.x+p2.x)/2; point.y = (p1.y+p2.y)/2; return point; } double calculate_pslope(Point p1, Point p2) { double dy = p1.y - p2.y; double dx = p1.x - p2.x; double slope = dy/dx; // this is p1 <-> p2 slope return -1/slope; } int calculate_y_knowing_x(double pslope, Point center, double x, Point *point) { double min= 0.00; double max= 512.00; double y = (pslope * (x - center.x)) + center.y; if(y >= min && y <= max) { point->x = corner; point->y = y; printf("++> found Y for X, point is P(%f, %f)\n", point->x, point->y); return 1; } return 0; } int calculate_x_knowing_y(double pslope, Point center, double y, Point *point) { double min= 0.00; double max= 512.00; double x = (y - center.y + pslope*center.x)/pslope; if(x >= min && x <= max) { point->x = x; point->y = y; printf("++> found X for Y, point is: P(%f, %f)\n", point->x, point->y); return 1; } return 0; } int main(int argc, char **argv) { Point A, B; // parse argv and define A and B // this code is omitted here, let's assume: // A.x = 175.00; // A.y = 420.00; // B.x = 316.00; // B.y = 62.00; Point C; Point D; Point center; double pslope; center = calculate_center(A, B); pslope = calculate_pslope(A, B); // Here's where the fun happens: // I'll need to find the right succession of calls to calculate_*_knowing_* // for 4 cases: x=0, X=512 #=> call calculate_y_knowing_x // y=0, y=512 #=> call calculate_x_knowing_y // and do this 2 times for both C and D points. // Also, if point C is found, point D should not be on the same side (thus C != D) // for the given A and B points the succession is: calculate_y_knowing_x(pslope, center, 0.00, C); calculate_y_knowing_x(pslope, center, 512.00, D); // will yield: C(0.00, 144.308659), D(512.00, 345.962291) // But if A(350.00, 314.00) and B(106.00, 109.00) // the succesion should be: // calculate_y_knowing_x(pslope, center, 0.00, C); // calculate_x_knowing_y(pslope, center, 512.00, D); // to yield C(0.00, 482.875610) and D(405.694672, 0.00) return 0; } This is C code. Notes: * *The image was drawn by hand. *The coordinate system is rotated 90° CCW but should not have an impact on the solution *I'm looking for an algorithm in C, but I can read other programming languages *This is a 2D problem A: You have the equation for CD (in the form (y - y0) = m(x - x0)) which you can transform into the form y = mx + c. You can also transform it into the form x = (1/m)y - (c/m). You then simply need to find solutions for when x=0, x=512, y=0, y=512. A: We start from the center point C and the direction of AB, D: C.x = (A.x+B.x) / 2 C.y = (A.y+B.y) / 2 D.x = (A.x-B.x) / 2 D.y = (A.y-B.y) / 2 then if P is a point on the line, CP must be perpendicular to D. The equation of the line is: DotProduct(P-C, D) = 0 or CD = C.x*D.x + C.y*D.y P.x * D.x + P.y * D.y - CD = 0 for each of the four edges of the square, we have an equation: P.x=0 -> P.y = CD / D.y P.y=0 -> P.x = CD / D.x P.x=512 -> P.y = (CD - 512*D.x) / D.y P.y=512 -> P.x = (CD - 512*D.y) / D.x Except for degenerate cases where 2 points coincide, only 2 of these 4 points will have both P.x and P.y between 0 and 512. You'll also have to check for the special cases D.x = 0 or D.y = 0. A: The following code should do the trick: typedef struct { float x; float y; } Point; typedef struct { Point point[2]; } Line; typedef struct { Point origin; float width; float height; } Rect; typedef struct { Point origin; Point direction; } Vector; Point SolveVectorForX(Vector vector, float x) { Point solution; solution.x = x; solution.y = vector.origin.y + (x - vector.origin.x)*vector.direction.y/vector.direction.x; return solution; } Point SolveVectorForY(Vector vector, float y) { Point solution; solution.x = vector.origin.x + (y - vector.origin.y)*vector.direction.x/vector.direction.y; solution.y = y; return solution; } Line FindLineBisectorIntersectionWithRect(Rect rect, Line AB) { Point A = AB.point[0]; Point B = AB.point[1]; int pointCount = 0; int testEdge = 0; Line result; Vector CD; // CD.origin = midpoint of line AB CD.origin.x = (A.x + B.x)/2.0; CD.origin.y = (A.y + B.y)/2.0; // CD.direction = negative inverse of AB.direction (perpendicular to AB) CD.direction.x = (B.y - A.y); CD.direction.y = (A.x - B.x); // for each edge of the rectangle, check: // 1. that an intersection with CD is possible (avoid division by zero) // 2. that the intersection point falls within the endpoints of the edge // 3. if both check out, use that point as one of the solution points while ((++testEdge <= 4) && (pointCount < 2)) { Point point; switch (testEdge) { case 1: // check minimum x edge of rect if (CD.direction.x == 0) { continue; } point = SolveVectorForX(CD, rect.origin.x); if (point.y < rect.origin.y) { continue; } if (point.y > (rect.origin.y + rect.height)) { continue; } break; case 2: // check maximum x edge of rect if (CD.direction.x == 0) { continue; } point = SolveVectorForX(CD, rect.origin.x + rect.width); if (point.y < rect.origin.y) { continue; } if (point.y > (rect.origin.y + rect.height)) { continue; } break; case 3: // check minimum y edge of rect if (CD.direction.y == 0) { continue; } point = SolveVectorForY(CD, rect.origin.y); if (point.x < rect.origin.x) { continue; } if (point.x > (rect.origin.x + rect.width)) { continue; } break; case 4: // check maximum y edge of rect if (CD.direction.y == 0) { continue; } point = SolveVectorForY(CD, rect.origin.y + rect.height); if (point.x < rect.origin.x) { continue; } if (point.x > (rect.origin.x + rect.width)) { continue; } break; }; // if we made it here, this point is one of the solution points result.point[pointCount++] = point; } // pointCount should always be 2 assert(pointCount == 2); return result; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7503795", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: how to control media player using script or code Is there a media player, where you can control its audio and video using script or code.for example lets say i want to pause the video after n secs, which player supports this? I am looking for free opensource solution which runs on desktop i.e windows 7. A: I'm not the kind of giving the entire solution. But here's a good place to start. It shows how to embed Windows Media Player in a Windows Form. http://msdn.microsoft.com/en-us/library/bb383953(v=vs.90).aspx You'll have access to control like play, stop, etc. A: VideoLan supports such use. For instance, see here: http://www.videolan.org/doc/play-howto/en/ch04.html From the link: --extraintf allows you to select extra interface modules that will be launched in addition to the main one. This is mainly useful for special control interfaces, like HTTP, RC (Remote Control), ... (see below) The RC interface is probably best from a pure code/script point-of-view. The HTTP interface is oriented towards a human using a webpage, but could be controlled from code, too.
{ "language": "en", "url": "https://stackoverflow.com/questions/7503797", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I do a sub-select in LINQ? I am new to SQL server, please can any body help me out how to write this query in LINQ. SELECT [Plan_Num] ,(select top 1 ba_level_code + ' - ' + ba_level_desc from baLevel where ba_level_code = '0' + Level_Num) as [Level] ,(select top 1 cast(Column_Num as varchar) + ' - ' + Column_Description from baPlanColumnStructure where Column_Num = CL.Column_Num) as [Column] ,[Sort_Order] FROM baCodeLibrary CL where code_id = 25468 and isactive = 1 order by [Plan_num] Thanks A: You are looking for something like this var query = from cl in context.BaCodeLibrary where cl.code_id == 25468 && cl.isactive == 1 orderby cl.Plan_num select new { Level = (from ba in context.baLevel where ba.ba_level_code == ("0" + ba.Level_Num) select ba.ba_level_code + " - " + ba.ba_level_desc).Take(1), Column = (from ba in context.baPlanColumnStructure where ba.Column_Num == cl.Column_Num select ba.ba_level_code + " - " + ba.ba_level_desc).Take(1), Sort_Order = cl.Sort_Order }
{ "language": "en", "url": "https://stackoverflow.com/questions/7503799", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Javascript in VisualStudio 2010 Are there any good, reliable plugins for Visual Studio that make Javascript development less painful? Every time I write a closing brace or a semicolon VS feels the need to inappropriately and incorrectly re-indent nearby code. A: Have you tried looking under Tools --> Options --> Text Editor --> JScript? There are lots of settings you can change there to tell VS to indent or not indent code. A: JetBrains ReSharper 6 supports JavaScript quite good. Unfortunately it is quite slow.
{ "language": "en", "url": "https://stackoverflow.com/questions/7503806", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: css background image not seamless I am using html5 and am trying to create a rough edged seamless border(top, sides + bottom). I am aware ie8 does not support the CSS3 border image. IE8 is as far back as am willing to cater for. So am using 3 div's to have the background image display, the only problem is depending on the length of the content, the bottom background image does not align nicely and make the box appear seamless, due to the repeated middle image being cut off prior to the point where the border merges. I have used a brush in photoshop to create the jagged container. I have had a nose around about this but can not find a solution to fit. A: The solution is to set a specific increase of height increment for your content area. This can be done in a couple of ways: * *If your content is mostly text, you can set your line-height and/or the height of any other used elements to be the desired increment (or a multiple thereof) and hope for the best. *If this will not work, the only other way would be to use JavaScript. Here are a couple discussions of this very challenge, including some thoughts on using line height and some starts at workable JavaScript code: * *http://doctype.com/any-way-increase-hieght-div-specific-increment *http://www.dynamicdrive.com/forums/showthread.php?t=64034
{ "language": "en", "url": "https://stackoverflow.com/questions/7503808", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: why apache server redicect /doc to usr/share/doc I have the rewrite ruls in .htaccess file under /var/www in my ubuntu10.4 server like below, When the url appears to be http://127.0.0.1/doc/view, the webpage shows "The requested URL /doc/view was not found on this server", and then I check the apach log, it logs "File does not exist: /usr/share/doc/view", so apprently apache redirect the /doc/view to /usr/share/doc/view. I don't know what it is going on here, can anybody help? thanks for help. Options +FollowSymLinks IndexIgnore */* <IfModule mod_rewrite.c> RewriteEngine on # if a directory or a file exists, use it directly RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d # otherwise forward it to index.php RewriteRule . index.php </IfModule> A: Apache's default config on many distributions makes it so you can go to http://localhost/doc/to read the Apache documentation. You can edit this out in your httpd.conf or apache2.conf file if you need to use /doc for your own URLs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7503814", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How do I add values of one Table to another in Mathematica? I have created a Table of values known as "value1". The "value1" is nothing but a z co-ordinate values alternatively can be called "zone" . These values depending upon the x co-ordinate and y co-ordinate given as "x" and "y" respectively. The code is give below value1 = Table[{(10*(Cos[((x - 75)*2*3.14159)/ 200]^2)*(Cos[((y - 75)*2*3.14159)/200]^2)) + 20}, {y, 0, 20, 5}, {x, 0, 20, 5}] The output of "value1" or "zone" is {{22.5}, {21.7274}, {21.0305}, {20.4775}, {20.1224}}, {{21.7274}, and so on I have another table of values known as "value 2". This table also gives me a different z co-ordinate value it can be alternatively called "ztwo" . This values also depends upon the x and y co-ordinates defined by "x" and "y" respectively. Note the z value is generated defined by the expression given below (((70 - ((10*(Cos[((x - 75)*2*3.14159)/ 200]^2)*(Cos[((y - 75)*2*3.14159)/200]^2)) + 20))*0.3333)) I have used the above expression in the table below to generate the "ztwo" values value2 = Table[{x,y, (((70 - ((10*(Cos[((x - 75)*2*3.14159)/ 200]^2)*(Cos[((y - 75)*2*3.14159)/200]^2)) + 20))*0.3333))}, {y, 0, 20, 5}, {x, 0, 20, 5}] Output of "value2" {{{0, 0, 15.8318}, {5, 0, 16.0892}, {10, 0, 16.3215}, {15, 0, 16.5059}, {20, 0, 16.6242}}, {{0, 5, 16.0892}, {5, 5,16.2672}, {10, 5, 16.4277}, {15, 5, 16.555},and so on As you can see from above the "value2" is in form of {x1,y1,ztwo1},{x2,y2,ztwo2},{x3,y3,ztwo3}..and so on I want to create a table of values know as "value3" which is basically the addition z values from "value 1" known to us as "zone" to ONLY the z values of "value2" known to us as "ztwo" to get the table "value3". In table "value3" only the z values change but it SHOULD be expressed as in form below {0,0,38.3317},{5,0,37.5592},{10,0,36.8623} and so on Explanation: How do I get the above?? this is the "zone" values: {{22.5}, {21.7274}, {21.0305}, {20.4775}, {20.1224}}, {{21.7274}, and so on Below is "ztwo" values but expressed in{x,y,z} format {{{0, 0, 15.8318}, {5, 0, 16.0892}, {10, 0, 16.3215}, {15, 0, 16.5059}, {20,0,16.6242}}, {{0, 5, 16.0892} and so on Now I want a table of "value 3" whose z values change since it is the addition of corresponding z co-ordinate values from table "value1" and table "value2" {0,0,15.8318+22.5},{5,0,16.0892+21.7274},{10,0,16.3215+36.8623} and so on Which will lead to the desired, ideal output like this: {0,0,38.3317},{5,0,37.5592},{10,0,36.8623} and so on Question How Do I create the Table "Value3" which give me the desired output by adding the corresponding z values from table "value1" to table "value2" A: You have a small typo in your code... there should be a comma between y and (((70 - ... in the definition of value2 in order to get the result that you posted below. Fixing that, you can do the following to get your result: value3 = value2; value3[[All, All, 3]] += value1[[All, All, 1]]; EDIT: The code above does the addition the way you want it. I think the confusion is because you want each of the three coordinates as a list instead of a matrix. For that, you simply need to Flatten the list at Level 1. Flatten[value3, 1] Out[1]= {{0, 0, 38.3317}, {5, 0, 37.8167}, {10, 0, 37.3521}, {15, 0, 36.9833}, {20, 0, 36.7466}, {0, 5, 37.8167}, {5, 5, 37.4608}, {10, 5, 37.1397}, {15, 5, 36.885}, {20, 5, 36.7214}, {0, 10, 37.3521}, {5, 10, 37.1397}, {10, 10, 36.9482}, {15, 10, 36.7962}, {20, 10, 36.6986}, {0, 15, 36.9833}, {5, 15, 36.885}, {10, 15, 36.7962}, {15, 15, 36.7258}, {20, 15, 36.6806}, {0, 20, 36.7466}, {5, 20, 36.7214}, {10, 20, 36.6986}, {15, 20, 36.6806}, {20, 20, 36.669}}
{ "language": "en", "url": "https://stackoverflow.com/questions/7503818", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: UITableViewController cell design issue I have a UITableViewController with an attached xib file. Inside the xib file i have a TableViewCell object with a view inside it along with labels on the view. Below is an image of what my result should be: pic1 http://casperslynge.dk/2.png And below is how my tableview is looking atm. pic2 http://casperslynge.dk/iphone1.png My issue is that I can't get the table view cell to fill the entire window. Have tried everything inside the interface builder. Nothing to do with the origin or the width/height. Below is how I instantiate my cell with the xib file and fill my labels with data. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString * CompanyListCellIdentifier = @"CompanyList"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CompanyListCellIdentifier]; if (cell == nil) { NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"CompanySubscriptionView" owner:self options:nil]; cell = [topLevelObjects objectAtIndex:0]; } NSUInteger row = [indexPath row]; CompanyModel *company = [list objectAtIndex:row]; name.text = company.name; network.text = company.networks; NSString* subscriptionCountString = [NSString stringWithFormat:@"%d", company.subscriptions.count]; subscriptionCount.text = subscriptionCountString; fromPrice.text = company.fromPrice; NSString* trustScoreString = [NSString stringWithFormat:@"%d", company.trustScore]; trustScore.text = trustScoreString; cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; return cell; } The weird thing is that in the next view when one of the cell's are pressed, I have no issue making the view fill the entire width and height, and it is created in exactly the same way (see picture below). Is it something in the xib file that I am doing wrong or in the code? pic3 http://casperslynge.dk/iphone2.png Can anybody help? A: As I see from screenshots you are trying to use table view with grouped style while you definitely need a plain one (at least for first view).
{ "language": "en", "url": "https://stackoverflow.com/questions/7503819", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Trying to sort out msi installer security permission requirements I've been asked to sort out what the security requirements are for our MSI installers. Unfortunately, I'm a bit stuck on what is required of a Windows Installer Component ID Launch Condition. I can't seem to dig up where those component id's are even stored. Any insight would be greatly appriciated. A: The short answer: there are no permissions required. Everyone can evaluate the launch condition. Components are handled internally by Windows Installer, along with the cached MSI. It doesn't matter where their information is stored because Windows Installer is fully integrated with user accounts, permissions and the UAC. Basically, Windows Installer can do whatever it wants. None of its built-in actions will fail because of permissions because they were designed this way. Additonally, searches only read information. Since the component information is stored internally and it's not accessible to your users, there's no reason a permission problem would occur.
{ "language": "en", "url": "https://stackoverflow.com/questions/7503825", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Multiple handler loop Android I am trying to design a program that makes multiple API calls on a website (Each "name" has several modes that I have to loop through before I move on to the next name). The problem is, you are limited to calling the API once every second. I thought the handler was the way to go but now I don't think so. It runs through the loop just fine but I don't think so. I get the following error: EDIT: Figured out that this was being caused by 09-21 22:33:46.760: ERROR/AndroidRuntime(9683): FATAL EXCEPTION: AsyncTask #1 09-21 22:33:46.760: ERROR/AndroidRuntime(9683): java.lang.RuntimeException: An error occured while executing doInBackground() 09-21 22:33:46.760: ERROR/AndroidRuntime(9683): at android.os.AsyncTask$3.done(AsyncTask.java:266) 09-21 22:33:46.760: ERROR/AndroidRuntime(9683): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273) 09-21 22:33:46.760: ERROR/AndroidRuntime(9683): at java.util.concurrent.FutureTask.setException(FutureTask.java:124) 09-21 22:33:46.760: ERROR/AndroidRuntime(9683): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307) 09-21 22:33:46.760: ERROR/AndroidRuntime(9683): at java.util.concurrent.FutureTask.run(FutureTask.java:137) 09-21 22:33:46.760: ERROR/AndroidRuntime(9683): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1081) 09-21 22:33:46.760: ERROR/AndroidRuntime(9683): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:574) 09-21 22:33:46.760: ERROR/AndroidRuntime(9683): at java.lang.Thread.run(Thread.java:1020) 09-21 22:33:46.760: ERROR/AndroidRuntime(9683): Caused by: android.content.res.Resources$NotFoundException: String array resource ID #0x7f050002 09-21 22:33:46.760: ERROR/AndroidRuntime(9683): at android.content.res.Resources.getStringArray(Resources.java:459) 09-21 22:33:46.760: ERROR/AndroidRuntime(9683): at com.companionfree.flurryanalytics.APICallData.doInBackground(APICallData.java:66) 09-21 22:33:46.760: ERROR/AndroidRuntime(9683): at com.companionfree.flurryanalytics.APICallData.doInBackground(APICallData.java:1) 09-21 22:33:46.760: ERROR/AndroidRuntime(9683): at android.os.AsyncTask$2.call(AsyncTask.java:252) 09-21 22:33:46.760: ERROR/AndroidRuntime(9683): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305) 09-21 22:33:46.760: ERROR/AndroidRuntime(9683): ... 4 more When I make this call in my Asynchronous task: String[] metrics = r.getStringArray(R.array.metric_apicall); I don't think my code is designed right for what I am trying to do. Can anyone tell me if this is the right approach?...Also, APICallData(MainActivity.this, app, mode).execute(); is an asynchronous task. //Other code above this irrelevant mApp = 0; mMode = 0; callAPI(mMode, names[mApp]); mMode++; while (mApp < names.length) { while (mMode < metrics.length) { Handler handler = new Handler(); handler.postDelayed(new Runnable() { public void run() { callAPI(mMode, names[mApp]); } }, 1010); mMode++; } mMode = 0; mApp++; } private void callAPI(int mode, String app) { new APICallData(MainActivity.this, app, mode).execute(); } A: I think you should use Timer and TimerTask and exeute it with an interval of 1 sec.
{ "language": "en", "url": "https://stackoverflow.com/questions/7503829", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Regex to deterime text 'http://...' but not in iframes, embeds...etc This regex is used to replace text links with a clickable anchor tag. #(?<!href="|">)((?:https?|ftp|nntp)://[^\s<>()]+)#i My problem is, I don't want it to change links that are in things like <iframe src="http//... or <embed src="http://... I tried checking for a whitespace character before it by adding \s, but that didn't work. Or - it appears they're first checking that an href=" doesn't already exist (?) - maybe I can check for the other things too? Any thoughts / explanations how I would do this is greatly appreciated. Main, I just need the regex - I can implement in CakePHP myself. The actual code comes from CakePHP's Text->autoLink(): function autoLinkUrls($text, $htmlOptions = array()) { $options = var_export($htmlOptions, true); $text = preg_replace_callback('#(?<!href="|">)((?:https?|ftp|nntp)://[^\s<>()]+)#i', create_function('$matches', '$Html = new HtmlHelper(); $Html->tags = $Html->loadConfig(); return $Html->link($matches[0], $matches[0],' . $options . ');'), $text); return preg_replace_callback('#(?<!href="|">)(?<!http://|https://|ftp://|nntp://)(www\.[^\n\%\ <]+[^<\n\%\,\.\ <])(?<!\))#i', create_function('$matches', '$Html = new HtmlHelper(); $Html->tags = $Html->loadConfig(); return $Html->link($matches[0], "http://" . $matches[0],' . $options . ');'), $text); } A: You can expand the lookbehind at the beginning of those regexes to check for src=" as well as href=", like this: (?<!href="|src="|">)
{ "language": "en", "url": "https://stackoverflow.com/questions/7503834", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Overriding package configured variables in SSIS 2008 using DTEXEC /SET I'm having a problem transitioning a 2005 package to 2008 - it appears that in 2008, package variables configured to use a Configuration Filter (eg populate from [SSIS Configurations]) will not honor the /SET command provided by dtexec.exe to override a package variable value at runtime. The issue is documented here http://dougbert.com/blogs/dougbert/archive/2009/04/07/understand-how-ssis-package-configurations-are-applied.aspx What's the most straight-forward solution for this? I want the old SSIS 2005 behavior where, a package variable is initially loaded from [SSIS Configurations] but I can override it at runtime if I explicitly call /SET I have a work-around but am hoping for a better solution - I basically have 2 versions of a variable I want ...eg NETWORK_PATH, NETWORK_PATH_CONFIG ...I put an expression on NETWORK_PATH to use the NETWORK_PATH_CONFIG (this variable would be populated from [SSIS Configurations]) if the value of NETWORK_PATH is initially NULL at runtime when the expression is first evaluated otherwise use the value that was provided (presumably by dtexec /SET) A: You either use /Conn to change the location of your config settings and have the different settings there or you remove the variable from the configurations completely so that it can be set in the dtexec /set parameter. If you want to have a default and override then you will have to go with the /conn parameter and change the location of the settings. e.g. "C:\Program Files (x86)\Microsoft SQL Server\100\DTS\Binn\DTExec.exe" /File "C:\Path\To\My\Package\Import Types.dtsx" /Conn Connection1;"Provider=SQLNCLI10;Server=MYSERVER;Database=DB_ONE;Uid=USERNAME;Pwd=PASSWORD;" /Conn Connection2;"Provider=SQLNCLI10;Server=MYSERVER;Database=DB_TWO;Uid=USERNAME;Pwd=PASSWORD;" It appears someone thought this was better than the 2005 method. I would like to know his rationale before I hit him.
{ "language": "en", "url": "https://stackoverflow.com/questions/7503837", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: wordpress query_posts problem So I have a custom template that display posts from a particular category (depending on the get_post_meta('Category')). The page works flawlessly for displaying posts from a 'News' Category. However, using the exact same code (minus how its displayed), it has problems with the Pagination for posts from the Calendar Category. Basically, the first page of Calendar posts display correctly, and then when you hit 'next page', the url updates to page/2, but the same posts are on the page. Here's the code: <?php $category = get_post_meta($post->ID, 'Category', true); ?> <?php $cat = get_cat_ID($category); ?> <?php $paged = (get_query_var('page')) ? get_query_var('page') : 1; ?> <?php $args = array( 'cat' => $cat, 'paged' => $paged ); ?> <?php query_posts($args); ?> <?php if (have_posts()) : ?> <?php while (have_posts()) : the_post(); ?> <!-- If its a Calendar page --> <?php if ($cat == 1): ?> <div class='entry'> <!-- List all Calendar info and Custom Fields --> <ul> <li><h3><?php the_title(); ?></h3></li> <li><?php the_content(); ?></li> <!-- ...And displays other data, etc..... --> </ul> </div> <?php else: ?> <div class='entry'> <ul> <li><?php the_title(); ?></a></h3></li> <li><?php the_time('F jS, Y'); ?></li> <li><?php the_content(); ?></li> <!-- And display other data, etc .... --> </ul> </div> <?php endif; ?> <?php endwhile; ?> <!-- Posts Nav Links --> <?php posts_nav_link(' | ', '&laquo; Newer Entries', 'Older Entries &raquo;'); ?> <?php endif; ?> A: More than likely this has to do with how you are setting the paged parameter for query_posts() in a custom template. Read more about this here: http://scribu.net/wordpress/wp-pagenavi/right-way-to-use-query_posts.html In a nutshell you may need to use get_query_var('paged').
{ "language": "en", "url": "https://stackoverflow.com/questions/7503839", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Cross Browser Cookie Expiration Inconsistencies I'm looking for a way to set cookies with a short duration against all browsers. Apparently each browser handles the PHP setcookie method differently. Below are my results. The PHP code: setcookie("TestCookie", $value, time()+7200, "/", ".domain.com", 1, true); The Results: OPERA 11.10 Local time of test: 1316621628 PHP Server Time: Wed Sep 21 07:58:35 PDT 2011 Cookie Expiration Time: 2011-09-21 - 20:58:35 Chrome 6.0.472.63 Local time of test - 1316621761 PHP Server Time - Wed Sep 21 08:01:21 PDT 2011 Cookie Expiration Time - Wednesday, September 21, 2011 9:01:21 PM Firefox 4 Local time of test: 1316622064 PHP Server Time: Wed Sep 21 08:07:38 PDT 2011 CookieExpiration Time: Wednesday, September 21, 2011 10:22:50 PM Safari 3.2.3 Local time of test: 1316622359 PHP Server Time: Wed Sep 21 08:10:48 PDT 2011 CookieExpiration Time: 9/21/11 5:10 PM Internet Explorer 8 Local time of test: 1316623009 PHP Server Time: Wed Sep 21 08:21:37 PDT 2011 Cookie Data: TestCookie x domain.com/ 9728 3932016640 30177410 2837190416 30177404 As you can see, the expiration date/time for the cookies varies widely from working as intended to being several hours in the past to only being 1 hour! Very frustrating. In addition to trying the above method, I've also tried setting the exact expiration date/time via unixtime... I've done this with both time() at the PHP level, or utilizing the browser's unixtime retrieved through JavaScript. setcookie("TestCookie", $value, 1316621928, "/", ".domain.com", 1, true); Each browser handles this differently as well. I can't seem to find one method that works the same for all browsers. Is anyone aware of a method that accomplishes this? Thank you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7503845", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is there a way to access Microsoft OCS Directory/Presence information using a web service? We are working on a client app that should search and download directory information from Microsoft OCS server (OCS old as well as Lync). Does OCS provide web services type api? From what I understand, the client needs to do sip handshake before it can do directory related queries. Having dependency on sip stack is not desirable. So I am wondering if there is a way (like SOAP web service or something like that) to do it. The client is a C++ client with access to gSoap or curl type library running on Linux platform. Thanks for your help. A: No, there is no web service out of the box that gives you what you need. I thin your best bet would be to build a UCMA application that would sit on an application server inside your OCS/Lync infrastructure. You could then build a web service to access this. For OCS 2007, you'd need to use UCMA 1.0. For OCS 2007 R2, UCMA 2.0 and for Lync, UCMA 3.0
{ "language": "en", "url": "https://stackoverflow.com/questions/7503847", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Improving Google Maps Performance I have to draw about 10000 line on Google Maps. So, it is spending too much time in draw() method. Moving on map becomes very laggy. Is there any way to cache drawing or can I draw just the part of map / canvas which is currently seen on screen? A: drawing 10000 lines will never get lag free. I'm guessing you connect points. Here is an implementation of point Clustering in mapView and also renders the visible ones if you want. So you can draw lines to the clustered points. A: Now I can draw all 10000 lines without any lag. It is all about designing draw() method carefully. I moved some object creating operations (like Path, Point) out of draw(). I saw that especially projection.toPixels(geoPoint, point); is very expensive operation. Finally I set an alpha constant which holds the pixel value of finger movement. And it only draws when pixelX or pixelY movement is bigger than alpha. A: Have a look at this post, it suggests drawing your lines into a shape then drawing that to the mapview. Here: Cache whats being draw on MapView in Android Just a suggestion on this one, you may want to try saving the MapView as a bitmap then render that instead (depending on your situation). Here: Save MapView as a Bitmap
{ "language": "en", "url": "https://stackoverflow.com/questions/7503848", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Android 2.2 2.3 workaround for device-width media query I've observed a problem on Android 2.2 and 2.3 native browser where device-width CSS media query and window.screen.width both report sizes based on your webpage document and scaling applied. Example: 1:1 scaling, 960px wide page will show proper device width (say, 320px) Example: fit-screen scaling, 960px wide page, improperly reports 960px device width So with appropriate viewport meta tag content it seems predictable. However, in my case I cannot rely on the meta tag. Does anyone use a workaround to get a reliable device width measurement in Android irrespective of viewport meta tag? Other platforms do report this correctly across all scaling. Ref: http://code.google.com/p/android/issues/detail?id=11961 A: window.outerWidth and window.outerHeight always report the browser pixels (ie screen resolution minus UI bars, typically 480x762 on a Galaxy S.) You may then to throw in window.devicePixelRatio to calculate the virtual pixel width (320px).
{ "language": "en", "url": "https://stackoverflow.com/questions/7503851", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: JBossCache eviction listener I am new on JBossCache. Reading the user documentation it says that a listener could be added to the Eviction class used, but I wasn't able to found how to do add one to the configuration file, or how that should be added. I have tried to add an @CacheListener with a method @NodeEvicted, but that method @CacheListener public class EvictionListener { @NodeEvicted public void nodeEvicted(NodeEvent ne) { System.out.println("Se borro el nodo"); } } and add it to the cache instance CacheFactory factory = new DefaultCacheFactory(); this.cache = factory.createCache(); EvictionListener listener = new EvictionListener(); this.cache.create(); this.cache.addCacheListener(listener); but the sysout isn't executed. For testing it, I am just running a simple Main value. This is the configuration value I am using: <jbosscache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="urn:jboss:jbosscache-core:config:3.2"> <transaction transactionManagerLookupClass="org.jboss.cache.transaction.GenericTransactionManagerLookup"/> <eviction wakeUpInterval="20"> <default algorithmClass="org.jboss.cache.eviction.FIFOAlgorithm" wakeUpInterval="20"> <property name="maxNodes" value="20" /> </default> </eviction> </jbosscache> A: The problem was solved because I wasn't reading the XML configuration file. I was missing: factory.createCache(file);
{ "language": "en", "url": "https://stackoverflow.com/questions/7503852", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: It.IsAny(), It.IsAny(), Times.Never(). What do they do? I wonder if you could help me understand the following line: mock.Verify(m => m.ProcessOrder(It.IsAny<Cart>(), It.IsAny<ShippingDetails>()), Times.Never()); The test method: [TestMethod] public void Cannot_Checkout_Empty_Cart() { // Arrange - create a mock order processor Mock<IOrderProcessor> mock = new Mock<IOrderProcessor>(); // Arrange - create an empty cart Cart cart = new Cart(); // Arrange - create shipping details ShippingDetails shippingDetails = new ShippingDetails(); // Arrange - create an instance of the controller CartController target = new CartController(null, mock.Object); // Act ViewResult result = target.Checkout(cart, shippingDetails); // Assert - check that the order hasn't been passed on to the processor mock.Verify(m => m.ProcessOrder(It.IsAny<Cart>(), It.IsAny<ShippingDetails>()), Times.Never()); // Assert - check that the method is returning the default view Assert.AreEqual("", result.ViewName); // Assert - check that we are passing an invalid model to the view Assert.AreEqual(false, result.ViewData.ModelState.IsValid); } A: It.IsAny<Cart> matches any value of type Cart. Since you have Times.Never, you actually verify that the method has never been called with the two parameters (Card, ShippingDetails). A: @Wiktor has it right, but just to clarify the difference. The current check is making sure that the method has not been called with ANY cart or ANY shipping details. This might seem excessive, as perhaps this might be sufficient: // Assert - check that the order hasn't been passed on to the processor mock.Verify(m => m.ProcessOrder(cart, shippingsDetails), Times.Never()); after all it is probable that the processing will be done with the given cart and shipping details. However it is possible that the cart could have been cloned, or some shipping details could have been loaded from the users preferences or something, and the It.IsAny<T> allows you to check that the method was not called regardless of the arguments, as otherwise the verification would only happen with those specific instances as arguments. EDIT To answer the comment. Imagine another test where instead you wanted to check that the order was processed, and that it was processed with the correct arguments and not with some different users cart and shipping details: // Arrange - create an empty cart Cart cart = new Cart(); // Arrange - create shipping details ShippingDetails shippingDetails = new ShippingDetails(); // Arrange - create an instance of the controller CartController target = new CartController(null, mock.Object); // Act ViewResult result = target.Checkout(cart, shippingDetails); //Assert - check the order was processed once with the //correct cart and shipping details mock.Verify(m => m.ProcessOrder(cart, shippingDetails), Times.Once()); now this tests fails if the ProcessOrder method is not called with exactly the same cart and shipping details that was expected. If it happened to use another users cart or shipping details then the test would fail. Hope this clear up the difference between specifying the arguments explicitly and using It.IsAny<T> A: It is verifying that the method ProcessOrder was never called using any type of Cart and ShippingDetails as arguments during the test.
{ "language": "en", "url": "https://stackoverflow.com/questions/7503854", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: jquery mobile finger(s) detection With jquery mobile, is it possible to detect the number of fingers that are on the screen? I am an UI student trying to put together an application for a school project. Essentially I need to have a different feedback for one, two and three finger swipe but I am not sure on how jquery mobile or TouchSwipe plug-in do detection. Thank you. A: jQuery mobile (as of version 1.03b) only supports basic swipes, and does not distinguish between 1, 2, and 3 fingers. touchSwipe (as of version 1.2.4) does support multi-finger swipes by passing in a finger option, however, the options are limited to either 1 or 2 fingers. A: To my knowledge, there is currently no support for multiple fingers in jquery mobile and last time i checked TouchSwipe, it didn't feature that either. But there is another plugin - jQuery Multiswipe that should support multiple fingers. http://plugins.jquery.com/project/multiswipe
{ "language": "en", "url": "https://stackoverflow.com/questions/7503855", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: py2exe executable generates log file error Py2exe builds the executable without exceptions. When I run the executable, a log file is generated with the following: Traceback (most recent call last): File "ecm2es_gui.py", line 10, in <module> File "weblogin.pyo", line 4, in <module> File "mechanize\__init__.pyo", line 122, in <module> File "mechanize\_mechanize.pyo", line 14, in <module> File "mechanize\_html.pyo", line 19, in <module> File "mechanize\_form.pyo", line 64, in <module> ImportError: No module named inspect When I run the program from Python Shell, Eclipse, or Geany I get no errors and it runs OK. I thought my problem was with the installation of Mechanize or the eggs but now I don't think this is the problem. Any ideas? TIA - Brad UPDATE... this is my setup.py file: from distutils.core import setup import py2exe import sys; sys.argv.append('py2exe') includes = [] excludes = ['_ssl', 'pdb', 'unittest', 'inspect', 'pyreadline', 'difflib', 'doctest', 'locale', 'optparse', 'pickle', 'calendar', '_gtkagg', '_tkagg', 'bsddb', 'curses', 'email', 'pywin.debugger', 'pywin.debugger.dbgcon', 'pywin.dialogs'] packages = [] dll_excludes = [] setup( options = {"py2exe": {"compressed": 1, "optimize": 2, "bundle_files": 3, "includes": includes, "excludes": excludes, "packages": packages, "dll_excludes": dll_excludes, "dist_dir": "dist", "xref": False, "skip_archive": False, "ascii": False, "custom_boot_script": '', } }, # zipfile = None, name='EnerSave Uploader', version='0.5', description='Upload ECM-1240 Data to EnerSave', author='Brad Norman', windows=[{"script":"ecm2es_gui.py", "icon_resources": [(1, "favicon.ico")]} ] ) A: The error is ImportError: No module named inspect And in your setup script you have inspect in the list of excludes. Remove it from the excludes, and py2exe will package it with your executable so mechanize can use it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7503861", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Visio control is resetting to old data when show() is called I have a project which contains multiple forms that have a microsoft visio activex control in them. For some reason they keep interfering with one another. Here's a snip it of my code, simplified: private void OpenRDM() { if (RDMform == null) { // Constructor opens a new form, and populates a Visio control on it RDMform = new RDM.MainForm(); } RDMform.Show(); } private void OpenPSM() { if (PSMform == null) { // Constructor opens a new form, and populates a Visio control on it PSMform = new PSM.MainForm(); } PSMform.Show(); // Problem occurs here, PSM Visio control gains contents of RDM's Visio Control } public void main() { OpenRDM(); RDMform.Hide(); OpenPSM(); PSMForm.Hide(); } I can call one of these functions and it works fine, but if I hide the form, and then call the other one, its Visio control loads with the contents of the first form, instead of the correct new stuff. I traced it, and the second Visio control is populated just fine, until the second Show() method is called, at which point it mysteriously goes back to the contents of the first Visio control. I can't figure out what is going on here, Visio seems to think that they are the same control. Edit* In response to comment about setting the .src property. The source is a behemoth, so I can't reasonably post everything it does. But here's those lines. in RDM: If visioControl.Src <> TemplateFullName Then visioControl.Src = TemplateFullName Else visioControl.Src = "" visioControl.Src = TemplateFullName End If in PSM: drawingControl.Src = string.Empty; drawingControl.Src = vstFilepath; InitializeFlowDiagram(dbFilepath); // updates shapes from database values Both modules actually use the same visio diagram including page names, they just display it in different ways. So I'd like to be able to back and forth between them without having to reload everything. Maybe the activeWindow is involved in the problem, I'll have to do more research.
{ "language": "en", "url": "https://stackoverflow.com/questions/7503868", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: .net page validation before control submits i have a control inside a larger form (to upload files) and I need it to validate the entire page before it submits. <asp:Button ID="btnUpload" runat="server" CssClass="button2" Text="Upload" OnClientClick="if(Page_ClientValidate()) {return Page_IsValid;}" onclick="btnUpload_Click" ValidationGroup="Bgroup" /> because this is a sub control it is not part of the main validation group (i dont want to validate it unless they hit the upload button) currently the validation fires but then the page still submits? If the page doesnt validate I would like to stop it from submiting Thanks! edit i changed the onclientclick to javascript:return productsValidation() which is defined as function productsValidation() { if(Page_ClientValidate()) { return true; }else { return false; } } and now it will stop at the validation but it wont submit once you update the required fields???? I got this working but i had to have it validate each of the groups separately because evidently there are othervalidation groups on the page that were not valid a la function productsValidation() { if(Page_ClientValidate('g1') && Page_ClientValidate('g2')) { return true; }else { return false; } } A: I got this working but i had to have it validate each of the groups separately because evidently there are othervalidation groups on the page that were not valid a la function productsValidation() { if(Page_ClientValidate('g1') && Page_ClientValidate('g2')) { return true; }else { return false; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7503870", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What rules govern inline jslint directives I'm trying to keep a jslint exclusion as close to the error as possible to not hide any errors by mistake. The unused parameter in the example is x in function f2 and I would like to only exclude this occurrence. The first example, excluding the surrounding function works, but will hide other errors if any: /*jslint unparam: true*/ function test1() { var f1 = function (x) { alert(x); }, f2 = function (x) {}; f1(0); f2(0); } /*jslint unparam: false*/ Surrounding the var statement also works, but will hide errors in f1: function test2() { /*jslint unparam: true*/ var f1 = function (x) { alert(x); }, f2 = function (x) {}; /*jslint unparam: false*/ f1(0); f2(0); } This one generates an error: "Expected an identifier and instead saw '/*jslint' (a reserved word).". function test3() { var f1 = function (x) { alert(x); }, /*jslint unparam: true*/ f2 = function (x) {}; /*jslint unparam: false*/ f1(0); f2(0); } The question is, where in the source are you allowed to have jslint directives? A: Only excluding one of the functions in the same var declaration is not possible. As said in the comment, only complete statements can have jslint directives; ended up with the following: function test4() { var f1, f2; f1 = function (x) { alert(x); }; /*jslint unparam: true*/ f2 = function (x) {}; /*jslint unparam: false*/ f1(0); f2(0); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7503872", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Java correct way convert/cast object to Double I need to convert Object o to Double. Is the correct way to convert it to String first? A: You can use the instanceof operator to test to see if it is a double prior to casting. You can then safely cast it to a double. In addition you can test it against other known types (e.g. Integer) and then coerce them into a double manually if desired. Double d = null; if (obj instanceof Double) { d = (Double) obj; } A: new Double(object.toString()); But it seems weird to me that you're going from an Object to a Double. You should have a better idea what class of object you're starting with before attempting a conversion. You might have a bit of a code quality problem there. Note that this is a conversion, not casting. A: If your Object represents a number, eg, such as an Integer, you can cast it to a Number then call the doubleValue() method. Double asDouble(Object o) { Double val = null; if (o instanceof Number) { val = ((Number) o).doubleValue(); } return val; } A: In Java version prior to 1.7 you cannot cast object to primitive type double d = (double) obj; You can cast an Object to a Double just fine Double d = (Double) obj; Beware, it can throw a ClassCastException if your object isn't a Double A: Also worth mentioning -- if you were forced to use an older Java version prior to 1.5, and you are trying to use Collections, you won't be able to parameterize the collection with a type such as Double. You'll have to manually "box" to the class Double when adding new items, and "unbox" to the primitive double by parsing and casting, doing something like this: LinkedList lameOldList = new LinkedList(); lameOldList.add( new Double(1.2) ); lameOldList.add( new Double(3.4) ); lameOldList.add( new Double(5.6) ); double total = 0.0; for (int i = 0, len = lameOldList.size(); i < len; i++) { total += Double.valueOf( (Double)lameOldList.get(i) ); } The old-school list will contain only type Object and so has to be cast to Double. Also, you won't be able to iterate through the list with an enhanced-for-loop in early Java versions -- only with a for-loop. A: I tried this and it worked: Object obj = 10; String str = obj.toString(); double d = Double.valueOf(str).doubleValue(); A: You can't cast an object to a Double if the object is not a Double. Check out the API. particularly note valueOf(double d); and valueOf(String s); Those methods give you a way of getting a Double instance from a String or double primitive. (Also not the constructors; read the documentation to see how they work) The object you are trying to convert naturally has to give you something that can be transformed into a double. Finally, keep in mind that Double instances are immutable -- once created you can't change them. A: Tried all these methods for conversion -> public static void main(String[] args) { Object myObj = 10.101; System.out.println("Cast to Double: "+((Double)myObj)+10.99); //concates Double d1 = new Double(myObj.toString()); System.out.println("new Object String - Cast to Double: "+(d1+10.99)); //works double d3 = (double) myObj; System.out.println("new Object - Cast to Double: "+(d3+10.99)); //works double d4 = Double.valueOf((Double)myObj); System.out.println("Double.valueOf(): "+(d4+10.99)); //works double d5 = ((Number) myObj).doubleValue(); System.out.println("Cast to Number and call doubleValue(): "+(d5+10.99)); //works double d2= Double.parseDouble((String) myObj); System.out.println("Cast to String to cast to Double: "+(d2+10)); //works }
{ "language": "en", "url": "https://stackoverflow.com/questions/7503877", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "31" }
Q: Passing JSONArray to PHP from Android I have read through many other questions regarding PHP and JSONArray looping. I am sending in a JSONArray of values of different students with their class and studentId from my Android device. Using these values, I search the database for their names and return a JSONArray. JSON Input: [{"studentId":"2","class":"2a","dbname":"testDb"}] <?php $jsonString = $_POST['json']; //see comment below $jArray = json_decode($jsonString, true); $conn = mysql_connect('localhost', 'user', 'pwd' ); mysql_select_db('dbname', $conn); foreach( $jArray as $obj ){ $className = $obj['class']; //String $id= $obj['studentId']; //int $result = mysql_query("SELECT name FROM student WHERE class='$className' AND id='$id'"); $e=mysql_fetch_assoc($result); //will only fetch 1 row of result $output[]=$e; } echo (json_encode($output)); ?> Android HttpClient client = new DefaultHttpClient(); HttpResponse response; try{ HttpPost post = new HttpPost("http://abc/getName.php"); List<NameValuePair> nVP = new ArrayList<NameValuePair>(2); nVP.add(new BasicNameValuePair("json", studentJson.toString())); //studentJson is the JSON input //student.Json.toString() produces the correct JSON [{"studentId":"2","class":"2a","dbname":"testDb"}] post.setEntity(new UrlEncodedFormEntity(nVP)); response = client.execute(post); if(response!=null){ //process data send from php } } SOLVED: See answer below A: SOLVED: Finally understood what was the problem. After posting from Android to PHP script, my JSONArray becomes [{\"studentId\":"2\",\"class\":\"2a\",\"dbname\":\"testDb\"}] To remove the "\", use PHP command stripslashes Spent 4 hours debugging! Hope this will be a good guide for those that wants to send and retrieve data between Android and PHP A: Here's your problem: print_r(json_decode('[{"regNo":"2","class":"2a","dbname":"TestData"}]',true)); returns Array ( [0] => Array ( [regNo] => 2 [class] => 2a [dbname] => TestData ) ) meaning your decoded json is put within an array Use array_shift(json_decode($jsonString, true)); to remove the parent array.
{ "language": "en", "url": "https://stackoverflow.com/questions/7503878", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Twitter script not working in IE9? I'm trying to get this script to work in IE9, but not sure whats wrong...it should just pull the feed of my twitter... <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ $.getJSON("http://api.twitter.com/1/statuses/user_timeline.json?screen_name=somiac&callback=?", function(data) { for(var i=0;i<data.length;i++) { if(i==3) break; console.log(data[i].text); $('.tweet_container').append("<div class='tweet'>" + data[i].text + "</div>"); } }); }); </script> A: as far as i know there is no console.log() integrated with internet explorer ...
{ "language": "en", "url": "https://stackoverflow.com/questions/7503880", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Can not get UITableView to Display NSArray Sounds like a question that has been answered... maybe but i have checked all of the possible solutions i believe and nothing will work for me. My .h file looks like this #import <UIKit/UIKit.h> @interface epsMenuPage : UIViewController<UITableViewDelegate,UITableViewDataSource>{ NSArray *listData; ... UITableView *menuList; ... } @property (nonatomic,retain) NSArray *listData; ... @property (nonatomic, retain) IBOutlet UITableView *menuList; ... @end My .m file looks like this @implementation epsMenuPage @synthesize listData; ... @synthesize menuList; - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // Custom initialization } return self; } - (void)didReceiveMemoryWarning { // Releases the view if it doesn't have a superview. [super didReceiveMemoryWarning]; // Release any cached data, images, etc that aren't in use. } #pragma mark - View lifecycle - (void)viewDidLoad { //Arrays credit,debit and both creditListData = [[NSArray alloc]initWithObjects:@"Return",@"Force Sale",@"Authorize Only",@"Total Sales",@"Items Sold",@"Reciept's", nil]; debitListData = [[NSArray alloc]initWithObjects:@"Return",@"Force Sale",@"Authorize Only",@"Total Sales",@"Items Sold",@"Reciept's", nil]; bothListData = [[NSArray alloc]initWithObjects:@"Batch History",@"Settle Batch", nil]; self.listData = creditListData; [menuList reloadData]; [super viewDidLoad]; // Do any additional setup after loading the view from its nib. self.view.backgroundColor =[UIColor colorWithRed:255/255.0 green:95/255.0 blue:95/255.0 alpha:1.0]; [colorChange setBackgroundColor:[UIColor colorWithRed:255/255.0 green:95/255.0 blue:95/255.0 alpha:1.0]]; [self.view addSubview:creditTabButton]; [self.view addSubview:debitTabButton]; [self.view addSubview:bothTabButton]; [self.view addSubview:creditButtonText]; [self.view addSubview:debitButtonText]; [self.view addSubview:bothBottonText]; [self.view addSubview:colorChange]; } - (void)viewDidUnload { [self setTitleBAckButton:nil]; [self setTitleSettingsButton:nil]; [self setCreditTabButton:nil]; [self setDebitTabButton:nil]; [self setBothTabButton:nil]; [self setMenuList:nil]; [self setColorChange:nil]; [self setCreditButtonText:nil]; [self setDebitButtonText:nil]; [self setBothBottonText:nil]; [super viewDidUnload]; // Release any retained subviews of the main view. // e.g. self.myOutlet = nil; } - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { // Return YES for supported orientations return (interfaceOrientation == UIInterfaceOrientationPortrait); } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [self.listData count]; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *SimpleTableIdentifier = @"tableID"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SimpleTableIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:SimpleTableIdentifier] autorelease]; } NSUInteger row = [indexPath row]; cell.textLabel.text = [self.listData objectAtIndex:row]; return cell; } - (void)dealloc { [titleBAckButton release]; [titleSettingsButton release]; [creditTabButton release]; [debitTabButton release]; [bothTabButton release]; [menuList release]; [colorChange release]; [creditButtonText release]; [debitButtonText release]; [bothBottonText release]; [listData release]; [super dealloc]; } - (IBAction)titleBackClick:(id)sender { [self.parentViewController dismissModalViewControllerAnimated:YES]; } - (IBAction)titleSettingsClick:(id)sender { } - (IBAction)creditTabClick:(id)sender { self.listData = creditListData; [menuList reloadData]; [colorChange setBackgroundColor:[UIColor colorWithRed:255/255.0 green:95/255.0 blue:95/255.0 alpha:1.0]]; [self.view addSubview:creditTabButton]; [self.view addSubview:creditButtonText]; [self.view addSubview:colorChange]; self.view.backgroundColor = [UIColor colorWithRed:255/255.0 green:95/255.0 blue:95/255.0 alpha:1.0]; } - (IBAction)debitTabClick:(id)sender { self.listData = debitListData; [menuList reloadData]; [colorChange setBackgroundColor:[UIColor colorWithRed:244/255.0 green:133/255.0 blue:33/255.0 alpha:1.0]]; [self.view addSubview:debitTabButton]; [self.view addSubview:debitButtonText]; [self.view addSubview:colorChange]; self.view.backgroundColor = [UIColor colorWithRed:244/255.0 green:133/255.0 blue:33/255.0 alpha:1.0]; } - (IBAction)bothTabClick:(id)sender { self.listData = bothListData; [menuList reloadData]; [colorChange setBackgroundColor:[UIColor colorWithRed:72/255.0 green:72/255.0 blue:255/255.0 alpha:1.0]]; [self.view addSubview:bothTabButton]; [self.view addSubview:bothBottonText]; [self.view addSubview:colorChange]; self.view.backgroundColor = [UIColor colorWithRed:72/255.0 green:72/255.0 blue:255/255.0 alpha:1.0]; } @end I really for the life of me can not figure out why it wont display to my TableView, i have tried so many different tutorials. any help is greatly appreciated. A: You're never adding the menuList table view to your view. Add it and see if that does the trick: // In -viewDidLoad [self.view addSubview:menuList]; EDIT 1: Did you declare properties in your .h? These aren't visible, so it appears as if you're not creating or adding your table view to the view controller's view. However, if you are using IBOutlets, then this probably isn't the issue. EDIT 2: From the comments below, your dataSource is nil, which is exactly why nothing is being displayed. Make sure your table view in Interface Builder has its dataSource outlet pointing to your view controller. To be double sure, delete the table view from Interface Builder and add it back again. Make sure your connections are exactly right. Also try cleaning the project and rebuilding, as well as restarting Xcode. A: It looks like you are missing the required datasource method: - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView; { return 1; } Also, it looks like you are not actually initializing your UIButton's, or anything you are adding as a subview. Are you using a nib?
{ "language": "en", "url": "https://stackoverflow.com/questions/7503881", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Int-Pointer to unmanaged code I'm pretty new to C# and have a simple(?) question. From unmanaged code I receive an int-pointer: public foo(ref IntPtr state) { _myState = state; } _myState is a IntPtr member of the class. Now I want to exchange states via _myState with the unmanaged C++ code. Everything works if I write this: public foo(ref IntPtr state) { _myState = state; ....do some stuff state = 7; } In the unmanaged application I can see the new value 7. But if I write this: public foo(ref IntPtr state) { _myState = state; ...do some stuff _myState = 7; } then nothing happens. The initial value of state is 0, and when changing myState to 7 it is not updated in the unmanaged application. How can I assign a member variable like _myState to the state parameter as a "pointer", so when state is updated, _myState is also updated? In C++ this would be no problem with a pointer... Ok, here is the real code: [DllExport("QFX_InitializeInterfaceObject", CallingConvention = CallingConvention.StdCall)] public static void QFX_InitializeInterfaceObject( long windowHandle, ref IntPtr processState) { ChartWindowHandle = (IntPtr)windowHandle; OrderCommandProcessState = processState; } All I want is that OrderCommandProcessState gets the same reference as processState to its value. A: First off, I want to make sure this point is clear: an IntPtr is just an integer that happens to be the same size as a native pointer on that machine architecture -- it's a 64 bit integer on x64 systems, for example. It does not necessarily have the semantics of a pointer, though of course it is common for interop code to stuff pointers into IntPtrs as a way of marshalling them around safely. Moving on to your specific question, let's ignore the fact that it's an IntPtr. Pretend it's just an int, because that's basically what it is: public void Foo(ref int x) // x is an alias to another variable of type int. { int y = x; // y is a copy of the contents of x y = 7; // The contents of y are no longer a copy of the contents of x } Changing y does not in any way change x; x is an alias to a different variable, and y briefly has a copy of the contents of that variable. It is not in any way an alias to that same variable. How can I make one variable into an alias to another variable, so when the state of the one variable is updated, the linked variable is also updated? In C++ this would be no problem with a pointer. Today in the safe subset you can only do so via "ref" and "out" parameters to methods. The "ref" parameter becomes an alias to the given variable. That is the only safe way that you can directly make one variable into an alias for another. The CLR supports ref locals as well. We could implement such a feature, and in fact I have prototyped it in C#. In my prototype you could say: public void Foo(ref int x) // x is an alias to another variable of type int. { ref int y = ref x; // y is now an alias to the same variable that x aliases! y = 7; // changing y now changes x, and whatever x // aliases, because those are all the same variable } But we have not added this feature to C# and have no plans to do so any time soon. If you have a compelling usage case for it, I'd love to hear it. (UPDATE: The feature was added to C# 7.) (The CLR also permits "ref" return types. However, the CLR does NOT permit making an alias to a variable and then storing that alias in a field! The field might be of longer lifetime than the linked variable, and the CLR designers wish to avoid that whole class of bugs that plagues C and C++.) If you know that the variable is pinned to a particular location in memory then you can turn off the safety system and make a pointer to that variable; you then have a perfectly ordinary pointer that you can use as you would in C++. (That is, if a pointer ptr refers to a variable then *ptr is an alias to that variable.) unsafe public void Foo(int* x) // *x is an alias to a variable of type int. { int* y = x; // *y is now an alias to the same variable that *x aliases *y = 7; // changing *y now changes *x, and whatever *x // aliases, because those are all the same variable } The CLR puts no restrictions on how pointers can be used; you are free to store them in fields if you want. However, if you turn the safety system off then you are responsible for ensuring that the garbage collector (or whatever memory manager owns that storage -- it might not be managed memory) is not going to change the location of the aliased variable for the lifetime of the pointer. Do not turn off that safety system unless you really know what you are doing; that safety system is there to protect you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7503883", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Adding action to DOM element added through AJAX having a slight problem here. I have a post stream on my site, each post has buttons that execute different actions that are setup in my $(document).ready() now, to add posts I make an AJAX call that returns the html for the new post element, but the actions in the my previous $(document).ready() do not apply to this new element, and adding it in a $(document).ready() for the element causes the buttons from the already posted elements to be duplicated. Any idea how I can get around this? A: The elements that added after documnet ready event don't accept binding events (you call it ations). You may use .click() or .hover() or .bind('click', function(){}) and neither works. You can use jQuery .live() or .delegate() Using delegate is much better because when you use live for click (for example) it means you'r listening to any click happening on your document and determining if it's that click you where looking for or not? But with delegate you limit the clicks that computer process to find your click. $('.myinput').live('click', function(){ // do something if a click happened and it was on my input }) $('.myDiv').delegate('.myinput', 'click', function(){ // do something if a click happened in my div and it was on my input }) A: if you use $(selector).live(eventType, handler) it should add events to all elements matching that selector.. even if they are added after the DOM is loaded: http://api.jquery.com/live/ A: like @Mohsen said there was a way to solve this using .live() now its depreciated and there is alternate way: How to change depreciated method? $( selector ).live( events, data, handler ); // jQuery 1.3+ $( document ).delegate( selector, events, data, handler ); // jQuery 1.4.3+ $( document ).on( events, selector, data, handler ); // jQuery 1.7+ link: jQuery .live() I had thesame problem and this last one with ".on" works fine for me. Maybe someone have thesame problem and use it too
{ "language": "en", "url": "https://stackoverflow.com/questions/7503886", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can i make a screenshot of an HTML page (jpeg, png, etc..)? I just want to make a screenshot of the website like it is rendered in the browser and save it as an image programaticaly. Let's say i have a website, and i want a preview function when i scroll over a link. From my research i found that i can start a firefox instance from command line, and there is some plugin that can make the screenshot and return it, than shutting down the instance. But, in order to do this i need to start the xserver and i don't want to do this as it's potencialy dangerous for my server from a security point of view. My ideea is to create a virtual machine on the server running xserver with firefox, and my script to connect to the virtual machine, start the firefox instance there, get the image and return it to the browser. This should be possible but seems to be very complicated. So my question is: Do you know any other alternative to accomplish this in a more simple/elegant way? Your opinions are highly appreciated. A: Ok, I found a good solution. I can use CasperJS/PhantomJS (http://casperjs.org/) or other headless browser, so I don't need the xserver running. Thanks all for support ! A: Cutycapt is what you need: CutyCapt is a small cross-platform command-line utility to capture WebKit's rendering of a web page into a variety of vector and bitmap formats, including SVG, PDF, PS, PNG, JPEG, TIFF, GIF, and BMP. It is already packaged in Debian (available since Squeeze) and Ubuntu.
{ "language": "en", "url": "https://stackoverflow.com/questions/7503890", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Android AppWidget, Massive layout discrepancy I'm creating an App Widget, and I'm having a strange issue. In the Eclipse graphical layout editor, my widget's layout looks like this: However, when I install it on an emulator/my phone, it looks like this: And here is the layout code in question: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_gravity="center_horizontal" android:gravity="center_horizontal"> <RelativeLayout android:background="@drawable/blackbg" android:layout_width="290dp" android:layout_height="145dp"> <ImageView android:layout_width="wrap_content" android:src="@drawable/clock_colon" android:layout_height="107dp" android:layout_marginRight="10dp" android:layout_marginLeft="10dp" android:layout_marginTop="5dp" android:layout_centerInParent="true" android:id="@+id/colon" /> <ImageView android:layout_width="wrap_content" android:src="@drawable/num_0" android:layout_height="107dp" android:layout_marginRight="5dp" android:layout_marginLeft="5dp" android:id="@+id/hour2" android:layout_toLeftOf="@id/colon" android:layout_centerVertical="true" /> <ImageView android:layout_width="wrap_content" android:src="@drawable/num_1" android:layout_height="107dp" android:layout_marginRight="5dp" android:layout_marginLeft="5dp" android:id="@+id/hour1" android:layout_marginTop="5dp" android:layout_toLeftOf="@id/hour2" android:layout_centerVertical="true" /> <ImageView android:layout_width="wrap_content" android:src="@drawable/num_3" android:layout_height="107dp" android:layout_marginRight="5dp" android:layout_marginLeft="5dp" android:id="@+id/minute1" android:layout_marginTop="5dp" android:layout_toRightOf="@id/colon" android:layout_centerVertical="true" /> <ImageView android:layout_width="wrap_content" android:src="@drawable/num_2" android:layout_height="107dp" android:layout_marginRight="5dp" android:layout_marginLeft="5dp" android:id="@+id/minute2" android:layout_marginTop="5dp" android:layout_toRightOf="@id/minute1" android:layout_centerVertical="true" /> <ImageView android:layout_width="wrap_content" android:src="@drawable/clock_pm" android:layout_height="wrap_content" android:id="@+id/clock_ampm" android:layout_below="@id/minute2" android:layout_alignParentRight="true" android:layout_marginRight="15dp" android:layout_marginBottom="5dp" /> </RelativeLayout> </LinearLayout> So what do you think? How come the numbers are getting cut off and spaced strangely like this. Thanks! A: You are setting manually the height of your RelativeLayout and the height of your ImageViews to 107dp and your images may not fit properly inside your ImageView. So you should consider the following: * *Supporting Multiple Screens Resources *Setting the scale of your ImageView to android:scaleType:centerInside *You should also consider using wrap_content for your layout height and width instead of manually setting the dimensions in dp *You can also try the attribute android:adjustViewBounds="true" for your ImageViews if they still don't get displayed correctly A: The problem ended up being that I had set the size for the container RelativeLayout. Apparently you can't do that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7503901", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to reduce memory pressure and thread usage when handling a large file upload in ASP.NET? What I would like to do is stream the request to a file store asynchronously so that the incoming request does not take up a lot of memory and so that handling thread is not held up for IO. I see that there is an asynchronous HTTP handler that I can implement. This looks like it would help with the thread usage, but it looks like the request has already been fully copied into memory by this point by IIS/ASPNET. Is there a way to keep ASP.NET from reading the entire request in before handling it? A: There is a new method added to the HttpRequest in .NET 4 called GetBufferlessInputStream(), which gives you synchronous access to the request stream. From the MSDN article: This method provides an alternative to using the InputStream property. The InputStream property waits until the whole request has been received before it returns a Stream object. In contrast, the GetBufferlessInputStream method returns the Stream object immediately. You can use the method to begin processing the entity body before the complete contents of the body have been received. The ability to access the request stream asynchronously will be available in .NET 4.5. See the What's New in ASP.NET 4.5 article for more information. It looks like there will be several nice ASP.NET performance improvements in 4.5. A: you are not searching SO enough. the solution you need is explained here, step by step, in very much details: Efficiently Uploading Large Files via Streaming check this one, your question is a duplicated: Streaming uploaded files directly into a database table A: While this SO question is specifically about MVC, the answers should work for ASP.NET generally. Specifically, people appear to have had a good experience with Darren Johnstone's UploadModule.
{ "language": "en", "url": "https://stackoverflow.com/questions/7503902", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Simulate this slider effect with jquery (instead of mootools) [Horizontal accordion effect] I can use javascript and everything else, but before reinventing the wheel, I would like to know if there is already a similar plugin for jquery because I would like to use that framework and not mootools. I don't have problems with money, expecially for a 5€ template, but really I would like to use jquery because I studied it and not mootools. The template: http://www.globbersthemes.com/demo/upsilum/ EDIT 1: I changed the title for future references for people that know the correct name of this type of effect, thanks to everyone. A: i always liked the jquery tools tabs for this - see http://flowplayer.org/tools/demos/tabs/accordion-horizontal.html A: Here a plugin that might interest you : http://www.portalzine.de/Horizontal_Accordion_Plugin_2/index.html A: Here, I reinvented the wheel. But had looot of fun! :) Tested in all modern browsers + IE 6-7-8 * *Instead of using 'title' images now you can use classic editable text! *Set desired 'start' tab EDIT: added/fixed title support (rotaion for IE 6-7-8) H - ACCORDION DEMO The simple HTML: <div id="acc"> <div class="title"><p class="button">Title 1</p></div> <div class="cont">Cont 1</div> <div class="title"><p class="button">Title 2</p></div> <div class="cont">Cont 2</div> <!-- more tabs here.... --> </div> The CSS style Ex: .title{ cursor:pointer; position:relative; float:left; width:20px; height:200px; background:#444; color:#ccc; padding:15px; border-left:3px solid #aaa; } .cont{ position:relative; float:left; width:300px; background:#999; height:200px; padding:15px; } .slide{ position:relative; float:left; overflow:hidden; width:0px; } .active{ background:#cf5; color:#444; } .button{ white-space:nowrap; margin-top:180px; font-size:20px; line-height:25px; text-align:left; } And the fun part: jQuery ! //+IE678//// HORIZONTAL ACCORDION // roXon ////// var curr = 3; // set desired opened tab var contW = $('.cont').outerWidth(true); $('.cont').wrap('<div class="slide" />'); $('.slide').eq(curr-1).width(contW).prev('.title').addClass('active'); $('.title').click(function(){ $(this).addClass('active').siblings().removeClass('active'); $('.slide').stop().animate({width:0},700); $(this).next('.slide').stop().animate({width:contW},700); }); // TITLE ROTATION IE 6-7-8 FIX // var titleH = $('.title').height(); var btn = $('.button'); btn.css('-webkit-transform','rotate(-90deg)'); btn.css('-moz-transform','rotate(-90deg)'); btn.css('transform','rotate(-90deg)'); if($.browser.msie && $.browser.version<="8.0"){ btn.css({ filter: 'progid:DXImageTransform.Microsoft.BasicImage(rotation=3)', width: titleH+'px', position:'absolute', marginTop:'0px' }); } One more thing- you'll just have to wrap the accordion into a positioned 'container' with set height and width to avoid accordion elements 'dance' on window resize.
{ "language": "en", "url": "https://stackoverflow.com/questions/7503905", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Attempting to write constructors for subclass inheriting from class, guessing at syntax, expected-primary-expression error? I have a class Sphere that inherits from class Shape (for a homework project): Within Shape I have three constructors. The declarations from Shape.h are as follows: Shape(); Shape(Vector); Shape(Vector, float[]); Within Sphere my constructors inherit from these constructors. The declarations in my Sphere.h file are as follows: Sphere(): Shape() {}//line 17 Sphere(Vector, float): Shape(Vector) {}//line 18 Sphere(Vector, float, float[]): Shape(Vector, float[]) {}//line 19 My syntax here is based largely on looking at templates. While my first language was C++, I was unfortunately taught other concepts, like inheritance, only in Java. Anyway, I have the following error messages upon `make': Sphere.h: In constructor ‘Sphere::Sphere(Vector, float)’: Sphere.h:18: error: expected primary-expression before ‘)’ token Sphere.h: In constructor ‘Sphere::Sphere(Vector, float, float*)’: Sphere.h:19: error: expected primary-expression before ‘,’ token Sphere.h:19: error: expected primary-expression before ‘float’ Can you help me understand these messages and what might be causing them? I first tried letting them be expressed in the typical way, i.e., instead of Sphere(): Shape(); and then describing the constructor itself in the .cc file, I did as I had seen done in some online tutorials, without really understanding why: Sphere(): Shape() {} This didn't change anything, the problem remained. Thanks for your help! A: You need to specify names, not just types, for the parameters, and pass the names, not the types. For example: Sphere(Vector a, float b, float[] c): Shape(a, c) {} A: You haven't given your constructor arguments any names. This is ok, so long as you don't actually want to use those arguments! A: Your initialization list belongs in the constructor's implementation and isn't part of the constructor's declaration (or prototype). You seem to be putting it with both. You can either do: // Sphere.h struct Sphere { Sphere(); }; // Sphere.cpp Sphere::Sphere() : Shape() { } Or you can do: // Sphere.h struct Sphere { Sphere() : Shape() { } }; // Sphere.cpp // No constructor here; you defined it in the header.
{ "language": "en", "url": "https://stackoverflow.com/questions/7503917", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: From iPhone to Mac i've ben creating an iPhone game like theEagle1100 teaches in a YouTube tutorial. But now I want to do the same for Mac, and I'm real noob. My first problem is that I don't know how to get the ball move. For iPhone it worked like this: ball.center = CGPointMake(ball.center.x + ballVelocity.x, ball.center.y + ballVelocity.y); I can set the location of ball like this: [ball setFrame:CGRectMake(144, 30, 32, 32)]; then I add the ballVelocity to the y value like this: [ball setFrame:CGRectMake(144, 30 + ballVelocity.y, 32, 32)]; but now it adds it to 30. How can I add velocity to the current location of the ball so it could move???? A: Just like you did with ball.center.y, you just use the frame's origin instead of the center. NSRect frame = [ball frame]; frame.origin.y += ballVelocity.y; [ball setFrame:frame];
{ "language": "en", "url": "https://stackoverflow.com/questions/7503919", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Problems with update_attributes for boolean field I have my model like this field :first_name, :type => String field :last_name, :type => String field :admin, :type => Boolean, :default => false field :write_article, :type => Boolean, :default => false Now, when I try to update my model with @user = User.find(params[:id]) if @user.update_attributes(params[:user]) flash[:notice] = "Successfully updated User." redirect_to users_path else render :action => 'edit' end the write_article field is not updated. It is always false. I tried to debug the code and I do get write_article = 1 in the params[:user]. However when updating the value is still set to false. So, I had to add the following @user.write_article = params[:user]['write_article'] explicitly set the value before using update_attributes call. Any suggestion? It should have worked without the above line A: Your code indicates that you aren't using ActiveRecord. If you are using an ORM other than ActiveRecord, you might want to mention which one you use (e.g., DataMapper, Mongoid). If your field is not updated for some reason, that might be due to mass assignment. Try adding attr_accessible :admin. See the details on the mass assignment issue at the Rails Guide.
{ "language": "en", "url": "https://stackoverflow.com/questions/7503923", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Sql Query Help in select statement/Oracle Discoverer I have a table as follows. Id Code Indicator 1 AB 1 CD Y 1 EF 2 BC Y 3 AB 4 GH 4 AB Y 5 CD 5 BC Now I need to retrieve the ID's which do not have any indicator associated to them. In this case, the retrieved rows should be ID Code Indicator 3 AB 5 CD 5 BC Thanks to y'll I got it in sql but I have the same table as a view in Oracle discoverer. How do i write a report to get the same result?All help much appreciated!! A: This should do it (Warning: Untested): select id, code from table where id not in (select id from table where indicator='Y') A: SELECT * FROM TABLE t1 WHERE T1.ID in (SELECT t2.ID FROM Table t2 GROUP BY t2.ID HAVING MAX(t2.Indicator) = 'Y')
{ "language": "en", "url": "https://stackoverflow.com/questions/7503924", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: DB2 Select Query with data in file Lets say I have a csv file(ids.csv) with ids like 101,102,103......1MILLION I wanted to select data from the table by reading ids from file in the where clause Something like select * from employee where id in (<I wanted to read ids from external csv file>) Is this possible in any database. I am interested in db2. Due to limitation in character length in sql if i put all these ids in in clause its not allowing to run a query. Right now I am chunking ids in to smaller set and running the query. A: Import the data into a table using the DB2 IMPORT command. It will be something like: db2 import from ids.csv of del create into id_table You can read more about the command at the above link. Once that's done it's a simple matter of: select * from employee where id in (select id from id_table)
{ "language": "en", "url": "https://stackoverflow.com/questions/7503928", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP IMAP not working, installed with Macports I recently installed PHP5 with Macports using sudo port install php5 +imap. However, when I run /opt/local/bin/php -i, I don't see the IMAP module listed under the other modules. Is there an additional step or change I need to make to php.ini or otherwise to get this module enabled? Also, running /usr/bin/php -i (I believe this is the php NOT installed by Macports) also does not show IMAP configured. A: PHP modules have been available as variants in previous versions of the php5 port, but have been moved into their own ports long time ago. You can see the available variants with port variants php5, which does not list that +imap anymore. Most probably you followed an oudated tutorial. To get the IMAP module install the port php5-imap: sudo port install php5-imap
{ "language": "en", "url": "https://stackoverflow.com/questions/7503930", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Facebook session in an iframe application breaks ajax calls I've a facebook application, which conncets to facebook via the PHP-SDK. $facebook = new Facebook(array( 'appId' => FACEBOOK_APP_ID, 'secret' => FACEBOOK_SECRET_KEY, )); $user = $facebook->getUser(); if ($user) { try { $user_profile = $facebook->api('/me'); } catch (FacebookApiException $e) { error_log($e); $user = null; } } Everything is fine, I let the browser open and don't respond to my app. After a while I try to send a form in the app via ajax. It seems that the session is invalid? Facebook will authorize my app again load the ajax url into the browsers address bar and attach the new session param to that url and breaks the app. Is there anything I could do to pretend facebook to "reload" or pass the ajax/form action to the browser address bar? Before every request is processed I check whether the user is still active or not, that might be the problem? $user = $facebook->getUser(); if ($user != 0) { if($this->userProfile == null){ try { // Proceed knowing you have a logged in user who's authenticated. $this->userProfile = $facebook->api('/me'); } catch (FacebookApiException $e) { error_log($e); $user = null; } } }else{ $this->userProfile = null; } if ($this->userProfile != null) { $filterChain->run(); } else { $loginUrl = $facebook->getLoginUrl( array('scope' => 'publish_stream','redirect_uri' => 'REDIRECT_URI')); } echo("<script> top.location.href='" . $loginUrl . "'</script>"); Should I use an other approch? Thanks in advance! A: You really shouldn't be processing ajax calls the same way as regular page fetches. Generally if something like an expired session happens within an ajax process you want to send an error code back to the main page and let it handle it at the top level. I'm guessing that the info you send back from this ajax request gets immediately parsed as HTML? Which means that if you send back a <script>top.location=xxx</script> block, it gets executed and redirects the browser to the new location. Again that's probably not the best way to handle things, but it would still work if the redirect_uri were set appropriately (to the url of the page as a whole). Because the getLoginUrl() is called while within the ajax page, the redirect_uri is set to that url instead, so after the new authorization is completed that's where the browser is sent back to (at the top level now). So while probably not the best overall structure, a quick workaround would be to override the redirect_uri setting when you are within an ajax call, and make it point to the parent page instead of itself.
{ "language": "en", "url": "https://stackoverflow.com/questions/7503933", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Add "My Cart" to top.links magento in local.xml or checkout.xml? Two parts to this question: * *How can I add My Cart to either local.xml or checkout.xml? I have a custom template, that never had it called. Looking for where it is being removed, but not sure I am looking in the right place. I have tried adding to local.xml <reference name="root"> <reference name="top.links"> <action method="addCartLink"></action> </reference> </reference> But it breaks magento. Basically I have a soft add to cart and want to pull the default magento "My Cart" to the header, so the ajax updates on page like it does in the default magento template. 2nd par - Where does the code for "My Cart" live to tweak it? A: <reference name="top.links"> <block type="checkout/links" name="checkout_cart_link"> <action method="addCartLink"></action> </block> </reference> You may have to clear your cache.
{ "language": "en", "url": "https://stackoverflow.com/questions/7503937", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can we run a batch file (.bat) from the shared path I have a shared path (like //servername/c$/batches/) where all my batch files are located now I am writing an web application in C# to run .bat files from that application. I know way to do it when I have a physical path. But here I dont have a physical path. Is it possible to do it. EDIT# 1 I execute my bat files just by double clicking on them or open the cmd progam on the physical server and then navigate to the drive and execute the bat file. EDIT #2 when I put UNC path the get the following error I getting an error myprogram.exe is not recognized as an internal or external command operable program or batch file. 9009 A: Batch files don't support UNC paths as their "current directory". There's a hackish work around of doing: pushd "%~dp0" your batch stuff popd %~dp0 expands to the current (d)rive/(p)ath/(0)batchfilename example: ok. a Simple batch file: pushd %~dp0 echo "Hello from batch land" echo %~dp0 popd put that on a server somewhere, and try to run it via a unc path: C:\> \\server\share\test.bat You'll get as output: C:\>pushd \\server\share\ Z:\>echo Hello from batch land Hello from batch land Z:\>echo \\server\share\ \\server\share\ Z:\>popd C:\> Weird, but it works. A: That's called a UNC path. You can use it just like any other path. However, the user that your ASP.Net code is running as must have read access to the network share. A: Apparently, you do have a current-directory issue. The .bat file is trying to run myprogram.exe from the current directory. You can make a wrapper batch file on your local machine that maps the network share: pushd \\server\c$\dir call filename.bat popd You can put this wrapper file anywhere, then call it from your code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7503944", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Detect a keystroke in matlab while viewing a figure? I'm trying to sort through some image data in matlab and want to prompt the user for input about a series of images. Each time I show an image I want to pause and wait for a keystroke and perform a different action depending on what was pressed. Current Best Solution: responses = zeros(length(images),1); for i = 1:length(images) im = imread(images{i}.fname); h = figure(1); imshow(im); % instead of just pause, I want to get the keystroke (k) that was pressed waitforbuttonpress; k = get(h,'CurrentCharacter'); switch lower(k) case 'a' responses(i) = 1; case 'b' responses(i) = 2; end end A: You could use the KeyPressFcn property of the figure environment which should be set to a handle of a callback function that receives an event structure containing the character pressed. See the Matlab documentation for details and example. Also you can look at the CurrentKey property of the figure environment but it will not give you a way to know when the key is actually pressed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7503963", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I see what jQuery Mobile loaded in the background? Using jQuery Mobile, I have seen how it adds to the existing DOM when links are clicked and a related page is served. Then, when ready, it switches to that new data-role="page". But when I do a "view source" in the browser (Google Chrome or Mozilla Firefox), I see the original page, as delivered, without the additional things loaded later (DOM injections). How can I see what the browser really has (post-render HTML)? If it happens to be a JavaScript solution, please don't presume I know where to put it and how to trigger it to show the content. A: In Chrome: Wrench > Tools > Developer Tools would be a way to see the 'live' DOM.
{ "language": "en", "url": "https://stackoverflow.com/questions/7503968", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Understanding AsyncTask Once an AsyncTask call is finished is the thread deleted? I stored an AsyncTask in a var "guiThread = (GUIAsyncTask) new GUIAsyncTask()". The first call to execute() works but subsequent calls don't. So, do I just create new tasks whenever I need them? I was under the impression that I used my variable over and over and calling new over and over would spin up thousands/millions of threads. A: AsyncTasks are one-time uses. They start, execute, then die. Then you have a choice of keeping the reference around to gather information from it that may be stored in the class post-execute, or dumping the reference and letting the garbage collector handle it. If you want to start the AsyncTask again, you have to create a new object and start it. A: Nope you need to create a new AyncTask everytime you want to use it. A: An AsyncTask must be created any time it is to be used
{ "language": "en", "url": "https://stackoverflow.com/questions/7503970", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: NSManagedObjectContext's registeredObjects won't return anything unless a fetch is executed beforehand Cheers, I'm experiencing a problem with core data, I guess I'm just looking in the wrong direction again. My managedObjectContext will return an empty NSSet if I call registeredObjects on it. If I execute a fetch beforehand however, it will return the same objects that as the fetch did just a moment ago. There's no multithreading going on. Here's what I do: [self setupContext]; // This will set up managedObjectContext, which is a property of this class // Fetching... NSFetchRequest *request = [[NSFetchRequest alloc] init]; NSEntityDescription *foo = [NSEntityDescription entityForName:@"Foo" inManagedObjectContext:managedObjectContext]; [request setEntity:foo]; NSError *fetchError = nil; NSArray *fetchResults = [managedObjectContext executeFetchRequest:request error:&ftchError]; NSLog(@"Fetch returned %i objects.", [fetchResults count]); [request release]; // Done fetching... NSArray *allObjects = [[managedObjectContext registeredObjects] allObjects]; NSLog(@"Context contains %i objects...", [allObjects count]); The store contains 30 objects. If I run the code above, both NSLogs will report five objects. If I remove the fetch part between the two comments, it will report zero objects for the whole context. Note that I am at no point commiting or otherwise changing the contexts contents. Do I need to force the context into refreshing itself first? I've never done this before though and I don't recall registeredObjects failing on me like this on other occasions in the first place. Any suggestions appreciated! Toastor A: You may be confused about what registeredObjects means. This is the set of objects that are currently in the NSManagedObjectContext. This is not the set of objects in the store, just the ones in the context. If you haven't fetched or otherwise registered the objects in the context, then they won't be in registeredObjects.
{ "language": "en", "url": "https://stackoverflow.com/questions/7503971", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Need some help understanding faulting in Core Data I have a Core Data entity that uses a custom subclass of NSManagedObject. I have a few instance variables and properties on it that aren't associated with Core Data attributes or relationships. An example of the kind of thing I'm doing is this: @interface Root : NSManagedObject { Foo *foo; Bar *bar; } @property (nonatomic, retain) Foo *foo; @property (nonatomic, retain) Bar *bar; // Core Data generated @property (nonatomic, retain) Node *relationship; @property (nonatomic, retain) NSString *attribute; -(void)awake; @end @implementation Root @synthesize foo; @synthesize bar; @dynamic relationship; @dynamic attribute; -(void)awakeFromInsert { [super awakeFromInsert]; [self awake]; } -(void)awakeFromFetch { [super awakeFromFetch]; [self awake]; } -(void)awake { Foo *newFoo = [[Foo alloc] init]; self.foo = newFoo; [newFoo release]; // bar is not automatically initialized, but can be set by something external } -(void)didTurnIntoFault { [foo release]; foo = nil; [bar release]; bar = nil; [super didTurnIntoFault]; } @end Now in my app I get an instance of Root by a fetch request once when the app launches, and I retain it until the app quits. (Actually it's a bit more complicated because you can delete the root instance and create a new one, but at most one exists at a time and it is retained.) So my hope is that didTurnIntoFault will never be called until my app quits. If it did, then at some point I would refer to root.foo or root.bar and get nil. That would be an error for my app. A Root instance should always have a non-nil value for foo and bar; foo is created whenever the instance is loaded, and bar is set by the caller immediately after fetching the root instance. Can I rely on didTurnIntoFault not being called, if my code is retaining the NSManagedObject? If I don't want didTurnInfoFault to be called, why do I have it? Well, I have to clean up sometime. Maybe I should really put that code into dealloc, if I don't want those instance variables released until the program quits. But I think I read some documentation that discouraged using dealloc for subclasses of NSManagedObject. A: If your object exists in the underlying file store then it can potentially be faulted out at any time due to low memory warnings etc. But from your code it looks like all you need is a simple lazily-initialized property, i.e. override the 'foo' getter like this: - (Foo *)foo { if (!foo) { foo = [[Foo alloc] init]; } return foo; // or [[foo retain] autorelease] if you need that safety } This is guaranteed not to return nil, and you can still release and nil out the instance variable if you want in didTurnIntoFault. The next time the getter is called a new ivar will be initialized again. A: My interpretation of the documentation is that your object won't be turned back into a fault unless you do it yourself (refreshObject:mergeChanges and a couple of other methods in the docs: http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CoreData/Articles/cdPerformance.html#//apple_ref/doc/uid/TP40003468-SW4). It also does explicity tell you not to override dealloc, so I would say you're doing the right thing. Would be very interested to hear other thoughts on the topic, though.
{ "language": "en", "url": "https://stackoverflow.com/questions/7503972", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How do I add a new element to the existing XML file on Windows Phone 7 using LINQ to XML? For the last couple of hours I was struggling with LINQ to XML on Windows Phone 7. I simply just want to add new element to an existing XML file. XElement newItem = new XElement("item",new XAttribute("id",3), new XElement("content","Buy groceries"), new XElement("status","false")); IsolatedStorageFile isFile = IsolatedStorageFile.GetUserStoreForApplication(); IsolatedStorageFileStream stream = new IsolatedStorageFileStream("/Items.xml", System.IO.FileMode.Open, isFile); XDocument loadedDoc = XDocument.Load(stream); loadedDoc.Add(newItem); loadedDoc.Save(stream); Generally I'm experiencing very weird behavior. Sometimes I am getting an error "Operation not permitted on IsolatedStorageFileStream.". Sometimes it is "Root element is missing" and sometimes it is "Unexpected XML declaration. The XML declaration must be the first node in the document, and no white space characters are allowed to appear before it." If, for example, I would change System.IO.FileMode.Open to Create I would get "Root element is missing" but apart from that there doesn't seem to be any pattern according to which error occurs. It all seems like its my XML file which causes the problem: <?xml version="1.0" encoding="utf-8" ?> <items> <item id="1"> <content>Get groceries</content> <status>false</status> </item> <item id="2"> <content>Wash your car</content> <status>true</status> </item> </items> It doesn't get any simpler than that and I am absolutely sure I don't have any white spaces before the declaration in the actual XML file. And to make it all even more weird I have downloaded little sample application that uses the same technique of writing to XML file. When I try to run it I am getting a very familiar error: Unexpected XML declaration. The XML declaration must be the first node in the document, and no white space characters are allowed to appear before it. Here is link to that thread: http://mobileworld.appamundi.com/blogs/petevickers/archive/2010/12/06/windows-phone-7-linq-to-xml-corruption.aspx/ Yesterday I installed Windows Phone SDK 7.1 BETA. Could that be causing the problem? It seems like the problem is with locating xml file in isolated storage. I have created completely new project and new xml file inside. Thats the only code I have: // Constructor public MainPage() { InitializeComponent(); var isFile = IsolatedStorageFile.GetUserStoreForApplication(); var stream = isFile.OpenFile("file.xml", System.IO.FileMode.Open, System.IO.FileAccess.ReadWrite); } I'am still getting: Operation not permitted on IsolatedStorageFileStream. I have tried going into properties of file.xml changing Built action and copy to output directory but that didn't work. I tried adding: isFile.Dispose(); I also tried adding conditional statement: if (isFile.FileExists("file.xml"))... But he couldn't find the file. I have never been so stuck in my life. Please advice me what else can i try. A: You're trying to save to the same stream you loaded from - but without "rewinding" it to the start. I don't know whether isolated storage streams are seekable, but you can try just changing the code to: XDocument loadedDoc = XDocument.Load(stream); loadedDoc.Add(newItem); stream.Position = 0; loadedDoc.Save(stream); Note that while we don't need to reset the size of stream in this case as we're adding content, in other cases you might need to do so in order to avoid "leftover" bits at the end of the file. Alternatively, load the document and close the stream, then open up a new stream to the same file. Note that you should use using statements to close the streams after each use, e.g. using (var isFile = IsolatedStorageFile.GetUserStoreForApplication()) { XDocument loadedDoc; using (var stream = isFile.OpenFile("/Items.xml", FileMode.Open)) { loadedDoc = XDocument.Load(stream); } loadedDoc.Add(newItem); using (var stream = isFile.OpenFile("/Items.xml", FileMode.Create)) { loadedDoc.Save(stream); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7503976", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: The language of the file referenced by the 'CodeFile' attribute does not match the language specified by the 'Language' attribute in the current file When trying to edit a aspx page in Visual Studio i get the error: The language of the file referenced by the 'CodeFile' attribute does not match the language specified by the 'Language' attribute in the current file. What's the problem? DocumentSearch.aspx: <%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="DocumentSearch.aspx.cs" Inherits="DocumentSearch" Title="@Pepsi" %> ... C# looks like it matches .cs to me. DocumentSearch.aspx.cs: using System; using System.Data; using System.Data.Common; using System.Configuration; using System.Collections; using System.Collections.Generic; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class DocumentSearch : System.Web.UI.Page { ... What's the problem? A: i found the problem. It's that The Visual Studio language support for C# has not been installed. The error message i was getting was misleading. The problem was that Visual Studio did not have C# installed - not that there was any mismatch. The reason C# was not installed is because i ran the wrong version of Visual Studio. From the start menu i ran: Microsoft Visual Studio 2008 when i should have ran Microsoft Visual Studio 2008 The problem, of course, is that the former isn't really Visual Studio. It's actually: Microsoft Visual Studio 2008 Shell (integrated mode) Which is why C# wasn't available.
{ "language": "en", "url": "https://stackoverflow.com/questions/7503981", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Drag and drop on iPad I have a webpage that features jQuery drag and drop. It works on all desktop browsers but not on iPads. Somehow the click + drag event is captured to move the page up and down. So, how is drag-and-drop generally done on iPads without writing iPad apps? A: You can't use the mouse events ... you need to change to touch events http://ross.posterous.com/2008/08/19/iphone-touch-events-in-javascript/ One way is to divide both code using a mobile Framework, like jQTouch, jQMobile, etc... Here is a simple test using jQTouch Just added a simple test of my own using jQuery UI Sortable for both Browser and iPad http://jsbin.com/ujeyac/19/ using jQuery UI Sortable demo code and the Touch Events code, works great!
{ "language": "en", "url": "https://stackoverflow.com/questions/7503983", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How can i run my statements from the terminal for Java? How can i run my statements from the terminal? $ java -c System.out.println("test"); bash: syntax error near unexpected token `(' A: Look up BeanShell! It's not quite "pure" Java, but it's super close and really useful! www.beanshell.org A: What you are looking for is Groovy, it is a dynamic superset of Java. Which means you can run any Java statement as a Groovy statement. It has an interactive REPL shell that can execute Java statements or Groovy statements equally as well. You can also write scripts using plain Java statements as well, no need for Groovy syntax short cuts or extensions and run them as scripts. groovy -e "println 'Hello ' + args[0]" World A: If you don't need something professional, you can use simple shell script to wrap your statement in function and class body, compile and execute it. #!/bin/sh echo "class Main\n{\npublic static void main(String[] args)\n{" > /tmp/Main.java echo $* >> /tmp/Main.java echo "\n}\n}\n" >> /tmp/Main.java javac /tmp/Main.java || exit 1 exec java -cp /tmp/ Main
{ "language": "en", "url": "https://stackoverflow.com/questions/7503985", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Very long json response stops and sends HTTP headers as text then continues I am totally lost with this problem. I have an ajax query which gets a json response. The query works fine in most situations however seems to stumble when the json response is very large. The problem is the response ends up in the form: ...est":"test length"}]]} HTTP/1.1 200 OK Date: Wed, 21 Sep 2011 17:10:32 GMT Server: Apache/2.2.11 (Win32) mod_ssl/2.2.11 OpenSSL/0.9.8k PHP/5.3.0 X-Powered-By: PHP/5.3.0 Expires: Thu, 19 Nov 1981 08:52:00 GMT Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0 Pragma: no-cache Keep-Alive: timeout=5, max=90 Connection: Keep-Alive Transfer-Encoding: chunked Content-Type: text/html 5b03d {"ResultsInfo":{"RequestID":"131661886010","FeedCompletion":{"0":"100"}},"ResultsData":[[{"test":"test length"},{"test":"test length"}, ...0 The ... represent more of the same "{"test":"test length"}," string So the reponse seems to be in the form: * *Last part of the data *http response header printed out in the body *The characters '5b03d' *First part of the data *The character '0' There is NOT an EXACT length of response that this occurs at however it is fine at 360791 characters but not at 372797 characters. I am using the Yii PHP framework, but have searched far and wide and not seen anything in there forums. It seems to me like the webserver is separating the response into several pieces or timing out and starting again. Or perhaps there is a max size of return? EDIT_____________________________________ I have tried the application/json content type as suggested but it is stil happening. Tes text part of the header that is returned in the body is as follows (when using applciaiton/json encoding): HTTP/1.1 200 OK Date: Thu, 22 Sep 2011 08:48:28 GMT Server: Apache/2.2.11 (Win32) mod_ssl/2.2.11 OpenSSL/0.9.8k PHP/5.3.0 X-Powered-By: PHP/5.3.0 Expires: Thu, 19 Nov 1981 08:52:00 GMT Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0 Pragma: no-cache Keep-Alive: timeout=5, max=89 Connection: Keep-Alive Transfer-Encoding: chunked Content-Type: application/json How do I turn off chunked encoding for this particular script? **EDIT 2_________________________________ I have now added a content length to my headers and the response header I get is still printed out in the body as: HTTP/1.1 200 OK Date: Thu, 22 Sep 2011 11:55:39 GMT Server: Apache/2.2.11 (Win32) mod_ssl/2.2.11 OpenSSL/0.9.8k PHP/5.3.0 X-Powered-By: PHP/5.3.0 Expires: Thu, 19 Nov 1981 08:52:00 GMT Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0 Pragma: no-cache Content-Length: 372797 Keep-Alive: timeout=5, max=90 Connection: Keep-Alive Content-Type: application/json So it looks like it is no longer being sent as chunked. However the same problem exists - the response has content then the header printed out then more content. **The only difference now is it doesnt have the '5b03d' or '0' characters in the response. EDIT_3___________________________ As asked for here is a summary of my php code $dataArray = array( 'ResultsData'=>array( array('test'=>'test length'), array('test'=>'test length'), array('test'=>'test length'), ... )); $return = json_encode($dataArray); header('Content-Length: '.strlen($return)); header('Content-type: application/json'); echo $return; A: what you are seeing here is chunked transfer encoding - http://en.wikipedia.org/wiki/Chunked_transfer_encoding this causes problems in combination with the content type being text/html. setting the content type to application/json should fix the problem. A: I have a Java server that responds with json code, giving me the corruption you seem to describe. When the returned json grows big, the text is corrupted. Different browsers shows different corruptions, but the same browser very often corrupts in the same places. In one of my tests I sendt 9492 bytes. The first 1495 were OK, the next 5204 were missing, although a Wireshark analyses showed the bytes in the tcp stream. Then the next 1495 bytes arrived safely, while the next 1298 were missing. These numbers are an example. Other browsers will present different corruptions for the same sending. The same browsers may repeat almost the same numbers. For example is the first corruption almost always on the same byte for Chrome. A json amount limited to say 4000 bytes always succed. I have not found a way to stop chunkin by setting content-length in this context. Just to give you an idea of the codes credibility: The same Javaserver has served browsers with html for more than 12 years without corruption. But the Json response is sendt by the outputstream without me setting the headers. I think the headers are composed by the apache server when I send from my own java-program. A: I have not found an answer to this question however have isolated the problem. In a standard php file I wrote this code: <?php // Make a large array of strings for($i=0;$i<10000;$i++) { $arr[] = "testing this string becuase it is must longer than all the rest to see if we can replicate the problem. testing this string becuase it is must longer than all the rest to see if we can replicate the problem. testing this string becuase it is must longer than all the rest to see if we can replicate the problem."; } // Create one large string from array $var = implode("-",$arr); // Set HTTP headers to ensure we are not 'chunking' response header('Content-Length: '.strlen($var)); header('Content-type: text/html'); // Print response echo $var; ?> and went to it in a browser and got the same problem. Could someone else try this for me? (I have tried on two computers now with same result) A: I had never problems sending chunked Json. But.. Right content will be chunked because the content-length is unkown while PHP echo this and that to the client. * *ob_start() ... ob_end_flush() ensures that the content will be send at once and the content-lenth header will be set automatically. *Compressed data will be never chunked. So: ob_start(ob_gzhandler) ... ob_end_flush() is effective. *Test your json inside the client script. *Its useless to repeat 'test'. There is a limit for nestings. dataArray = array('ResultsData'=>array(length0,length1,length2,...)); echo json_encode($dataArray,JSON_NUMERIC_CHECK); JSON_NUMERIC_CHECK strips quotes from numbers. * *?5b03d? Do you try to sending binary strings? *I think a content length of 373kb is far from memory overflow?
{ "language": "en", "url": "https://stackoverflow.com/questions/7503991", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Auto populate text box when Check box id checked - Jquery I working to put functionality for a check box. When the check box is checked I would like to auto populate the text box with yes. But I couldn't able to get the functionality. Any insights is highly appreciated. Below is code I tried to work with <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"> </script> <script language="JavaScript"> $(document).ready(function() { $('#checkboxid').attr('checked', true) { $("input[Title='Text Box Name']").val("Yes"); } }); </script> Below is the HTML code for those two items. Please bare with my HTML code, it is auto generated code for Sharepoint. For Text Box and Check Box <TR><TD nowrap="true" valign="top" width="190px" class="ms-formlabel"> <H3 class="ms-standardheader"> <nobr>Text Box name</nobr> </H3></TD><TD valign="top" class="ms-formbody" width="400px"> <div align="left" class="ms-formfieldcontainer"> <div class="ms-formfieldlabelcontainer" nowrap="nowrap"> <span class="ms-formfieldlabel" nowrap="nowrap">Text Box name</span></div> <div class="ms-formfieldvaluecontainer"><span dir="none"> <input name="ctl00$m$g_89e4bf6d_529c_49e0_95e0_7024e4172c50$ctl00$ctl04$ctl63$ctl00$ctl00$ctl04$ctl00$ctl00$TextField" type="text" maxlength="255" id="ctl00_m_g_89e4bf6d_529c_49e0_95e0_7024e4172c50_ctl00_ctl04_ctl63_ctl00_ctl00_ctl04_ctl00_ctl00_TextField" title="Text Box name" class="ms-long" /><br></span></div></div></TD></TR> <TR><TD nowrap="true" valign="top" width="190px" class="ms-formlabel"> <H3 class="ms-standardheader"> <nobr>Check Box name</nobr> </H3></TD> <TD valign="top" class="ms-formbody" width="400px"> <div align="left" class="ms-formfieldcontainer"> <div class="ms-formfieldlabelcontainer" nowrap="nowrap"> <span class="ms-formfieldlabel" nowrap="nowrap">Check Box name</span></div> <div class="ms-formfieldvaluecontainer"><span dir="none"> <input id="ctl00_m_g_89e4bf6d_529c_49e0_95e0_7024e4172c50_ctl00_ctl04_ctl60_ctl00_ctl00_ctl04_ctl00_ctl00_BooleanField" type="checkbox" name="ctl00$m$g_89e4bf6d_529c_49e0_95e0_7024e4172c50$ctl00$ctl04$ctl60$ctl00$ctl00$ctl04$ctl00$ctl00$BooleanField" /><br> </span></div></div></TD></TR> A: $('#checkboxid').attr('checked', true) { $("input[Title='Text Box Name']").val("Yes"); } This sets the checkbox to checked and adds the value, but doesn't do anything on events. $('#checkboxid').change(function(){ $('input[Title='Text Box Name']").val(""); if ($('#checkboxid').is(':checked')) { $("input[Title='Text Box Name']").val("Yes"); } }); A: If you want to check the condition only during page load try this: $(document).ready(function(){ if($('#checkboxid').is(':checked')) { $("input[Title='Text Box name']").val("Yes"); } }); If you want to check for the condition everytime the checkex is clicked, try this: $(document).ready(function(){ $('#checkboxid').click(function(){ $("input[Title='Text Box name']").val($(this).is(':checked')?"Yes":""); }); }); A: $(function(){ $('#checkboxId').click(function(e)){ if($(this).is(':checked')){ $("input[Title='Text Box Name']").val("Yes"); } } } replace checkboxId with the Id of your checkbox. A: var textboxid = "#ctl00$m$g_89e4bf6d_529c_49e0_95e0_7024e4172c50$ctl00$ctl04$ctl63$ctl00$ctl00$ctl04$ctl00$ctl00$TextField"; var checkboxid = "#ctl00_m_g_89e4bf6d_529c_49e0_95e0_7024e4172c50_ctl00_ctl04_ctl60_ctl00_ctl00_ctl04_ctl00_ctl00_BooleanField"; $(document).ready(function () { $(checkboxid).change(function () { if ($(this).prop("checked")) { $(textboxid).val("Yes") } }); //to trigger the event on load in case the checkbox is checked when the page loads $(checkboxid).trigger("change"); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7503995", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ASP.net quiz engine, sort of I am adding some basic functionality to my companies website. When a potential employee clicks on a link to apply for a job, there will be a list of questions with yes/no radio buttons to prequalify applicants. I have looked through several tutorials on setting up a quiz engine since that is basically what I am doing but my company execs want the questions listed on one page and not one quesiton per page. I am having trouble with two parts of this (heck, can't sort out how to do it at all really). First issue is on how to display the questions, I was thinking that I should use a repeater. Second issue is passing the answers back to the database, I would assume I should use a for-each loop. As a noob webdev on a one person team, I am having a hard time doing this as well. I don't want someone to do this for me as I want/need to learn the right way but if anyone can point me in the right direction, it would be much appreciated. A: I was thinking that I should use a repeater Yep! Second issue is passing the answers back to the database, I would assume I should use a for-each loop. This will work : Here's how: From: ASP .NET - How to Iterate through a repeater? foreach(RepeaterItem item in myRepeater.Items){ if(item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem){ // do something with the item RadioButtonList radioChoices = (RadioButtonList) item.FindControl("myControl") ; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7503996", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: When/why does my Java singleton instance get destroyed? I have an android app that is setup to start a Java activity (call it MyJavaActivity), which in turn launches a NativeActivity. When the NativeActivity finishes it returns back to MyJavaActivity. I also have a Java singleton class (call it MyJavaSingleton) which I would like to stay in memory throughout my application's lifecycle. I set some of the singleton class's member variables from my NativeActivity (using JNI), which can later be retrieved by MyJavaActivity. The problem is, MyJavaSingleton instance seems to be in memory until NativeActive exits, but somehow seems to be set to null again when MyJavaActivity starts up again, so all the variables I had set in NativeActivity are now reset to their defaults. Why does this happen? public class MyJavaActivity extends Activity implements View.OnTouchListener { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); MyJavaSingleton.Instance().DoStuff(); } @Override public boolean onTouch(View arg0, MotionEvent arg1) { Intent intent = new Intent(MyJavaActivity.this, NativeActivity.class); startActivity(intent); // at this point, android_main will be executed } } ///////////////////////////// public class MyJavaSingleton { static private MyJavaSingleton mInstance = null; synchronized public static MyJavaSingleton Instance() { if( mInstance == null ) { mInstance = new MyJavaSingleton(); Log.v(TAG, "New MyJavaSIngleton instance"); } return mInstance; } } ///////////////////////////// // Native void android_main(struct android_app* state) { // Do various stuff, set some variables on the MyJavaSingleton // At this point, MyJavaSingleton.mInstance is still at the same address in memory, which is good // ANativeActivity_finish(state->activity); exit(0); // Problem: sometime after this exit and before MyJavaActivity::onCreate is called, MyJavaSingleton.mInstance is set to null! } In the above code extraction, "New MyJavaSIngleton instance" is printed when the app is first started, and then again right after the NativeActivity exits (ie after android_main is exited) and MyJavaActivity's onCreate is called again. Why does MyJavaSingleton.mInstance become NULL when reentering MyJavaActivity? A: Be sure to read the documentation on the process lifecycle: http://developer.android.com/guide/topics/fundamentals/processes-and-threads.html#Lifecycle In this case, whenever your app is in the background (in terms of activities, none of your activities are visible to the user), your process can be killed at any time. If the user later returns to one of your activities, a new process will be created and a new instance of the activity created. A: Each Android app runs in its own process so as long as it keeps running, your singleton will be available. When the process dies, your singleton is lost. Therefore when the app is re-launched this singleton object will need to be re-created. A: I'd make mInstance private. Just in case some other code is accidentally setting it. A: "Android OS can and will terminate your singleton and not even tell you about it." Source: http://www.2linessoftware.com/2010/08/03/singletons-and-services-and-shutdowns-oh-my/ The author of that article suggests some solutions, such as using a Service, or subclassing the Application class. There seems to be quite a bit of support for the latter: How to declare global variables in Android?
{ "language": "en", "url": "https://stackoverflow.com/questions/7503997", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: iAd in multiple views look I have 1 UIView and 2 links on it to other 2 views. On key pressed I have the following: [self addSubview:view1]; or [self addSubview:view2]; respectively I have used your suggestions on iAd and I have successfully achieved to show on UIView (let call it parent) iAD advertisement. But when I navigate to view1 or to view2 iAD does not appear. I use [self.view addSubview:_adBannerView]; in abcViewController.m what I want is to add iAd advertisement on view1 and view2 too. can you please illuminate me how to manage this? I will appreciate this very much. A: Just in case anyone was looking at this question and wanted to know how to use a single iAd ADBannerView in multiple places, this WWDC video will walk you through the entire process (note that you have to log into your developer account to view it): https://developer.apple.com/videos/wwdc/2011/?id=505
{ "language": "en", "url": "https://stackoverflow.com/questions/7504002", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Hibernate selecting from multiple mapped entities? I'm trying to figure out how Hibernate handles the following situation: Say I have entities A, and B properly mapped in an hbm file. If I write an HQL query the selects from both of them (e.g. from A, B where ...) what is returned? I assume it cannot be cast to either the object representing A, or B since it is some combination of these two. A: In fact what you're trying to do is called a projection. Hibernate all by itself will return a List (untyped) of all the beans that are returned by your query. If you;re using the JPA implementation, you can actually decalre a Class which would contain the aggregated values of the results you're getting back, something like this: @SqlResultSetMapping( name="DepartmentSummary", entities={ @EntityResult(entityClass=Department.class, fields=@FieldResult(name="name", column="DEPT_NAME")), @EntityResult(entityClass=Employee.class) }, columns={@ColumnResult(name="TOT_EMP"), @ColumnResult(name="AVG_SAL")} )
{ "language": "en", "url": "https://stackoverflow.com/questions/7504004", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: SQL SERVER ODBC ERROR(Invalid object name) but when I add in SQL query mydb.dbo.mytable all works fine I have an old asp.net 1 project (it works fine on old server, mytable exist in db. Now I am trying to upgrade it to asp.net 4 My connection string is: <add key="SqlConnection" value="DRIVER={SQL Server};SERVER=bel\SQLEXPRESS;Trusted_connection=yes;DAT­ABASE=mydb;option=3;"/> I get error ERROR [42S02] [Microsoft][ODBC SQL Server Driver][SQL Server]Invalid object name 'mytable'. OdbcCommand dataCommand = new OdbcCommand("select * from mytable", dataConnection); dataCommand.CommandTimeout = 900; OdbcDataReader dataReader = dataCommand.ExecuteReader(CommandBehavior.CloseConnection); When I wrote SQL as select * from mydb.dbo.mytable all works fine What I should change in db settings (security, schema, dbo) or in connection string? A: My guess, seeing that you're using ODBC, is that your ODBC connection doesn't specify a default database, and so it's using master. You can either: * *specify the database in your connection string using "Database=myDBname" or "InitialCatalog=myDBname" *change the default database in your ODBC connection, as shown here in XP/Server 2003
{ "language": "en", "url": "https://stackoverflow.com/questions/7504006", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: avoid explicit passing of lookup table In my very simple boolean expression toy program, I have the following evaluation function: eval' :: Expr -> M.Map Char Bool -> Bool eval' (Const c) values = c eval' (Var v) values = M.findWithDefault False v values eval' (Not x) values = not (eval' x values) eval' (And a b) values = eval' a values && eval' b values eval' (Or a b) values = eval' a values || eval' b values eval' (Xor a b) values = eval' a values /= eval' b values I was wondering if there was a way to pass the values table implicitly? Maybe with the help of Monads? A: This is exactly what the Reader monad is for: The Reader monad (also called the Environment monad). Represents a computation, which can read values from a shared environment, pass values from function to function, and execute sub-computations in a modified environment. As Sjoerd notes, the monad gives more power here than you need, but you can still use the Reader monad for this problem without so much as typing do: import qualified Data.Map as M import Control.Applicative ( (<$>), (<*>) ) import Control.Monad.Reader data Expr = Const Bool | Var Char | Not Expr | And Expr Expr | Or Expr Expr | Xor Expr Expr Just put your environment type as the first argument to the Reader type constructor, and your original result type as the second. eval' :: Expr -> Reader (M.Map Char Bool) Bool Instead of just c as the value of the Const case, use return to lift it into the monad: eval' (Const c) = return c When you need the environment for looking up the value of a variable, use ask. Using do notation, you can write the Var case like this: eval' (Var v) = do values <- ask return (M.findWithDefault False v values) I think it's nicer, though, to use fmap a.k.a. <$>: eval' (Var v) = M.findWithDefault False v <$> ask Similarly, the unary not can be fmapped over the result of the recursion: eval' (Not x) = not <$> eval' x Finally, the Applicative instance of Reader makes the binary cases pleasant: eval' (And a b) = (&&) <$> eval' a <*> eval' b eval' (Or a b) = (||) <$> eval' a <*> eval' b eval' (Xor a b) = (/=) <$> eval' a <*> eval' b Then, to get it all started, here's a helper to create the initial environment and run the computation: eval :: Expr -> [(Char,Bool)] -> Bool eval exp env = runReader (eval' exp) (M.fromList env) A: In this case, do not pass values at all: eval' :: Expr -> M.Map Char Bool -> Bool eval' e values = eval'' e where eval'' (Const c) = c eval'' (Var v) = M.findWithDefault False v values eval'' (Not x) = not (eval'' x) ... A: Do you know the extension implicit parameters? It could be quite helpful. A: Monads would work, but in my opinion using Applicative is cleaner here: eval' :: Expr -> M.Map Char Bool -> Bool eval' (Const c) = pure c eval' (Var v) = M.findWithDefault False v eval' (Not x) = not <$> eval' x eval' (And a b) = (&&) <$> eval' a <*> eval' b eval' (Or a b) = (||) <$> eval' a <*> eval' b eval' (Xor a b) = (/=) <$> eval' a <*> eval' b This is using the ((->) r) instance, like the Reader monad/applicative, but without the newtype wrapper.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504012", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Google Maps Api - Deleting marker with mouseclick I got a problem with deleting a marker on mouse click. Well, the thing isnt as simple as it seems. function addPoint(event) { path.insertAt(path.length, event.latLng); var marker = new google.maps.Marker({ position: event.latLng, map: map }); markers.push(marker); google.maps.event.addListener(marker, 'click', function() { marker.setMap(null); markers.splice(i, 1); } ); If i used that code, adding listener right away when creating marker, deleting it would be easy, cuz i refer to marker.setMap(null);. But in my case i want them to be created, and then i want to add the event listener to them using function usun(){ for (var i=0; i<markersArray.length; i++){ google.maps.event.addListener(marker, 'click', function() { alert('lol'); }); } I am pushing each marker to markersArray which lets me to add event to each of it now, but how can i delete it? When i put marker.setMap(null); in place of the alert, it says marker is not defined, and i dunno how can i refer to marker i just clicked :S also cant use marker as global variable, cuz i am getting Uncaught TypeError: Cannot read property '__e3_' of undefined error. EDIT: if i try using function usun(){ for (var i=0; i<markersArray.length; i++){ google.maps.event.addListener(markersArray[i], 'click', function() { markersArray[i].setMap(null); }); } } i get the error Uncaught TypeError: Cannot call method 'setMap' of undefined. Thats why i was sure i need to use "marker". A: In your for loop you are not referring to the marker that is in the array. try this: function usun(){ for (var i=0; i < markersArray.length; i++){ google.maps.event.addListener(markersArray[i], 'click', function() { this.setMap(null); }); } working example: http://jsfiddle.net/52nJc/1/
{ "language": "en", "url": "https://stackoverflow.com/questions/7504017", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Database on Amazon AWS or dedicated server I'm building an application that will utilize the Amazon API to retrieve products. I'm trying to determine if I'll have any advantage storing data on the Amazon server or a standard dedicated/shared server. Can anyone help me out please? A: The answer depends on the performance requirements of your database. Storage options available in AWS are quite slow compared to local storage or a SAN. If you have a smallish solution with modest traffic, AWS is fine. For high volume, high performance requirements I cannot suggest AWS. I have prototyped two applications on AWS, and both were migrated to dedicated hardware once they had to handle serious customer volume. A: We have been running TONS of load test on amazon. The pricing model can be great if you program in the automatic scale down of services. If you are small like a http://alvazan.com site, it works great on amazon PLUS when we moved the site, our people in China could access it 5 times faster while it was the same speed in the US. Then if you use a nosql database(I have a client that I am doing testing for), we just ran 80 nodes and it scaled up great!!!! You have to use way more load balancers than you normally would and do round robin DNS though ELB's wil do this for you if you don't use the VPC. All in all, we have been turning up 100 nodes every once in a while to do testing and only spend 500USD for this month. The scale up fast is great at amazon and even if you host your own on dedicated hardware, I would recommend a VPN in from your current production so that you can "burst" very cheaply while you order the hardware to backfill more demand from your market. ONE MORE HUGE THING: If you use cassandra, the write is first in memory on 2 nodes and then asynchronously done to the disk so the probability of data loss is the same as an RDBMS BUT is MUCH MUCH faster since your app only waits for it to write to memory instead of waiting to write to disk. later, Dean
{ "language": "en", "url": "https://stackoverflow.com/questions/7504019", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Redirect from mobile site (jQuery mobile) to main site styles linger I am using jQuery mobile and MVC 2.0 for my mobile site. I have a link on the mobile site to go to the main site. The problem is that when I land on the main site my styles still look like jQuery mobile styles. If I refresh the page then it correctly shows the main site's styles. I am wondering how to force out the jQuery mobile styles and/or make sure that I get my main site styles when I land on the (login) page. Details: Sites served under IIS 7.5. Main Site in Classic 2.0 (VB.NET) with "sub"-site in Integrated 2.0 (MVC, jQuery mobile beta 3). dev environ Windows 7 / VS 2010 / .NET 3.5. (to deploy on Server 2008) Thanks for any insight. -Brian A: It's possible that your link is still being navigated by the jQuery Mobile AJAX navigation system; you can get around this by putting a rel="external" attribute on the link: <a href="www.fullsite.com" rel="external">Full Site</a>
{ "language": "en", "url": "https://stackoverflow.com/questions/7504024", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to make a call in j2me by using SIP protocol? How to make a j2me application which allows the user to call? A: it depends on whether target device supports JSR 180 SIP API for J2ME or not
{ "language": "en", "url": "https://stackoverflow.com/questions/7504025", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: PowerShell + WebAdministration - How to get website from webapplication? I'm writing a PowerShell script to perform certain administrative functions in IIS 7.5. import-module WebAdministration In some cases I know the name of the web application I want to work with but not the web site it is under. Getting the application is easy: $app = get-webapplication -name 'MyApp' But I cannot figure out how to get the name of the web site given the app. It doesn't seem to be a property off the webapplication object. Best I could come up with was trying to get it via test-path: get-website | where {test-path "iis:\sites\$_.name\MyApp"} For some reason that comes up empty. Any thoughts on how to go about this? Thanks in advance. A: I haven't dug into why, but if you use an asterisk or question mark anywhere in the string it works like a wildcard and returns as such. I.E. get-website -name '*myapp' Name ID State Physical Path Bindings ---- -- ----- ------------- -------- myapp 12 Started C:\inetpub\wwwroot http:*:80: amyapp 13 Stopped C:\anetpub\ http:*:81: aamyapp 14 Stopped C:\another\place http:172.198.1.2:80:host.header.com or get-website -name '?myapp' Name ID State Physical Path Bindings ---- -- ----- ------------- -------- amyapp 13 Stopped C:\anetpub http:*:81: A: Try this $app = get-webapplication -name 'MyApp' foreach($a in $app) { $a.Attributes[0].Value; } This will give you all the names of the Web Applications, sometimes you can have more than 1 name for a single Web Applications. For more information see the link http://nisanthkv.blog.com/2012/07/06/name-of-web-applications-using-powershell/ Hope it helps.. A: This is how you can get the site name: $siteName = (Get-WebApplication -name 'YourApp').GetParentElement().Attributes['name'].Value Or even shorter: $siteName = (Get-WebApplication -name 'YourApp').GetParentElement()['name']
{ "language": "en", "url": "https://stackoverflow.com/questions/7504027", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Read out node content with xpath from several xml files I have a question regarding reading out the node content with XPath from several XML files. I am fully aware that there are masses of resources on the internet on this issue and please, believe me, it really drives me crazy. I want to read out information from files from the reuters rcv1 experimental corpus. all the files in this corpus share the same information. I post the structure here as an example: <?xml version="1.0" encoding="iso-8859-1" ?> <newsitem itemid="1000000" id="root" date="xxx" xml:lang="en"> <title>title title title</title> <headline>headline headline headline</headline> <byline>Jack Daniels</byline> <dateline>Blabla</dateline> <text> <p> Paragraph 1 Paragraph 1 Paragraph 1 Paragraph 1 Paragraph 1 </p> <p> Paragraph 2 Paragraph 2 Paragraph 2 Paragraph 2 Paragraph 2 </p> <p> Paragraph 3 Paragraph 3 Paragraph 3 Paragraph 3 Paragraph 3 </p> <p> Paragraph 4 Paragraph 4 Paragraph 4 Paragraph 4 Paragraph 4 </p> </text> <copyright>(c) Reuters Limited 1996</copyright> <metadata> <codes class="bip:countries:1.0"> <code code="MEX"> <editdetail attribution="Reuters BIP Coding Group" action="confirmed" date="1996-02-20"/> </code> </codes> <codes class="bip:topics:1.0"> <code code="xxx"> <editdetail attribution="Reuters BIP Coding Group" action="confirmed" date="1996-08-20"/> </code> <code code="xxx"> <editdetail attribution="Reuters BIP Coding Group" action="confirmed" date="xxx"/> </code> <code code="xxx"> <editdetail attribution="Reuters BIP Coding Group" action="confirmed" date="xxx"/> </code> <code code="xxx"> <editdetail attribution="Reuters BIP Coding Group" action="confirmed" date="xxx"/> </code> <code code="xxx"> <editdetail attribution="Reuters BIP Coding Group" action="confirmed" date="xxx"/> </code> </codes> <dc element="dc.publisher" value="Reuters Holdings Plc"/> <dc element="dc.date.published" value="xxx"/> <dc element="dc.source" value="Reuters"/> <dc element="dc.creator.location" value="xxx"/> <dc element="dc.creator.location.country.name" value="xxx"/> <dc element="dc.source" value="Reuters"/> </metadata> </newsitem> The final goal of my task is to transfer these several thousand files into CSV. I am doing this with the software rapidminer by addressing the different node contents via their XPath address. This is absolutely no problem for all points but one, the content of <text></text>. With //newsitem/text/p/node() he always only delivers the first paragraph. What I am looking for, however, would be to extract all the plain text from all paragraphs. This means the CSV files should look approximately like this: title, headline, date, text, location titleblabla, headlineblabla, xxx, paragraph 1 paragraph 2 paragraph 3, anywhere othertitleblabla, otherheadlineblabla, otherdatexxx, other paragraph 1 paragraph 2 paragraph 3, nowhere Please, could somebody be so nice to help me achieve this by addressing it with XPath? I have also tried the whole thing with string matches but this takes ages and additionally I have to get rid of the XML tags. Thank you very much, alexandre (a desperate xpath/xml newbie) A: It seems from your description that RapidMiner retrieves the string value of the node(-set) selected by a given XPath expression. By definition, the string value of a node-set is the string value of the first node in this node-set -- this matches exactly your description of the problem. Solution: Instead of: //newsitem/text/p/node() use: /newsitem/text The string value of the only elementselected in the provided document with the expression above (by definition) is the concatenation of all of its text-node descendents -- exactly what you want.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504029", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: stdlib "Unique" method does not work I'm trying to use the C++ Standard Library algorithm unique (with BinaryPredicate). I've created a vector of pairs; each pair is like "(first=a vector of 4 doubles, second=an integer)". The second element serves as index so after using `unique, I can still tell the original index. In the example below, I've created something like this: 10 20 30 40, 1 10 20 30 40, 2 10 20 30 40, 3 10 20 30 40, 4 10 20 30 40, 5 10 20 30 40, 6 Now I want to use the unique function to compare only the first element of each pair. I've used a customize binary predictor uniquepred. Indeed, it works, but the vector is not reduced after using unique. EXPECTED RESULT Size before=6 equal! equal! equal! equal! equal! Size after=1 ACTUAL RESULT Size before=6 equal! equal! equal! equal! equal! Size after=6 Minimum working example follows. Please help me debugging this. #include <iostream> #include <vector> #include <algorithm> using namespace std; typedef std::vector<double> V1db; typedef std::pair<V1db, int > Pairs; typedef std::vector<Pairs> Vpairs; bool uniquepred( const Pairs& l, const Pairs& r) { if (l.first==r.first) cout<<"equal!"<<endl; return l.first == r.first; } int main() { Vpairs ak; V1db u2(4); u2[0]=10;u2[1]=20;u2[2]=30;u2[3]=40; Pairs m2; m2.first = u2; m2.second= 1; ak.push_back(m2); m2.second= 2; ak.push_back(m2); m2.second= 3; ak.push_back(m2); m2.second= 4; ak.push_back(m2); m2.second= 5; ak.push_back(m2); m2.second= 6; ak.push_back(m2); cout<<"Size before="<<ak.size()<<endl; unique(ak.begin(), ak.end(), uniquepred); cout<<"Size after="<<ak.size()<<endl; return 0; } A: You want to do: ak.erase(unique(ak.begin(), ak.end(), uniquepred), ak.end()); The reason for this is that std::unique reorders the values. It doesn't delete them though and you are left with a new range, from begin() to the iterator that unique returns. The container itself is not altered, other than this reordering. There's no "remove at position X" method on vectors, even if there was it would invalidate the iterators. The unique algorithm by design doesn't even know anything about the underlying container, so it can work with any valid pair of iterators. The only requirement is that they are ForwardIterators. A: std::unique does work; you forgot to look it up in your favourite C++ library documentation to find out what it does. It functions a little weirdly, like std::remove, in that it actually just moves stuff around and gives you the end iterator to the new range. The underlying container is not resized: you have to do erasure yourself: ak.erase(std::unique(ak.begin(), ak.end(), uniquepred), ak.end());
{ "language": "en", "url": "https://stackoverflow.com/questions/7504030", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: AppStore Update Policy Just wondering what will happen if the current app version supports OS 10.6.6 upwards and you upload a version that is built for Lion. Will the 10.6 users be still able to download the version that is for 10.6 or will they be forced to upgrade to 10.7? My guess is the latter, but I'm not 100% sure. How would you handle the jump from 10.6 to 10.7? A: Apple's storefront database knows which version of OS X your app currently requires (the Deployment Target), and thus might not allow the App Store application on your Mac to update an app if the Mac on which the App Store application is running does not have a proper OS version for that app. A: Any update replaces the previous version. If the new version you plan to release requires 10.7, then I strongly encourage you to disclose that information in the update so that users who plan not to upgrade right away will know not to install your update.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504031", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Silverlight UI Freezes When Rendering Multiple DataGrids I'm experiencing issues with the Silverlight UI (and indeed the browser) freezing when databinding/rendering datagrids. I have been able to reproduce the issue with the code below which uses 4 grids. In practice we will be using more than 4 grids. I've found that if I only have a single grid and many more rows (e.g. 3000) everything is fine. It looks like there there is contention between the four datagrids when they are trying to bind/render which is causing the UI to lockup. Is this a known issue with silverlight? What work arounds are there? Code to reproduce problem Data object: public class DataObject { public string Column0 { get; set; } public string Column1 { get; set; } public string Column2 { get; set; } ... public string Column30 { get; set; } public DataObject() { Random r = new Random(DateTime.Now.Millisecond); Column0 = r.Next(1000).ToString(); Column1 = r.Next(1000).ToString(); Column2 = r.Next(1000).ToString(); ... Column30 = r.Next(1000).ToString(); } } Codebehind: public partial class MainPage : UserControl { private ObservableCollection<DataObject> _data = new ObservableCollection<DataObject>(); public MainPage() { InitializeComponent(); PopulateData(); DataContext = _data; } private void PopulateData() { for (int i = 0; i < 300; i++) { _data.Add(new DataObject()); } } public ObservableCollection<DataObject> Data { get { return _data; } set { _data = value; } } } XAML: <UserControl x:Class="SilverlightGridTest.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:sdk="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data"> <Grid x:Name="LayoutRoot" Background="White"> <ScrollViewer> <StackPanel> <sdk:DataGrid Grid.Row="0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" ItemsSource="{Binding}" Width="800" Height="700" AutoGenerateColumns="False"> <sdk:DataGrid.Columns> <sdk:DataGridTextColumn Binding="{Binding Column0, Mode=TwoWay}" IsReadOnly="True" /> <sdk:DataGridTextColumn Binding="{Binding Column1, Mode=TwoWay}" IsReadOnly="True" /> <sdk:DataGridTextColumn Binding="{Binding Column2, Mode=TwoWay}" IsReadOnly="True" /> ... <sdk:DataGridTextColumn Binding="{Binding Column30, Mode=TwoWay}" IsReadOnly="True" /> </sdk:DataGrid.Columns> </sdk:DataGrid> <sdk:DataGrid Grid.Row="0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" ItemsSource="{Binding}" Width="800" Height="700" AutoGenerateColumns="False"> <sdk:DataGrid.Columns> <sdk:DataGridTextColumn Binding="{Binding Column0, Mode=TwoWay}" IsReadOnly="True" /> <sdk:DataGridTextColumn Binding="{Binding Column1, Mode=TwoWay}" IsReadOnly="True" /> <sdk:DataGridTextColumn Binding="{Binding Column2, Mode=TwoWay}" IsReadOnly="True" /> ... <sdk:DataGridTextColumn Binding="{Binding Column30, Mode=TwoWay}" IsReadOnly="True" /> </sdk:DataGrid.Columns> </sdk:DataGrid> <sdk:DataGrid Grid.Row="0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" ItemsSource="{Binding}" Width="800" Height="700" AutoGenerateColumns="False"> <sdk:DataGrid.Columns> <sdk:DataGrid.Columns> <sdk:DataGridTextColumn Binding="{Binding Column0, Mode=TwoWay}" IsReadOnly="True" /> <sdk:DataGridTextColumn Binding="{Binding Column1, Mode=TwoWay}" IsReadOnly="True" /> <sdk:DataGridTextColumn Binding="{Binding Column2, Mode=TwoWay}" IsReadOnly="True" /> ... <sdk:DataGridTextColumn Binding="{Binding Column30, Mode=TwoWay}" IsReadOnly="True" /> </sdk:DataGrid.Columns> </sdk:DataGrid> <sdk:DataGrid Grid.Row="0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" ItemsSource="{Binding}" Width="800" Height="700" AutoGenerateColumns="False"> <sdk:DataGrid.Columns> <sdk:DataGrid.Columns> <sdk:DataGridTextColumn Binding="{Binding Column0, Mode=TwoWay}" IsReadOnly="True" /> <sdk:DataGridTextColumn Binding="{Binding Column1, Mode=TwoWay}" IsReadOnly="True" /> <sdk:DataGridTextColumn Binding="{Binding Column2, Mode=TwoWay}" IsReadOnly="True" /> ... <sdk:DataGridTextColumn Binding="{Binding Column30, Mode=TwoWay}" IsReadOnly="True" /> </sdk:DataGrid.Columns> </sdk:DataGrid> </StackPanel> </ScrollViewer> </Grid> A: You should consider using a data pager to only show a certain amount of rows at one time.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504033", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Jquery droppable option breaks the draggable behavior of that element If I specify the accept option for a droppable that is also draggable this breaks the draggable behavior of that droppable. To prevent nesting of these draggable droppables, I specify the accept option to be only the class that belongs in the droppable. I do this with $('div.link_drop_box', $('#'+card_id)).droppable({ accept: '.link' });. Here is the javascript where I specify the droppable draggable div. // Define more LinkCard options $('#'+card_id).css('width',350); $('#'+card_id).css('height',250); $('#'+card_id).resizable(); $('#'+card_id).draggable(); $('#'+card_id).draggable("option", "handle", '.linkcard_header'); $('#'+card_id+' p').editableText(); $('#'+card_id).draggable({ stop: function(event, ui) { update_linkcard_xml(card_id) } }); // Make droppable $('div.link_drop_box', $('#'+card_id)).droppable({ accept: '.link' }); $('div.link_drop_box', $('#'+card_id)).droppable({ drop: function( event, ui ) { var $item = ui.draggable; $item.fadeOut(function() { $item.css( {"left":"", "top":"", "bottom":"", "right":"" }).fadeIn(); }); $item.appendTo( this ); } }); Now the droppable divs aren't draggable anymore. The strange behavior is that there are several such droppable divs. The first one is still draggable, the the others are not. What could cause the accept option to break the draggable behavior. A: Found the problem. Should put all the options in one droppable Method. The following works. $('div.link_drop_box', $('#'+card_id)).droppable({ drop: function( event, ui ) { var $item = ui.draggable; $item.fadeOut(function() { $item.css( {"left":"", "top":"", "bottom":"", "right":"" }).fadeIn(); }); $item.appendTo( this ); /* update_links_xml("card_id"); */ }, out: function( event, ui ) { /* update_links_xml("card_id"); */ }, accept: ".link", });
{ "language": "en", "url": "https://stackoverflow.com/questions/7504034", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: newbie css/php question - how to get a div between a label and an input with cakephp I'm using cakephp. I have a form where one of the inputs is there for users to enter a money amount into. I'm trying to get a £ symbol to appear in a div beside the form input which would both be below the form label. In otherwords I want the label to be on one line, then beneath that a div with the £ in it and beside, on the same line, the input. I use this to make the input echo $form->input('Campaign.target', array('label'=>'I want to raise', 'between'=>'<div id="currencySymbol">£</div>')); and it outputs: <div class="input text required"> <label for="CampaignTarget">I want to raise</label> <div id="currencySymbol">£</div> <input name="data[Campaign][target]" type="text" maxlength="11" id="CampaignTarget" /> </div> I've tried floating things, inlines blaa blaa etc but I'm a bit of a newb with css and in a hurry. Can anyone set me straight? Cheers :) A: You should use a <span> instead of a <div> so that you get an inline element.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504042", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Query to select last order (entry) of every product belonging to user that's not returned I am stuck with rather confusing query. Assume I have a ProductLending table that tracks what product each user has borrowed, when it was renewed, was it returned or not etc.. Given a user, I want to be able to select, all unique products that are still with the user. table example: userid DateRenewed ProductId isReturned ```````````````````````````````````````````````` 1 2011-07-21 15 0 1 2011-08-20 16 0 1 2011-09-21 15 1 2 2011-09-21 17 0 1 2011-09-21 15 0 This is a mock up so sorry if it's not accurate. Now, given userId = 1, I want to select just unique productId that are NOT returned, but are with the user. So this should give me 15, 16 as result, as even though 15 was returned, it was re-borrowed. If we delete the last row, then the result would just be 16, since user has only 16 with him. I tried ordering by dateRenewed and selecting top 1 but it did totally something else.. how do I construct a query for this please? A: If product is not returned by user, then the sum of bought products must be larger than sum of returned products SELECT userid,ProductId FROM <table> GROUP BY userid,ProductId HAVING SUM(CASE CAST(isReturned AS INT) WHEN 0 THEN 1 ELSE 0 END)-SUM(CAST(isReturned AS INT))>0 A: Try this: ;WITH qry AS ( SELECT *, ROW_NUMBER() OVER(PARTITION BY userID, ProductID ORDER BY DateRenewed DESC) rn FROM YourTable ) SELECT * FROM qry WHERE rn = 1 AND isReturned = 0; A: select distinct ProductId from TABLE_NAME t1 where UserId= @UserId and IsReturned = 0 and not exists ( select * from TABLE_NAME t2 where t2.UserId = t1.UserId and t2.ProductId = t1.ProductId and t2.IsReturned = 1 and t2.DateRenewed > t1.DateRenewed )
{ "language": "en", "url": "https://stackoverflow.com/questions/7504043", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MVC3 Pass viewmodel object with Iqueryable back to Controller I have a view that I pass a viewmodel object to that contains an IQueryable<> object. This object is used to populate an mvccontrib grid. The view also contains other partial views that allow the user to filter the data within the grid. Once the grid is filtered I would like the user to be able to export the Iqueryable object to another controller actionresult method which then calls another viewmodel that exports the data to Excel. Here is the snippet of the view that calls the Export actionresult() method: @using (Html.BeginForm("Export", "Home", FormMethod.Post, new { Model })) { <p> <input class="button" value="Export to Excel" type="submit" /> </p> } Model does contain the IQueryable object. When I debug the code I can view the viewmodel object, and of course in order to populate the IQueryable I must enumerate the object. I have also created another viewmodel object that, once the Model object is passed back to the actionresult method attempts to enumerate the IQueryable object by either using the .ToList() method or the AsEnumerable() method. But in all cases the IQueryable object is pass to the controller as a null object. Here is the action result method that is being called from the view: [HttpPost] [AcceptVerbs(HttpVerbs.Post)] public ActionResult Export(PagedViewModel<NPSProcessed> NPSData) { string message = ""; NPSData Query = new Models.NPSData(NPSData); Query.IData = NPSData.Query.ToList(); // Opening the Excel template... FileStream fs = new FileStream(Server.MapPath(@"\Content\NPSProcessedTemplate.xls"), FileMode.Open, FileAccess.Read); MemoryStream ms = new MemoryStream(); ee.ExportData(fs, ms, Query.IData, message); // Sending the server processed data back to the user computer... return File(ms.ToArray(), "application/vnd.ms-excel", "NPSProcessedNewFile.xls"); } Any assistance would be greatly appreciated. Thanks Joe A: You cannot pass complex objects around like this: new { Model }. It would have been to easy :-). You will have to send them one by one: new { prop1 = Model.Prop1, prop2 = Model.Prop2, ... } Obviously this could get quite painful. So what I would recommend you is to send only an id: new { id = Model.id } and then inside your controller action that is supposed to export to Excel use this id to fetch the object from wherever you fetched it initially in the GET action (presumably a database or something). If you want to preserve the paging, and stuff that the user could have performed on the grid, you could send them as well to the server: new { id = Model.id, page = Model.CurrentPage, sortColumn = Model.SortBy } Another possibility (which I don't recommend) consists into saving this object into the session so that you can fetch it back later. Yet another possibility (which I still don't recommend) is to use the MVCContrib's Html.Serialize helper which allows you to serialize an entire object graph into a hidden field and it will be sent to the server when the form is submitted and you will be able to fetch it as action argument. A: The simple answer is: don't put IQueryable properties in your model. The model should be purely simple objects and validation attributes. Keep the queryability in your controller.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504049", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Generally speaking; what changes should I make to a website to make it ipad/iphone/android friendly I am wondering what changes ( if any ) that I should consider making to a website to make it more friendly to mobile devices. I am focusing mainly on use in landscape mode. I know i can remove sidebars and that type of think but I am more interested in some simple and basic adjustments rather than fully accommodating mobile use ( in other words i estimate a low use of the site in mobile and there is not a budget to develop a dedicated mobile site/app ). I guess I already know about fallback images for flash and maybe increasing text size but is there anything else ? A: For Android friendliness, check out the myriad tips suggested here: Tips for optimizing a website for Android's browser? For iOS friendliness, this blog post has some good tips: Designing an iPhone-friendly Website A: The primary concern is to have it display reasonably well scaled, for which you will need to use the viewport tag. Other than that you'll need to worry about the various javascript/css inconsistencies between webkit, safari, etc. Also, since the user is likely to be on a weak connection, you should go back to 1990s style concern over your code and image weight. Try to keep things as light as possible to reduce download times. The rule of thumb used to be, no individual page should be larger than 100k. This may be controversial, but in my opinion you should avoid using frameworks (jquery, etc) that download a ton of functions, of which you then use practically none. Unless your site is really dependent on it, just write your own functionality and save the bandwidth. And of course if iPhone is your concern (or any iOS device) then Flash is a non-starter. A: I would suggest to use as little dynamic elements as possible. Avoid things like divs with inner scrolling. In the end it is important to test your site on a touch controlled device because that's the main difference.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504050", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Where's root_path or root_url? In rails, there are a lot of helpers to direct our actions, like collections_path new_member_path edit_member_path and so on. But where is the root? Is there a helper always points to my homepage? A: These helpers exist, but you have to set your root url before, in config/routes.rb: root :to => "controller#action" You can use root_url and root_path afterwards. Be warned that there's a catch when doing redirections with the _path helpers, you should use the _url ones when redirecting (see @LanguagesNamedAfterCoffee's comment for the details).
{ "language": "en", "url": "https://stackoverflow.com/questions/7504053", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "31" }
Q: python salesforce library to get salesforce data? Is there a library or package which we can use with python to connect to salesforce and get data? A: There's also a package called simple_salesforce . You can install it with: $ pip install simple_salesforce You can gain access to your Salesforce account with the following: from simple_salesforce import Salesforce sf = Salesforce(username='youremail@abc.com', password='password', security_token='token') The readme is helpful with regards to details... A: I use beatbox Example to query for a lead by email address import beatbox sf_username = "Username" sf_password = "password" sf_api_token = "api token" def get_lead_records_by_email(email) sf_client = beatbox.PythonClient() password = str("%s%s" % (sf_password, sf_api_token)) sf_client.login(sf_username, password) lead_qry = "SELECT id, Email, FirstName, LastName, OwnerId FROM Lead WHERE Email = '%s'" % (email) records = sf_client.query(lead_qry) return records To get other data look at the salesforce api docs view other beatbox examples here A: This one is the best in my experience: http://code.google.com/p/salesforce-python-toolkit/ A: Here is the ready code to get anyone started. For fetching reports from SFDC. import pandas as pd import numpy as np from pandas import DataFrame, Series from simple_salesforce import Salesforce #imported salesforce sf = Salesforce(username='youremail@domain.com', password='enter_password', security_token = 'Salesforce_token') salesforce token is received in email everytime you change your password. import requests #imported requests session = requests.Session() #starting sessions from io import StringIO #to read web data error_report_defined = session.get("https://na4.salesforce.com/xxxxxxxxxxxx?export=1&enc=UTF-8&xf=csv".format('xxxxxxxxxxxx'), headers=sf.headers, cookies={'sid': sf.session_id}) df_sfdc_error_report_defined = pd.DataFrame.from_csv(StringIO(error_report_defined.text)) df_sfdc_error_report_defined = df_sfdc_error_report_defined.to_csv('defined.csv', encoding = 'utf-8') error_report = pd.read_csv('defined.csv') #your report is saved in csv format print (error_report) A: Although this is not Python specific. I came across a cool tool for the command line. You could run bash commands as an option.. https://force-cli.heroku.com/ Usage: force <command> [<args>] Available commands: login force login [-i=<instance>] [<-u=username> <-p=password>] logout Log out from force.com logins List force.com logins used active Show or set the active force.com account whoami Show information about the active account describe Describe the object or list of available objects sobject Manage standard & custom objects bigobject Manage big objects field Manage sobject fields record Create, modify, or view records bulk Load csv file use Bulk API fetch Export specified artifact(s) to a local directory import Import metadata from a local directory export Export metadata to a local directory query Execute a SOQL statement apex Execute anonymous Apex code trace Manage trace flags log Fetch debug logs eventlogfile List and fetch event log file oauth Manage ConnectedApp credentials test Run apex tests security Displays the OLS and FLS for a give SObject version Display current version update Update to the latest version push Deploy artifact from a local directory aura force aura push -resourcepath=<filepath> password See password status or reset password notify Should notifications be used limits Display current limits help Show this help datapipe Manage DataPipes
{ "language": "en", "url": "https://stackoverflow.com/questions/7504057", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: How can I perform a diff that ignores all comments? I have a large codebase that was forked from the original project and I'm trying to track down all the differences from the original. A lot of the file edits consist of commented out debugging code and other miscellaneous comments. The GUI diff/merge tool called Meld under Ubuntu can ignore comments, but only single line comments. Is there any other convenient way of finding only the non-comment diffs, either using a GUI tool or linux command line tools? In case it makes a difference, the code is a mixture of PHP and Javascript, so I'm primarily interested in ignoring //, /* */ and #. A: To use visual diff, you can try Meld or DiffMerge. DiffMerge Its rulesets and options provide for customized behavior. GNU diffutils From the command-line perspective, you can use --ignore-matching-lines=RE option for diff, for example: diff -d -I '^#' -I '^ #' file1 file2 Please note that the regex has to match the corresponding line in both files and it matches every changed line in the hunk in order to work, otherwise it'll still show the difference. Use single quotes to protect pattern from shell expanding and to escape the regex-reserved characters (e.g. brackets). We can read in diffutils manual: However, -I only ignores the insertion or deletion of lines that contain the regular expression if every changed line in the hunk (every insertion and every deletion) matches the regular expression. In other words, for each non-ignorable change, diff prints the complete set of changes in its vicinity, including the ignorable ones. You can specify more than one regular expression for lines to ignore by using more than one -I option. diff tries to match each line against each regular expression, starting with the last one given. This behavior is also well explained by armel here. See also: * *How to diff files ignoring comments (lines starting with #)? Alternatively, check other diff apps, for example: * *for macOS: Code compare and merge tools *for Windows: 3-way merge tools for Windows A: See our Smart Differencer line of tools, which compare computer language source files using the language structure rather than the layout as a guide. This in particular means it ignores comments and whitespace in comparing code. There is a SmartDifferencer for PHP. A: You can filter both files through stripcmt first which will remove C and C++ comments. For removing # comments, sed 's/#.*//' will remove those. Of course you will loose some context when removing comments first, but on the other hand differences in comments will not make any problems. I think I would have done it like the following (described for a single file, automate as required): * *If the latest version of the original code base is A and the latest of the copied code base is B, let's call the versions with comments removed for A' and B' (e.g. save those to temporarily files while processing). *Find some common origin version and strip comments from that into O' (alternatively just re-use B' for this). *Perform a 3-way merge of O', A' and B' and save to C'. KDiff3 is an excellent tool for this. *Now you have the code changes you want merged, however C' is without comments, so get back into "normal" mode, do a new 3-way merge with A' as base and A and C'. This will pick up the changes between A' and C' (which is the code changes what you want) into the normal code base with comments based on version A. Drawing version trees on paper is before you start is highly recommended to get a clear picture of which versions you want to work on. But don't be limited of what the tree is showing, you can merge any version and in any direction if you just figure out what versions to use. A: diff <file1> <file2> | grep -v '^[<>]\ #' Far from perfect but it will give an idea of the differences A: gnu diff supports ignoring lines wich match a regular expression: diff --ignore-matching-lines='^#' file1 file2 and for folders: diff -[bB]qr --ignore-matching-lines='^#' folder1/ folder2/ This would ignore all lines which start with a # at the line beginning. A: I tried: diff file1 file2 and diff -d -I ^#.\* file1 file2 and the result was the same in both cases - included comments; however, diff -u file1 file2 | grep -v '^ \|^.#\|^.$' gives what I need: real diffs only, no comments, no empty lines. ;) A: Try: diff -I REGEXP -I REGEXP2 file1 file 2 See: Regular expression at Wikipedia Below are examples of regular expressions that would cause a diff to ignore a preprocessor directive and both standard comment block types. In example: \#*\n /***/ //*\n
{ "language": "en", "url": "https://stackoverflow.com/questions/7504059", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "19" }
Q: UIDatePicker with 15m interval but always exact time as return value I've got a UIDatePicker in Time mode with an interval of 15 minutes. Let's say it's 7:22PM. The value that the date picker shows per default is the current time rounded to the next higher/lower value, in this case, it's 7:15PM. If the user interacts with the date picker, the value that's shown is also the value returned. However if there hasn't been any user interaction and I get the time with [UIDatePicker date] the return value is the exact current time, i.e. 7:22 to stick with the example. Is there any way to always get the value that's actually shown on the date picker instead of the current unrounded time, even if the user hasn't explicitly picked a value? I've already tried to set the picker manually with [UIDatePicker setDate:[NSDate date]] but that doesn't change the behavior. A: I've modified @ima747 's answer for Swift 3/4 and as an extension of UIDatePicker. picker.clampedDate extension UIDatePicker { /// Returns the date that reflects the displayed date clamped to the `minuteInterval` of the picker. /// - note: Adapted from [ima747's](http://stackoverflow.com/users/463183/ima747) answer on [Stack Overflow](http://stackoverflow.com/questions/7504060/uidatepicker-with-15m-interval-but-always-exact-time-as-return-value/42263214#42263214}) public var clampedDate: Date { let referenceTimeInterval = self.date.timeIntervalSinceReferenceDate let remainingSeconds = referenceTimeInterval.truncatingRemainder(dividingBy: TimeInterval(minuteInterval*60)) let timeRoundedToInterval = referenceTimeInterval - remainingSeconds return Date(timeIntervalSinceReferenceDate: timeRoundedToInterval) } } A: This isn't a perfect solution but it works for me. I've taken it from another post and modified it to accept different values. - (NSDate*)clampDate:(NSDate *)dt toMinutes:(int)minutes { int referenceTimeInterval = (int)[dt timeIntervalSinceReferenceDate]; int remainingSeconds = referenceTimeInterval % (minutes*60); int timeRoundedTo5Minutes = referenceTimeInterval - remainingSeconds; if(remainingSeconds>((minutes*60)/2)) {/// round up timeRoundedTo5Minutes = referenceTimeInterval +((minutes*60)-remainingSeconds); } return [NSDate dateWithTimeIntervalSinceReferenceDate:(NSTimeInterval)timeRoundedTo5Minutes]; } Feed it an input date and a minute value (taken from the UIDatePicker.minuteInterval in the case of this thread) and it will return a time clamped to that interval which you can feed to the picker. A: @ima747 is right if I've changed date picker's default value then it's working fine and if I've read date from picker control without onChange then it's returning wrong date value. But I've checked that, date picker control have set default date (current date and may be it use nearest time milliseconds) If I set it to custom date and also set time to any date and 1:00:AM so now my time picker always open with 1:00:AM instead of current time
{ "language": "en", "url": "https://stackoverflow.com/questions/7504060", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "18" }
Q: Does Java allow nullable types? In C# I can a variable to allow nulls with the question mark. I want to have a true/false/null result. I want to have it set to null by default. The boolean will be set to true/false by a test result, but sometimes the test is not run and a boolean is default to false in java, so 3rd option to test against would be nice. c# example: bool? bPassed = null; Does java have anything similar to this? A: Sure you can go with Boolean, but to make it more obvious that your type can have "value" or "no value", it's very easy to make a wrapper class that does more or less what ? types do in C#: public class Nullable<T> { private T value; public Nullable() { value = null; } public Nullable(T init) { value = init; } public void set(T v) { value = v; } public boolean hasValue() { return value != null; } public T value() { return value; } public T valueOrDefault(T defaultValue) { return value == null ? defaultValue : value; } } Then you can use it like this: private Nullable<Integer> myInt = new Nullable<>(); ... myInt.set(5); ... if (myInt.hasValue()) .... int foo = myInt.valueOrDefault(10); Note that something like this is standard since Java8: the Optional class. https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html A: Yes you can. To do this sort of thing, java has a wrapper class for every primitive type. If you make your variable an instance of the wrapper class, it can be assigned null just like any normal variable. Instead of: boolean myval; ... you can use: Boolean myval = null; You can assign it like this: myval = new Boolean(true); ... And get its primitive value out like this: if (myval.booleanValue() == false) { // ... } Every primitive type (int, boolean, float, ...) has a corresponding wrapper type (Integer, Boolean, Float, ...). Java's autoboxing feature allows the compiler to sometimes automatically coerce the wrapper type into its primitive value and vice versa. But, you can always do it manually if the compiler can't figure it out. A: In Java, primitive types can't be null. However, you could use Boolean and friends. A: No. Instead, you can use the boxed Boolean class (which is an ordinary class rather a primitive type), or a three-valued enum. A: you can use : Boolean b = null; that is, the java.lang.Boolean object in Java. And then also set true or false by a simple assignment: Boolean b = true; or Boolean b = false; A: No but you may use Boolean class instead of primitive boolean type to put null A: If you are using object, it allows null If you are using Primitive Data Types, it does not allow null That the reason Java has Wrapper Class A: No, in java primitives cannot have null value, if you want this feature, you might want to use Boolean instead.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504064", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "44" }
Q: What is the best approach to write a data access object (DAO)? I was trying to write a user authentication system in Java. So I wrote some DAO class. First I did write a class named Persistence which is abstract. It is responsible for holding some common attributes. And wrote a class named User extending Persistence class. Those classes are – public abstract class Persistance { private Date createdDate; private Date lastUpdatedDate; private long version; private boolean isDeleted; //getter and setters } and the user class public class User extends Persistance{ private String username; private String password; private String passwordConfired; // getters and setters } My questions are- what is the best way to write variable name, which one is good, createdDate or dateCreated, deleted or isDeleted etc. And is this approach is okay or is there more good approach ? And how to implement data versioning? A: To write a DAO, typically you create an interface that defines the behavior of the DAO. interface MyObjDao { public int save(MyObj myObj); public void delete (MyObj myObj); // as many methods as you need for data acess } and then you create the actual implementation class MyObjDaoImpl implements MyObjDao { // implement methods here } The advantages of this are: 1) Because you define an interface, mocking DAOs is easy for any testing framework 2) The behavior is not tied to an implementation -- your DAOImpl could use jdbc, hibernate, whatever Your Persistance class is really a base class for all entities -- i.e. all classes instances of which get saved, where you want to represent some common fields in one place. This is a good practice -- I wouldn't call the class Persistance, something like BaseEntity is better (IMHO). Be sure to have javadocs that explain the purpose of the class. With respect to variable names, as long as they make sense and describe what they are for, its good. so dateCreated or createdDate are both fine; they both get the idea across. A: You are mixing a DAO (data access object) and a VO (value object) - also known as a DTO (data transfer object) - in the same class. Example using an interface for DAO behavior (blammy and kpow might be webservice, oracle database, mysql database, hibernate, or anything meaningful): public interface UserDTO { boolean deleteUser(String userId); UserVO readUser(String userId); void updateUser(String userId, UserVO newValues); } package blah.blammy; public class UserDTOImpl implements UserDTO { ... implement it based on blammy. } package blah.kpow; public class UserDTOImpl implements UserDTO { ... implement it based on kpow. } Example VO: public class UserVO { String firstName; String lastName; String middleInitial; ... getters and setters. } I prefer to identify the target of the delete using an ID instead of a VO object. Also, it is possible that an update will change the target identified by user ID "smackdown" to have user ID "smackup", so I generally pass an id and a VO. A: A good approach would be to use JPA with all of its features, this tutorial was really helpful. It explains how to use the @PrePersist and @PreUpdate annotations for setting create and update timestamps. Optimistic locking is supported by the @Version annotation. A: My questions are- what is the best way to write variable name, which one is good, createdDate or dateCreated, deleted or isDeleted etc. createdDate or dateCreated is very subjective. In databases, I have mostly seen createdDate though. Between deleted and isDeleted, I prefer (again subjective) deleted. I think the getter method can be named isDeleted().
{ "language": "en", "url": "https://stackoverflow.com/questions/7504070", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to setup table prefix in symfony2 Like in question topic, how can I setup default table prefix in symfony2? The best if it can be set by default for all entities, but with option to override for individual ones. A: Having just figured this out myself, I'd like to shed some light on exactly how to accomplish this. Symfony 2 & Doctrine 2.1 Note: I use YML for config, so that's what I'll be showing. Instructions * *Open up your bundle's Resources/config/services.yml *Define a table prefix parameter: Be sure to change mybundle and myprefix_ parameters: mybundle.db.table_prefix: myprefix_ *Add a new service: services: mybundle.tblprefix_subscriber: class: MyBundle\Subscriber\TablePrefixSubscriber arguments: [%mybundle.db.table_prefix%] tags: - { name: doctrine.event_subscriber } *Create MyBundle\Subscriber\TablePrefixSubscriber.php <?php namespace MyBundle\Subscriber; use Doctrine\ORM\Event\LoadClassMetadataEventArgs; class TablePrefixSubscriber implements \Doctrine\Common\EventSubscriber { protected $prefix = ''; public function __construct($prefix) { $this->prefix = (string) $prefix; } public function getSubscribedEvents() { return array('loadClassMetadata'); } public function loadClassMetadata(LoadClassMetadataEventArgs $args) { $classMetadata = $args->getClassMetadata(); if ($classMetadata->isInheritanceTypeSingleTable() && !$classMetadata->isRootEntity()) { // if we are in an inheritance hierarchy, only apply this once return; } $classMetadata->setTableName($this->prefix . $classMetadata->getTableName()); foreach ($classMetadata->getAssociationMappings() as $fieldName => $mapping) { if ($mapping['type'] == \Doctrine\ORM\Mapping\ClassMetadataInfo::MANY_TO_MANY && array_key_exists('name', $classMetadata->associationMappings[$fieldName]['joinTable']) ) { // Check if "joinTable" exists, it can be null if this field is the reverse side of a ManyToMany relationship $mappedTableName = $classMetadata->associationMappings[$fieldName]['joinTable']['name']; $classMetadata->associationMappings[$fieldName]['joinTable']['name'] = $this->prefix . $mappedTableName; } } } } *Optional step for postgres users: do something similary for sequences *Enjoy A: Simshaun's answer works fine, but has a problem when you have a single_table inheritance, with associations on the child entity. The first if-statement returns when the entity is not the rootEntity, while this entity might still have associations that have to be prefixed. I fixed this by adjusting the subscriber to the following: <?php namespace MyBundle\Subscriber; use Doctrine\Common\EventSubscriber; use Doctrine\ORM\Event\LoadClassMetadataEventArgs; use Doctrine\ORM\Mapping\ClassMetadataInfo; class TablePrefixSubscriber implements EventSubscriber { protected $prefix = ''; /** * Constructor * * @param string $prefix */ public function __construct($prefix) { $this->prefix = (string) $prefix; } /** * Get subscribed events * * @return array */ public function getSubscribedEvents() { return array('loadClassMetadata'); } /** * Load class meta data event * * @param LoadClassMetadataEventArgs $args * * @return void */ public function loadClassMetadata(LoadClassMetadataEventArgs $args) { $classMetadata = $args->getClassMetadata(); // Only add the prefixes to our own entities. if (FALSE !== strpos($classMetadata->namespace, 'Some\Namespace\Part')) { // Do not re-apply the prefix when the table is already prefixed if (false === strpos($classMetadata->getTableName(), $this->prefix)) { $tableName = $this->prefix . $classMetadata->getTableName(); $classMetadata->setPrimaryTable(['name' => $tableName]); } foreach ($classMetadata->getAssociationMappings() as $fieldName => $mapping) { if ($mapping['type'] == ClassMetadataInfo::MANY_TO_MANY && $mapping['isOwningSide'] == true) { $mappedTableName = $classMetadata->associationMappings[$fieldName]['joinTable']['name']; // Do not re-apply the prefix when the association is already prefixed if (false !== strpos($mappedTableName, $this->prefix)) { continue; } $classMetadata->associationMappings[$fieldName]['joinTable']['name'] = $this->prefix . $mappedTableName; } } } } } This has a drawback though; A not wisely chosen prefix might cause conflicts when it's actually already part of a table name. E.g. using prefix 'co' when theres a table called 'content' will result in a non-prefixed table, so using an underscore like 'co_' will reduce this risk. A: Alternate answer This is an update taking into account the newer features available in Doctrine2. Doctrine2 naming strategy Doctrine2 uses NamingStrategy classes which implement the conversion from a class name to a table name or from a property name to a column name. The DefaultNamingStrategy just finds the "short class name" (without its namespace) in order to deduce the table name. The UnderscoreNamingStrategy does the same thing but it also lowercases and "underscorifies" the "short class name". Your CustomNamingStrategy class could extend either one of the above (as you see fit) and override the classToTableName and joinTableName methods to allow you to specify how the table name should be constructed (with the use of a prefix). For example my CustomNamingStrategy class extends the UnderscoreNamingStrategy and finds the bundle name based on the namespacing conventions and uses that as a prefix for all tables. Symfony2 naming strategy Using the above in Symfony2 requires declaring your CustomNamingStragery class as a service and then referencing it in your config: doctrine: # ... orm: # ... #naming_strategy: doctrine.orm.naming_strategy.underscore naming_strategy: my_bundle.naming_strategy.prefixed_naming_strategy Pros and cons Pros: * *running one piece of code to do one single task -- your naming strategy class is called directly and its output is used; *clarity of structure -- you're not using events to run code which alter things that have already been built by other code; *better access to all aspects of the naming conventions; Cons: * *zero access to mapping metadata -- you only have the context that was given to you as parameters (this can also be a good thing because it forces convention rather than exception); *needs doctrine 2.3 (not that much of a con now, it might have been in 2011 when this question was asked :-)); A: Also, you can use this bundle for the new version of Symfony (4) - DoctrinePrefixBundle A: I don't when to implement a solution that involved catching event (performance concern), so I have tried the Alternate Solution but it doesn't work for me. I was adding the JMSPaymentCoreBundle and wanted to add a prefix on the payment tables. In this bundle, the definition of the tables are in the Resources\config\doctrine directory (xml format). I have finally found this solution: 1) copy doctrine directory containing the definitions on the table and paste it in my main bundle 2) modify the name of the tables in the definitions to add your prefix 3) declare it in your config.yml, in the doctrine/orm/entity manager/mapping section (the dir is the directory where you have put the modified definitions): doctrine: orm: ... entity_managers: default: mappings: ... JMSPaymentCoreBundle: mapping: true type: xml dir: "%kernel.root_dir%/Resources/JMSPayment/doctrine" alias: ~ prefix: JMS\Payment\CoreBundle\Entity is_bundle: false A: tested with Symfony 6 : Create a class that extends Doctrine's UnderscoreNamingStrategy and handles the prefix : <?php # src/Doctrine/PrefixedNamingStrategy.php namespace App\Doctrine; use Doctrine\ORM\Mapping\UnderscoreNamingStrategy; class PrefixedNamingStrategy extends UnderscoreNamingStrategy { private const PREFIX = 'sf'; public function classToTableName($className) { $underscoreTableName = parent::classToTableName($className); return self::PREFIX . '_' . $underscoreTableName; } } and configure doctrine to use it : # config/packages/doctrine.yaml doctrine: orm: naming_strategy: 'App\Doctrine\PrefixedNamingStrategy' A: @simshaun answer is good, but there is a problem with Many-to-Many relationships and inheritance. If you have a parent class User and a child class Employee, and the Employee own a Many-to-Many field $addresses, this field's table will not have a prefix. That is because of: if ($classMetadata->isInheritanceTypeSingleTable() && !$classMetadata->isRootEntity()) { // if we are in an inheritance hierarchy, only apply this once return; } User class (parent) namespace FooBundle\Bar\Entity; use Doctrine\ORM\Mapping as ORM; /** * User * * @ORM\Entity() * @ORM\Table(name="user") * @ORM\InheritanceType("SINGLE_TABLE") * @ORM\DiscriminatorColumn(name="type", type="string") * @ORM\DiscriminatorMap({"user" = "User", "employee" = "\FooBundle\Bar\Entity\Employee"}) */ class User extends User { } Employee class (child) namespace FooBundle\Bar\Entity; use Doctrine\ORM\Mapping as ORM; /** * User * * @ORM\Entity() */ class Employee extends FooBundle\Bar\Entity\User { /** * @var ArrayCollection $addresses * * @ORM\ManyToMany(targetEntity="\FooBundle\Bar\Entity\Adress") * @ORM\JoinTable(name="employee_address", * joinColumns={@ORM\JoinColumn(name="employee_id", referencedColumnName="id")}, * inverseJoinColumns={@ORM\JoinColumn(name="address_id", referencedColumnName="id")} * ) */ private $addresses; } Address class (relation with Employee) namespace FooBundle\Bar\Entity; use Doctrine\ORM\Mapping as ORM; /** * User * * @ORM\Entity() * @ORM\Table(name="address") */ class Address { } With the original solution, if you apply pref_ prefixe to this mapping, you will end up with tables : * *pref_user *pref_address *employee_address Solution A solution can be to modify, in the answer of @simshaun, the point 4 like this: *Create MyBundle\Subscriber\TablePrefixSubscriber.php <?php namespace MyBundle\Subscriber; use Doctrine\ORM\Event\LoadClassMetadataEventArgs; class TablePrefixSubscriber implements \Doctrine\Common\EventSubscriber { protected $prefix = ''; public function __construct($prefix) { $this->prefix = (string) $prefix; } public function getSubscribedEvents() { return array('loadClassMetadata'); } public function loadClassMetadata(LoadClassMetadataEventArgs $args) { $classMetadata = $args->getClassMetadata(); // Put the Many-yo-Many verification before the "inheritance" verification. Else fields of the child entity are not taken into account foreach($classMetadata->getAssociationMappings() as $fieldName => $mapping) { if($mapping['type'] == \Doctrine\ORM\Mapping\ClassMetadataInfo::MANY_TO_MANY && array_key_exists('name', $classMetadata->associationMappings[$fieldName]['joinTable']) // Check if "joinTable" exists, it can be null if this field is the reverse side of a ManyToMany relationship && $mapping['sourceEntity'] == $classMetadata->getName() // If this is not the root entity of an inheritance mapping, but the "child" entity is owning the field, prefix the table. ) { $mappedTableName = $classMetadata->associationMappings[$fieldName]['joinTable']['name']; $classMetadata->associationMappings[$fieldName]['joinTable']['name'] = $this->prefix . $mappedTableName; } } if($classMetadata->isInheritanceTypeSingleTable() && !$classMetadata->isRootEntity()) { // if we are in an inheritance hierarchy, only apply this once return; } $classMetadata->setTableName($this->prefix . $classMetadata->getTableName()); } } Here we handle the Many-to-Many relationship before verifying if the class is the child of an inheritance, and we add $mapping['sourceEntity'] == $classMetadata->getName() to add the prefix only one time, on the owning entity of the field.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504073", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "20" }
Q: parsing a php value for example: $value_array = array("fu" => "bar", "banana" => "apple"); for example: echo $value_array["fu"]; # output will be bar okay, i have this value: $value = "fuu:bar:12:apple"; okay, i'd like to parse the $value and write "bar" value to the screen, but i don't know how i can do this job. A: umm, why delimit by :? It'd be a lot easier with fuu:bar;12:apple but to go with what you have... $value = explode(':',$value); $values = array(); foreach ($value as $k => $v) { if ($k %2 != 0) $values[$value[($k - 1)]] = $v; } A: Try using explode function. A: $bar_val = explode(":", $value); echo $bar_val[1]; Demo: http://codepad.org/pyoyfk8n
{ "language": "en", "url": "https://stackoverflow.com/questions/7504074", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Unit testing won't setup properly on existing project, works fine on new projects I have a iOS project that I've been using since iOS 2.0, and currently I'm working on updates using Xcode 4.1 and I'm finally wanting to set up unit testing. I found this step by step guide on how to set them up, and I've tried following it multiple times specifically the Logic tests part. When I try running the test test that is setup when you do this it fails with the message: Undefined symbols for architecture i386: "_main", referenced from: start in crt1.10.6.o ld: symbol(s) not found for architecture i386 clang: error: linker command failed with exit code 1 (use -v to see invocation) I have not added any code to the template file, and no framework changes and I get this. So I went and created a new single view project WITHOUT unit testing, then after the project was setup I followed the same above guide to setup logic tests, and when I hit test it runs and fails with the appropreate sample STAssert string. I'm not doing anything different between the two projects. What can I do other then create a new project and migrate all my files over? A: I ended up just creating a new project and migrating everything back in. Now it works.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504076", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jquery address crawling - logic issues I'm using the jquery address plugin to build an ajax driven site, and i've got it working! Yay! For the purposes of this question we can use the test site: http://www.asual.com/jquery/address/samples/crawling http://www.asual.com/download/jquery/address (I had to remove two calls to urlencode() to make the crawling example work.) I'm encountering a problem with the $crawling->nav() call. It basically uses js and php to load parts of an xml file into the dom. I (mostly) understand how it works, and I would like to modify the example code to include sub pages. For example, I would like to show 'subnav-project.html' at '/!#/project' and '/!#/project/blue', but not at '/!#/contact'. To do this, I figure php should 'know' what page the user is on, that way I can base my logic off of that. Is this crazy? Can php ever know the current state of the site if I'm building it this way? If not, how does one selectively load html snippets, or modify what links are shown in navigation menus? I've never gotten too crazy with ajax before, so any feedback at all would be helpful. EDIT This is the crawling class. class Crawling { const fragment = '_escaped_fragment_'; function Crawling(){ // Initializes the fragment value $fragment = (!isset($_REQUEST[self::fragment]) || $_REQUEST[self::fragment] == '') ? '/' : $_REQUEST[self::fragment]; // Parses parameters if any $this->parameters = array(); $arr = explode('?', $fragment); if (count($arr) > 1) { parse_str($arr[1], $this->parameters); } // Adds support for both /name and /?page=name if (isset($this->parameters['page'])) { $this->page = '/?page=' . $this->parameters['page']; } else { $this->page = $arr[0]; } // Loads the data file $this->doc = new DOMDocument(); $this->doc->load('data.xml'); $this->xp = new DOMXPath($this->doc); $this->nodes = $this->xp->query('/data/page'); $this->node = $this->xp->query('/data/page[@href="' . $this->page . '"]')->item(0); if (!isset($this->node)) { header("HTTP/1.0 404 Not Found"); } } function base() { $arr = explode('?', $_SERVER['REQUEST_URI']); return $arr[0] != '/' ? preg_replace('/\/$/', '', $arr[0]) : $arr[0]; } function title() { if (isset($this->node)) { $title = $this->node->getAttribute('title'); } else { $title = 'Page not found'; } echo($title); } function nav() { $str = ''; // Prepares the navigation links foreach ($this->nodes as $node) { $href = $node->getAttribute('href'); $title = $node->getAttribute('title'); $str .= '<li><a href="' . $this->base() . ($href == '/' ? '' : '?' . self::fragment . '=' .html_entity_decode($href)) . '"' . ($this->page == $href ? ' class="selected"' : '') . '>' . $title . '</a></li>'; } echo($str); } function content() { $str = ''; // Prepares the content with support for a simple "More..." link if (isset($this->node)) { foreach ($this->node->childNodes as $node) { if (!isset($this->parameters['more']) && $node->nodeType == XML_COMMENT_NODE && $node->nodeValue == ' page break ') { $str .= '<p><a href="' . $this->page . (count($this->parameters) == 0 ? '?' : '&') . 'more=true' . '">More...</a></p>'; break; } else { $str .= $this->doc->saveXML($node); } } } else { $str .= '<p>Page not found.</p>'; } echo(preg_replace_callback('/href="(\/[^"]+|\/)"/', array(get_class($this), 'callback'), $str)); } private function callback($m) { return 'href="' . ($m[1] == '/' ? $this->base() : ($this->base() . '?' . self::fragment . '=' .$m[1])) . '"'; } } $crawling = new Crawling(); A: You won't be able to make server-side decisions using the fragment-identifier (i.e., everything to the right of the # character). This is because browsers don't send fragment-identifiers to the server. If you're going to want to make server-side decisions, you'll need to use some JavaScript assistance (including AJAX) to communicate what the current fragment-identifier is.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504078", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Parsing comments, finding links and embedded video Right now I have a variable: $blogbody which contains the entire contents of a blog. I'm using the following to convert URLS to clickable links: $blogbody = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]","<a href=\"\\0\">\\0</a>", $blogbody); And the following to resize embedded video: $blogbody = preg_replace('/(width)=("[^"]*")/i', 'width="495"', $blogbody); The problem I'm running into is the embedded video not working, comes back with an Access Forbidden error (403). If I remove the line to convert URLS to links, the embedded video works fine. Not sure how to get these two working together. If anyone else has a better solution to converting URLS to clickable links and resizing embedded video let me know! A: This might be happening because the link which you use to embed the video also gets his <a href=''> tags added. So instead of just converting all links, check that they don't have ' or " directly behind or in front of them - this will make sure that the embedded videos' links won't get anchor tags.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504079", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Query Python dictionary to get value from tuple Let's say that I have a Python dictionary, but the values are a tuple: E.g. dict = {"Key1": (ValX1, ValY1, ValZ1), "Key2": (ValX2, ValY2, ValZ2),...,"Key99": (ValX99, ValY99, ValY99)} and I want to retrieve only the third value from the tuple, eg. ValZ1, ValZ2, or ValZ99 from the example above. I could do so using .iteritems(), for instance as: for key, val in dict.iteritems(): ValZ = val[2] however, is there a more direct approach? Ideally, I'd like to query the dictionary by key and return only the third value in the tuple... e.g. dict[Key1] = ValZ1 instead of what I currently get, which is dict[Key1] = (ValX1, ValY1, ValZ1) which is not callable... Any advice? A: Use tuple unpacking: for key, (valX, valY, valZ) in dict.iteritems(): ... Often people use for key, (_, _, valZ) in dict.iteritems(): ... if they are only interested in one item of the tuple. But this may cause problem if you use the gettext module for multi language applications, as this model sets a global function called _. As tuples are immutable, you are not able to set only one item like d[key][0] = x You have to unpack first: x, y, z = d[key] d[key] = x, newy, z A: Just keep indexing: >>> D = {"Key1": (1,2,3), "Key2": (4,5,6)} >>> D["Key2"][2] 6 A: Using a generator expression! for val in (x[2] for x in dict): print val You don't need to use iteritems because you're only looking at the values.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504081", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: Thread memory changes while suspended I suspended a thread in another process using SuspendThread and then I get its context using GetThreadContext. GetThreadContext succeeds. Then I read parts of its stack with ReadProcessMemory. I do some stuff (still when the thread is suspended) and then I read the same memory again. I assumed that while the thread is suspended, its memory should stay the same but I get different results in the memory readings. What could cause this and how can I make the memory remain the same? A: * *What could cause this? Many things could cause this but the likely (p = .999999) cause is that some buggy code of yours is polluting the thread's memory by writing into it. *and how can I make the memory remain the same? There's only one answer here: fix the bug in your code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504086", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: light weight java web framework with jdk1.3 here is situation, my boss ask me to develop a web application for querying and editing data of tables in a database. Then server environment is restricted to jdk1.3 with websphere(a old version, i dont remember which) as application server. This web application need to be light weight as the server is old and slow. the database to be connected is not finalized and my boss proposed to use jdni for later switching database, i will be using oracle for testing. As the websphere is not yet setup in server, my boss ask me to test on jboss 3.2.7 first and later migrate to websphere when it is ready. Is there any framework that is light weight and compatible for jdk1.3, jboss and websphere that simplify the task like object relational model, mvc etc. A: Use straight forward JSP + Servlets + JDBC approach since you need every thing to be lightweight and JDK 1.3 compatible. Use Apache DBUtils to ease JDBC pains. A: Develop a new app on JDK 1.3 and an old version of WebSphere? What's the rationale for this poor decision? That JDK reached its EOL on 25-Oct-2004. That's almost seven years ago! That's pre-generics, pre-collections, pre-concurrency package, pre-generational garbage collection, and a host of other improvements. You and your boss should reconsider this decision. There's no reason that would explain it. If it's cost, get a free Java app container. If it's a web app, use Spring and deploy on Tomcat; if you require EJBs, use JBOSS.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504098", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Optimizing performance of Windows Forms InitializeComponent automatically I have a program with a full GUI that takes around 750 ms to load thanks to InitializeComponent(). After some research, it seems there are a few techniques to improve the time it takes for .NET to trundle through the InitializeComponent section. These include: 1: Using NGen or similar. 2: Using multi-threading as shown in Speed-optimise Windows Forms application 3: Miscellaneous techniques such as setting control properties before adding them as shown in Optimising InitializeComponent (takes 1 second!). Unfortunately (1) only improved my case by around 20%, and (2) and (3) are time consuming to implement, and sacrifice the convenience of the full GUI designer. Are there any automated solutions out there that take the source code directly, and produce a shorter, more efficient InitializeComponent()? A: For a Windows Forms application, a 750 ms startup time is quite good actually. Unless you want to spend countless hours just to gain another 20%, concentrate your efforts to user convenience. I highly doubt that there is an automated solution for this by the way, it would be very hard for a tool to guess what is not needed for your design.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504109", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How could I substring an NSString to the third occurrence of a character? I want to count the ',' characters and substring when it has been repeated 3 times. Input: 9,1,2,3,9 Output: 9,1,2 A: I am pretty sure something that specific would not have a build in method. Off the top of my head: for(unsigned int i = 0; i < [string length]; ++i) { if([string characterAtIndex:i] == ',') { ++commaCount; if(commaCount == 3) { return [string substringWithRange: NSMakeRange(0, i)]; } } } http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html The apple reference documents are usually a good place to start. A: [yourString substringFromIndex:[yourString rangeOfString:@","].location] Something like that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504115", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Is it possible to use a variable for a javascript reference Instead of: <script src="/scripts/myJsFile.v1.js" type="text/javascript></script> Have something like <script src="/scripts/myJsFile." + versionVar + ".js" type="text/javascript></script> This way when we update the js version files the user won't have to clear their cache. A: Not in that way, because you're mixing HTML and JavaScript together. HTML does not have JavaScript variables available. What you can do, however, is adding the <script> tag dynamically, i.e. through JavaScript. That way, you obviously are able to use variables: <script> var versionVar = "1.0"; window.addEventListener('load', function() { // on load var scriptTag = document.createElement('script'); // create tag scriptTag.src = "/scripts/myJsFile." + versionVar + ".js" // set src attribute scriptTag.type = "text/javascript"; //set type attribute document.getElementsByTagName('head')[0].appendChild(scriptTag); // append to <head> }, false); </script> A: You can't do this in your HTML file directly. But still you can do this inside an script tag if versopnVar is a JavaScript variable in your window context: <script type="text/javascript"> var script = document.createElement('script'); script.setAttribute('src', '/scripts/myJsFile.' + versionVar + '.js'); script.setAttribute('type', 'text/javascript'); document.body.appendChild(script); </script> At the end, it's not a good aproach doing this. Please read this article at a list apart to get informed. Alternative Style: Working With Alternate Style Sheets A: Check out how Google loads their Analytics. Then maybe try something similar like: (function() { var versionVar = 9; var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.src = 'http://www' + '.google-analytics.com/ga' + versionVar + '.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); A: It would probably be better to do something like <script src="/scripts/myJsFile.js?v1" type="text/javascript></script> Then, when you make and update: <script src="/scripts/myJsFile.js?v2" type="text/javascript></script> Which will cause most browsers to pull the file rather than pull from cache. This means that you won't have separate JS files. But will just be forcing the user to pull the most recent. Also, if you want it to always pull the file you can, in a similar manner, append a random int. A: You cannot do that straight out. One way is with some server side code. For example in php: <?php $version = "1.0"; ?> <script src="/scripts/myJsFile.<?php echo $version ?>.js" type="text/javascript></script> A: Not exactly that way, but you can create a new script node with e.g. document.createElement and add it to the page. var s = document.createElement("script"); s.src = ... document.body.appendChild(s); You can also use the document.write call to do the same... A: You'd have to update your page to update the variable. Also, you'd have to update your javascript file name every time you changed it. You can use a query string to make your JS unique. <script src="/scripts/myJsFile.js?version=2" type="text/javascript></script> marshall & I had the same Idea. Also, you'd have to update your HTML file every time you updated your Javascript file.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504117", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }