text
stringlengths
8
267k
meta
dict
Q: Android: Telnet using Socket - missing last line I'm trying to write some MUD Client for android, and I run into problem with output from server. I can't get my app to show last line (Login prompt) in console.. try { Socket socket = new Socket("studnia.mud.pl", 4004); OutputStream out = socket.getOutputStream(); PrintWriter output = new PrintWriter(out); output.println("Siema, pisze klient mudowy pod androida wiec nie bijcie że testuje na studni. :("); BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream())); String line="1"; while(line!=null){ line = input.readLine(); Log.i("Socket", line); } socket.close(); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } A: readLine() does not return the login prompt line because this line is not yet complete - there is no line-termination character until the login name has been entered. In order to get the partial line with the prompt, you cannot use readLine(); try something like while (input.ready()) { int c = input.read(); ... } or input.read(cbuf, 0, len).
{ "language": "en", "url": "https://stackoverflow.com/questions/7549164", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Global Application_Start not firing calling my service using Named Pipes I have a service running on Named Pipes. The service should do some stuff on startup, so I defined this in the Global.asax. Now I am experiencing that this is not being when the service receives it first call. Is using Named Pipes different in this way? protected void Application_Start(object sender, EventArgs e) { Log.Information("Application_Start()."); DoSomeStuff(); } A: Non-HTTP endpoints do not pass the IIS processing pipeline and will get routed directly to the WCF runtime. This means that you can't use an HttpModule to pre- or post-process requests. In addition, the Application_Start and Application_End of the HttpApplication class (global.asax) don't fire. So if you want to run startup or cleanup code for such services, you have to use the events of the ServiceHost class. Source
{ "language": "en", "url": "https://stackoverflow.com/questions/7549166", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Keyboard navigation of cell grouping hierarchy? I find cell grouping very useful in organizing my notebooks. I've been navigating this hierarchy by clicking with the mouse in the brackets on the right hand side of the notebook, but that's kind of tedious and requires some hand-eye coordination that degrades in the early morning hours. I'd really like to be able to navigate with the keyboard, but I've been unable to do this with any shortcuts that I could find. I usually use the Mac version of Mm. The arrow keys (or Ctl-F,B,P,N a la emacs) will move the cursor between cells displayed, and Ctl-. will select enclosing groups, essentially moving up the group hierarchy as I wish to do. And Cmd-' will open/close a group. However, I've not found a way to otherwise move through the groupings - primarily, say, moving the selection forward and backward at the same level but perhaps also down a level. Have I missed a shortcut or is there a better way to navigate the hierarchy? The specific problem I have in mind is the following: Suppose I have a collection of cells, grouped in sections A, B and C with subsections in each A1, A2, B1, B2, with cells A1a, A1b, etc. If I'm in cell A1a I can use ctl-. to select successively higher groupings - from A1a to A1 to A, for example. Now I have the whole A section selected. What I would like to do is to move to section C. If I use the arrow keys, I will advance to the next displayed cell at any level after the selected A (alternating with insertion points between those cells). But what I would like to do is to advance at the same (Section) level - to section B, then to section C. And then perhaps to drop the selection down to the subsection level - C1 - and advance to C3. Its not a big deal, but I arrange my longer notebooks hierarchically like this to reflect a logical organization in my mind, and it would be very convenient to navigate the notebook more like I am thinking about the problem. A: It is not too clear to me exactly what you want, but this might help you. If you select a cell bracket and use the arrow keys, you will select a nearby cell bracket. If you instead select inside a cell and use the arrow keys you will move inside the cell first and then inside nearby cells. If you want to move a selected cell somewhere else: * *select the cell bracket *type ctrl/cmd -X to cut the cell and put it on the clipboard *move with arrows or otherwise to another location on the nb (between cells) *type ctrl/cmd -V to paste the cut cell into the new place This way you can quickly alter the cell hierarchy and order A: You can add at least part of the functionality you want through editing MenuSetup.tr or KeyEventTranslations.tr. These are important system files, so be careful. Start by copying the file you are going to edit from the $InstallationDirectory to $UserBaseDirectory in the same tree. This should look something like: \AppData\Roaming\Mathematica\SystemFiles\FrontEnd\TextResources\Windows\MenuSetup.tr Now, editing the file in the new location, you can add menu items and key commands. Under the Menu["&Cell", section, being careful to respect brackets and commas, I add: MenuItem["Next Cell", FrontEndExecute@{FrontEnd`SelectionMove[FrontEnd`SelectedNotebook[], Next, CellGroup]}, MenuKey[".", Modifiers->{"Control"}] ] This adds a new menu item under Cell, and a new keyboard command to move to the next CellGroup: Ctrl+.. This should allow you to move from one highlighted cell group, such as a section, to the next group at the same level. This is the easiest of the commands to implement. I may return to this to try to implement some of the other commands, or you may experiment yourself with the arguments of SelectionMove to see what can be done.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549168", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is '\0' guaranteed to be 0? I wrote this function in C, which is meant to iterate through a string to the next non-white-space character: char * iterate_through_whitespace(unsigned char * i){ while(*i && *(i++) <= 32); return i-1; } It seems to work quite well, but I'm wondering if it is safe to assume that the *i will be evaluated to false in the situation that *i == '\0', and it won't iterate beyond the end of a string. It works well on my computer, but I'm wondering if it will behave the same when compiled on other machines. A: In C, '\0' has the exact same value and type as 0. There is no reason to ever write '\0' except to uglify your code. \0 might however be useful inside double quotes to make strings with embedded null bytes. A: The standard says: A byte with all bits set to 0, called the null character, shall exist in the basic execution character set; it is used to terminate a character string. A: Yes -- but in my opinion it's better style to be more explicit: while (*i != '\0' && ... But the comparison to 32 is hardly the best approach. 32 happens to be the ASCII/Unicode code for the space character, but C doesn't guarantee any particular character set -- and there are plenty of control characters with values less than 32 that aren't whitespace. Use the isspace() function. (And I'd never name a pointer i.) A: The ASCII standard dictates that the NUL character is encoded as the byte 0. Unless you stop working with encodings that are backwards compatible with ASCII, nothing should go wrong. A: I find the other answers inadequate because they do not provide a direct answer to the question in the title. Is '\0' guaranteed to be 0? No, the integer value of the construction '\0' is not guaranteed to be 0 by the C standard. Regarding the null character, all we know is that (C99 p.17, C11 p.22) [a] byte with all bits set to 0, called the null character, shall exist in the basic execution set. and that (C99 p. 61, C11 p.69) [t]he construction '\0' is commonly used to represent the null character. Emphasis on "commonly used". There is no guarantee.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549170", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "21" }
Q: Can this CSS class written in shorter, better way? Can you write this CSS class in a shorter way? Thank you. .MessageTitle a, .MessageTitle a:visited, .MessageTitle a:active, .MessageTitle a:hover,.MessageSender a, .MessageSender a:visited, .MessageSender a:active, .MessageSender a:hover { text-decoration: none; outline: none; display:block; vertical-align: middle; text-align: center; color: Black; line-height:30px; } .MessageTitle a:active, .MessageTitle a:hover,.MessageSender a:active, .MessageSender a:hover { text-decoration: underline; } A: You could apply a single class to the anchor so you aren't defining the same groups twice. .messageLink, .messageLink:visited { color: #000; display:block; line-height:30px; outline: none; text-align: center; text-decoration: none; vertical-align: middle; } .messageLink:active, .messageLink:hover { text-decoration:underline; } A: The really short way would be to look at Less CSS. www.lesscss.org A: .MessageTitle a, .MessageSender a { text-decoration: none; outline: none; display:block; vertical-align: middle; text-align: center; color: Black; line-height:30px; } .MessageTitle a:active, .MessageTitle a:hover, .MessageSender a:active, .MessageSender a:hover { text-decoration: underline; } .MessageSender a:visited, .MessageSender a:visited { text-decoration: none; } You should probably also include :focus. I would also use :link. In practice, for proper DRY brevity, simplicity and UX consistency, I would declare all these styles globally on the bare a selector, so more like this: a:link { text-decoration: none; outline: none; color: Black } a:active, a:hover, a:focus { text-decoration: underline} a:visited { text-decoration: none} .MessageTitle a, .MessageSender a { display:block; vertical-align: middle; text-align: center; line-height:30px; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7549176", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Expires vs max-age, which one takes priority if both are declared in a HTTP response? If a HTTP response that returns both Expires and max-age indications which one is used? Cache-Control: max-age=3600 Expires: Tue, 15 May 2008 07:19:00 GMT Considering that each one refers to a different point in time. A: See this answer: Difference between three .htaccess expire rules If a response includes both an Expires header and a max-age directive, the max-age directive overrides the Expires header, even if the Expires header is more restrictive. This rule allows an origin server to provide, for a given response, a longer expiration time to an HTTP/1.1 (or later) cache than to an HTTP/1.0 cache. This might be useful if certain HTTP/1.0 caches improperly calculate ages or expiration times, perhaps due to desynchronized clocks. A: This case is explained in the official RFC on W3C. The max-age directive takes priority over Expires
{ "language": "en", "url": "https://stackoverflow.com/questions/7549177", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "49" }
Q: SignalR + posting a message to a Hub via an action method I am using the hub- feature of SignalR (https://github.com/SignalR/SignalR) to publish messages to all subscribed clients: public class NewsFeedHub : Hub public void Send(string channel, string content) { Clients[channel].addMessage(content); } This works fine when calling "Send" via Javascript, but I would also like the web application to publish messages (from within an ASP.NET MVC action method). I already tried instantiating a new object ob NewsFeedHub and calling the Send method, but this results in an error (as the underlying "Connection" of the Hub is not set). Is there a way to use the Hub without a connection? A: Please note that the SignalR API has changed multiple times since this question was asked. There is a chance that some answers will become out of date. This does not mean that they should be down-voted as they were correct at the time of writing There is another updated answer for this, as seen in the SignalR Wiki c# Public ActionResult MyControllerMethod() { var context = GlobalHost.ConnectionManager.GetHubContext<MyHub>(); context.Clients.All.methodInJavascript("hello world"); // or context.Clients.Group("groupname").methodInJavascript("hello world"); } vb.net Public Function MyControllerMethod() As ActionResult Dim context = GlobalHost.ConnectionManager.GetHubContext(Of MyHub)() context.Clients.All.methodInJavascript("hello world") '' or context.Clients.Group("groupname").methodInJavascript("hello world") End Function Update This code has been updated. Follow http://www.asp.net/signalr/overview/signalr-20/hubs-api/hubs-api-guide-server for changes. If you are using DI container If you are using a DI container to wire up your hubs, get IConnectionManager from your container, and call GetHubContext on that connectionManager. A: 2018 February, Short and simple solution For solving this I usually design my hubs in the following way: public class NewsFeedHub : Hub { private static IHubContext hubContext = GlobalHost.ConnectionManager.GetHubContext<NewsFeedHub>(); // Call this from JS: hub.client.send(channel, content) public void Send(string channel, string content) { Clients.Group(channel).addMessage(content); } // Call this from C#: NewsFeedHub.Static_Send(channel, content) public static void Static_Send(string channel, string content) { hubContext.Clients.Group(channel).addMessage(content); } } So it's easy to call from Javascript and from back-end code as well. The two methods are resulting in the same event at the client. A: I was looking for .NET Core solution and Google sent me here, seems like no one mentioned .NET Core solution, so here you go: The Hub, nothing fancy here: public class MyHub : Hub { // ... } Inside your controller: public class HomeController : Controller { readonly IHubContext<MyHub> _hub; public HomeController(IHubContext<MyHub> hub) { _hub = hub; } public IActionResult Index() { // ... await _hub.Clients.All.SendAsync("ReceiveMessage", "Hello from HomeController"); // ... } } A: Following on from DDan's answer you can create an overloaded static method and keep common logic in one method - I use this pattern public class ChatHub : Hub { private static IHubConnectionContext<dynamic> GetClients(ChatHub chatHub) { if (chatHub == null) return GlobalHost.ConnectionManager.GetHubContext<ChatHub>().Clients; else return chatHub.Clients; } // Call from JavaScript public void Send(string message) { Send(message, this); } // Call from C# eg: Hubs.ChatHub.Send(message, null); public static void Send(string message, ChatHub chatHub) { IHubConnectionContext<dynamic> clients = GetClients(chatHub); // common logic goes here clients.All.receiveSend(message); } } Then from your controller you can use Hubs.ChatHub.Send(arg1, null); A: update 2012: This answer is old, too! SignalR's public API is in constant flux, it seems. Tim B James has the new, proper API usage as of July 2012. update 2019 Don't use this answer anymore. New versions of SignalR that work on AspNetCore should refer to the accepted answer by Tim B James, or other up-voted answers. I'm leaving this answer here for history's sake. The currently accepted answer from Mike is old, and no longer works with the latest version of SignalR. Here's an updated version that shows how to post a message to a hub from an MVC controller action: public ActionResult MyControllerMethod() { // Important: .Resolve is an extension method inside SignalR.Infrastructure namespace. var connectionManager = AspNetHost.DependencyResolver.Resolve<IConnectionManager>(); var clients = connectionManager.GetClients<MyHub>(); // Broadcast to all clients. clients.MethodOnTheJavascript("Good news!"); // Broadcast only to clients in a group. clients["someGroupName"].MethodOnTheJavascript("Hello, some group!"); // Broadcast only to a particular client. clients["someConnectionId"].MethodOnTheJavascript("Hello, particular client!"); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7549179", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "65" }
Q: Search for file by creation Time I'm trying to write C++ code in windows to find a file by creation time, not by name of file. Can't seem to find anything. Any help or suggestions are welcome. A: If you are looking for files that are under 20 seconds old, searching the whole tree could take longer than that. If you are looking for files that were created while your program is running, you could use ReadDirectoryChangesW to wait for notifications of file changes with a filter of either FILE_NOTIFY_CHANGE_FILE_NAME or FILE_NOTIFY_CHANGE_CREATION. If your program is looking for changes that happened shortly before it started up, you could use the somewhat more complicated change journal API. You would want to use FSCTL_READ_USN_JOURNAL with a filter value of USN_REASON_FILE_CREATE. A: If you are using FindFirstFile and FindNextFile to walk through directories, the file creation times are in the WIN32_FIND_DATA structure.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549180", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Coercing from Arrays Suppose I have this simple class: class Color attr_accessor :rgb def initialize(ary) @rgb = ary end def +(other) other = Color.new(other) unless Color === other Color.new(@rgb.zip(other.rgb).map {|p| [p.reduce(:+), 255].min }) end end I know this is a bad way to implement it but this is the shortest way I can think. c100 = Color.new([100, 100, 100]) c100 + c100 #=> Color(200, 200, 200) c100 + c100 + c100 #=> Color(255, 255, 255) It also works if I give an Array as Colors: c100 + [50, 50, 50] #=> Color(150, 150, 150) But I can't to this: [50, 50, 50] + c100 #=> TypeError: can't convert Color into Array Defining coerce doesn't work. How can I make it working? A: It's because the code [50, 50, 50] + c100 calls the + method on Array, not Color, and that method can't convert a color to an Array. By contrast, c100 + [50, 50, 50] does call Color's + method. However, even if you define a conversion method in Color: class Color def to_ary return @rgb end end the Array method will not work as you expect; the result will be the concatenation of the two arrays, since Array's + method concatenates their operands, rather than adding their elements: irb>[50,50,50]+c100 => [50,50,50,100,100,100] Here, the result will be an Array, rather than a Color. EDIT: The only way I see of making this work is to alias the + method of Array to handle the special case of receiving a Color as the second operand. However, I will admit that this approach is rather ugly. class Array alias color_plus + def +(b) if b.is_a?(Color) return b+self end return color_plus(b) end end A: Elaborating further on @peter-o answer I came up with this implementation that, although uggly in the sense that it redefines several methods of Array, it pretty much manages to be a good workaround for the expected behaviour, I don't think I would ever fit this in production code but I really liked the challenge... Sorry for diverging on the color subject but I didn't know what the expected behaviour for minus and times would be. class Array alias :former_plus :+ alias :former_minus :- alias :former_times :* def +(other) former_plus(other) rescue TypeError apply_through_coercion(other, :+) end def -(other) former_minus(other) rescue TypeError apply_through_coercion(other, :-) end def *(other) former_times(other) rescue TypeError apply_through_coercion(other, :*) end # https://github.com/ruby/ruby/blob/ruby_1_9_3/lib/matrix.rb#L1385 def apply_through_coercion(obj, oper) coercion = obj.coerce(self) raise TypeError unless coercion.is_a?(Array) && coercion.length == 2 coercion[0].public_send(oper, coercion[1]) rescue raise TypeError, "#{obj.inspect} can't be coerced into #{self.class}" end private :apply_through_coercion end One of the chalenges was to make sure the inverted call on the Point#- method would not return unexpected results, hence the @coerced instance variable as a control flag on the object. class Point attr_reader :x, :y def initialize(x, y) @x, @y, @coerced = x, y, false end def coerce(other) @coerced = true [self, other] end def coerced?; @coerced end def +(other) other = Point.new(*other) if other.respond_to? :to_ary Point.new(@x + other.x, @y + other.y) end def -(other) other = Point.new(*other) if other.respond_to? :to_ary if coerced? @coerced = false; other + (-self) else self + (-other) end end def -@; Point.new(-@x, -@y) end def *(other) case other when Fixnum then Point.new(@x*other, @y*other) when Point then Point.new(@x*other.x, @y*other.y) when Array then self * Point.new(*other) end end end After all, what this code manages to achieve is adding coerce functionality to the Array class where it didn't exist, explicitly to methods Array#+, Array#- and Array#*.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549181", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Android Paint: .measureText() vs .getTextBounds() I'm measuring text using Paint.getTextBounds(), since I'm interested in getting both the height and width of the text to be rendered. However, the actual text rendered is always a bit wider than the .width() of the Rect information filled by getTextBounds(). To my surprise, I tested .measureText(), and found that it returns a different (higher) value. I gave it a try, and found it correct. Why do they report different widths? How can I correctly obtain the height and width? I mean, I can use .measureText(), but then I wouldn't know if I should trust the .height() returned by getTextBounds(). As requested, here is minimal code to reproduce the problem: final String someText = "Hello. I believe I'm some text!"; Paint p = new Paint(); Rect bounds = new Rect(); for (float f = 10; f < 40; f += 1f) { p.setTextSize(f); p.getTextBounds(someText, 0, someText.length(), bounds); Log.d("Test", String.format( "Size %f, measureText %f, getTextBounds %d", f, p.measureText(someText), bounds.width()) ); } The output shows that the difference not only gets greater than 1 (and is no last-minute rounding error), but also seems to increase with size (I was about to draw more conclusions, but it may be entirely font-dependent): D/Test ( 607): Size 10.000000, measureText 135.000000, getTextBounds 134 D/Test ( 607): Size 11.000000, measureText 149.000000, getTextBounds 148 D/Test ( 607): Size 12.000000, measureText 156.000000, getTextBounds 155 D/Test ( 607): Size 13.000000, measureText 171.000000, getTextBounds 169 D/Test ( 607): Size 14.000000, measureText 195.000000, getTextBounds 193 D/Test ( 607): Size 15.000000, measureText 201.000000, getTextBounds 199 D/Test ( 607): Size 16.000000, measureText 211.000000, getTextBounds 210 D/Test ( 607): Size 17.000000, measureText 225.000000, getTextBounds 223 D/Test ( 607): Size 18.000000, measureText 245.000000, getTextBounds 243 D/Test ( 607): Size 19.000000, measureText 251.000000, getTextBounds 249 D/Test ( 607): Size 20.000000, measureText 269.000000, getTextBounds 267 D/Test ( 607): Size 21.000000, measureText 275.000000, getTextBounds 272 D/Test ( 607): Size 22.000000, measureText 297.000000, getTextBounds 294 D/Test ( 607): Size 23.000000, measureText 305.000000, getTextBounds 302 D/Test ( 607): Size 24.000000, measureText 319.000000, getTextBounds 316 D/Test ( 607): Size 25.000000, measureText 330.000000, getTextBounds 326 D/Test ( 607): Size 26.000000, measureText 349.000000, getTextBounds 346 D/Test ( 607): Size 27.000000, measureText 357.000000, getTextBounds 354 D/Test ( 607): Size 28.000000, measureText 369.000000, getTextBounds 365 D/Test ( 607): Size 29.000000, measureText 396.000000, getTextBounds 392 D/Test ( 607): Size 30.000000, measureText 401.000000, getTextBounds 397 D/Test ( 607): Size 31.000000, measureText 418.000000, getTextBounds 414 D/Test ( 607): Size 32.000000, measureText 423.000000, getTextBounds 418 D/Test ( 607): Size 33.000000, measureText 446.000000, getTextBounds 441 D/Test ( 607): Size 34.000000, measureText 455.000000, getTextBounds 450 D/Test ( 607): Size 35.000000, measureText 468.000000, getTextBounds 463 D/Test ( 607): Size 36.000000, measureText 474.000000, getTextBounds 469 D/Test ( 607): Size 37.000000, measureText 500.000000, getTextBounds 495 D/Test ( 607): Size 38.000000, measureText 506.000000, getTextBounds 501 D/Test ( 607): Size 39.000000, measureText 521.000000, getTextBounds 515 A: You can do what I did to inspect such problem: Study Android source code, Paint.java source, see both measureText and getTextBounds methods. You'd learn that measureText calls native_measureText, and getTextBounds calls nativeGetStringBounds, which are native methods implemented in C++. So you'd continue to study Paint.cpp, which implements both. native_measureText -> SkPaintGlue::measureText_CII nativeGetStringBounds -> SkPaintGlue::getStringBounds Now your study checks where these methods differ. After some param checks, both call function SkPaint::measureText in Skia Lib (part of Android), but they both call different overloaded form. Digging further into Skia, I see that both calls result into same computation in same function, only return result differently. To answer your question: Both your calls do same computation. Possible difference of result lies in fact that getTextBounds returns bounds as integer, while measureText returns float value. So what you get is rounding error during conversion of float to int, and this happens in Paint.cpp in SkPaintGlue::doTextBounds in call to function SkRect::roundOut. The difference between computed width of those two calls may be maximally 1. EDIT 4 Oct 2011 What may be better than visualization. I took the effort, for own exploring, and for deserving bounty :) This is font size 60, in red is bounds rectangle, in purple is result of measureText. It's seen that bounds left part starts some pixels from left, and value of measureText is incremented by this value on both left and right. This is something called Glyph's AdvanceX value. (I've discovered this in Skia sources in SkPaint.cpp) So the outcome of the test is that measureText adds some advance value to the text on both sides, while getTextBounds computes minimal bounds where given text will fit. Hope this result is useful to you. Testing code: protected void onDraw(Canvas canvas){ final String s = "Hello. I'm some text!"; Paint p = new Paint(); Rect bounds = new Rect(); p.setTextSize(60); p.getTextBounds(s, 0, s.length(), bounds); float mt = p.measureText(s); int bw = bounds.width(); Log.i("LCG", String.format( "measureText %f, getTextBounds %d (%s)", mt, bw, bounds.toShortString()) ); bounds.offset(0, -bounds.top); p.setStyle(Style.STROKE); canvas.drawColor(0xff000080); p.setColor(0xffff0000); canvas.drawRect(bounds, p); p.setColor(0xff00ff00); canvas.drawText(s, 0, bounds.bottom, p); } A: My experience with this is that getTextBounds will return that absolute minimal bounding rect that encapsulates the text, not necessarily the measured width used when rendering. I also want to say that measureText assumes one line. In order to get accurate measuring results, you should use the StaticLayout to render the text and pull out the measurements. For example: String text = "text"; TextPaint textPaint = textView.getPaint(); int boundedWidth = 1000; StaticLayout layout = new StaticLayout(text, textPaint, boundedWidth , Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false); int height = layout.getHeight(); A: There is another way to measure the text bounds precisely, first you should get the path for the current Paint and text. In your case it should be like this: p.getTextPath(someText, 0, someText.length(), 0.0f, 0.0f, mPath); After that you can call: mPath.computeBounds(mBoundsPath, true); In my code it always returns correct and expected values. But, not sure if it works faster than your approach. A: The mice answer is great... And here is the description of the real problem: The short simple answer is that Paint.getTextBounds(String text, int start, int end, Rect bounds) returns Rect which doesn't starts at (0,0). That is, to get actual width of text that will be set by calling Canvas.drawText(String text, float x, float y, Paint paint) with the same Paint object from getTextBounds() you should add the left position of Rect. Something like that: public int getTextWidth(String text, Paint paint) { Rect bounds = new Rect(); paint.getTextBounds(text, 0, end, bounds); int width = bounds.left + bounds.width(); return width; } Notice this bounds.left - this the key of the problem. In this way you will receive the same width of text, that you would receive using Canvas.drawText(). And the same function should be for getting height of the text: public int getTextHeight(String text, Paint paint) { Rect bounds = new Rect(); paint.getTextBounds(text, 0, end, bounds); int height = bounds.bottom + bounds.height(); return height; } P.s.: I didn't test this exact code, but tested the conception. Much more detailed explanation is given in this answer. A: Sorry for answering again on that question... I needed to embed the image. I think the results @mice found are missleading. The observations might be correct for the font size of 60 but they turn much more different when the text is smaller. Eg. 10px. In that case the text is actually drawn BEYOND the bounds. Sourcecode of the screenshot: @Override protected void onDraw( Canvas canvas ) { for( int i = 0; i < 20; i++ ) { int startSize = 10; int curSize = i + startSize; paint.setTextSize( curSize ); String text = i + startSize + " - " + TEXT_SNIPPET; Rect bounds = new Rect(); paint.getTextBounds( text, 0, text.length(), bounds ); float top = STEP_DISTANCE * i + curSize; bounds.top += top; bounds.bottom += top; canvas.drawRect( bounds, bgPaint ); canvas.drawText( text, 0, STEP_DISTANCE * i + curSize, paint ); } } A: DISCLAIMER: This solution is not 100% accurate in terms of determining the minimal width. I was also figuring out how to measure text on a canvas. After reading the great post from mice i had some problems on how to measure multiline text. There is no obvious way from these contributions but after some research i cam across the StaticLayout class. It allows you to measure multiline text (text with "\n") and configure much more properties of your text via the associated Paint. Here is a snippet showing how to measure multiline text: private StaticLayout measure( TextPaint textPaint, String text, Integer wrapWidth ) { int boundedWidth = Integer.MAX_VALUE; if (wrapWidth != null && wrapWidth > 0 ) { boundedWidth = wrapWidth; } StaticLayout layout = new StaticLayout( text, textPaint, boundedWidth, Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false ); return layout; } The wrapwitdh is able to determin if you want to limit your multiline text to a certain width. Since the StaticLayout.getWidth() only returns this boundedWidth you have to take another step to get the maximum width required by your multiline text. You are able to determine each lines width and the max width is the highest line width of course: private float getMaxLineWidth( StaticLayout layout ) { float maxLine = 0.0f; int lineCount = layout.getLineCount(); for( int i = 0; i < lineCount; i++ ) { if( layout.getLineWidth( i ) > maxLine ) { maxLine = layout.getLineWidth( i ); } } return maxLine; } A: The different between getTextBounds and measureText is described with the image below. In short, * *getTextBounds is to get the RECT of the exact text. The measureText is the length of the text, including the extra gap on the left and right. *If there are spaces between the text, it is measured in measureText but not including in the length of the TextBounds, although the coordinate get shifted. *The text could be tilted (Skew) left. In this case, the bounding box left side would exceed outside the measurement of the measureText, and the overall length of the text bound would be bigger than measureText *The text could be tilted (Skew) right. In this case, the bounding box right side would exceed outside the measurement of the measureText, and the overall length of the text bound would be bigger than measureText A: This is how I calculated the real dimensions for the first letter (you can change the method header to suit your needs, i.e. instead of char[] use String): private void calculateTextSize(char[] text, PointF outSize) { // use measureText to calculate width float width = mPaint.measureText(text, 0, 1); // use height from getTextBounds() Rect textBounds = new Rect(); mPaint.getTextBounds(text, 0, 1, textBounds); float height = textBounds.height(); outSize.x = width; outSize.y = height; } Note that I'm using TextPaint instead of the original Paint class.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549182", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "201" }
Q: What is the correct term for ->,->* and .* operators? Wikipedia refers to them as: -> Member b of object pointed to by a ->* Member pointed to by b of object pointed to by a .* Member pointed to by b of object a But I need to refer to them without using "a" and "b". Do they have any names? A: The standard has calls ->* and .* "pointer-to-member operators" (5.5). The former expects the first operand to be of pointer type, the second of class type. Similarly, -> and . are called "class member access" (5.2.5), or "dot" and "arrow". A: If you're discussing them in conversation, I us the terms:: -> "Arrow" eg. "B-arrow-A" ->* "Arrow-star" eg. "B-arrow-star-A" .* "Dot-star" eg. "B-dot-star-A" When writing about them, I prefer the terms others have mentioned. A: I believe it is * *member access operator (–>) *pointer-dereference operator (*) *Pointer-to-member selection (.*) [according to here, at least]
{ "language": "en", "url": "https://stackoverflow.com/questions/7549187", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Are event listeners in jQuery removed automatically when you remove the element using .html()? In jQuery if we use .remove() for removing some element, then all bound events and jQuery data associated with the elements are removed. But what happens if we "remove" the elements with .html()? Do we need to unbind all the elements prior to change any html for avoiding memory leaks? A: Yes, they will be removed. jQuery will clean up events etc related to the removed elements. It will NOT copy events if you do something like $(elm1).html($elm2.html()) A: Yeah, they will be removed even when you use html(). The jQuery source code confirms it. A: Just to expand a bit: * *.remove(), .html(), .empty(), etc - all remove listeners *.detach() does not remove listeners *.clone() has parameters letting you decide if data/listeners are copied So if you want to retain listeners, use .detach().
{ "language": "en", "url": "https://stackoverflow.com/questions/7549188", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: Phonegap error using web database : "result of expression mydb.transaction is not a function" I'm trying to use html5's web-database using phonegap for an iOS app for the first time. But I'm stuck at this error which says "result of expression mybd.transaction is not a function" If I check using alerts, initDB is getting executed but when it comes to createTables function, the above error rises and I'm helpless from thereon. I've used this implementation -> http://wiki.phonegap.com/w/page/16494756/Adding%20SQL%20Database%20support%20to%20your%20iPhone%20App <script type="text/javascript"> function validateFloat() { var mydb=false; var fuelUnits = document.myForm.UnitsOfFuel; var bFuelUnits = false; var bUnitPrice = false; switch (isNumeric(fuelUnits.value)) { case true: bFuelUnits = true; fuelUnits.style.background="white"; break; case false: fuelUnits.focus(); fuelUnits.style.background="yellow"; break; } var unitPrice = document.myForm.PricePerUnit; switch (isNumeric(unitPrice.value)) { case true: bUnitPrice = true; unitPrice.style.background="white"; break; case false: unitPrice.focus(); unitPrice.style.background="yellow"; break; } if(bFuelUnits && bUnitPrice) { if(initDB(mydb)) { if(createTables(mydb)) { loadCelebs(); return true; } else return false; } else return false; } else { return false; } } function isNumeric(n) { var n2 = n; n = parseFloat(n); return (n!='NaN' && n2==n); } // initialise the database function initDB(mydb) { try { if (!window.openDatabase) { alert('not supported'); return false; } else { var shortName = 'phonegap'; var version = '1.0'; var displayName = 'PhoneGap Test Database'; var maxSize = 65536; // in bytes mydb = openDatabase(shortName, version, displayName, maxSize); alert("initDB"); return true; } } catch(e) { // Error handling code goes here. if (e == INVALID_STATE_ERR) { // Version number mismatch. alert("Invalid database version."); return false; } else { alert("Unknown error "+e+"."); return false; } return true; } } // db error handler - prevents the rest of the transaction going ahead on failure function errorHandler(transaction, error) { alert("errorHandler"); // returns true to rollback the transaction return true; } // null db data handler function nullDataHandler(transaction, results) { } // create tables for the database function createTables(mydb) { try { mydb.transaction( function(tx) { tx.executeSql('CREATE TABLE celebs(id INTEGER NOT NULL PRIMARY KEY, name TEXT NOT NULL DEFAULT "");', [], nullDataHandler(tx,results), errorHandler(tx,error)); tx.executeSql('insert into celebs (id,name) VALUES (1,"Kylie Minogue");', [], nullDataHandler(tx,results), errorHandler(tx,error)); tx.executeSql('insert into celebs (id,name) VALUES (2,"Keira Knightley");', [], nullDataHandler(tx,results), errorHandler(tx,error)); }); alert("createTables"); return true; } catch(e) { alert(e.message); return false; } } // load the currently selected icons function loadCelebs() { try { mydb.transaction( function(tx) { tx.executeSql('SELECT * FROM celebs ORDER BY name',[], celebsDataHandler(tx,results), errorHandler(tx,error)); }); } catch(e) { alert(e.message); } } // callback function to retrieve the data from the prefs table function celebsDataHandler(transaction, results) { alert("here also?"); // Handle the results var html = "<ul>"; for (var i=0; i<results.rows.length; i++) { var row = results.rows.item(i); html += "<li>"+row['name']+"</li>\n"; } html +="</ul>"; alert(html); } </script> A: You need to return the newly created mydb instance that is created within the initDB() function and then use the returned instance. If you are reassigning a new value to a parameter that is passed into a function (which is what you are doing), it needs to be returned or the changes will be lost. Note that if you are passing in an object to the function (which you are not doing), you can modify properties of that object and those changes will be persisted outside the scope of that function. function initDB(mydb) { mydb.initialized = true; } mydb.initialized = false; initDB(mydb); // mydb.initialized => true vs... function initDB(mydb) { mydb = new DB(); // new reference mydb.initialized = true; } mydb.initialized = false; initDB(mydb); // mydb.initialized => false Of course, you are also passing in a primitive boolean value, not an object. Primitives are passed by value so you must return the newly created mydb. UPDATE You are also using your passed-in transaction handlers wrong. Look at the phone gap wiki again to see how they are assigning the function references to variables and passing those references into the transaction methods. As it is now, you are calling the functions instead of passing them. So, instead of this (what you are doing now): function errorHandler(tx, error) { alert("error"); return true; } function nullDataHandler(tx, results) { } tx.executeSql('insert into celebs (id,name) VALUES (1,"Kylie Minogue");', [], nullDataHandler(tx, results), errorHandler(tx, error)); do this: var errorHandler = function (tx, error) { alert("error"); return true; } var nullDataHandler = function(tx, results) { } tx.executeSql('insert into celebs (id,name) VALUES (1,"Kylie Minogue");', [], nullDataHandler, errorHandler); I hope this clears it up. Also, remember, if this answered your question, upvote it and mark it as the answer for a reference to future visitors.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549190", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Asynctask and onclicklistener android 2.3.3 versus 3.2 On my nexus One (android 2.3.3) the following program behaves differently from my xoom (android 3.2): public class TestOnclickWithAsyncTask extends Activity { private int mClicked = 0; private final static String TAG = "TestOnclickWithAsyncTask"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); RelativeLayout relativeLayout= (RelativeLayout) findViewById(R.id.img_control_panel); final Button button = new Button(this); button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { mClicked++; Log.i (TAG, "Clicked "+ mClicked + " times"); } }); relativeLayout.addView(button); new LongTask().execute(); } private class LongTask extends AsyncTask<Void , Void, Void> { private ProgressDialog dialog; protected void onPreExecute() { dialog = new ProgressDialog(TestOnclickWithAsyncTask.this); dialog.setMessage("Waiting "); dialog.setIndeterminate(true); dialog.setCancelable(true); try { dialog.show(); } catch (Exception e){} } protected Void doInBackground(Void... notused) { try { Thread.sleep (30000); } catch (InterruptedException e) { e.printStackTrace(); }//do long task return null; } protected void onPostExecute(Void unusedg) { dialog.dismiss(); Log.i (TAG,"Long task finished"); } } } On my Nexus I can't press the button while the asynctask is running (desired behavior): 09-26 00:45:34.361: INFO/TestOnclickWithAsyncTask(3803): Long task finished 09-26 00:45:36.463: INFO/TestOnclickWithAsyncTask(3803): Clicked 1 times 09-26 00:45:36.814: INFO/TestOnclickWithAsyncTask(3803): Clicked 2 times 09-26 00:45:37.975: INFO/TestOnclickWithAsyncTask(3803): Clicked 3 times 09-26 00:45:38.435: INFO/TestOnclickWithAsyncTask(3803): Clicked 4 times On my xoom I can just press the button and the progress indicator disappears. 09-26 00:49:05.440: INFO/TestOnclickWithAsyncTask(5887): Clicked 1 times 09-26 00:49:06.230: INFO/TestOnclickWithAsyncTask(5887): Clicked 2 times 09-26 00:49:06.580: INFO/TestOnclickWithAsyncTask(5887): Clicked 3 times 09-26 00:49:06.840: INFO/TestOnclickWithAsyncTask(5887): Clicked 4 times 09-26 00:49:08.170: INFO/TestOnclickWithAsyncTask(5887): Clicked 5 times 09-26 00:49:08.560: INFO/TestOnclickWithAsyncTask(5887): Clicked 6 times 09-26 00:49:30.960: INFO/TestOnclickWithAsyncTask(5887): Long task finished 09-26 00:49:32.800: INFO/TestOnclickWithAsyncTask(5887): Clicked 7 times 09-26 00:49:33.810: INFO/TestOnclickWithAsyncTask(5887): Clicked 8 times Why does this differ? And more importantly how can I prevent the xoom from canceling the progress dialog? A: Why do you call setCancelable(true) when you don't want it to be that way? Maybe this will solve your issue... Just a hint: try { dialog.show(); } catch (Exception e) { } * *Why are you doing that? *Enclosing code in try ... catch with a general exception catch without a reaction is a really bad habit. When you do that you should always leave a comment with a good reason for that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549192", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: boost single thread libraries in cygwin I just built and installed boost_1_47_0 using the following on cygwin ./bootstrap.sh --with-libraries=chrono,date_time,exception,filesystem,graph,graph_parallel,iostreams,math,program_options,random,serialization,signals,system,test,thread,wave link=static link=shared threading=single threading=multi then I ran the below, ./b2 --layout=tagged and the message indicated that it: failed updating 2 targets and skipped 7 targets.... but I continued and ran ./b2 --layout=tagged install however, I look in /usr/local/lib and I only have those libraries with suffix -mt My programs are looking for the libraries without the -mt suffix. but since it didn't work, I ran in sequence: bjam --clean debug release ./bootstrap.sh --with-libraries=all ./b2 ./b2 --layout=tagged ./b2 --layout=tagged install but I still see only the -mt libraries in /usr/local/lib can anyone please suggest how this can be fixed (my programs look for libboost_date_time and not libboost_date_time-mt)...thx! A: You need to use "--layout=system"
{ "language": "en", "url": "https://stackoverflow.com/questions/7549195", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Compilation Error Error: Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately. Compiler Error Message: CS0103: The name 'movies' does not exist in the current context Source Error: Line 12: } Line 13: <h1>Movies</h1> Line 14: <p>There Are @movies.Count Movies.</p> Line 15: <ul class="thumbnails gallery"> Line 16: @foreach (var movie in movies) { Source File: c:\Users\Oval Office\Documents\My Web Sites\mynewdb\Movies\Browse.cshtml Line: 14 Code: @{ var v1 = UrlData[0]; Page.Title = "Movies"; var db = Database.Open("mysql"); if (v1 == "" || v1 == null) { var movies = db.Query(@"SELECT * FROM movies ORDER BY title ASC").ToList(); }else{ var movies = db.Query(@"SELECT * FROM movies WHERE title LIKE '@0%' ORDER BY title ASC", v1).ToList(); } } <h1>Movies</h1> <p>There Are @movies.Count Movies.</p> <ul class="thumbnails gallery"> @foreach (var movie in movies) { <li class="gallery"> <a href="@Href("~/Movies/View", movie.id)"> <img alt="@movie.title (@movie.year)" title="@movie.title (@movie.year)" src="@Href("~/Photo/Thumbnail", movie.img)" class="thumbnail-no-border" /> <span class="below-image">@movie.title</span> <span class="image-overlay"><strong>@movie.year</strong></span> </a> </li> } </ul> And v1 will represent either a number or a letter to sort the listings by. But i keep getting this error. What is written wrong? Maybe a fresh pair of eyes will help :D As you see in my code example above the variable Movies is based on an if/else statement. But if/else doesn't seem to like pushing out variables, or maybe i'm just writing it wrong... A: the answer is simple, it didn't need to be wrapped in an if/else statement as the statement works both ways with this query type: var v1 = Request["sort"]; var movies = db.Query(@"SELECT * FROM movies WHERE title LIKE '" + v1 + "%' ORDER BY title ASC").ToList();
{ "language": "en", "url": "https://stackoverflow.com/questions/7549197", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Dynamic HTML Form Generation via GUI I'm looking to create a system where users can create a survey. Pretty much I'm trying to make a form that makes forms. It needs to be fairly extensive and cover inputs, selects, textareas, and other form elements. Right now, I'm using a templating engine with jQuery, but it's getting really messy and I feel that there's a better way to accomplish this. The user needs to be able to add, edit, and remove questions & their options (answers). They also need to be able to specify question type (multiple choice, range slider, short answer, etc) and it needs to support image upload. I've scoured Google but haven't found what I'm looking for. Is there an existing js library or framework I could use to easily add & remove elements in DOM while keeping track of element type and hierarchy? Or perhaps an API I could use? I don't feel like reinventing the wheel on this one. A: How about https://github.com/powmedia/backbone-forms ? A: Last time I needed this, i used the jQuery Form Builder plugin. It even comes with its own DB stuff for storing the forms and its own HTML renderer for output. Yummy! A: I think you may end up inventing your own solution, but it may not be re-inventing. I think the best solution would be for you to make a DSL (Domain Specific Language), and in Javascript you can see some slides on this at: http://ajaxian.com/archives/metaprogramming-dsl-javascript-presentation. Another nice blog on this is: http://www.mailsend-online.com/blog/a-dsl-in-javascript.html By doing this route it should simplify your design, while making it as flexible as you desire.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549198", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Make a unique object JavaScript I am trying to create a program which saves info about an element into a new JavaScript Object, or really into any sort of object from any language. Here's an example. Somebody clicks a create button and It prompts them to name a CSS Class. After that, they are asked to fill out a form with a list of properties. How ever, the properties need to be saved to Local place because it is meant to be a static page they will be working on, without an account. Basically, this is what I am asking. Is there a way to create a 'static' object in JavaScript, that will be only created once the form is filled out and has a unique name. There will need to be multiple made most likely. Here's the format I was thinking document.formname.blah.value = { type=document.formname.id.value; border='1px solid #000' } I know I am little hard to understand I am sorry. But does anybody know a way for me to do this?? A: I'm not quite sure whether I get it right, but how about an basic javascript object stored in a global variable? window.blah = { type: document.formname.id.value, border: '1px solid #000' }; If you want to assign that object to a dom node, you can use jquery's data() method: var blah = { ...(see above).. }; $(document.formname.blah).data('whateverThisIs', blah); A: I actually found a way! It was pretty simple actually. It is when a new element is created, a new object is created called element, and from there that element is pushed into an array. So what happens is you end up with an array with Objects in it that can be accessed using a simple for loop or a dom This function. Thanks though!
{ "language": "en", "url": "https://stackoverflow.com/questions/7549201", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to disable animation for code nested in a UIView animation block? There's a method which is called inside an animation block by a third party API. In that method I'm supposed to build some subviews. But in this case I don't want animation to happen when constructing the subviews. Is there a way of saying "[UIView dontAnimateFromHere] ... [UIView nowYouMayAnimateAgain]"? A: For iOS 7 and later, there is this UIView's +performWithoutAnimation:. Note that performWithoutAnimation is useful for immediately executing a change while you are within an animation block, but it will not disable animation calls made within the nested block, so use it for convenience, but it is not as robust as setAnimationsEnabled of the original answer. A: Yes indeed, there is such a way. It's like this: [UIView setAnimationsEnabled:NO]; // Animations happen here [UIView setAnimationsEnabled:YES]; ...this will disable both UIView animations triggered via blocks and animations triggered using the old begin/end methods. That said, I'm assuming your third party library is pre-compiled otherwise you could modify the source directly: it is of course possible it's doing something weird and animating in another way, so your mileage may vary with this solution. This won't disable the changes being made in the animation blocks: they'll simple happen immediately. Otherwise you'd risk bad things happening since your third party API would be making assumptions about where views might be that weren't true.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549207", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Type conversion of &self causes compiler error In an ARC environment, I have the following code: NSInvocation* invocation = [NSInvocation invocationWithMethodSignature:signature]; [invocation setTarget:delegate]; [invocation setSelector:@selector(restClient:loadedFile:contentType:eTag:)]; // Error Here! [invocation setArgument:&self atIndex:2]; [invocation setArgument:&filename atIndex:3]; [invocation setArgument:&contentType atIndex:4]; [invocation setArgument:&eTag atIndex:5]; Setting the argument to index 2 (&self) causes the following compiler error: Sending *const __strong * to parameter of type void * changes retain/release properties I have no idea how to fix this while keeping valid code. At the moment I'm just sticking in NULL and wrapping the invoke statement in a try/catch block, but that's a less-than-ideal solution. A similar issue, if anyone would be kind enough to address it as well: With this line of code (from the MPOAuth library) status = SecItemCopyMatching((__bridge CFDictionaryRef)searchDictionary, (CFTypeRef *)&attributesDictionary); I get the following error Cast of an indirect pointer to an Objective-C pointer to 'CFTypeRef ' (aka 'const void *') is disallowed with ARC A: this line: status = SecItemCopyMatching((__bridge CFDictionaryRef)searchDictionary, (CFTypeRef *)&attributesDictionary); can be resolved as following: CFTypeRef outDictionaryRef; status = SecItemCopyMatching((__bridge CFDictionaryRef)searchDictionary, &outDictionaryRef; attributesDictionary = (__bridge_transfer NSDictionary *) outDictionaryRef; So in essence just give the reference type it expects as the out param. And when the out param is filled out, transfer the ownership to your cocoa type. A: You should be able to cast it to get an appropriate pointer type: NSInvocation* invocation = [NSInvocation invocationWithMethodSignature:signature]; [invocation setTarget:delegate]; [invocation setSelector:@selector(restClient:loadedFile:contentType:eTag:)]; Foo *foo = self; [invocation setArgument:&foo atIndex:2]; [invocation setArgument:&filename atIndex:3]; [invocation setArgument:&contentType atIndex:4]; [invocation setArgument:&eTag atIndex:5]; A: Rather than changing the SDK (Dropbox has said that they'll be posting an ARC-compatible version soon), I found out that I can use ARC selectively for a file. So I did that. And then I upgraded to the 1.0b2, which is packaged as a library and so the issue is solved.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549209", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Sorted linked list and the addSorted function problem. So I've been working on this for awhile and I can't seem to figure out what's wrong. This addSorted function adds in all the correct values in their respectable places of the sorted array but when it goes into add a 0 to the front of the list, the program will not terminate and there is no result displayed. Anyone have any clue of why this may be? void addSorted(Data * newData){ if(head == NULL) { head = new LinkNode(newData); return; } LinkNode * current = head; LinkNode * previous = NULL; while(current != NULL) { if(newData->compareTo(current->data) == -1) { LinkNode * newNode = new LinkNode(newData); newNode->next = current; if(previous == NULL) { current->next = newNode; } else { newNode->next = previous->next; previous->next = newNode; } return; } previous = current; current = current->next; } previous->next = new LinkNode(newData); } A: Is the result of compareTo being -1 mean that it is less than the current node? And if previous==NULL you set current->next to point to the newNode, which means they are pointing to each other, as newNode->next is also pointing to the current node. I think the root of your problem may be this, actually. newNode->next = current; current->next = newNode; Hopefully by putting it this way you can see what I am talking about.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549211", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Rails 3.1 and Asset Pipeline: Trouble on deploying with Capistrano I just switched from Ruby on Rails 3.0.10 to 3.1.0 and I would like to deploy my asset files by using the Capistrano gem (my local machine is a MacOs running Snow Leopard, my remote machine is running Ubuntu 10.04 Lucid). So, as wrote in the Official Guide, I uncomment the load 'deploy/assets' in my Capfile like this: # Uncomment if you are using Rails' asset pipeline load 'deploy/assets' Now, when I run the cap deploy command I get the following error (the error is explained at the bottom): ... * executing "cd /<application_absolute_path>/releases/20110925223032 && rake RAILS_ENV=production RAILS_GROUPS=assets assets:precompile" servers: ["<my_web_site_ip>"] [<my_web_site_ip>] executing command ** [out :: <my_web_site_ip>] (in /<application_absolute_path>/releases/20110925223032) *** [err :: <my_web_site_ip>] rake aborted! *** [err :: <my_web_site_ip>] uninitialized constant Rake::DSL *** [err :: <my_web_site_ip>] /usr/local/lib/ruby/1.9.1/rake.rb:2482:in `const_missing' *** [err :: <my_web_site_ip>] /usr/local/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/tasklib.rb:8:in `<class:TaskLib>' *** [err :: <my_web_site_ip>] /usr/local/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/tasklib.rb:6:in `<module:Rake>' *** [err :: <my_web_site_ip>] /usr/local/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/tasklib.rb:3:in `<top (required)>' *** [err :: <my_web_site_ip>] /usr/local/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/testtask.rb:4:in `require' *** [err :: <my_web_site_ip>] /usr/local/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/testtask.rb:4:in `<top (required)>' *** [err :: <my_web_site_ip>] /usr/local/lib/ruby/gems/1.9.1/gems/railties-3.1.0/lib/rails/test_unit/testing.rake:2:in `require' *** [err :: <my_web_site_ip>] /usr/local/lib/ruby/gems/1.9.1/gems/railties-3.1.0/lib/rails/test_unit/testing.rake:2:in `<top (required)>' *** [err :: <my_web_site_ip>] /usr/local/lib/ruby/gems/1.9.1/gems/railties-3.1.0/lib/rails/test_unit/railtie.rb:12:in `load' *** [err :: <my_web_site_ip>] /usr/local/lib/ruby/gems/1.9.1/gems/railties-3.1.0/lib/rails/test_unit/railtie.rb:12:in `block in <class:TestUnitRailtie>' *** [err :: <my_web_site_ip>] /usr/local/lib/ruby/gems/1.9.1/gems/railties-3.1.0/lib/rails/railtie.rb:183:in `call' *** [err :: <my_web_site_ip>] /usr/local/lib/ruby/gems/1.9.1/gems/railties-3.1.0/lib/rails/railtie.rb:183:in `block in load_tasks' *** [err :: <my_web_site_ip>] /usr/local/lib/ruby/gems/1.9.1/gems/railties-3.1.0/lib/rails/railtie.rb:183:in `each' *** [err :: <my_web_site_ip>] /usr/local/lib/ruby/gems/1.9.1/gems/railties-3.1.0/lib/rails/railtie.rb:183:in `load_tasks' *** [err :: <my_web_site_ip>] /usr/local/lib/ruby/gems/1.9.1/gems/railties-3.1.0/lib/rails/engine.rb:395:in `block in load_tasks' *** [err :: <my_web_site_ip>] /usr/local/lib/ruby/gems/1.9.1/gems/railties-3.1.0/lib/rails/application/railties.rb:8:in `each' *** [err :: <my_web_site_ip>] /usr/local/lib/ruby/gems/1.9.1/gems/railties-3.1.0/lib/rails/application/railties.rb:8:in `all' *** [err :: <my_web_site_ip>] /usr/local/lib/ruby/gems/1.9.1/gems/railties-3.1.0/lib/rails/engine.rb:395:in `load_tasks' *** [err :: <my_web_site_ip>] /usr/local/lib/ruby/gems/1.9.1/gems/railties-3.1.0/lib/rails/application.rb:99:in `load_tasks' *** [err :: <my_web_site_ip>] /usr/local/lib/ruby/gems/1.9.1/gems/railties-3.1.0/lib/rails/railtie/configurable.rb:30:in `method_missing' *** [err :: <my_web_site_ip>] /<application_absolute_path>/releases/20110925223032/Rakefile:7:in `<top (required)>' *** [err :: <my_web_site_ip>] /usr/local/lib/ruby/1.9.1/rake.rb:2373:in `load' *** [err :: <my_web_site_ip>] /usr/local/lib/ruby/1.9.1/rake.rb:2373:in `raw_load_rakefile' *** [err :: <my_web_site_ip>] /usr/local/lib/ruby/1.9.1/rake.rb:2007:in `block in load_rakefile' *** [err :: ] /usr/local/lib/ruby/1.9.1/rake.rb:2058:in `standard_exception_handling' *** [err :: <my_web_site_ip>] /usr/local/lib/ruby/1.9.1/rake.rb:2006:in `load_rakefile' *** [err :: <my_web_site_ip>] /usr/local/lib/ruby/1.9.1/rake.rb:1991:in `run' *** [err :: <my_web_site_ip>] /usr/local/bin/rake:31:in `<main>' command finished in 4301ms *** [deploy:update_code] rolling back * executing "rm -rf /<application_absolute_path>/releases/20110925223032; true" servers: ["<my_web_site_ip>"] [<my_web_site_ip>] executing command command finished in 377ms failed: "sh -c 'cd /<application_absolute_path>/releases/20110925223032 && rake RAILS_ENV=production RAILS_GROUPS=assets assets:precompile'" on <my_web_site_ip> So, I tried to solve the problem following the answer to this question: # Rakefile require 'rake/dsl_definition' require File.expand_path('../config/application', __FILE__) <MyApplicationName>::Application.load_tasks After I run again the cap deploy command I get the following error: ... * executing "cd /<application_absolute_path>/releases/20110925160036 && rake RAILS_ENV=production RAILS_GROUPS=assets assets:precompile" servers: ["<my_web_site_ip>"] [<my_web_site_ip>] executing command *** [err :: <my_web_site_ip>] /usr/local/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/file_utils.rb:10: warning: already initialized constant RUBY *** [err :: <my_web_site_ip>] /usr/local/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/file_utils.rb:84: warning: already initialized constant LN_SUPPORTED ** [out :: <my_web_site_ip>] (in /<application_absolute_path>/releases/20110925160036) *** [err :: <my_web_site_ip>] WARNING: Global access to Rake DSL methods is deprecated. Please include *** [err :: <my_web_site_ip>] ... Rake::DSL into classes and modules which use the Rake DSL methods. *** [err :: <my_web_site_ip>] WARNING: DSL method Object#mkdir_p called at /usr/local/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/file_utils_ext.rb:36:in `mkdir_p' *** [err :: <my_web_site_ip>] WARNING: Global access to Rake DSL methods is deprecated. Please include *** [err :: <my_web_site_ip>] ... Rake::DSL into classes and modules which use the Rake DSL methods. *** [err :: <my_web_site_ip>] WARNING: DSL method Object#mkdir_p called at /usr/local/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/file_utils_ext.rb:36:in `mkdir_p' *** [err :: <my_web_site_ip>] WARNING: DSL method Object#mkdir_p called at /usr/local/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/file_utils_ext.rb:36:in `mkdir_p' *** [err :: <my_web_site_ip>] WARNING: DSL method Object#mkdir_p called at /usr/local/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/file_utils_ext.rb:36:in `mkdir_p' ... *** [err :: <my_web_site_ip>] WARNING: DSL method Object#mkdir_p called at /usr/local/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/file_utils_ext.rb:36:in `mkdir_p' ... *** [err :: <my_web_site_ip>] WARNING: DSL method Object#mkdir_p called at /usr/local/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/file_utils_ext.rb:36:in `mkdir_p' ... *** [err :: <my_web_site_ip>] rake aborted! *** [err :: <my_web_site_ip>] stack level too deep *** [err :: <my_web_site_ip>] /usr/local/lib/ruby/1.9.1/ostruct.rb:92 command finished in 48421ms Where the code related to Capistrano is wrong? How to use correctly the load 'deploy/assets' statement in order to make the deployment process to work? A: Have you tried simply defining your own task? That's what I did when I ran into this issue: task :precompile, :role => :app do run "cd #{release_path}/ && rake assets:precompile" end after "deploy:finalize_update", "deploy:precompile" You do need RVM initialization for this if you use RVM
{ "language": "en", "url": "https://stackoverflow.com/questions/7549214", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Zend_Db_Table: Delete multiple entries I wanted to delete some db entries and each of them has a unique ID. My current code looks so, taken from here: Zend Framework: How to delete a table row where multiple things are true? $where = array(); foreach ($IDs as $ID) { $where[] = $this->getAdapter()->quoteInto('id = ?', $ID); } $this->delete($where); This is called inside the model class extends by Zend_Db_Table_Abstract. The query looks now like that: DELETE FROM `shouts` WHERE (id = '10') AND (id = '9') AND (id = '8') That doesn't work of course because of the AND's, this have to be OR's to work correctly, but how could I get this work so? A: Try this: $where = $this->getAdapter()->quoteInto('id IN (?)', $IDs); $this->delete($where);
{ "language": "en", "url": "https://stackoverflow.com/questions/7549217", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Iterating over a JavaScript object to bind keys Considering the following code: controls = { 'w': 'up', 's': 'down', 'a': 'left', 'd': 'right' }; keysPressed = []; for (control in controls) { direction = controls[control]; $(document).bind('keydown', control, function() { keysPressed.push(direction); }); } Only the right direction gets bound, and it is bound to all four keys. This is obviously not intended, but what am I missing about JavaScript that prevents all the properties from being bound appropriately? EDIT: For clarification, I'm using jQuery.hotkeys to handle key names. And this is a snippet; you can assume all variables have been declared. Also, code is in a safety function wrapper. SOLUTION: I solved it with this modification: controls = { 'w': 'up', 's': 'down', 'a': 'left', 'd': 'right' }; keysPressed = []; addToKeyPressArray = function(value) { return function() { keysPressed.push(value); }; }; removeFromKeyPressArray = function(value) { return function() { keysPressed = keysPressed.filter(value); }; }; for (control in controls) { direction = controls[control]; $(document).bind('keydown', control, addToKeyPressArray(direction)); $(document).bind('keyup', control, removeFromKeyPressArray(direction)); } That's an odd JavaScript quirk. A: Seems to me like it's probably the basic "closure in for loop" issue that many people trip up on with JS. An explanation and solution is easy to find via google, here's one for example: http://www.mennovanslooten.nl/blog/post/62 A: This is how I would do it: $( document ).keypress( function ( e ) { var char = String.fromCharCode( e.keyCode ); if ( controls[ char ] ) { keysPressed.push( controls[ char ] ); } }); A: You didn't declare the direction variable (using var), so it will be in global scope. This means the for-loop will run and then direction will be set to right. All keys are bound, but all call keysPressed.push(direction); // and that is: keysPressed.push("right"); Also I recommend to read Jani's post (and the related article) as you could have walked into that issue as well.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549218", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: reed solomon library I'm about writing a qr code generator , should I write reed solomon error correction methods by myself or is there any free library in PHP or Python to do that ? thank you A: Yes.. There is an QR code library in PHP. Check the link below: http://phpqrcode.sourceforge.net/ A: Here's a Python and Google Chart solution. A: This came up high on google, so why not point you to this one: https://github.com/dineshrabara/barcode OR http://framework.zend.com/manual/1.12/en/zend.barcode.creation.html A: I created a Python package galois that extends NumPy arrays over Galois fields. The Galois field arithmetic is written in Python but JIT compiled with Numba. So the arithmetic is as fast, or nearly as fast, as native NumPy. Included in the library are Reed-Solomon codes.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549222", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Facebook Open Graph OG: Meta Tags - Works only sometimes? I have a like button on my site, i have defined all the og: meta tags and its works for most of most pages, but doesnt for 2 other pages. Its using a template so its exactly the same code, how can it work for some but not all pages? For the pages it doesnt work, it doesnt pick up the title, image, link or description, basically any of the meta tags information. Working like button.... http://www.imoffonholiday.com/holiday.php?id=des_home&destination=faliraki Not working Like button http://www.imoffonholiday.com/holiday.php?id=des_home&destination=ayianapa Any ideas? A: One usual problem is caching. If you were testing and at some point had the wrong data in the metatags facebook will cache that info. One simple wat to test if it is a caching issue is to add a random param at the end of the URL. so www.yourpage.com/index.php?cacheBust=1 A: Running the Facebook Debugger often clears those kind of things up. It appears to refresh the FB cache when you do.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549223", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java program will not output to file This is a very basic program for Uni which writes user data to a file. I have followed the instructions clearly yet it does not seem to output the data to a file. All it does is create an empty file. I'm using Ubuntu, if this makes a difference. import java.util.Scanner; import java.io.*; /** This program writes data to a file. */ public class FileWriteDemo { public static void main(String[] args) throws IOException { String fileName; // File name String friendName; // Friend's name int numFriends; // Number of friends // Create a Scanner object for keyboard input Scanner keyboard = new Scanner(System.in); // Get the number of friends System.out.print("How many friends do you have? "); numFriends = keyboard.nextInt(); // Consume the remaining new line character keyboard.nextLine(); // Get the file name System.out.print("Enter the filename: "); fileName = keyboard.nextLine(); // Open the file PrintWriter outputFile = new PrintWriter(fileName); // Get data and write it to a file. for (int i = 1; i <= numFriends; i++) { // Get the name of a friend System.out.print("Enter the name of friends " + "number " + i + ": "); friendName = keyboard.nextLine(); } // Close the file outputFile.close(); System.out.println("Data written to the file."); } } A: You are creating a PrintWriter instance but nothing is being written to it. Perhaps you meant to include outputFile.println(friendName) inside the for-loop? A: Try for (int i = 1; i <= numFriends; i++) { // Get the name of a friend System.out.print("Enter the name of friends " + "number " + i + ": "); friendName = keyboard.nextLine(); outputFile.println(friendName); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7549224", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: mysql database logic My question is more of trying to understand what and how I can get something done. Here's the thing: I got a job to build this application for a school to manage student bio data, work-out and handle student information and basic finance management. Based on requirements I got from meets with my client, I have an ERD of a proposed MySQL Database with 23 different tables. The one part I would like to understand quickly is displaying data based on school terms. There are 3 terms in a year, each with its own summaries at the end of each term. At the end of 3 terms, a year has gone by and a student is promoted or demoted. So my question is, how can I render my data to show 3 different terms and also to create a new year working out how to either promote a student or make the student repeat the class its in? A: 23 different tables? I'd like to see that model. I don't think you should have one table per term. You'll have to keep adding tables every term, every year. Sounds like a transcript table should have term and year columns that are incremented or decremented as a student progresses through. It should also have a foreign key relationship with its student: it's a 1:1 between a student and their transcript. I would have a separate transcript table because I'd prefer keeping it separate from basic personal information about a student. A transcript would refer to the courses taken each term, the grade received for each, and calculate overall progress. If I queried for the transcript for an individual student, I should be able to see every year, every term, every course, every grade in reverse chronological order.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549230", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Getting a profile report for images and js files I'm using mvc3, and mvc mini profile is displaying multiple popup boxes for a single page request because it is profiling for images and js files. Have you guys experienced this also? What did you do? A: You are seeing those timings cause they are going through the managed pipeline. This also happens to mean that your page is a bit slower cause you have static content that is served dynamically. See also, for details on how to disable it from being profiled: Mini MVC profiler: appears to be displaying profile times for every static resource
{ "language": "en", "url": "https://stackoverflow.com/questions/7549232", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Multiple Pushpin and UI Lag I am currently disaply over 500 pushpins on my bing map using the below code. Loading of these pushpins is causing a serious lag on the UI, so I was wondering if it is possible to load these incrementally based on the users position, but still use this code? I have seen other examples using bindings and obseravable collections, but I would like to find a solution for the below code if possible. foreach (var root in Transitresults) { var pin = new Pushpin { Location = new GeoCoordinate { Latitude = root.Lat, Longitude = root.Lon }, Background = accentBrush, Content = root.Name, Tag = root, }; BusStopLayer.AddChild(pin, pin.Location); } A: Check out this post, It's a good tutorial on only showing the pins that are actually in view: Awkward Coder: How many pins can Bing Maps handle in a WP7 app
{ "language": "en", "url": "https://stackoverflow.com/questions/7549234", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jQuery UI Tabs - ajax php I have some really standard jQuery UI tabs that work fine on my Mac in Safari, Chrome and Firefox however the content doesn't load on the iPad / iPhone and I don't understand why, here's a link: http://www.hostelcities.com/dev/tabbed_layout/jquery-ui-tabs/ajaxjqueryuitabs.php The first two tabs, Monday and Tuesday are here: http://www.hostelcities.com/dev/tabbed_layout/jquery-ui-tabs/monday.php http://www.hostelcities.com/dev/tabbed_layout/jquery-ui-tabs/tuesday.php I would appreciate some help - thanks. A: The Tab content shouldn't include any of the standard html tags such as: html, head and body.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549241", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: looping through an object passed in via JQUERY as an array and using c# webmethod to get data out all, I'm getting to my webmethod in my code behind but I'm having problems deserializing my json data. I have no good reference but here is what I"m trying to do. My the code in my webmethod is not allowing me to get the data out passed from my ajax call. thanks for any help. $("[id$=rdbSaveAjax1]").click(function () { var mappedJobRole = new Array(); $(".jobRole").each(function (index) { var jobRoleIndex = index; var jobRoleID = $(this).attr('id'); var jobRoleName = $(this).text(); // add all the roleids and rolenames to the job role array. var roleInfo = { "roleIndex": jobRoleIndex, "roleID": jobRoleID, "roleName": jobRoleName }; queryStr = { "roleInfo": roleInfo }; mappedJobRole.push(queryStr); }); $.ajax({ type: "POST", url: "Apage.aspx/Save_Mapped_Role", data: "{'savedRole': " + JSON.stringify(mappedJobRole) + "}", contentType: "application/json; charset=utf-8", dataType: "json", async: false, success: function (data) { alert("successfully posted data"); }, error: function (data) { alert("failed posted data"); } }); }); In my code behind I can't seem to get the data out. My class: public class MappedRole { public int Index { get; set; } public string RoleID { get; set; } public string RoleName { get; set; } } My webmethod: [WebMethod] public static bool Save_Mapped_Role(object savedRole) { bool success = false; JavaScriptSerializer js = new JavaScriptSerializer(); IList<MappedRole> role = new JavaScriptSerializer().Deserialize<IList<MappedRole>>savedRole); int Index = role[0].Index; string RoleID = role[0].RoleID; string RoleName = role[0].RoleName; return success; } A: This line seems to be missing an opening parenthese IList<MappedRole> role = new JavaScriptSerializer().Deserialize<IList<MappedRole>>savedRole); Should read IList<MappedRole> role = new JavaScriptSerializer().Deserialize<IList<MappedRole>>(savedRole); Furthermore, in order to use the Deserialize method, you need to create classes based on the JSON variables you are passing. For example based on the JSON object you created, you should have the two classes below. SavedRole Class public class SavedRole { public roleInfo[] { get; set; } } roleInfo Class public class roleInfo { public int roleIndex { get; set; } public string roleID { get; set; } public string roleName { get; set; } } Now the Deserialze method will do its magic and populate the objects for you. Then you'll be able to loop through the object and do what you need with the data. [WebMethod] public static bool Save_Mapped_Role(object savedRole) { bool success = false; var serializer = new JavaScriptSerializer(); SavedRole role = serializer.Deserialize<SavedRole>(savedRole); //Loop through the data like so int roleIndex = 0; string roleID = null; string roleName = null; foreach (var item in role.roleInfo) { roleIndex = item.roleIndex; roleID = item.roleID; roleName = item.roleName; //Do more logic with captured data } return success; } Hope that helps A: this post explain how you can convert a JSON to C#: Parse JSON in C# If you don't want to use that, you need to do some changes in your project: First, to get the your RoleInfo, you need to transform it in a Dictionary like: (((object[])savedRole)[0] as Dictionary<string, object>)["roleInfo"] After that, you can manipule your object to create your List: var list = ((object[])savedRole); IList<MappedRole> role = new List<MappedRole>(); foreach (var item in list) { var dic = ((item as Dictionary<string, object>)["roleInfo"] as Dictionary<string, object>); MappedRole map = new MappedRole() { roleIndex = Convert.ToInt32(dic["roleIndex"]), roleID = dic["roleID"].ToString(), roleName = dic["roleName"].ToString() }; role.Add(map); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7549244", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Activity wont start with "startActivity();" Here's my code for DroidArmoryActivity package com.maxgenero.droidarmory; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; public class DroidArmoryActivity extends Activity implements View.OnClickListener { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } @Override public void onClick(View v) { // TODO Auto-generated method stub switch(v.getId()) { case R.id.ibM4A1: Intent intentM4A1 = new Intent("com.maxgenero.droidarmory.M4A1GUN"); startActivity(intentM4A1); break; } } } It's not starting the java file (Activity) at all, no errors. Btw, the case is looking for an imageButton. Here's my Manifest, at least the part you need: <activity android:name=".M4a1" android:label="@string/app_name" android:screenOrientation="landscape"> <intent-filter> <action android:name="com.maxgenero.droidarmory.M4A1" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity> And the file name for the java file is M4a1.java. If you need more info let me know, thanks. A: I dont see where you define a listener on your Button or your View that will be clicked to launch the second Activity ?? yourView.setOnClickListener(this); the second thing is that you should add declare your activity on your manifest file on the tag like this : <activity android:name="your.package.name.NameOfYourAcitivity" /> the last thing is : try to instantiate the intent like this : this.startActivity(new Intent(this, SecondActivity.class)); Regards, A: Instead of... case R.id.ibM4A1: Intent intentM4A1 = new Intent("com.maxgenero.droidarmory.M4A1GUN"); startActivity(intentM4A1); Try Intent intentM4A1 = new Intent(this, ACTIVITY_NAME.class); startActivity(intentM4A1); Also dont forget to call your setOnclickListener().
{ "language": "en", "url": "https://stackoverflow.com/questions/7549252", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: C++ program to calculate greatest common divisor I have started this program to calculate the greatest common divisor. This is what I have so far: #include <iostream> #include <math.h> using namespace std; int getGCD(int a, int b) { a = a % b; if (a == 0) { return b; b = b % a; } if (b == 0) { return a; } } int main() { int x, y; cout << "Please enter two integers x and y, for GCD calculation" << endl; cin >> x >> y; cout << "The GCD of " << x << "and " << y << " is" << getGCD(x, y) << endl; return 0; } I always get a 0 for the GCD. What am I doing wrong? A: You should be looping through to find this, and it may help if you put, with some equations, your algorithm for how this should work. But you have two problems I see, unless you are calling this inside of another loop. You are returning in both cases, either the if or else, so you only go through here once. Also, this part makes no sense, why modify the b value after doing a return? return b; b = b%a; You should be using recursion for this, btw. http://rosettacode.org/wiki/Greatest_common_divisor#Recursive_Euclid_algorithm A: int getGCD(int a, int b) { //here we need to check if b == 0 return a if (b == 0) { return a; } return gcd(b, a % b); } Euclid's Algorithm Implementation
{ "language": "en", "url": "https://stackoverflow.com/questions/7549255", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: NSManagedObject Faulted I have an NSManagedObject that has some of its properties initialized at the start of the program. When I refer to this object later, it appears to be faulted, and the properties are not accessible. I'm not sure what I need to do. This is related to a new feature added to a program that has been operating smoothly with core-data in all other ways. Here is a code snippet where it is initialized as a property value of a singleton. (That singleton is accessible by many parts of my code): favoritesCollection = [[SearchTerms alloc] initWithEntity:[NSEntityDescription entityForName:@"SearchTerms" inManagedObjectContext:moc] insertIntoManagedObjectContext:moc]; favoritesCollection.keywords = @"Favorites List"; favoritesCollection.isFavoritesCollection = [NSNumber numberWithBool:YES]; favoritesCollection.dateOfSearch = [NSDate NSCExtendedDateWithNaturalLanguageString:@"4000"]; favoritesCollection.pinColorIndex = 0; [moc save:&error]; NSLog(@"(favoritesCollection) = %@", favoritesCollection); } return favoritesCollection; When I look at favoritesCollection with the NSLog, I see this (I added some newlines to make it easier to read): (favoritesCollection) = <SearchTerms: 0x5c28820> (entity: SearchTerms; id: 0x5a6df90 <x-coredata://3936E19F-C0D0-4587-95B6-AA420F75BF78/SearchTerms/p33> ; data: { dateOfSearch = "4000-09-25 12:00:00 -0800";...*more things after this* After the return, another NSLog shows that contents are intact. When I refer to this instance later, I can see this in the debugger: <SearchTerms: 0x5c28820> (entity: SearchTerms; id: 0x5a6df90 <x-coredata://3936E19F-C0D0-4587-95B6-AA420F75BF78/SearchTerms/p33> ; data: <fault>) and that's all. So I believe that the object is retained (I explicitly retain it where it is returned). I have zombies on and it doesn't look like a zombie. I have only one managedObjectContext in the program, maintained in the singleton. So what is happening, and how do I get to the properties that were saved? A: There is nothing wrong with your object and I think you might be misinterpreting the meaning of "fault" here. From Apple's documentation: "Faulting is a mechanism Core Data employs to reduce your application’s memory usage..." Once you try and access any of the object's properties it will hit the database for all of the object's properties. More details here http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CoreData/Articles/cdFaultingUniquing.html A: Faults are CoreData's way of having loose links to other entities. Just access the values via properties or valueGorKey and you will see them populated just in time. A: I'm a little late getting back to this, but I found out that some steps in my program were out of order. Instead of deleting the database contents (something I do at startup every time, for now) and then creating and adding this entity, I had created and added the entity and then deleted the database contents. The pointer to the favoritesCollection entity is held for the lifetime of the program, so I would have expected it be able to see its contents any time after it was created. From the Core Data Programming Guide Fault handling is transparent—you do not have to execute a fetch to realize a fault. If at some stage a persistent property of a fault object is accessed, then Core Data automatically retrieves the data for the object and initializes the object (see NSManagedObject Class Reference for a list of methods that do not cause faults to fire). This process is commonly referred to as firing the fault. Core Data automatically fires faults when necessary (when a persistent property of a fault is accessed). From what I can tell by reading the programming guide, seeing faults on relationships (links to other entities) is normal when looking at any particular entity. But seeing faults on the persistent property values is not mentioned. I believe that, in general, if the object is in memory, then its properties should not be faulted, but its relationships may be faulted. The fact that the favoritesCollection entity was fully faulted (properties and relationships) and the fault did not get resolved revealed a problem. In this case it is consistent with the entity no longer existing in the database.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549257", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Regular expressions - remove all non-alpha-numeric characters CRLF problem First off, if it's not clear from the tag, I'm doing this in PHP - but that probably doesn't matter much. I have this code: $inputStr = strip_tags($inputStr); $inputStr = preg_replace("/[^a-zA-Z\s]/", " ", $inputStr); Which seems to remove all HTML tags and virtually all special and non-alphabetic characters perfectly. The one problem is, for some reason, it doesn't filter out carraige return/line feeds (just the combination). If I add this line: $inputStr = preg_replace("/\s+/", " ", $inputStr); at the end, however, it works great. Can someone tell me: * *Why doesn't the first preg_replace filter out the CR/LFs? *What this second preg_repalce is actually doing? I understand the first one for the most part, but hte second one is confusing me - it works but I don't know why. *Can I combine them into 1 line somehow? A: * *You told it to remove everything except letters and whitespace. Newlines are whitespace, so they don't get removed. You could use \h instead of \s to only exclude horizontal whitespace. *It simply means "replace every sequence of one or more whitespace characters (\s+) with a single space." *preg_replace("/[^A-Za-z]+/", " ", ...) might do. A: * *\s matches whitespace such as \n. *It is replacing all whitespace characters with a space. *You could make it one unreadable line, but probably not one regex. A: Your first regex is removing all characters that are not letters or whitespace. CRLFs are whitespace, so they aren't filtered out. The second one is replacing whitespace with a space character. Essentially it condenses sequences of whitespace into a single space (due to the quantifier being greedy). I suggest removing the \s from the first regex, see if that works.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549258", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is there a quick way to unbind keys in Emacs? I did a ctrl h b to view all my bindings in emacs. Now I want to unbind a lot of keys, simply because I never use those functions of Emacs and I don't want to perform them when I accidently press the bound keys! This also frees up a lot of keys for other tasks (for use with Cedet for example). So apart from global-unset-key, is there any method to remove bindings in bulk? C-a move-beginning-of-line C-b backward-char C-c mode-specific-command-prefix C-d delete-char C-e move-end-of-line C-f forward-char C-g keyboard-quit C-h help-command C-k kill-line C-l recenter-top-bottom C-n next-line C-o open-line C-p previous-line C-q quoted-insert C-t transpose-chars C-u universal-argument C-v scroll-up C-x Control-X-prefix C-z suspend-frame ESC ESC-prefix I want to remove most of these bindings which are absolutely useless for me. A: There's no built-in way to unset a lot of keys, because it's easy to do it yourself: (Edited for strict correctness:) (dolist (key '("\C-a" "\C-b" "\C-c" "\C-d" "\C-e" "\C-f" "\C-g" "\C-h" "\C-k" "\C-l" "\C-n" "\C-o" "\C-p" "\C-q" "\C-t" "\C-u" "\C-v" "\C-x" "\C-z" "\e")) (global-unset-key key)) Although I have to say that most of the commands you call "useless" I would call "essential." (Edited to add:) As for freeing up keys for other tasks, there's plenty of unused key real estate: * *Key sequences consisting of C-c followed by a letter are by convention reserved for users. *If you have an extra modifier available, like Option on the Mac or the Windows key on a PC, you can associate it with an Emacs modifier like super. I have super-b bound to browse-url-at-point, for example. *If you're not on a plain terminal, the shift key becomes available to distinguish key sequences. For example, I have shift-meta-b bound to bury-buffer. *For commands that are useful but not run often enough to warrant a dedicated key sequence, you can use defalias to provide a shorter name. In my .emacs file, I have (defalias 'ru 'rename-uniquely) and (defalias 'c 'calendar) (among many others). A: global-unset-key and local-unset-key are useful, but it's worth having an answer to this question that points out that the general way to unbind a key (for any keymap) is to define a binding of nil: (define-key KEYMAP KEY nil) If you follow the code for either of those other functions, you'll notice that this is exactly what they do.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549259", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "28" }
Q: WPF black spaces on resize When i create a band new WPF project without changing any code whatsoever does this on resize. It stays this way if i minimize or drag across monitors. Is this supposed to happen? It does this with all of my WPF applications so i set ResizeMode="CanMinimize" . Thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/7549262", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: When to use CCSpriteBatchNode? in Cocos2d I will be playing an animation. The animation has about 12 frames, and each frame is rather big. In fact, the -hd version of each frame is quite huge. Anyway, first, I created it by putting all 12 frames in a texture using Zwoptex. The texture is about 2048x2048. This is so I can animate a CCSprite in a CCSpriteBatchNode using that texture. But I seem to be getting a level 2 memory warning. Now that I think of it, I don't think CCSpriteBatchNode was supposed to be used for one sprite. I guess it was only useful if you wanted to draw lots of sprites that use the same texture. So I want to know: Should I animate the sprite frame by frame (no huge texture)? Or is it possible to use that huge texture but in a different way? A: You are right about CCSpriteBatchNode. CCSpriteBatchNode is like a batch node: if it contains children, it will draw them in 1 single OpenGL call (often known as "batch draw"), in absence of CCSpriteBatchNode (in this case) all the "batch draw" will be called as many time as number of children (sprites). A CCSpriteBatchNode can reference one and only one texture (one image file, one texture atlas) i.e. sprite sheet created by zwoptex. Only the CCSprites that are contained in that texture can be added to the CCSpriteBatchNode. All CCSprites added to a CCSpriteBatchNode are drawn in one OpenGL ES draw call. If the CCSprites are not added to a CCSpriteBatchNode then an OpenGL ES draw call will be needed for each one, which is less efficient. According to your scenario, you don't have to use CCSpriteBatchNode since there is only one texture rendered at any given time. So I want to know: Should I animate the sprite frame by frame (no huge texture)? Or is it possible to use that huge texture but in a different way? It doesn't matter. You will be loading the 2048 x 2048 texture anyways. The issue to ponder is why only one 2048 x 2048 texture is giving you a Level 2 warning? how many such textures are you loading. BTW 2048 x 2048 is only supported on iPod3G/iPhone3GS above (which is fine). In case you are loading many textures (which seems true to me). You need to program some logic where you can unload the texture when they are not necessary. Do look at the following methods: [[CCSpriteFrameCache sharedSpriteFrameCache] removeSpriteFramesFromFile:fileName]; [[CCSpriteFrameCache sharedSpriteFrameCache] removeUnusedSpriteFrames]; [[CCTextureCache sharedTextureCache] removeUnusedTextures]; As far as animation is concerned you can create CCAnimation and use that or (depending upon your scenario) you can use setDisplayFrame(CCSpriteFrame frame);
{ "language": "en", "url": "https://stackoverflow.com/questions/7549266", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: omniauth gowalla strategy error: comparison of String with Bignum failed as far as I can get gowalla auth code response contains both expires_at and expires_in but expires_at is not valid date string so it throws error while comparing dates any idea to hack omniauth or gowalla strategy would be very welcome!!! rails 3.0.9 ruby 1.9.2 comparison of String with Bignum failed oauth2 (0.5.0) lib/oauth2/access_token.rb:72:in `<' oauth2 (0.5.0) lib/oauth2/access_token.rb:72:in `expired?' oa-oauth (0.3.0) lib/omniauth/strategies/oauth2.rb:67:in `callback_phase' { "scope":"read", "expires_at":"Sun, 09 Oct 2011 12:47:37 -0000", "username":"altuure", "expires_in":1172767, "refresh_token":"XX", "access_token":"XX" } A: Why don't you just use whatever you can. expires_in appears to be an interval, so you can do: expires_at = Time.now + json["expires_in"].to_i That said, the date string for expires_at definitely parses in 1.9.2-p290 (using DateTime.parse(str)). There's always DateTime.strptime if you need to parse a date/time string according to a given format. A: sorry for delay but I commited the patch to the github you can find the details over here http://github.com/intridea/omniauth/issues/485 –
{ "language": "en", "url": "https://stackoverflow.com/questions/7549272", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Auto-Load a html table with combobox I want to load different html tables when I select an option in my combobox. For example if I have a combobox with 4 categories (Cars, Bikes, Motorbikes and Airplanes) I would like that when I select one of the options, the specific table loads... and the tables may be different in size (not all the tables are for example 3 rows and 3 cells, each one of the tables may not be the same in structure) <select name="um" id="um" class="select_opt"> <option value="Car">Car</option>" <option value="Bike">Bike</option>" <option value="Motorbike">Motorbike</option>" <option value="Airplane">Airplane</option>" <table id="Car" cellspacing="0"> <tr> <th scope="alt">Title 1</th> </tr> <tr> <td>Something 1</td> <td>Something 2</td> </tr> </table> I have the combobox and one of the tables, I would like to see that table when I select the "Car" option... the same with the rest of the options in the combobox. How can I do this? A: Here are two ways to do this, one with pure JavaScript (no library) and the other using jQuery. The process involves hiding all the tables then based on the value of the selected option choose the correct table to show. The example tables have various columns (1-4) since you mentioned your tables may be various sizes as well. JavaScript only: example jsfiddle var tables = [ document.getElementById('Car'), document.getElementById('Bike'), document.getElementById('Motorbike'), document.getElementById('Airplane') ]; document.getElementById('um').onchange = function() { // hide all tables for (var i in tables) { tables[i].style.display = "none"; } // get selected value and show it's table var selectedValue = this[this.selectedIndex].value; if (selectedValue) { document.getElementById(selectedValue).style.display = "block"; } }; jQuery: example jsfiddle // reuse variable to hide all tables var $tables = $('table'); // Combobox change event $('.select_opt').change(function() { $tables.hide(); $('#' + $(this).val()).show(); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7549274", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: c++ char arrays, use in cin.getline() I have the following code: char myText[256]; cin.getline(myText,256); Why exactly do I have to pass a character array to cin.getline() and not a string? I have read that in general it is better to use strings than character arrays. Should I then convert a character array to a string after retrieving input with cin.getline(), if that is possible? A: That's an unfortunate historical artifact, I believe. You can however, use the std::getline free function instead. std::string myText; std::getline(std::cin,myText); A: You are using the member method of istream. In this case cin. This function's details can be found here : http://en.cppreference.com/w/cpp/io/basic_istream/getline However you could use std::getline Which uses a string instead of a char array. It's easier to use string since they know their sizes, they auto grow etc. and you don't have to worry about the null terminating character and so on. Also it is possible to convert a char array to a string by using the appropriate string contructor.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549280", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: sqlite iphone best practice for reading data I'm trying to make an app, that reads from an SQLite3 database. I plan to pre-load data during development, so the app does not need to modify anything in the database, only read from it, make queries, etc. What is the best practice for solely reading data? Should I open the database, read the data, and close it, with each query? The app will be making many small queries and a few large ones. Is it better to have the database open for the duration of the app, or open/close it with each fetch? A: Reading: 1. For queries, it's important to re-use compiled statements. 2. Make sure you use parameters so you can re-use those compiled queries When you call sqlite3_prepare_v2, it compiles the statement and gives you a reference to the statement back. Find a way to save that off and re-use it. See the code below for *statement. You pass &statement into prepare. Also, note the use of ? for parameters. If you're going to re-use the statement, it's important to call sqlite3_reset() againt the statement, rebind the inputs from the program (parameters) and execute it again. sqlite3_stmt *statement; NSString *querySQL = @"update contacts set name=?,address=?,phone=? where id=?"; NSLog(@"query: %@", querySQL); const char *query_stmt = [querySQL UTF8String]; // preparing a query compiles the query so it can be re-used. // find a way to save off the *statement so you can re-use it. sqlite3_prepare_v2(_contactDb, query_stmt, -1, &statement, NULL); // use sqlite3_bind_xxx functions to bind in order values to the params sqlite3_bind_text(statement, 1, [[contact name] UTF8String], -1, SQLITE_STATIC); sqlite3_bind_text(statement, 2, [[contact address] UTF8String], -1, SQLITE_STATIC); sqlite3_bind_text(statement, 3, [[contact phone] UTF8String], -1, SQLITE_STATIC); sqlite3_bind_int64(statement, 4, [[contact id] longLongValue]); Always check the return codes! and log or handle the errors. rc = sqlite3_step(stmt); switch (rc) { case SQLITE_ROW: // ... break; case SQLITE_OK: case SQLITE_DONE: break; default: // .... } return NO; } if you get an error, log or get the eror message to provide more info: - (NSString*)errorMessage { return [NSString stringWithCString:sqlite3_errmsg(_sqlite3) encoding:NSUTF8StringEncoding]; } A: Use sqlite_open_v2 with the SQLITE_OPEN_READONLY flag. For example, I use the following method to open a database for reading only. // Open for reading only. - (int) openDatabaseAtPath:(NSString *) path { if (database != nil) { sqlite3_close(self.database); [self setDatabase:nil]; } int errorCode = SQLITE_OK; errorCode = sqlite3_open_v2([path UTF8String], &database, SQLITE_OPEN_READONLY, NULL); return errorCode; } A: Unless you copy the database to the Documents directory, you work with the DB from the resource dir, and that one is readonly. A: When you open the database using sqlite_open_v2 and the SQLITE_OPEN_READONLY flag, SQLite opens the file itself in read-only mode, so even if your application, due to a bug, corrupts memory belonging to SQLite, the database will stay untouched. With this in mind, I'd keep the database open until the application quits. (You may wish to close it if you receive a low-memory notification and reopen it on demand, but opening and closing it for every query would be wasteful.) A: As per you question you want to read data from database. So following are the answer of you questions. * *No need to open db each time when you fire the query. Just one it one time. It is better if you create singleton class and open db in it for first time when it initiate. *Use following code method which will work for all select queries which has conditional select, group by etc. *I) it takes Output/result column names as input array ii ) TableName iii) Where condition iv)OrderBy clause v)group By clause - (NSMutableArray *)runSelecteQueryForColumns: (NSArray *)p_columns ontableName: (NSString *)p_tableName withWhereClause: (NSString *)p_whereClause withOrderByClause: (NSString *)p_orederByCalause withGroupByClause: (NSString *)p_groupByClause { NSMutableArray *l_resultArray = [[NSMutableArray alloc] init]; if(!self.m_database) { if(![self openDatabase]) { sqlite3_close(self.m_database); //NSLog(@"error in select : DB creating : %@",p_whereClause); return nil; } } NSMutableString *l_simpleQuery =[[NSMutableString alloc] initWithString:@"Select"] ; if(p_columns) { for(int l_row = 0 ; l_row < [p_columns count] ; l_row++) { if(l_row != [p_columns count]-1) { [l_simpleQuery appendString:[NSString stringWithFormat:@" %@,", [p_columns objectAtIndex:l_row]]]; } else { [l_simpleQuery appendString:[NSString stringWithFormat:@" %@", [p_columns objectAtIndex:l_row]]]; } } } else { [l_simpleQuery appendString:@" *"]; } [l_simpleQuery appendString:[NSString stringWithFormat:@" From %@",p_tableName]]; if(p_whereClause) { [l_simpleQuery appendString:[NSString stringWithFormat:@" %@",p_whereClause]]; } if(p_groupByCaluase) { [l_simpleQuery appendString:[NSString stringWithFormat:@" %@",p_groupByCaluase]]; } if(p_orederByCalause) { [l_simpleQuery appendString:[NSString stringWithFormat:@" %@",p_orederByCalause]]; } //NSLog(@"Select Query: - %@",l_simpleQuery); const char *l_query_stmt = [l_simpleQuery UTF8String]; sqlite3_stmt *l_statement = nil; int i = sqlite3_prepare_v2(self.m_database, l_query_stmt, -1, &l_statement, NULL); if (i == SQLITE_OK) { while(sqlite3_step(l_statement) == SQLITE_ROW) { [l_resultArray addObject:[self createDictionary:l_statement]]; } sqlite3_finalize(l_statement); } else { sqlite3_finalize(l_statement); //sqlite3_close(l_database); DDLogError(@"%@ - error in SQL :%@",THIS_FILE,l_simpleQuery); return nil; } //NSLog(@"RESULT %@",l_resultArray); return l_resultArray; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7549281", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How can you make a java object override its methods? Here's what I'm thinking. So lets say I have a class called intro and I want to do something when it starts and finishes. I'm wondering how could I do something like this: public Main(){ //Calls the object that overrides its own methods new Intro(){ @Override public void onStartIntro(){ } @Override public void onFinishIntro(){ } } What would need to happen in the Intro class to enable something like this? A: just create an abstract class to force overriding of the methods (but a non-abstract class with non-final methods will also do) abstract class Intro { abstract void onStartIntro(); abstract void onFinishIntro(); } A: Maybe Something like this: public class Main(){ public Main(){ new Intro(); } private class Intro extends SomeOtherClass{ @Override public void onStartIntro(){ /*...Code...*/ } @Override public void onFinishIntro(){ /*...Code...*/ } } } Intro would only be available inside your "Main" class...
{ "language": "en", "url": "https://stackoverflow.com/questions/7549283", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to merge two images into one with asp.net I am working on an asp.net project. I am searching for a solution such that after a background image of a div is chosen. The user selects another image and coordinate. Then, this image will be merged on the background image with the defined coordinate. Thanks in advance. A: If you wish to combine two images,firstly you must upload them into server via ajax requests. Read this article : combining images After you combine them,let the user download the new one. Also if you're looking for an editor to do so,I suggest to place them on html5 canvas. Best Regards A: Your post is quite general, but look in to System.Drawing and using an AJAX call to post both images (as well as the coordinates chosen) and then return the combined image which can then be displayed. Without more specifics that's really all I can offer.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549285", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What's the equivalent syntax of while($row = mysql_fetch_array($result)) for a "for loop" I wanted to know if it was possible to write the following expression while($row = mysql_fetch_array($result)) with a "for loop" instead of a "while loop." So that the below code would print the same result. while($row = mysql_fetch_array($result)){ echo $row['name']; } EDIT: I use PDO I just thought this would be an expression more people have seen. And as far as the answers go, yeah I agree it would be pointless. I'm just having trouble understanding how the internal pointer increments. A: It would be really pointless, but you could do: for(;$row = mysql_fetch_array($result);) { echo $row['name']; } However, you should seriously consider using PDO. A: for($row = NULL; $row = mysql_fetch_array($result);;) { echo $row['name']; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7549286", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I access a model in JSTL outside of EL? In Expression Language, I can access my model like so: ${model.member} How do I achieve the same thing when I want to use <%=some_method(${model.member}); %> The reason is because I have some HTML helper methods I created to separate logic from UI, and I need to pass a member of the model to create the user control. A: The JSP's main method has the following signature: _jspService(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException Based on this, you can access the request and response objects programattically from a scriptlet. For example: <%= request.getParameter("foo").toString() %> or <%= request.getAttribute("bar").toString() %> If you want to do something more complication, you could precede these with scriptlets to declare / initialize local (Java) variables; e.g. <% String foo = request.getParameter("foo") == null ? "no foo" : request.getParameter("foo").toString(); %> <%= foo %> You can use this to lookup your model in the request or response object (I think it will be an attribute of the request with name "model"), cast it to the appropriate type, and call its getter methods. The reason is because I have some HTML helper methods I created to separate logic from UI, and I need to pass a member of the model to create the user control. A better idea would be to turn those helper methods into custom JSP tags so that you can use them without resorting to scriptlets. JSPs with embedded scriptlets are generally thought to be hard to read and hard to maintain. One small mistake (or one change to the model API) and the JSP generates bad Java on your deployment platform and you get a broken page. A: Take a look at JSTL custom functions. It allows a way for you to call static functions from your code in a JSTL standard way. You just need to set then up in your tld file.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549287", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: DOM GetElementsByTagName Problem I am just starting out learning JavaScript and I have just reach the DOM section of my course. I have a page with 10 tags on it and I have created the following JavaScript to tell me how many I have. <script type="text/javascript"> var myLinks = document.getElementsByTagName("a"); console.log("We have ", myLinks.length ," many links on the page"); </script> However in the console it reports this: We have 0 many links on the page This is not true as there are 10 links, 9 in the navgation section of the website and 1 in the footer. If someone can tell me what I am doing wrong that would be great. Thanks A: You need to wrap this in an onload handler, because at the point of execution, the DOM isn't fully loaded: <script type="text/javascript"> window.onload = function() { var myLinks = document.getElementsByTagName("a"); console.log("We have ", myLinks.length ," many links on the page"); }; </script> A: Put the script at the end of your document (before you close </body>):
{ "language": "en", "url": "https://stackoverflow.com/questions/7549290", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Reading IA32 Assembly Code pertaining to using double arrays This is the exact question: The following Code transposes the elements of an M x M array, where M is a constant defined by #define: void transpose(Marray_t A) { int i, j; for (i = 0; i < M; i++) for (j = 0; j < i; j++) { int t = A[i][j]; A[i][j] = A[j][i]; A[j][i] = t; } } When compiled with optimization level -02, GCC generates the following code for the inner loop of the function: 1. .L3 2. movl (%ebx),%eax 3. movl (%esi,%ecx,4),%edx 4. movl %eax, (%esi,%ecx,4) 5. addl $1, %ecx 6. movl %edx, (%ebx) 7. addl $52,%ebx 8. cmpl %edi,%ecx 9. jl .L3 A. What is the value of M? B. What registers hold program values i and j? C. Write a C code version of transpose that makes use of the optimizations that occur in this loop. Use the parameter M in your code rather than numeric constant. So in my attempts to understand this, I notice that it is multiplying by 4, which means it stores types of 4 bytes (maybe an int or a pointer). Then, it increments i by $52 (I assume i) since it's a larger value, thus going to the next array) and $52 / 4 is 13. So I would guess that M = 13. Wrong? For B, I would guess that %ebx contains i and %ecx contains i. For C, I'm not exactly sure because I don't completely understand the loop presented. Let me try to understand by line number and tell me where I'm wrong. 1. is the beginning of the loop label obviously. 2. moves presumably the value of i into %eax. Then 3. has A[i][j] being stored into t. But... I really don't understand it. :/ Help?? A: I fixed some mistakes in the assembly code (%ecs -> %ecx and (ebx) -> (%ebx)) I hope I didn't inadvertently introduce new errors. On to the questions, where you are almost there with the understanding. Let's take the code line by line and attempt to translate it to C. L3: 2. movl (%ebx),%eax // We load a 32-bit value from the address stored in ebx. We can't yet deduce the type, but let's assume int for now int *ebx = ??; int eax = *ebx; 3. movl (%esi,%ecx,4),%edx // As you noted we're dealing with 32-bit values, so when converting to C we divide the index by 4 int *esi = ??; int ecx = ??; int edx = esi[ecx]; 4. movl %eax, (%esi,%ecx,4) esi[ecx] = eax; 5. addl $1, %ecx ecx++; 6. movl %edx, (%ebx) *ebx = edx; 7. addl $52,%ebx // Again we have to remember to divide by the size of the type used (4) ebx += 13; 8. cmpl %edi,%ecx 9. jl .L3 int edi = ??; if (ecx < edi) goto L3; From this we see that we have some unknown values that are initialized outside the inner loop, but we can also give good guesses as to what they are. * *ecx is incremented each loop iteration and then used to decide if we should continue the loop: it's obviously j from the C code. *edi is the value we compare j to when deciding whether to loop, but it isn't changed in the inner loop: it's i. *esi is indexed with row-wise with ecx (j), so it corresponds to &a[i][j]. *ebx is incremented by 52 (13 index positions) each loop iteration - as you might have guessed 13 is M - it corresponds to &m[j][i] and is moved to point at the j-th row element of the next column each iteration. Now we can answer the questions: A. What is the value of M? 13 B. What registers hold program values i and j? edi and ecx respectively. C. Write a C code version of transpose that makes use of the optimizations that occur in this loop. Use the parameter M in your code rather than numeric constant. This should be straight-forward at this point.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549291", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: C# Windows forms cascading windows I currently have a menu button that allows users to open a new dialog which I would like to be placed directly to the right of the main form. The user can open as many of these dialogs as they would like but I would like them to cascade on top of the first dialog that they opened (if there is one). I've seen ways to do something similar using an MdiLayout but this is just for normal dialogs. A: Do you want to loop through all the open dialogs, setting each windows location? this.Location = new Point(x,y); or int prevHeight =0; foreach (Form f in this.OwnedForms) { x += 5; y += prevHeight; f.Location = new Point(x, y); prevHeight += f.Height; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7549300", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: pushing onto navigation stack not within the nav controller I have this ad class which contains an UIImageView. I've added an instance of the class to my appdelegate onto the "window" view. Now, I want to, when the user taps the ad, push my "detailedViewController" onto the current navigation controller, which all of my tab bar items contain. I don't know if it is possible. Perhaps, I should just add my advertisement class to every view controller for every nav controller. However, if the user pushes or changes a view controller it would reset the class. I just want to overlay the ad once. EDIT: Let me rephrase, can I from the app delegate and from my object know which tab bar item is selected? If I can determine which tab bar item is selected I can point to the appropriate nav controller instance. A: Whoever owns the tab bar controller can do [myTabBarController selectedIndex]; or [myTabBarController selectedViewController]; The first one returns the index of the selected item, the second one the actual view controller, you might be better off with the first one. A: The easyiest way would be to present your DetailVC as a ModalView which also makes sense in semantics. Yes, it is possible to detect which tab is selected but it is easier to use the selectedViewController-property of UITabBarController. UIViewController *curVC = myTabBarController.selectedViewController; if([curVC isKindOfClass:UINavigationController.class]) { UINavigationController *nav = (UINavigationController*)curVC; [nav push...]; } else { // do sth else: go to webpage for instance }
{ "language": "en", "url": "https://stackoverflow.com/questions/7549303", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Referencing ActionScript file I have a process set up to create action script files. They hold functions that are called upon by my flash project. How can i reference these files so that the project knows the functions are there. with asp.net i would simply reference the .js file. Is it the same process? A: The process of importing files to be used by Flash is pretty straightforward: At the top of each external file there will be a package declaration, it basically represents it's path from the .fla file. For example: package com.site.objects The above represents an ActionScript file within a folder objects, within site, within com whose parent folder also contains the .fla file. When you're importing external files, you always start from the directory containing the .fla. This is always necessary with the exception of importing external files that are in the same directory as the file you're trying to access the class from. The import statement for the above example will look like this: import com.site.objects.MyClass; Once you've done this, you'll be able to: * *Create instances of the imported class. *Access static properties and methods defined within the class. *Extend the class to create a new class which will inherit it's properties. etc
{ "language": "en", "url": "https://stackoverflow.com/questions/7549304", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: "Single-page" JS websites and SEO There are a lot of cool tools for making powerful "single-page" JavaScript websites nowadays. In my opinion, this is done right by letting the server act as an API (and nothing more) and letting the client handle all of the HTML generation stuff. The problem with this "pattern" is the lack of search engine support. I can think of two solutions: * *When the user enters the website, let the server render the page exactly as the client would upon navigation. So if I go to http://example.com/my_path directly the server would render the same thing as the client would if I go to /my_path through pushState. *Let the server provide a special website only for the search engine bots. If a normal user visits http://example.com/my_path the server should give him a JavaScript heavy version of the website. But if the Google bot visits, the server should give it some minimal HTML with the content I want Google to index. The first solution is discussed further here. I have been working on a website doing this and it's not a very nice experience. It's not DRY and in my case I had to use two different template engines for the client and the server. I think I have seen the second solution for some good ol' Flash websites. I like this approach much more than the first one and with the right tool on the server it could be done quite painlessly. So what I'm really wondering is the following: * *Can you think of any better solution? *What are the disadvantages with the second solution? If Google in some way finds out that I'm not serving the exact same content for the Google bot as a regular user, would I then be punished in the search results? A: While #2 might be "easier" for you as a developer, it only provides search engine crawling. And yes, if Google finds out your serving different content, you might be penalized (I'm not an expert on that, but I have heard of it happening). Both SEO and accessibility (not just for disabled person, but accessibility via mobile devices, touch screen devices, and other non-standard computing / internet enabled platforms) both have a similar underlying philosophy: semantically rich markup that is "accessible" (i.e. can be accessed, viewed, read, processed, or otherwise used) to all these different browsers. A screen reader, a search engine crawler or a user with JavaScript enabled, should all be able to use/index/understand your site's core functionality without issue. pushState does not add to this burden, in my experience. It only brings what used to be an afterthought and "if we have time" to the forefront of web development. What your describe in option #1 is usually the best way to go - but, like other accessibility and SEO issues, doing this with pushState in a JavaScript-heavy app requires up-front planning or it will become a significant burden. It should be baked in to the page and application architecture from the start - retrofitting is painful and will cause more duplication than is necessary. I've been working with pushState and SEO recently for a couple of different application, and I found what I think is a good approach. It basically follows your item #1, but accounts for not duplicating html / templates. Most of the info can be found in these two blog posts: http://lostechies.com/derickbailey/2011/09/06/test-driving-backbone-views-with-jquery-templates-the-jasmine-gem-and-jasmine-jquery/ and http://lostechies.com/derickbailey/2011/06/22/rendering-a-rails-partial-as-a-jquery-template/ The gist of it is that I use ERB or HAML templates (running Ruby on Rails, Sinatra, etc) for my server side render and to create the client side templates that Backbone can use, as well as for my Jasmine JavaScript specs. This cuts out the duplication of markup between the server side and the client side. From there, you need to take a few additional steps to have your JavaScript work with the HTML that is rendered by the server - true progressive enhancement; taking the semantic markup that got delivered and enhancing it with JavaScript. For example, i'm building an image gallery application with pushState. If you request /images/1 from the server, it will render the entire image gallery on the server and send all of the HTML, CSS and JavaScript down to your browser. If you have JavaScript disabled, it will work perfectly fine. Every action you take will request a different URL from the server and the server will render all of the markup for your browser. If you have JavaScript enabled, though, the JavaScript will pick up the already rendered HTML along with a few variables generated by the server and take over from there. Here's an example: <form id="foo"> Name: <input id="name"><button id="say">Say My Name!</button> </form> After the server renders this, the JavaScript would pick it up (using a Backbone.js view in this example) FooView = Backbone.View.extend({ events: { "change #name": "setName", "click #say": "sayName" }, setName: function(e){ var name = $(e.currentTarget).val(); this.model.set({name: name}); }, sayName: function(e){ e.preventDefault(); var name = this.model.get("name"); alert("Hello " + name); }, render: function(){ // do some rendering here, for when this is just running JavaScript } }); $(function(){ var model = new MyModel(); var view = new FooView({ model: model, el: $("#foo") }); }); This is a very simple example, but I think it gets the point across. When I instante the view after the page loads, I'm providing the existing content of the form that was rendered by the server, to the view instance as the el for the view. I am not calling render or having the view generate an el for me, when the first view is loaded. I have a render method available for after the view is up and running and the page is all JavaScript. This lets me re-render the view later if I need to. Clicking the "Say My Name" button with JavaScript enabled will cause an alert box. Without JavaScript, it would post back to the server and the server could render the name to an html element somewhere. Edit Consider a more complex example, where you have a list that needs to be attached (from the comments below this) Say you have a list of users in a <ul> tag. This list was rendered by the server when the browser made a request, and the result looks something like: <ul id="user-list"> <li data-id="1">Bob <li data-id="2">Mary <li data-id="3">Frank <li data-id="4">Jane </ul> Now you need to loop through this list and attach a Backbone view and model to each of the <li> items. With the use of the data-id attribute, you can find the model that each tag comes from easily. You'll then need a collection view and item view that is smart enough to attach itself to this html. UserListView = Backbone.View.extend({ attach: function(){ this.el = $("#user-list"); this.$("li").each(function(index){ var userEl = $(this); var id = userEl.attr("data-id"); var user = this.collection.get(id); new UserView({ model: user, el: userEl }); }); } }); UserView = Backbone.View.extend({ initialize: function(){ this.model.bind("change:name", this.updateName, this); }, updateName: function(model, val){ this.el.text(val); } }); var userData = {...}; var userList = new UserCollection(userData); var userListView = new UserListView({collection: userList}); userListView.attach(); In this example, the UserListView will loop through all of the <li> tags and attach a view object with the correct model for each one. it sets up an event handler for the model's name change event and updates the displayed text of the element when a change occurs. This kind of process, to take the html that the server rendered and have my JavaScript take over and run it, is a great way to get things rolling for SEO, Accessibility, and pushState support. Hope that helps. A: If you're using Rails, try poirot. It's a gem that makes it dead simple to reuse mustache or handlebars templates client and server side. Create a file in your views like _some_thingy.html.mustache. Render server side: <%= render :partial => 'some_thingy', object: my_model %> Put the template your head for client side use: <%= template_include_tag 'some_thingy' %> Rendre client side: html = poirot.someThingy(my_model) A: To take a slightly different angle, your second solution would be the correct one in terms of accessibility...you would be providing alternative content to users who cannot use javascript (those with screen readers, etc.). This would automatically add the benefits of SEO and, in my opinion, would not be seen as a 'naughty' technique by Google. A: I think you need this: http://code.google.com/web/ajaxcrawling/ You can also install a special backend that "renders" your page by running javascript on the server, and then serves that to google. Combine both things and you have a solution without programming things twice. (As long as your app is fully controllable via anchor fragments.) A: So, it seem that the main concern is being DRY * *If you're using pushState have your server send the same exact code for all urls (that don't contain a file extension to serve images, etc.) "/mydir/myfile", "/myotherdir/myotherfile" or root "/" -- all requests receive the same exact code. You need to have some kind url rewrite engine. You can also serve a tiny bit of html and the rest can come from your CDN (using require.js to manage dependencies -- see https://stackoverflow.com/a/13813102/1595913). *(test the link's validity by converting the link to your url scheme and testing against existence of content by querying a static or a dynamic source. if it's not valid send a 404 response.) *When the request is not from a google bot, you just process normally. *If the request is from a google bot, you use phantom.js -- headless webkit browser ("A headless browser is simply a full-featured web browser with no visual interface.") to render html and javascript on the server and send the google bot the resulting html. As the bot parses the html it can hit your other "pushState" links /somepage on the server <a href="/someotherpage">mylink</a>, the server rewrites url to your application file, loads it in phantom.js and the resulting html is sent to the bot, and so on... *For your html I'm assuming you're using normal links with some kind of hijacking (e.g. using with backbone.js https://stackoverflow.com/a/9331734/1595913) *To avoid confusion with any links separate your api code that serves json into a separate subdomain, e.g. api.mysite.com *To improve performance you can pre-process your site pages for search engines ahead of time during off hours by creating static versions of the pages using the same mechanism with phantom.js and consequently serve the static pages to google bots. Preprocessing can be done with some simple app that can parse <a> tags. In this case handling 404 is easier since you can simply check for the existence of the static file with a name that contains url path. *If you use #! hash bang syntax for your site links a similar scenario applies, except that the rewrite url server engine would look out for _escaped_fragment_ in the url and would format the url to your url scheme. *There are a couple of integrations of node.js with phantom.js on github and you can use node.js as the web server to produce html output. Here are a couple of examples using phantom.js for seo: http://backbonetutorials.com/seo-for-single-page-apps/ http://thedigitalself.com/blog/seo-and-javascript-with-phantomjs-server-side-rendering A: Interesting. I have been searching around for viable solutions but it seems to be quite problematic. I was actually leaning more towards your 2nd approach: Let the server provide a special website only for the search engine bots. If a normal user visits http://example.com/my_path the server should give him a JavaScript heavy version of the website. But if the Google bot visits, the server should give it some minimal HTML with the content I want Google to index. Here's my take on solving the problem. Although it is not confirmed to work, it might provide some insight or idea's for other developers. Assume you're using a JS framework that supports "push state" functionality, and your backend framework is Ruby on Rails. You have a simple blog site and you would like search engines to index all your article index and show pages. Let's say you have your routes set up like this: resources :articles match "*path", "main#index" Ensure that every server-side controller renders the same template that your client-side framework requires to run (html/css/javascript/etc). If none of the controllers are matched in the request (in this example we only have a RESTful set of actions for the ArticlesController), then just match anything else and just render the template and let the client-side framework handle the routing. The only difference between hitting a controller and hitting the wildcard matcher would be the ability to render content based on the URL that was requested to JavaScript-disabled devices. From what I understand it is a bad idea to render content that isn't visible to browsers. So when Google indexes it, people go through Google to visit a given page and there isn't any content, then you're probably going to be penalised. What comes to mind is that you render content in a div node that you display: none in CSS. However, I'm pretty sure it doesn't matter if you simply do this: <div id="no-js"> <h1><%= @article.title %></h1> <p><%= @article.description %></p> <p><%= @article.content %></p> </div> And then using JavaScript, which doesn't get run when a JavaScript-disabled device opens the page: $("#no-js").remove() # jQuery This way, for Google, and for anyone with JavaScript-disabled devices, they would see the raw/static content. So the content is physically there and is visible to anyone with JavaScript-disabled devices. But, when a user visits the same page and actually has JavaScript enabled, the #no-js node will be removed so it doesn't clutter up your application. Then your client-side framework will handle the request through it's router and display what a user should see when JavaScript is enabled. I think this might be a valid and fairly easy technique to use. Although that might depend on the complexity of your website/application. Though, please correct me if it isn't. Just thought I'd share my thoughts. A: Use NodeJS on the serverside, browserify your clientside code and route each http-request's(except for static http resources) uri through a serverside client to provide the first 'bootsnap'(a snapshot of the page it's state). Use something like jsdom to handle jquery dom-ops on the server. After the bootsnap returned, setup the websocket connection. Probably best to differentiate between a websocket client and a serverside client by making some kind of a wrapper connection on the clientside(serverside client can directly communicate with the server). I've been working on something like this: https://github.com/jvanveen/rnet/ A: Use Google Closure Template to render pages. It compiles to javascript or java, so it is easy to render the page either on the client or server side. On the first encounter with every client, render the html and add javascript as link in header. Crawler will read the html only but the browser will execute your script. All subsequent requests from the browser could be done in against the api to minimize the traffic. A: This might help you : https://github.com/sharjeel619/SPA-SEO Logic * *A browser requests your single page application from the server, which is going to be loaded from a single index.html file. *You program some intermediary server code which intercepts the client request and differentiates whether the request came from a browser or some social crawler bot. *If the request came from some crawler bot, make an API call to your back-end server, gather the data you need, fill in that data to html meta tags and return those tags in string format back to the client. *If the request didn't come from some crawler bot, then simply return the index.html file from the build or dist folder of your single page application.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549306", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "127" }
Q: set a div image on another div image asp.net Would it be possible to set a div image over another div image in asp.net? For example: after having an image A, the user chooses an image B with location 10, 10 then the image B will be placed at location 10, 10 on the image A (not merging). Or it is required to use jQuery? Thanks in advance. A: I assume that you are running Web Forms. You can accomplish this by wrapping the images in a position relative div and then position them absolute, you can do this from the code behind. Here is the HTML + CSS to demonstrate this: http://jsfiddle.net/GuafM/ The serverside code to add the dot would look something like this: Image imgDot = new Image(); imgDot.ImageUrl = "http://upload.wikimedia.org/wikipedia/commons/6/6e/Paris_plan_pointer_b_jms.gif"; imgDot.Style["top"] = "10px"; imgDot.Style["left"] = "10px"; divImageWrapper.Controls.Add(imgDot); If you want the user to drag and drop (or similar complex client side behaviour) a image on top of another I would probably recommend that you use jQuery.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549308", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to return both stream and file length from WCF Restful json webservice? Hihi all, I am able to return stream from my WCF restful json webservice, everything works fine. But when I mixed the stream with another piece of data (both wrap into a custom class), upon consuming the webservice from my client, it gives an error message of "An existing connection was forcibly closed by the remote host". Any advice how can I achieve the above? What it's required for my webservice is to allow downloading of a file with the file length as an additional piece of information for validation at the client end. Thanks in advance! :) A: There are various restrictions while using Stream in WCF service contracts - as per this MDSN link, only one (output) parameter or return value (of type stream) can be used while streaming. In another MSDN documentation (this is anyway a good resource, if you want to stream large data using WCF), it has been hinted that one can combine stream and some input/output data by using Message Contract. For example, see this blog post where author has used explicit message contract to upload both file name & file data. You have to do the similar thing from download perspective. Finally, if nothing works then you can always push the file length as a custom (or standard such as content-length) HTTP header. If you are hosting in IIS then enable ASP.NET compatibility and use HttpContext.Current.Response to add your custom header.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549314", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MPI partition matrix into blocks I want to partition matrix into blocks (not stripes) and then distribute this blocks using MPI_Scatter. I came up with solution which works, but I think it is far from "best practice". I have 8x8 matrix, filled with numbers from 0 to 63. Then I divide it into 4 4x4 blocks, using MPI_Type_vector and distribute it via MPI_Send, but this require some extra computation since i have to compute offsets for each block in big matrix. If I use scatter, first (top left) block is transfered OK, but other blocks are not (wrong offset for start of block). So is it possible to transfer blocks of matrix using MPI_Scatter, or what is the best way to do desired decomposition? This is my code: #include <stdio.h> #include <stdlib.h> #include <mpi.h> #define SIZE 8 int main(void) { MPI_Init(NULL, NULL); int p, rank; MPI_Comm_size(MPI_COMM_WORLD, &p); MPI_Comm_rank(MPI_COMM_WORLD, &rank); char i; char a[SIZE*SIZE]; char b[(SIZE/2)*(SIZE/2)]; MPI_Datatype columntype; MPI_Datatype columntype2; MPI_Type_vector(4, 4, SIZE, MPI_CHAR, &columntype2); MPI_Type_create_resized( columntype2, 0, sizeof(MPI_CHAR), &columntype ); MPI_Type_commit(&columntype); if(rank == 0) { for( i = 0; i < SIZE*SIZE; i++) { a[i] = i; } for(int rec=0; rec < p; rec++) { int offset = (rec%2)*4 + (rec/2)*32; MPI_Send (a+offset, 1, columntype, rec, 0, MPI_COMM_WORLD); } } MPI_Recv (b, 16, MPI_CHAR, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); //MPI_Scatter(&a, 1, boki, &b, 16, MPI_CHAR , 0, MPI_COMM_WORLD); printf("rank= %d b= \n%d %d %d %d\n%d %d %d %d\n%d %d %d %d\n%d %d %d %d\n", rank, b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7], b[8], b[9], b[10], b[11], b[12], b[13], b[14], b[15]); MPI_Finalize(); return 0; } A: What you've got is pretty much "best practice"; it's just a bit confusing until you get used to it. Two things, though: First, be careful with this: sizeof(MPI_CHAR) is, I assume, 4 bytes, not 1. MPI_CHAR is an (integer) constant that describes (to the MPI library) a character. You probably want sizeof(char), or SIZE/2*sizeof(char), or anything else convenient. But the basic idea of doing a resize is right. Second, I think you're stuck using MPI_Scatterv, though, because there's no easy way to make the offset between each block the same size. That is, the first element in the first block is at a[0], the second is at a[SIZE/2] (jump of size/2), the next is at a[SIZE*(SIZE/2)] (jump of (SIZE-1)*(SIZE/2)). So you need to be able to manually generate the offsets. The following seems to work for me (I generalized it a little bit to make it clearer when "size" means "number of rows" vs "number of columns", etc): #include <stdio.h> #include <stdlib.h> #include <mpi.h> #define COLS 12 #define ROWS 8 int main(int argc, char **argv) { MPI_Init(&argc, &argv); int p, rank; MPI_Comm_size(MPI_COMM_WORLD, &p); MPI_Comm_rank(MPI_COMM_WORLD, &rank); char i; char a[ROWS*COLS]; const int NPROWS=2; /* number of rows in _decomposition_ */ const int NPCOLS=3; /* number of cols in _decomposition_ */ const int BLOCKROWS = ROWS/NPROWS; /* number of rows in _block_ */ const int BLOCKCOLS = COLS/NPCOLS; /* number of cols in _block_ */ if (rank == 0) { for (int ii=0; ii<ROWS*COLS; ii++) { a[ii] = (char)ii; } } if (p != NPROWS*NPCOLS) { fprintf(stderr,"Error: number of PEs %d != %d x %d\n", p, NPROWS, NPCOLS); MPI_Finalize(); exit(-1); } char b[BLOCKROWS*BLOCKCOLS]; for (int ii=0; ii<BLOCKROWS*BLOCKCOLS; ii++) b[ii] = 0; MPI_Datatype blocktype; MPI_Datatype blocktype2; MPI_Type_vector(BLOCKROWS, BLOCKCOLS, COLS, MPI_CHAR, &blocktype2); MPI_Type_create_resized( blocktype2, 0, sizeof(char), &blocktype); MPI_Type_commit(&blocktype); int disps[NPROWS*NPCOLS]; int counts[NPROWS*NPCOLS]; for (int ii=0; ii<NPROWS; ii++) { for (int jj=0; jj<NPCOLS; jj++) { disps[ii*NPCOLS+jj] = ii*COLS*BLOCKROWS+jj*BLOCKCOLS; counts [ii*NPCOLS+jj] = 1; } } MPI_Scatterv(a, counts, disps, blocktype, b, BLOCKROWS*BLOCKCOLS, MPI_CHAR, 0, MPI_COMM_WORLD); /* each proc prints it's "b" out, in order */ for (int proc=0; proc<p; proc++) { if (proc == rank) { printf("Rank = %d\n", rank); if (rank == 0) { printf("Global matrix: \n"); for (int ii=0; ii<ROWS; ii++) { for (int jj=0; jj<COLS; jj++) { printf("%3d ",(int)a[ii*COLS+jj]); } printf("\n"); } } printf("Local Matrix:\n"); for (int ii=0; ii<BLOCKROWS; ii++) { for (int jj=0; jj<BLOCKCOLS; jj++) { printf("%3d ",(int)b[ii*BLOCKCOLS+jj]); } printf("\n"); } printf("\n"); } MPI_Barrier(MPI_COMM_WORLD); } MPI_Finalize(); return 0; } Running: $ mpirun -np 6 ./matrix Rank = 0 Global matrix: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 Local Matrix: 0 1 2 3 12 13 14 15 24 25 26 27 36 37 38 39 Rank = 1 Local Matrix: 4 5 6 7 16 17 18 19 28 29 30 31 40 41 42 43 Rank = 2 Local Matrix: 8 9 10 11 20 21 22 23 32 33 34 35 44 45 46 47 Rank = 3 Local Matrix: 48 49 50 51 60 61 62 63 72 73 74 75 84 85 86 87 Rank = 4 Local Matrix: 52 53 54 55 64 65 66 67 76 77 78 79 88 89 90 91 Rank = 5 Local Matrix: 56 57 58 59 68 69 70 71 80 81 82 83 92 93 94 95
{ "language": "en", "url": "https://stackoverflow.com/questions/7549316", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: Creating an array list of names on SD Card Android I am in the process of developing an android app, and I need a way for the user to enter a Name and then save this name to a .txt file in the SD card. When the user adds another name, this file should be modified to include that name. I was thinking of an array list, but I've been trying for some time on things to use but I'm not sure how. (I don't think an object output stream would work(?)). Also, I need the user to be able to read and access this file within the app. Thanks in advance for the help. A: Is there a certain reason why you are using a .txt file? I would suggest you use a SQLite database for this particular project. EDIT: Here is the one of the best articles you can find on building SQLite in android. Building a Database For Android
{ "language": "en", "url": "https://stackoverflow.com/questions/7549319", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Constraining other application's window sizes through Qt Application I'm looking for a way in Qt to constrain other application window's (some will not be Qt) so that when maximized don't overlap my Qt application. Essentially I want to create the Windows Taskbar. I'd like the applications edge to dock to the appropriate edge of my Qt Taskbar in the same way that applications dock to the Windows taskbar when they are maximized. I envision this taskbar to exist along the top edge of the screen, but would like to allow users to decide which edge it will live on. I know it isn't hard to make a window that is always on top it's more the auto docking issue I'm having a hard time figuring out. I'm right now only looking to accomplish this on Windows. Thank for any help. A: Detailed explanation on how to do it would be too long for an answer here, but MSDN documentation on SHAppBarMessage should get you started. Taskbar created like that can even be part of winows taskbar ;)
{ "language": "en", "url": "https://stackoverflow.com/questions/7549323", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: html drop-down on Opera is missing padding On IE9, Firefox, and Chrome my dropdown lists look great. But Opera's are missing 2-3 pixels of padding, and I've got some forms with single-character entries in these menus and it looks bad. A space on either side will make it look good but it will look bad on the rest of the browsers, and also will screw up my scripts. A: Hard to tell without the code. However, you could use jQuery to target only Opera: if($.browser.opera){ $('select').css(//DO WHATEVER); } This would leave the other browsers untouched. Fwiw... I would check your visitor stats. Opera use may be so low/non-existent that fixes may be unnecessary. A: I did just create this to detect iOS devices: 138 (function () { 139 // ios detection (select menus are ugly) 140 if (navigator.userAgent.toLowerCase().search('iphone') != -1 || navigator.userAgent.toLo werCase().search('ipod') != -1 || navigator.userAgent.toLowerCase().search('ipad') != -1 ) { 141 // set css rule for input 142 var style = document.createElement('style'); 143 style.setAttribute('type','text/css'); 144 style.innerHTML = 'select{ color: #333; }'; // custom css for select on ios 145 document.getElementsByTagName('head')[0].appendChild(style); 146 } 147 })(); I reckon I could do much the same for Opera. As for the original problem, I made a new site to test the issue: 1 <head><style type='text/css'> 2 select { 3 background-color: #353535; 4 border: 2px solid #555555; 5 color: #c0c0c0; 6 } 7 </style></head><body> 8 <select> 9 <option>0</option> 10 </select></body> What's happening is that when I set styles that modify the border OR background-color for the select, it changes from the neat looking dropdown menu style to an old-fashioned looking squarer button, and also it gets rid of some padding. Nobody uses Opera, though, so I probably won't ever get around to "fixing" the problem. A: Thanks for the demo. Adding certain styles to SELECT has side effects, looks like a layout bug. What about adding something like this: width: 2em; text-align:center; ? I have not tested it in other browsers but it should merely "reinforce" their default rendering I guess..
{ "language": "en", "url": "https://stackoverflow.com/questions/7549325", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: OpenGL Ortho Coordinates I have an OpenGL view overlaid on top of an MKMapView. My goal is to have the coordinates of the glView to have the same values of the MKMapPoints on the map. To do this I found the values for the MKMapPoint on the top left and the bottom right of the map. CLLocationCoordinate2D coordinateTopLeft = [mapView convertPoint:CGPointMake(0, 0) toCoordinateFromView:mapView]; MKMapPoint pointTopLeft = MKMapPointForCoordinate(coordinateTopLeft); CLLocationCoordinate2D coordinateBottomRight = [mapView convertPoint:CGPointMake(mapView.frame.size.width, mapView.frame.size.width) toCoordinateFromView:mapView]; MKMapPoint pointBottomRight = MKMapPointForCoordinate(coordinateBottomRight); Then I set the right, left, bottom, and top coordinates of the glView to match these points accordingly. glOrthof(pointTopLeft.x, pointBottomRight.x, pointBottomRight.y, pointTopLeft.y, -1, 1); Unfortunately, this did not work. The triangles that I tried to draw did not work. I tested and the points that I was trying to draw were located in the correct domain. Am I just misunderstanding how the glOrthof method works? A: Have you tried flipping pointBottomRight.y and pointTopLeft.y? The OpenGL y-coordinate system is inverted from most commonly used conventions.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549327", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can I make a spark datagrid columnSeparator render before a rowSeparator? I have a black row separator and a grey column separator, but because the row separator gets rendered first, the column separator appears over the top of it, causing what appears to be breaks in the row separator. Is there any way to change the order these are rendered to prevent this? A: I cannot tell you a nice and clean way to do this, however there is a "patch/hack" for this :) Inside your DataGridSkin, in the place where you redefine the default rowSeparator use can force a greater depth. This is definitely a patch since you hardcode the depth, but it will work. <!--- @private --> <fx:Component id="rowSeparator"> <s:Line depth="1000"> <s:stroke> <s:SolidColorStroke color="0x0000FF" weight="5" caps="square"/> </s:stroke> </s:Line> </fx:Component>
{ "language": "en", "url": "https://stackoverflow.com/questions/7549328", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: facebook getloginurl authentication permissions seems having updated to the latest version of the facebook php sdk the following code is not working- $loginUrl = $facebook->getLoginUrl(array( 'canvas' => 0, 'fbconnect' => 1, 'req_perms' => 'publish_stream,status_update,offline_access' )); the user is not being asked for the extended permissions- some digging has come up with fb now requesting you add these permissions in the facbeook developer app- under Authenticated Referrals- i added them in and still nothing anyone any ideas- without being able to post when a user completes an action my app is useless and am out of a job update- the new sdk requires different params- $loginUrl = $facebook->getLoginUrl(array('scope' => 'publish_stream,status_update,offline_access')); A: $loginUrl = $facebook->getLoginUrl(array( 'canvas' => 0, 'fbconnect' => 1, 'scope' => 'publish_stream,status_update,offline_access' )); req_perms key changed to scope A: Yes, you are correct, the new oauth2 requires you to define the requested permissions in the scope parameter.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549330", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Google Chrome doesn't follow a link then scroll to #tag Chrome fails to follow a link and then scroll. For example if I am on the home page of my website (nanite.com.au) and the user clicks a link that contains products.html#build or http://nanite.com.au/products.html#build it fails to redirect to the new page. However the address bar does change to http://nanite.com.au/index.html#products.html#build Is this Chrome or have I coded something incorrectly? Just to clarify, if I am on the products.html page the scrolling works perfectly. A: If you look in the javascript that you're using for the scrolling effect we find this: $(document).ready(function() { $('a[href*=#]').bind("click", jump); return false; }); Basically any link that has a # in it will be made to scroll instead of actually changing page. You need to change this so it looks for where href begins with #. So you would change it to: $(document).ready(function() { $('a[href^=#]').bind("click", jump); return false; }); Notice that $('a[href*=#]') has become $('a[href^=#]').
{ "language": "en", "url": "https://stackoverflow.com/questions/7549334", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Passing query expressions over the wire with WCF I want to implement something like a WCF OData provider but using NetTcpBinding instead of WebHttpBinding / REST. I want the client to be able to write linq queries that are transparently serialized and sent to the server (or potentially, multiple servers, to consolidate distributed database instances). One way to do this is to implement a custom IQueryable provider. You could pass the query expression over the wire in (at least) two ways: 1) Serialize the expression to xml, send it, and deserialize it on the server 2) Pass what is more-or-less the precursor to raw SQL to the server in the form of DataContracts 1 is difficult and simply alot of work, and 2 obviously could pose security risks (sql injection). Say for instance a 'Where' expression was encapsulated and passed to the server like so, [DataContract] public class WhereFilter { [DataMember] public string Property { get; set; } [DataMember] public string Operation { get; set; } [DataMember] public string Value { get; set; } } Where the above ultimately represents the part of an SQL query that states 'Where [SomeColumn] = 'SomeValue'. My question is whether the WCF client-server connection could be made secure enough to warrant such an approach without presenting too much of a security risk? Or alternatively if there are any other ways of implementing an OData-like provider over NetTcpBinding i'd be interested. A: I'd begin by trying the Expression Tree Serialization project. It aims to allow serialization of expressions, but I haven't used it to comment on how well it works. Failing that, then you could construct queries using a DataContract. There are risks but you can always exclude unwanted operations (e.g. UPDATE or DELETE the UserRole table) through database permissions. Your WCF service should connect to the database with a dedicated account, and that account should only have permissions to do what it needs (no CREATE or DROP, only SELECT from relevant tables, etc). And of course you can also secure your WCF connection to stop unwanted connections (see WCF Security Overview). One option is to require certificate authentication - only those users with the relevant certificate will be able to use the service.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549336", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How do I pass an object by value? import std.stdio; class IntegerContainer { public int Integer = 1; } void DoubleInteger(IntegerContainer Container) { Container.Integer *= 2; } void main() { IntegerContainer Container = new IntegerContainer; // Internal integer defaults to one. DoubleInteger(Container); // Internal integer changes to two inside the function. writefln(Container.Integer); // Prints "2." } In D, reference vs. value is a trait of the type, rather than of the function parameter. Coming from C++, this feels really bad to me. It looks like there's a ref keyword to force pass-by-reference for functions accepting structs. Is there such an equivalent for passing classes by value? For example, let's say I want to make a function function that returns a sorted copy of a custom container class. In C++, that's as simple as using Foo Sorted(Foo Object), as opposed to Foo Sort(Foo& Object). I see no way of doing this in D without manually copying the object. A: Yeah, just use a struct instead of a class. But if you want to copy an object, then you have to implement cloning yourself. Note that the D designers didn't make this up; it's the exact same way in C#, and pretty similar in Java. The goal is to prevent objects from being copied excessively, which is seen as a downside of C++ (since it's very hidden in the code). A: Even in C++ this: Foo Sorted(Foo Object) is not that useful. What if the Object is already sorted and you don't need to create a copy? In D you will need to provide clone() of some such for your class and call it if needed. Otherwise use structs as Mehrdad mentioned. Edit: It is not clear what exactly "copying the object" should do. If it has array of objects inside shall it clone that array? And what about object references it contains? It is actually good that monsieur Walter Bright, author of D, did not provide copying of class instances by default. A: Classes are reference types by design. They're not supposed to be passed by value. It's exactly the same with Java and C#. However, unlike Java and C#, D has full-fledged user-defined value types as well, since it has structs (C# has structs too, but they're much more limited). The fact that C++ conflates the two causes problems such as object slicing. Now, obviously there are times when you want to copy a reference type. The solution to that is cloning. You give your class a clone function which returns a copy of the object it's called on. That way, you can copy it when you need to, and it only gets copied when you need it to be. Java and C# have a standard clone function that most types implement, but for whatever reason D does not. I'm not sure why. But it's still easy enough to declare such a function yourself for your own types. It just isn't going to be on Object, which would allow you to use it on pretty much any class object without caring what the actual type was like you can do in Java and C#. You could always create a copy constructor instead, if you prefer, but it's less flexible, because you have to know the type of the object being copied, whereas with clone, it can be any type derived from the type that clone returns (which would be Object in the case of Java and C# but would be whatever you decide in D, since the function is non-standard).
{ "language": "en", "url": "https://stackoverflow.com/questions/7549338", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: php arrays get the order number of a certain element Lets say i have an array in PHP $test['michael_unique_id'] = 3; $test['john_unique_id'] = 8; $test['mary_unique_id'] = 10; . . . . $test['jimmy_unique_id'] = 4; (the values (3,8,10.........4) are unique) Lets say i want to search for the unique id 10, and get the order of the matching element in the array. In this example, the third element has the value 10, so i should get the number 3. I can do it by scanning with a for loop looking for the value i'm searching and then get the $i value when i have a match, but i wonder if there is any built-in function (or a better method) that implements this. A: You can get all of the array's values as an array with array_values() and then use array_search() to get the position (offset) of that value in the array. $uniq_id = 10; $all_vals = array_values($test); // => array(3, 8, 10, ... ) echo array_search( $uniq_id, $all_vals ); // => 2 Because PHP array indices are zero-based, you'll get 0 for the first item, 1 for the second item, etc. If you want the first item to be "1," then just add one. All together now: $uniq_id = 10; echo array_search( $uniq_id, array_values( $test ) ) + 1; // => 3 It's not clear to me, however, that this is necessarily as performant as just doing a foreach: $uniq_id = 10; $idx = 1; foreach($test as $val) { if($val == $uniq_id) { break; } $idx++; } echo $idx; // => 3 A: Well, array_search will give you the key, but in your case, you want the index of that key, so I believe a loop is your best bet. Is there a good reason why you need the index? It doesn't seem very useful to me.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549339", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Can't encode slash in URL http://myhost/MyController/DoSomething/Anything%252fAnything is a bad request http://myhost/MyController/DoSomething/Anything%2fAnything is the same as http://myhost/MyController/DoSomething/Anything/Anything What URL sends the string "Anything/Anything" to my controller? How to make Html.ActionLink to generate that URL? EDIT: It should be able to handle "Anything/Anything/Anything/Anything....../Anything" also I'm using MVC 3. A: If you want to define a route that defines variable lenght routes, you can use this kind of definition: routes.MapRoute("MyRoute", "{controller}/{action}/{id}/{*catchall}", new { controller = "Home", action = "Index", id = UrlParameter.Optional }); Put it before others route definitions in your global.asax.cs A: The routing machinery wants to handle the slashes. So add a routing rule such as url = [controller]/[action]/[id1]/[id2] See post Or use urls such as http://myhost/MyController/DoSomething/Anything?id2=Anything It may be possible to handle as a default--but in that case, the rules for the other routes will have to explicitly NOT match your controller/action name. Otherwise a prior rule will apply. It could also be that the entire url is available from a system var. Is your controller being called at all?
{ "language": "en", "url": "https://stackoverflow.com/questions/7549340", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: PHP strlen - appending numbers based on string length I am trying to append random numbers to different numbers of characters. Can anyone tell me why this isn't working? $userName = $_SESSION['username']; if(strlen($userName == 3)){ $userName = $userName . rand(000,999); } else if (strlen($userName == 4)){ $userName = $userName . rand(00,99); } else if (strlen($userName == 5)){ $userName = $userName . rand(0,9); } echo "<br>" . $userName; A: Change: if(strlen($userName == 3)) To: if(strlen($userName) == 3) And repeat that correction for the other 2 conditions. That will solve your syntax errors, but I would solve this problem a different way: while (strlen($userName) < 6) { $userName .= rand(0,9); } A: 000 is still 0. Instead, use sprintf() to explicity specify how many zeros you want. $missingLen = 6 - strlen($username); if($missingLen > 0) { $username = sprintf('%s%0'.$missingLen.'d', $username, rand(0, pow(10, $missingLen) - 1)); } A: Without knowing what did not work: try to explicitly cast the number to a string: $userName .= (string)rand(0, 999);
{ "language": "en", "url": "https://stackoverflow.com/questions/7549342", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: as2 loadmovie problem When I am use this mc is loaded. loadMovie("contact/contact.swf",1); But When I use this not load mc. example = "contact/contact.swf"; loadMovie(example,1); How can I do this? Thanks for answers. A: try: var example:String = "contact/contact.swf"; loadMovie(example,1);
{ "language": "en", "url": "https://stackoverflow.com/questions/7549343", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP Flush All Levels of Output Buffering I'm trying to implement a simple Http Response class that implements Http Streaming (or Chunked-Encoding). For this to be possible, I need to set output_buffering = Off in the php.ini, and flush the output at certain intervals. PHP does a good job of this automatically - except for the actual flushing mechanism. I've gotten it to work, but I'm not sure if it's overboard. I want to know how to flush each level of output buffering at once, without calling a billion functions (I'm not sure which ones are redundant on which environments / in which scenarios). while (ob_get_level()) { ob_end_flush(); } // print the buffer flush(); ob_flush(); Is this overkill? A: You don't need ob_flush() and ob_end_flush(). Your while loop is sufficient. You should also look at: http://us.php.net/manual/en/function.ob-implicit-flush.php Your need for flush() after ob_end_flush() depends on how you set this function.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549347", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: not converted to the button in latest Firefox I've been working with https://github.com/webtechnick/CakePHP-Facebook-Plugin Anyways, the output to the page in html shows fb:login-button but it doesnt get convereted to the actual facebook button in Firefox. I have the facebook html tag, the fb init() at the bottom of my page. It works in IE9 (haven't checked other browsers). So why isn't it being converted by the fb javascript? A: Turns out its because I was logged in on facebook on FF, and not on IE. The login button doesn't show if you are logged in. A: You may need to include the proper xml namespace in the html tag. Something like this: <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" xmlns:fb="http://www.facebook.com/2008/fbml" xmlns:og="http://opengraphprotocol.org/schema/" lang="en">
{ "language": "en", "url": "https://stackoverflow.com/questions/7549348", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: HTML5 clearRect dont work Hello could somebody tell me wath is wrong with my code. When i do the clear rect, it's doesn't work. I just try to move the ball in the canvas. Actually my ball leave a mark. This kind of line is leave. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <script src="_js/jquery1.6.js" type="text/jscript"></script> </head> <body> <canvas id="dropBall" width="400" height="400"></canvas> <script> var dropBall = $("#dropBall")[0]; var dropContext = dropBall.getContext("2d"); dropContext.fillStyle = "green"; var ballX = 200; var ballY = 200; function activeBall() { dropContext.clearRect(0, 0, dropBall.width, dropBall.height); dropContext.arc(ballX, ballY, 10, 2 * Math.PI, 0, true); dropContext.fill(); ballY--; ballX++; var time = 100; setTimeout("activeBall()", time); } activeBall(); </script> </body> A: Shouldn't it be: dropContext.clearRect(ballX,ballY,dropBall.width,dropBall.height); or am I misunderstanding something? If you do it the other way around, then the only rectangle getting cleared is the square from (0,0) to (width of ball,height of ball). EDIT: It actually might be dropContext.clearRect(ballX-(dropBall.width/2),ballY-(dropBall.height/2),dropBall.width,dropBall.height); If your ball is centered at ballX. EDIT EDIT: I fixed it for you: function activeBall() { dropContext.clearRect(ballX-(dropBall.width/2),ballY-(dropBall.height/2),dropBall.width,dropBall.height); dropContext.beginPath(); dropContext.arc(ballX, ballY, 10, 2 * Math.PI, 0, true); dropContext.fill(); ballY--; ballX++; var time = 100; setTimeout("activeBall()", time); } * *You were clearing a rectangle on the top-left corner of your canvas. *You have to call beginPath() and then do all your drawing work. Clearing has to be called outside of beginPath() and fill(). The specific lines are: dropContext.clearRect(ballX-(dropBall.width/2),ballY-(dropBall.height/2),dropBall.width,dropBall.height); dropContext.beginPath(); A: Your Document DocType is wrong For HTML5 try <!DOCTYPE HTML> This can cause mis-behavior from some browsers.. some html resources... http://simon.html5.org/html-elements http://www.w3schools.com/html5/tag_doctype.asp
{ "language": "en", "url": "https://stackoverflow.com/questions/7549356", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: "java" succeeds," java emmarun" fails Disclaimer: I am new to java and emma. Details: * *I installed emma, and have worked through some of the examples. No problems. *I have a java project with a number of files that I wish to get a coverage report. *I type "javac -d out *.java". No errors. *I type "java -cp out Main". The program runs fine and I get the expected output. *I type "java emmarun -cp out Main". I get the following: emmarun: [MAIN_METHOD_NOT_FOUND] application class [Main] does not have a runnable public main() method Exception in thread "main" com.vladium.emma.EMMARuntimeException: [MAIN_METHOD_NOT_FOUND] application class [Main] does not have a runnable public main() method at com.vladium.emma.rt.AppRunner._run(AppRunner.java:546) at com.vladium.emma.rt.AppRunner.run(AppRunner.java:97) at com.vladium.emma.runCommand.run(runCommand.java:247) at emmarun.main(emmarun.java:27) Caused by: java.lang.IllegalAccessException: Class com.vladium.emma.rt.AppRunner$Invoker can not access a member of clas s Main with modifiers "public static" at sun.reflect.Reflection.ensureMemberAccess(Unknown Source) at java.lang.reflect.AccessibleObject.slowCheckMemberAccess(Unknown Source) at java.lang.reflect.AccessibleObject.checkAccess(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at com.vladium.emma.rt.AppRunner$Invoker.run(AppRunner.java:655) at java.lang.Thread.run(Unknown Source) My "Main.java" file looks like this: public class Main { public static void main( String[] args ) { NetworkSimplexTest nst = new NetworkSimplexTest(); nst.test(); } } I would post all the code, but it is rather lengthy. The simpler examples I tried work fine - emma automatically instruments and creates a coverage report, just like in the examples. It appears that Emma cannot find my "Main", but regular java can. What am I missing? A: Emma will expect the class to be defined as public, which was missing in your original code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549362", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: asp.net MVC3 global route and hardcoded routes I have an application that I am using a global route to query for the current path and return page specific data. I have the routes setup like this... routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Pages", "Pages", new { controller = "Pages", action = "Index" }); routes.MapRoute( "Navigation", "Navigation", new {controller = "Navigation", action = "Index"}); routes.MapRoute( "Default", // Route name "{*url}", // URL with parameters {controller}/{action}/{id} new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults ); The problem I am facing is when I go to /Pages to try and add new pages, the PageController fires like it is supposed to, but when debugging, after going to /Pages the app then makes a request for the HomeController. Am I missing something in my routing setup? A: The Default route is firing because of the {*url}. So any page that's not /Pages, will go to the default route. I need more info, but if you're trying to do /Pages/whatever, then you need to add an optional parameter on your Pages route: routes.MapRoute( "Pages", "Pages/{page}", new { controller = "Pages", action = "Index", page = UrlParameter.Optional }); A: Your default route is incorrect. It should look like the default route as defined when you open a new MVC 3 project, like so: routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults ); The problem is that the default route you defined will not parse any requests which reach it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549364", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to Get the Authorization header from wcf request interceptor I need to authenticate every request to wcf services public class AuthenticationInterceptor : RequestInterceptor { public AuthenticationInterceptor() : base(false) { } public override void ProcessRequest(ref System.ServiceModel.Channels.RequestContext requestContext) { //How to access Request Header (Authorization header) from here? } } A: You can get the headers from the System.ServiceModel.Channels.Message, so try var message = requestContext.RequestMessage; var request = (HttpRequestMessageProperty)message.Properties[HttpRequestMessageProperty.Name]; string authorization = request.Headers[HttpRequestHeader.Authorization];
{ "language": "en", "url": "https://stackoverflow.com/questions/7549368", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: preg_replace() Question Currently, I'm using the following code: preg_replace('/\s+/m','<br>',$var); to replace line ends with <br> elements. An example of what I want: Text Text Text Text Text Text Text Text Text Should end up being: Text Text Text<br>Text Text Text<br><br>Text Text Text This does what it needs to, but I'd like to recognize when there is a double space and add two breaklines, instead of a single one. How can I do this, while retaining the current effect for single break lines? I'm not too familiar with how preg_replace() works and I actually had to get help here to get that function in the first place. I took a look in the PHP manual and the function seemed a little confusing. Would anyone know of a site where I could learn how it works correctly? A: you can do this by adding the g-modifier to the preg_replace like so: preg_replace('/\s+/mg','<br>',$var); preg stands for Perl Regular Expression - you'll find a lot more examples with this search string, e.g. this site or this site (I'm actually unsure, what the m-modifier does?) Alternatively, you could use the simple $var = str_replace(' ', '<br', $var). I'm unsure, which one is faster. Edit: If you want to replace newlines with html-breaks, use the nl2br() function. A: php has a built in function for this echo nl2br( $var ); this does \n, \r\n, \r, and \n\r http://www.php.net/manual/en/function.nl2br.php A: You can simply replace each end-of-line character with <br />: $var = str_replace(array("\r\n", "\n"), '<br />', $var); There is no need to use a regular expression, but if you really want, you can use preg_replace to achieve the same effect: $var = preg_replace("/\r?\n/", '<br />', $var); A: Check out this one. Not sure you are asking for that, but at least it works for me $input = <<<DOC Test Test Test Test Test Test Test Test Test DOC; $output = preg_replace("/$/m","<br/>",$input); echo $output; Hovewer, nl2br does just the same. A: Is this what you’re trying to do? <?php $text = <<<EndText Text Text Text Text Text Text Text Text Text EndText; $text = str_replace("\r", "", $text); $text = str_replace("\n", "<br>", $text); echo $text; ?>
{ "language": "en", "url": "https://stackoverflow.com/questions/7549369", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Eclipse launch shortcuts for debug history The Run > Debug History menu item in Eclipse (Helios) contains a MRU list of debug history. These items are numbered from 1 to N suggesting that there is probably some keyboard shortcut or keyboard sequence I should be able to enter to relaunch a previous program but I cannot figure out what they might be. Specifically, if I want to relaunch the debug history item number 2, what must I type to use this feature? I know that there is the Window > Preference > General > Key settings page which lists the "Debug Android Application binding "Alt+Shift_A, D". This seems like exactly what I want but I can't seem to use it or rebind it to some custom key combination that works for me. Please tell me how to most easily relaunch Android apps in the debugger? A: One alternative is to use the accelerator keys to navigate the menu. On my computer it is: Alt + R, H, Number Alt+R gets you to get to Run menu, then H for Debug History, then one of the numbered alternatives. To make a run configuration always be visible in the Debug or Run history menus one can do the following: Select the Run menu → Run Configurations → [some config] → Common, then check Display in favourites box. A: For macOS users, you can make use of the menu search function: Cmd+Shift+/ (Cmd+?) => type: d h 1 and it will match Run > Debug History > 1
{ "language": "en", "url": "https://stackoverflow.com/questions/7549371", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Set a custom template variable in expressionengine I need to output the category for an entry a few times in an entry's template. So I want to get the output from the following and assign to a variable so I can reuse within the template: {exp:channel:entries channel="product" limit="1" status="open"} {categories}{category_name}{/categories} {/exp:channel:entries}" How do it do that? A: Now, you could enable the template to allow PHP, then you could write something like this: {exp:channel:entries channel="product" limit="1" status="open"} {categories} <?php $category = '{category_name}'; ?> {/categories} {/exp:channel:entries} Then you have the {category_name} stored in the php-variable "category". Later you can reuse it as you wish, like echoing it: <?php echo $category; ?> You can even compare it to other EE-tags: {exp:channel:entries channel="product" limit="1" status="open"} {if <?php $echo($category) ?> == title} This title have got the same value as the category! {/if} {/exp:channel:entries} A: Croxton's Stash: http://devot-ee.com/add-ons/stash does very nearly the same thing NSM Transplant (mentioned by Derek, above) does, and is free. One of these addons would definitely be the easiest way to do what you're trying to do. A: EE has no built-in way to save data from within a tag loop and reuse it elsewhere in the template, outside of that tag loop. One solution would be to use NSM Transplant to do exactly what you're looking to do. Another would be to wrap your whole entry page in your channel:entries tag, so you can just use the categories loop wherever you need it, then use embeds for anything that can't be nested inside channel:entries.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549372", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Adding two Xpath with union in PHP function? With the code below I show the titles of many RSS. Those RSS must be in the format of rss->channel->item where in the item you find title,description, pubDate and so on. My question is how to modify this, so It will also accept RSS that are in the format of feed->entry where in the entry you echo title,content,published? $feeds = array('', ''); // Get all feed entries $posts = array(); foreach ($feeds as $feed) { $xml = simplexml_load_file($feed); $posts = array_merge($posts, $xml->xpath('/rss/channel//item')); } // Sort feed entries by pubDate (ascending) usort($posts, 'mysort'); function mysort($x, $y) { return strtotime($y->pubDate) - strtotime($x->pubDate); } foreach ($posts as $post) { echo $post->description; // if the rss is in the format of rss->channel->item echo $post->content; // if the rss is in the format of feed->entry->content then } A: Use the XPath union (|) operator: /rss/channel/item | /rss/feed/entry For the sort use: published | pubDate Explanation: Union of mutually exclusive sets results in just one of them. A: If entry is directly under feed, change the XPath query from /rss/channel//item to /feed/entry. (If it isn't, you'll need /feed//entry; note the double backslash.) You'll also have to change the sorting function; I assume you'll want to sort according to published: return strtotime($y->published) - strtotime($x->published); Finally, modify the foreach loop to spit out the values you're interested in: foreach ($entries as $entry) { echo $entry->title; echo $entry->content; echo $entry->published; } A: You could run 2 xpath's. If the first doesn't return any results, you try the second. That may be the easiest and most pragmatic. A: This is what I wanted return strtotime(($y->pubDate)?$y->pubDate:$y->published) - strtotime(($x->pubDate)?$x->pubDate:$x->published);
{ "language": "en", "url": "https://stackoverflow.com/questions/7549376", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Windows Active Directory Emulator Is there a LDAP server emulator or a Windows Active Directory emulator, I'm talking something in the lines of smtp4dev which doesn't have to be configured and just work for a development environment in order to test authentication code. A: I suspect you might want to try Active Directory Lightweight Directory Services (AD LDS), formerly known as Active Directory Application Mode (ADAM).
{ "language": "en", "url": "https://stackoverflow.com/questions/7549378", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: HTML image map outside an image I have to generate <map> and <area> elements on a web page containing many images. Each image would have to be linked to its appropriate <map> via usemap="#map1", usemap="#map2", etc... As a nasty hack for this situation, I'd like to add one 1x1 absolutely positioned (top:0, left:0) <img> (the anchor-image). Then, I'd combine all the <area> tags into one <map> (the super-map), referenced by the anchor-image. Trying this, the <area> tags defined in the super-map do not activate when I mouseover them (they are outside of the 1x1 anchor-image). I tried making anchor-image width:100%, height:100% and playing with its z-index (I still have to interact with the images on the page for other reasons). Unfortunately, when the z-index makes the <area> elements clickable, it stops me from interacting with the images. Any ideas on what else I can try? Thanks! A: Can you elaborate on why you need so many maps? If you have a lot of images, why not split each one into a single action and simply place them in a tags? Or, why not combine the images into a larger one and then have fewer maps?
{ "language": "en", "url": "https://stackoverflow.com/questions/7549380", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Trying to set up a countdown timer in Android through multiple Activites I'm trying to create a app for airports, that the top line will always display a countdown timer to when the plane leaves. This is the code I had. This class is declared in each activity class. /countdowntimer is an abstract class, so extend it and fill in methods: public class MyCount extends CountDownTimer{ public MyCount(long millisInFuture, long countDownInterval) { super(millisInFuture, countDownInterval); } @Override public void onFinish() { tv.setText(”done!”); } @Override public void onTick(long millisUntilFinished) { tv.setText(”Left: ” + millisUntilFinished/1000); } } But I wanted it to run on all the activities. I was thinking about having the notification manger to start a thread every 10 seconds, but I cannot access the UI memory on its thread. Does anybody have a good solution to how to do this?
{ "language": "en", "url": "https://stackoverflow.com/questions/7549383", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: EER : Superclass/subclass Entity relationship, primary key mapping Here is the scenario. STUDENT, FACULTY are sub-classes of PERSON entity, and they have specialized attributes. Normally, we store common attributes in PERSON table (with p_id as pk) and store specialized in the subclasses. We map the subclass to the superclass using p_id by creating a column in the subclass. However, is it acceptable to do something like following. Instead of p_id as the mapping attribute in subclass, can we use something else belonging to the superclass which is unique but not pk. NOTE: The EER Diagram (conceptual design) still remains same! A: It's just a foreign key, even for supertype/subtype schemas. You can reference any column that's declared UNIQUE. I'm pretty sleepy, so I'm not sure how that would affect the updatable views. I don't think it would affect them, though. (Assuming you're using them. Some don't bother.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7549392", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is it a code smell that a repository has change events? I've not seen change events being used in repository pattern implementations, but I'd like to have my repository like this: interface IEntityRepository { event EventHandler<EntityChangedEventArgs> EntityAdded; event EventHandler<EntityChangedEventArgs> EntityRemoved; IEnumerable<Entity> GetAll(); Entity GetById(int id); } This is largely because my entities can be added and removed from the outside only, and not by the client of IEntityRepository. Am I thinking fundamentally wrong about the repository pattern by doing like this, or do I have a valid case? A: I'd say yes, if you intend to use Fowler's actual Repository Pattern. That pattern is intended to be a mediator between business and data layers by exposing a collection-like interface. It was not intended to actually hold data. That said, if you merely want to create a collection that wraps an API and exposes events when things change, by all means do so. Sometimes you don't need to follow a predefined pattern. If you want it to be a pattern, I'd say it looks more like an Object Pool or Observer pattern. Consider the case of IObservable using Reactive Extensions (Rx). It would allow you to react to the PInvoke layer, and force your responsibilities down the line. The code actually winds up being more effective than events. By using events, you have to maintain this repository, keep track of object lifetime, probably make this repository a singleton and give it some thread management. With Rx, you simply push an action on the observer's queue. But in the end, use whatever feels most natural to you. Patterns are just suggestions, and don't always exist for every potential use case. This is one of those cases. A: I have a similar issue where I need to publish events to an event store for CUD operations against a database (not concerned about Read operations). Rather than modify my repo I instead created a decorator and injected it (using SimpleInjector). That satisfies the Open/Closed principle and Single Responsibility, and actually it's provided a much cleaner way to handle that requirement.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549394", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Only Allow IMDB LINK REGEX solution PHP I want a regex solution to allow only http://www.imdb.com/title/ttANYNumberWOrdetc/ links Otherwise SHOW us error.. Incorrect link I am not too good with regex I just create this petren .. preg_match('/http:\/\/www.imdb.com\/title\/(.*)\//is', 'http://www.imdb.com/title/tt0087469/', $result); Its show me corect result but i think i missed some thing.. Thanks, A: How about something like this: http://(?:www\.)?imdb.com/title/tt[^/]+/. Example: <?php if ( preg_match('#^http://(?:www\.)?imdb\.com/title/tt[^/]+/$#', 'http://www.imdb.com/title/tt0448303/') ) echo 'Matches' . PHP_EOL; Explanation: The regular expression matches a string that starts with http:// followed either by imdb.com or www.imdb.com, then /title/tt followed by any character except for a / and that ends with a /. The # is the delimiter, the ^ indicated the beginning of the string and the $ the end. A: This should work: if (preg_match("#^(http://www.|https://www.)imdb.com/title/tt([a-zA-Z0-9]+)(?:/)(?:^[a-zA-Z0-9]+)?$#s", 'http://www.imdb.com/title/tt0364845/', $matches)) { echo 'yay'; } else { echo 'nay'; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7549401", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to program in Windows 7.0 to make it more deterministic? My understanding is that Windows is non-deterministic and can be trouble when using it for data acquisition. Using a 32bit bus, and dual core, is it possible to use inline asm to work with interrupts in Visual Studio 2005 or at least set some kind of flags to be consistent in time with little jitter? Going the direction of an RTOS(real time operating system): Windows CE with programming in kernel mode may get too expensive for us. A: There are third-party realtime extensions to Windows. See, e. g. http://msdn.microsoft.com/en-us/library/ms838340(v=winembedded.5).aspx A: Real time solutions for Windows such as LabVIEW Real-time or RTX are expensive; a stand-alone RTOS would often be less expensive (or even free), but if you need Windows functionality as well, you are perhaps no further forward. If cost is critical, you might run a free or low-cost RTOS in a virtual machine. This can work, though there is no cooperation over hardware access between the RTOS and Windows, and no direct communication mechanism (you could use TCP/IP over a virtual (or real) network I suppose. Another alternative is to perform the real-time data acquisition on stand-alone hardware (a microcontroller development board or SBC for example) and communicate with Windows via USB or TCP/IP for example. It is possible that way to get timing jitter down to the microsecond level or better. A: Windows is not an RTOS, so there is no magic answer. However, there are some things you can do to make the system more "real time friendly". * *Disable background processes that can steal system resources from you. *Use a multi-core processor to reduce the impact of context switching *If your program does any disk I/O, move that to its own spindle. *Look into process priority. Make sure your process is running as High or Realtime. *Pay attention to how your program manages memory. Avoid doing thigs that will lead to excessive disk paging. *Consider a real-time extension to Windows (already mentioned). *Consider moving to a real RTOS. *Consider dividing your system into two pieces: (1) real time component running on a microcontroller/DSP/FPGA, and (2) The user interface portion that runs on the Windows PC.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549402", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Check files in current directory How can I tell python to scan the current directory for a file called "filenames.txt" and if that file isn't there, to extract it from a zip file called "files.zip"? I know how to work zipfile, I just don't know how to scan the current directory for that file and use if/then loops with it.. A: import os.path try: os.path.isFile(fname) # play with the file except: # unzip file A: import os, zipfile if 'filenames.txt' in os.listdir('.'): print 'file is in current dir' else: zf = zipfile.ZipFile('files.zip') zf.extract('filenames.txt') A: From the documentation $ pydoc os.path.exists Help on function exists in os.path: os.path.exists = exists(path) Test whether a path exists. Returns False for broken symbolic links
{ "language": "en", "url": "https://stackoverflow.com/questions/7549403", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: BASH script to pass variables without substitution into new script As part of a system build script I have a script that creates various files and configurations. However one part of the build script creates a new script that contains variables that I don't want resolved when the build script runs. Code snippet example cat - > /etc/profile.d/mymotd.sh <<EOF hostname=`uname -n` echo -e "Hostname is $hostname" EOF I have tried all sorts of combinations of ' and " and ( and [ but I cannot get the script to send the content without substituting the values and placing the substitutes in the new script rather than the original text. Ideas? A: The easiest method, assuming you don't want anything to be substituted in the here doc, is to put the EOF marker in quotes, like this: cat - > /etc/profile.d/mymotd.sh <<'EOF' hostname=`uname -n` echo -e "Hostname is $hostname" EOF A: Easiest is to escape the $ echo -e "Hostname is \$hostname"
{ "language": "en", "url": "https://stackoverflow.com/questions/7549404", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: What platform(s) to use for developing an audio mixing web app? I am working on a browser-based application that is essentially a Digital Audio Workstation. I've seen one out there (at http://www.indabamusic.com), and it looks like it is a Java applet. Is a Java applet the best way to do this? I've read that C++ is generally more widely used for audio programs, and I've looked at Wt ( http://www.webtoolkit.eu/wt/) for a web interface option but it doesn't seem to be meant for this kind of use (correct me if I'm wrong). I have almost no experience with C++, so I might just be biased. A: You either want a java applet or to do it in Flash (perhaps Flex). It is generally messy to get C++ bits deployed broadly in a browser.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549408", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Counting number of unique pairs and instances of non-unique pairs in unsorted data I have data in the form of: ID ATTR 3 10 1 20 1 20 4 30 ... ... Where ID and Attr are unsorted and may contain duplicates. The range for the IDs are 1-20,000 or so, and ATTR are unsigned int. There may be anywhere between 100,000 and 500,000 pairs that I need to process at a single time. I am looking for: * *The number of unique pairs. *The number of times a non-unique pair pops up. So in the above data, I'd want to know that (1,20) appeared twice and that there were 3 unique pairs. I'm currently using a hash table in my naive approach. I keep a counter of unique pairs, and decrement the counter if the item I am inserting is already there. I also keep an array of IDs of the non-unique pairs. (All on first encounters) Performance and size are about equal concerns. I'm actually OK with a relatively high (say 0.5%) rate of false positives given the performance and size concerns. (I've also implemented this using a spectral bloom) I'm not that smart, so I'm sure there's a better solution out there, and I'd like to hear about your favorite hash table implementations/any other ideas. :) A: A hash table with keys like <id>=<attr> is an excellent solution to this problem. If you can tolerate errors, you can get smaller/faster with a bloom, I guess. But do you really need to do that?
{ "language": "en", "url": "https://stackoverflow.com/questions/7549410", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Logging in Scala: what to use when writing a library There are questions (here and here) about what library to use for logging in Scala, but I'd like to ask a more specific version of the question. When you're writing a library - ie some code that will become part of lots of different applictions - you don't have as much freedom to choose what you'd like to use. If you use a different logging solution from the one used in the rest of the application, then the poor application developer has to look in two (or more) places for his debugging information. So ideally you want to use something compatible with the most used solutions. Of the many logging solutions out there, a lot of them seem to go via slf4j. Does that mean any solution using slf4j would be best? Or slf4s? A: Yes, use SLF4J or a Scala wrapper around it. That way your clients get to choose the actual implementation of the logging. From this perspective it doesn't make any difference if you use a wrapper or the SLF4J API directly. The only real alternative is common.logging, but it has been effectively superseded. A: I would recommend log4j. It is quite popular and very flexible. I use it like this: java -Dlog4j.configuration=log4j.txt -cp .:app_name.jar com.your.program.Main with the config file in the local dir as: log4j.rootLogger=WARN, stdout, R log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout # Pattern to output the caller's file name and line number. log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n log4j.appender.R=org.apache.log4j.RollingFileAppender log4j.appender.R.File=example.log log4j.appender.R.MaxFileSize=100KB # Keep one backup file log4j.appender.R.MaxBackupIndex=1 log4j.appender.R.layout=org.apache.log4j.PatternLayout log4j.appender.R.layout.ConversionPattern=%d{ISO8601} %p %t %c - %m%n log4j.logger.com.your.program=DEBUG
{ "language": "en", "url": "https://stackoverflow.com/questions/7549415", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Marking view as dirty from another class Right now I'm building a game for Android. I have a class game.java that calls board.xml as it's view. Board.xml has the following: ... //Score info <edu.xxx.yyy.zzz.BoardView android:layout_height="wrap_content" android:layout_width="fill_parent" android:layout_weight="1"/> ... //pause button ... //submit button BoardView is a Java class that extends View and is used to draw the game board. Everything is being displayed correctly. I want to know if I can implement code in game.java that can mark areas of BoardView as dirty (namely after I hit that Submit button which changes some global variables). A: Give the BoardView an id in xml with the attribute android:id="@+id/myBoardView" Then just grab the BoardView using findViewById BoardView myBV = (BoardView) findViewById(R.id.myBoardView); Then simply mark the areas dirty that you want to be made dirty by using the invalidate method myBV.invalidate(); //invalidates the entire BoardView or Rect dirty = new Rect(...); myBV.invalidate(dirty); //marks the area defined by dirty as dirty or int left = 0; int right = 10; int top = 0; int bot = 10; myBV.invalidate(left, top, right, bot); //invalidates the area defined by these coords as dirty
{ "language": "en", "url": "https://stackoverflow.com/questions/7549419", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I chain methods in PHP? jQuery lets me chain methods. I also remember seeing the same in PHP so I wrote this: class cat { function meow() { echo "meow!"; } function purr() { echo "purr!"; } } $kitty = new cat; $kitty->meow()->purr(); I cannot get the chain to work. It generates a fatal error right after the meow. A: Place the following at the end of each method you wish to make "chainable": return $this; A: To answer your cat example, your cat's methods need to return $this, which is the current object instance. Then you can chain your methods: class cat { function meow() { echo "meow!"; return $this; } function purr() { echo "purr!"; return $this; } } Now you can do: $kitty = new cat; $kitty->meow()->purr(); For a really helpful article on the topic, see here: http://www.talkphp.com/advanced-php-programming/1163-php5-method-chaining.html A: Just return $this from your method, i.e. (a reference to) the object itself: class Foo() { function f() { // ... return $this; } } Now you can chain at heart's content: $x = new Foo; $x->f()->f()->f(); A: yes using php 5 you can return object from a method. So by returning $this (which points to the current object), you can achieve method chaining
{ "language": "en", "url": "https://stackoverflow.com/questions/7549423", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "23" }
Q: CSS dimming overlay I have a fullscreen (100% width and height) div that has a 60% opacity for the android browser (on a z index). On top of it, i have a form. However, everytime i try to open up the keyboard to enter any text, it seems like the keyboard is trying to push the div upwards, and it eventually just fails with the keyboard not opening up, or push the page to the very bottom. (Cyanogen mod behaviour) On android 2.2 with HTC sense, the behaviour is similar, on top of that, the input textbox will have another instance of itself directly above the textbox. Any idea how to avoid this type of behaviour?
{ "language": "en", "url": "https://stackoverflow.com/questions/7549427", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jQueryUI accordion causes wrapping when using the icon Using the baic redmond theme from jQueryUI, my accordians are not sitting right. I thought something in my stylesheet was causing issues, but I removed it and it is still funky. I stripped it way, way back to this and it's still wrapping the triangle icon and text on 2 x lines. <!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Nodes</title> <link rel="stylesheet" type="text/css" href="/DFCx/css/jQueryUI_redmond/jquery-ui-1.8.16.custom.css" /> <script type="text/javascript" src="/DFCx/js/jquery-1.6.2.min.js"></script> <script type="text/javascript" src="/DFCx/js/jquery-ui-1.8.16.custom.min.js"></script> <script type="text/javascript" src="/DFCx/js/page/Nodes/view.js"></script> </head> <body> <div id="accordion" class="accordion"> <h3>Title</h3> <div>junk</div> <h3>Title</h3> <div>junk</div> <h3>Title</h3> <div>junk</div> <h3>Title</h3> <div>junk</div> </div> </body> </html> The accordion script (view.js) just has: $( "#accordion" ).accordion({ autoHeight: false, collapsible: true, header: 'h3' }); The accordion works perfectly, opens, closes, fits and so forth, it just wraps the h3 when it puts the icon in place! see http://i.imgur.com/1fwD2.png for a screenshot sample of the result When I use "icons: false" in the accordion config it leaves the icons off and works as expected, but I'd like to have them there! Tried different UI stylesheets (overcast etc.) and all the same problem in different colours. Is there something I'm missing? -- update (not sure if it's a solution yet tho) In the jQueryUI css file was this line: .ui-icon { display: block; text-indent: -99999px; overflow: hidden; background-repeat: no-repeat; } which I edited to be .ui-icon { display: block; float: left; text-indent: -99999px; overflow: hidden; background-repeat: no-repeat; } (note added float:left;) This has fixed the icon positioning in the headings, and works a treat. Fingers crossed that it doesn't have any nasty flow-on affects for other icons :( A: Your titles should be wrapped in an <a> tag as well: <h3><a href="#">Title</a></h3> A: I have the same issue, and I used this to correct it: /* correct accordion headers*/ .ui-accordion-header span{ position: absolute; } .ui-accordion-header a { margin-left: 20px; } A: It may be that the generated CSS you're using does not include styles for accordions. Try to use a different CSS, for example, this one: http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.5/themes/base/jquery-ui.css. Or, choose the theme you are using from this page: http://blog.jqueryui.com/2010/09/jquery-ui-1-8-5/. You still need to ensure you style the accordion headers as documented (and suggested by Larry): <div id="accordion"> <h3><a href="#">First header</a></h3> <div>First content</div> <h3><a href="#">Second header</a></h3> <div>Second content</div> </div> A: What worked for me is the combined solution by @ton and @LarryLustig. * *Your titles should be wrapped in an <a> <h3><a href="#">Title</a></h3> *Style in page .ui-accordion-header span{ position: absolute; } .ui-accordion-header a { margin-left: 20px; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7549431", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Sencha Touch-- List in TabPanel not working So, I just started working with Sencha Touch. I want to include a list in a TabPanel but for some reason it isn't working. Please help. Thanks! HTML: <!DOCTYPE html> <html> <head> <title>Hello World</title> <script src="lib/touch/sencha-touch.js" type="text/javascript"></script> <script src="app/app.js" type="text/javascript"></script> <script src="app/rosterData.js" type="text/javascript"></script> <link href="lib/touch/resources/css/sencha-touch.css" rel="stylesheet"type="text/css" /> <link href="app/myAppStyle.css" rel="stylesheet" type="text/css" /> </head> <body></body> </html> Javascript: MyApp=new Ext.Application({ name: 'MyApp', launch: function() { MyApp.tabbedView= new Ext.TabPanel({ cardSwitchAnimation: 'slide', tabBar: { dock: 'bottom', layout: { pack: 'center' } }, items: [{ title: "Schedule", cls: 'card', iconCls: 'time', style: "background-color: #000", }, { title: "Roster", layout: 'fit', cls: 'card', iconCls: 'team', xtype: 'list', store: MyApp.RosterStore, itemTpl: '<div class="contact"><strong>{firstName}</strong> {lastName}</div>' style: "background-color: #aaa", }, { title: "Info", html: "Bye", cls: 'card homeScreen', iconCls: 'info', style: "background-color: #aaa", } ] }); Ext.regModel('PlayerName', { fields: ['firstName', 'lastName'] }); MyApp.RosterStore= new Ext.data.Store({ model: 'PlayerName', data: [ {firstName: "Shivam", lastName: "Thapar"}, {firstName: "Last", lastName: "First"}, {firstName: "Bob", lastName: "Smith"} ] }); MyApp.Viewport= new Ext.Panel({ fullscreen: true, layout: 'fit', style: "background-color: #fee", items: [MyApp.tabbedView] }); } }); A: Try putting your model and store definitions above the TabPanel definition. Model first Store next and then TabPanel
{ "language": "en", "url": "https://stackoverflow.com/questions/7549432", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do you hide your php source code? I have a php page which contains keys and salts and I would like to hide such information just in case. Anyone know a good free software that could do this? I have both zend and ion installed on my server, which I heard some source scramblers use. Any ideas? A: Your PHP source cannot be viewed directly via browser. You can obfuscate the php files on the server for extra protection. Obfuscation makes it more difficult for an attacker to understand your code, if he eventually gets in. Remember to keep an un-obfuscated back-up of your files. Check Out Obf http://www.pipsomania.com/best_php_obfuscator.do Zend Guard Or just search for http://www.google.com.ng/search?sourceid=chrome&ie=UTF-8&q=php+obfuscator
{ "language": "en", "url": "https://stackoverflow.com/questions/7549433", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Alternatives to Stateful Parsing I don't like stateful parsing. It seems to me there should be a better approach. Is there? Let me illustrate by example. Let's say I'm parsing a text file (YAML in this case, but it could be plain-text or XML. I'm making a simple trivia game; my game will contain sets of questions, each with two or more answers. In YAML, I might structure my file like: set: name: math questions question: text: 1 + 1 = ? answer: 3 answer: 4 best-answer: 2 question: text: 2 * 3 = ? answer: 5 best-answer: 6 set: name: chemistry questions question: text: the valence of a Chlorine free radical is? answer: 1 answer: 0 best-answer: -1 question: text: Xeon is a noble gas best-answer: true answer: false (I haven't used YAML in a while, apologies if it's pseudo-YAML.) When I'm parsing, if I read the current line and see "answer: ...," I have to know that I'm in the answer of a question of a set. This tends to be very stateful code, like: if (currentLine starts with "answer") currentQuestion.addAnswer(...) else if (currentLine starts with "question") currentQuestion = new question ... At any point in the parsing, we need a reference to the current object, which may be nested within several other objects. Part of the problem might be that my main loop iterates over each line, line by line. An alternative approach might be to just read the line, and depending on what it is, read several more lines as necessary. So again, my question: is there a stateless way to parse data? I have a feeling that an approach might exist that would be more clear and easier to read/understand/code than my usual stateful for-loops over all lines of text. A: You're apparently looking not for a "stateless" parsing, but for a non-imperative, pure functional parsing. Of course there is always a state of a sort, but with a functional approach your state is entirely implicit. Take a look at "Functional pearls: monadic parsing in Haskell" article, and check out various Parsec-like parsing combinators libraries, which exist for even so very imperative languages like Java and C++. A: What you describe is a more or less state machine driven parsing approach: you iterate over lines of the file, and a state variable keeps track of where in the parse tree you are. You might find it easier and cleaner to use recursive descent parsing, in which much of the state is implicit, in the form of the program stack. As others point out, parsing is inherently stateful, but recursive descent lets you keep less state explicitly. A: An alternative approach might be to just read the line, and depending on what it is, read several more lines as necessary. You just described "given a certain state, do something." That is, a stateful approach. So again, my question: is there a stateless way to parse data? Parsing is inherently stateful. The meaning of the data depends on the context. The context is the state. There's a reason that an introductory course in compilers starts with finite-state machines. A: The very concept of parsing implies that some pieces are one type of token, others are another, and others aren't valid at all. How are you going to know that without maintaining some kind of state that says "ok, i'm parsing a foo right now...this is what i should have here"?
{ "language": "en", "url": "https://stackoverflow.com/questions/7549437", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Catch onclick adsense event ? I wan't to send an ajax request if the user clicked on adsense . But because adsense code is in iframe I can't find a way to catch the onclick event .. any ideas plz ??! A: The simple answer is that you can't. Since adsense is likely on another domain, most access to the inside of the iframe is cut off. This is a cross-domain security feature built into all modern browsers. You may be able to catch the click event on the iframe (haven't personally tried before), but it's not going to tell you anything about the inside of the iframe.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549439", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: android long running service without notification I see this example with programs like Advance Task killer, Watch Dog, eBay, battery widgets, ect. There is a background service running that monitors device activity, a broadcastreceiver, but there is an option to disable the notification icon displayed. Currently my application works flawlessly by calling: Context context = getApplicationContext(); Intent intent = new Intent(context, SomeBackGroundService.class); context.startService(intent) and then in my service I am calling: startForeground(NOTIFICATION_ID, notification); Now how is it that these other applications can have a long running broadcastreceiver running without a notification icon? What do I need to do in order to disable/set ect as to hide the icon and add this feature to my application? Thanks in advance A: I'm not expert on this, but I disagree with the accepted answer. Your startForeground is key to ensuring that your service continues running. Without that, it might keep running, but it has a much lower priority so it is much more likely to be killed by the system. A: Create a notification that contains an icon made with a png and is only 1 pixel in height and width and make that pixel transparent. A: Your service is entirely independent of whether or not a notification exists for it. If you removed the line, startForeground, the service would continue to run. The only time a service stops is if you call context.stopService() or stopSelf(). Throw some logs into your service, and you'll see that it continues to run. Override the onStartCommand to determine behavior of your service after garbage collection: @Override public int onStartCommand(Intent intent, int flags, int startId() { super.onStartCommand(intent, flags, startId); doWork(); return START_STICKY; } START_STICKY recreates your service after garbage collection. START_REDELIVER_INTENT will recreate your service after garbage collection using the original intent, use this only if you need extra intent data.
{ "language": "en", "url": "https://stackoverflow.com/questions/7549442", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }