text
stringlengths
8
267k
meta
dict
Q: jQuery blur handler not working on div element? I don't understand why the jQuery blur handler isn't working in the most simple case. I'm literally creating a div 100px by 100px and setting a blur event on it, but it's not firing (JSFiddle): <div id="test">this is a test</div> $(document).ready(function() { $('#test').bind('blur', function() { alert('blur event!'); }); }); Is my understanding of blur wrong? I expect the blur event to fire when I click anywhere that is not the div...right? According to jQuery's documentation: In recent browsers, the domain of the event has been extended to include all element types. An element can lose focus via keyboard commands, such as the Tab key, or by mouse clicks elsewhere on the page. I've tried it on the latest Chrome and Firefox on Mac. A: From the W3C DOM Events specification: focus The focus event occurs when an element receives focus either via a pointing device or by tabbing navigation. This event is valid for the following elements: LABEL, INPUT, SELECT, TEXTAREA, and BUTTON. blur The blur event occurs when an element loses focus either via the pointing device or by tabbing navigation. This event is valid for the following elements: LABEL, INPUT, SELECT, TEXTAREA, and BUTTON. The jQuery docs state browsers extended the events to other elements, which I'm guessing means blur and focus are aliases for the more generic DOMFocusIn and DOMFocusOut events. Non-input elements aren't eligible to receive those by default though, and an element has to somehow gain focus before losing it - a blur still won't fire for every click outside the div. This SO question mentions that giving an element a tabindex would allow that, and seems to work for me in Chrome after modifying your jsFiddle. (Albeit with a fairly ugly outline.) A: As far as I knew, blur happens on inputs that had the focus, either way you say I expect the blur event to fire when I click anywhere that is not the div...right? Not exactly, the blur event only happens for an element that had the focus first So in order for a blur event to occur, you would first have to give focus to the div, how is the div getting focus first? If you are really try to determine if there was a click outside of your div, you need to attach a click handler to the document, and then check to see where your click came from. var div_id = "#my_div"; var outsideDivClick = function (event) { var target = event.target || event.srcElement; var box = jQuery(div_id); do { if (box[0] == target) { // Click occured inside the box, do nothing. return; } target = target.parentNode; } while (target); } jQuery(document).click(outsideDivClick); Just remember that this handler will be run for EVERY click on the page. (in the past if i ha to use something like this, i attach the handler when I need it, and remove it when I no longer need to look for it) A: A can't "blur" because that would involve the div having focus in the first place. Non-input elements like a and textarea can have focus, which is what jQuery's documentation refers to. What you need is the "mouseout" or "mouseleave" event (mouseleave doesn't bubble, mouseout does), which will be fired when the cursor leaves the div. If you need to have clicks, I would attach a "click" event to the body, as well as the div and stopping the event propagation on only the div: $("div").click(function(e) { return false; // stop propagation }); Or, if you're really determined, you can fake the appearance of a div with a and some CSS rules :) A: If you want something to happen while you move your mouse over the box, you could use the mouseover event.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536342", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Rails intermediate table assosciations I have a User model and a Tag model. The User has Skills and Interests. A Skill is a Tag, and an Interest is a Tag. I have a table for Users, Tags, UsersSkills, UsersInterests. The last two being the intermediate table. How do I associate all this. The following is what I have but is not working. Thanks ahead of time. #User model class User < ActiveRecord::Base has_and_belongs_to_many :skills has_and_belongs_to_many :interests end #Tag model class Tag < ActiveRecord::Base has_and_belongs_to_many :users end #Migrations create_table :users_interests, :id => false do |t| t.references :user t.references :tag end create_table :users_skills, :id => false do |t| t.references :user t.references :tag end A: SO here is the answer for anyone else experiencing this problem. The intermediate table had to have its name be alphabetically in order, even if that means readability goes down the tube. A join_table was then used. If this is not the right answer (it works but might not be good coding), please let me know. class User < ActiveRecord::Base has_and_belongs_to_many :skills, :class_name => "Tag", :join_table => "skills_users" has_and_belongs_to_many :interests, :class_name => "Tag", :join_table => "interests_users" end class Tag < ActiveRecord::Base has_and_belongs_to_many :users end create_table :skills_users, :id => false do |t| t.references :user t.references :tag end create_table :interests_users, :id => false do |t| t.references :user t.references :tag end A: It's expecting your join tables to have skill_id and interest_id FK's rather than tag_id. I believe you're looking for (don't have a terminal handy): class User < ActiveRecord::Base has_and_belongs_to_many :skills, :association_foreign_key => :tag_id has_and_belongs_to_many :interests, :association_foreign_key => :tag_id end
{ "language": "en", "url": "https://stackoverflow.com/questions/7536345", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Matching attributes list with or without quotes I'm trying to match a list of attributes that may have quotes around their value, something like this: aaa=bbb ccc="ddd" eee=fff What I want to get is a list of key/value without the quotes. 'aaa' => 'bbb', 'ccc' => 'ddd', 'eee' => 'fff' The code (ruby) looks like this now : attrs = {} str.scan(/(\w+)=(".*?"|\S+)/).each do |k,v| attrs[k] = v.sub(/^"(.*)"$/, '\1') end I don't know if I can get rid of the quotes by just using the regex. Any idea ? Thanks ! A: Try using the pipe for the possible attribue patterns, which is either EQUALS, QUOTE, NO-QUOTE, QUOTE, or EQUALS, NO-WHITESPACE. str.scan(/(\w+)=("[^"]+"|\S+)/).each do |k, v| puts "#{k}=#{v}" end Tested. EDIT | Hmm, ok, I give up on a 'pure' regex solution (that will allow whitespace inside the quotes anyway). But you can do this: attrs = {} str.scan(/(\w+)=(?:(\w+)|"([^"]+)")/).each do |key, v_word, v_quot| attrs[key] = v_word || v_quot end The key here is to capture the two alternatives and take advantage of the fact that whichever one wasn't matched will be nil. If you want to allow whitespace around the = just add a \s* on either side of it. A: I was able to get rid of the quotes in the regex, but only if I matched the quotes as well. s = "aaa=bbb ccc=\"ddd\" eee=fff" s.scan(/([^=]*)=(["]*)([^" ]*)(["]*)[ ]*/).each {|k, _, v, _ | puts "key=#{k} value=#{v}" } Output is: key=aaa value=bbb key=ccc value=ddd key=eee value=fff (Match not =)=(Match 0 or more ")(Match not " or space)(Match 0 or more ")zero or more spaces Then just ignore the quote matches in the processing. I tried a number of combinations with OR's but could not get the operator precedence and matching to work correctly. A: I don't know ruby, but maybe something like ([^ =]*)="?((?<=")[^"]*|[^ ]*)"? works?
{ "language": "en", "url": "https://stackoverflow.com/questions/7536348", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Python 2.5 zlib trouble I am trying to deploy an app on google app engine using bottle, a micro-framework, similar to flask. I am running on ubuntu which comes with python 2.7 installed but GAE needs version 2.5, so I installed 2.5. I then realized I didn't use make altinstall so I may have a default version problem now. But my real problem is that when I try to use the gae server to test locally I get the following error: Traceback (most recent call last): File "/opt/google/appengine/dev_appserver.py", line 77, in <module> run_file(__file__, globals()) File "/opt/google/appengine/dev_appserver.py", line 73, in run_file execfile(script_path, globals_) File "/opt/google/appengine/google/appengine/tools/ dev_appserver_main.py", line 156, in <module> from google.appengine.tools import dev_appserver File "/opt/google/appengine/google/appengine/tools/ dev_appserver.py", line 94, in <module> import zlib ImportError: No module named zlib Can you help me with this? A: How did you build Python 2.5? If you built it from sources yourself, there's a good possibility the zlib module didn't get built because the necessary libraries and header files weren't installed on your system. On Ubuntu, you need (I think) the zlib1g-dev package. This will be true for a variety of other modules as well (for example, without the appropriate OpenSSL development libraries/headers in place, you won't get the ssl module either). Someone may also have a python2.5 package for your version of Ubuntu (although neither Natty or Maverick appear to have one in the official repositories). A: Before figuring out that using a post-2.5 Python worked just fine as long as you didn't use any post-2.5 language features or packages (or additions to package), I wrote up a walkthrough for building 2.5 for Ubuntu here. It includes the bit you need for zlib. I'm now happily developing on Ubuntu using Python 2.6.5 (with SDK 1.5.4).
{ "language": "en", "url": "https://stackoverflow.com/questions/7536351", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using Same Value of Key in Same Array How do I write this code correctly? The fourth line, I want to use the values of the two first keys all within the same array. $pixel_percents = array( "complete"=>.5 * 768, "wip"=>round(.2 * 768, 0, PHP_ROUND_HALF_DOWN), "remain"=>$pixel_percents["complete"] - $pixel_percents["wip"] ); A: Just do it after $pixel_percents = array( "complete"=>.5 * 768, "wip"=>round(.2 * 768, 0, PHP_ROUND_HALF_DOWN), ); $pixel_percents['remain'] = $pixel_percents['complete'] - $pixel_percents['wip']; A: $pixel_percents = array(); $pixel_percents["complete"] = .5 * 768; $pixel_percents["wip"] = round(.2 * 768, 0, PHP_ROUND_HALF_DOWN); $pixel_percents["remain"] = $pixel_percents["complete"] - $pixel_percents["wip"];
{ "language": "en", "url": "https://stackoverflow.com/questions/7536355", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What's the difference between an MS Office Visual Studio Add-in, Shared Add-in, and Excel 2010 Add-in? I am using Visual Studio 2010 to create a new add-in for Excel. Ideally I would like it to work with Excel 2011 (Mac), 2010, and 2007. There are three template options to choose from when I start a new C# project. * *(Office) Excel 2010 Add-in *(Extensibility) Visual Studio Add-in *(Extensibility) Shared Add-in What are the differences between these template choices? Thanks in advance. A: From MS. As the name implies, you probably want to use shared add-in. * *Office Excel 2010 Add-in Creates an application-level add-in for Excel 2007 or Excel 2010. For more information, see Getting Started Programming Application-Level Add-Ins and Excel Solutions. * *(Extensibility) Visual Studio Add-in Visual Studio Add-ins add functionality to the Visual Studio and Visual Studio Macros environments. For more information, see How to: Create an Add-In. * *(Extensibility) Shared Add-in Shared Add-ins can add functionality to one or more Microsoft Office applications, as well as to Visual Studio. For more information, see How to: Create an Add-In. Reference: http://msdn.microsoft.com/en-us/library/0fyc0azh.aspx A: #1 and #3 will work for Windows machines, but straight from Geoff Darst of Microsoft's VSTO team, "the .Net Development Platform and Visual Studio Tools For Office are Windows only." You'll have to code in VBA to get functionality across all three versions. If you want to target just the Windows environment, make sure you target the 2007 version of Excel, as I don't believe solutions developed for Excel 2010 are backward compatible with Excel 2007.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536357", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Using a loop to query in mongoDB I'm thinking of using mongodb as a replacement for a few mysql tables that require a lot of queries (often in while/for loops) to fetch all of the data. Mongo seems like a good fit because I can run javascript directly against the console and lay out all of the queries and receive the data back. My question is whether or not it would be faster/make more sense to do this in mongo. My typical loops in Mysql are trying to query up a tree (kind of like a file structure). For example, we start with id 6, then we query its parent which is id 5, and then its parent, etc etc until we find a parent that ends with id 0. This can take up a lot of queries and I worry that mysql will fold under this. Sorry if I explained this poorly :P A: It depends how you store the tree structure. I think the question is not really about mongo vs. mysql, but rather how you are dealing with tree storage. It sounds like you are storing the structure as a list of tupples (id, parent_id). Instead of going back to the database for each iteration, you should get all the tupples with one query and use a simple tree building algorithm to build the structure (and filter it if you use more attributes than the tupple). Mongo won't solve your problem, because if you store each tree node as a document, you are going to end up in the same situation you're in now.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536360", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Query to loop through data in splunk I've below lines in my log: ...useremail=abc@fdsf.com id=1234 .... ...useremail=pqr@fdsf.com id=4565 .... ...useremail=xyz@fdsf.com id=5773 .... * *Capture all those userids for the period from -1d@d to @d *For each user, search from beginning of index until -1d@d & see if the userid is already present by comparing actual id field *If it is not present, then add it into the counter *Display this final count. Can I achieve this in Splunk? Thanks! A: Yes, there are several ways to do this in Splunk, each varying in degrees of ease and ability to scale. I'll step through the subsearch method: 1) Capture all those userids for the period from -1d@d to @d You want to first validate a search that returns only a list of ids, which will then be turned into a subsearch: sourcetype=<MY_SOURCETYPE> earliest=-1d@d latest=-@d | stats values(id) AS id 2) For each user, search from beginning of index until -1d@d & see if the userid is already present by comparing actual id field Construct a main search with a different timeframe that using the subsearch from (1) to match against those ids (note that the subsearch must start with search): sourcetype=<MY_SOURCETYPE> [search sourcetype=<MY_SOURCETYPE> earliest=-1d@d latest=-@d | stats values(id) AS id] earliest=0 latest=-1d@d This will return a raw dataset of all events from the start of the index up to but not including 1d@d that contain the ids from (1). 3) If it is not present, then add it into the counter Revise that search with a NOT against the entire subsearch and pipe the outer search to stats to see the ids it matched: sourcetype=<MY_SOURCETYPE> NOT [search sourcetype=<MY_SOURCETYPE> earliest=-1d@d latest=-@d | stats values(id) AS id] earliest=0 latest=-1d@d | stats values(id) 4) Display this final count. Revise the last stats command to return a distinct count number instead: sourcetype=<MY_SOURCETYPE> NOT [search sourcetype=<MY_SOURCETYPE> earliest=-1d@d latest=-@d | stats values(id) AS id] earliest=0 latest=-1d@d | stats dc(id) Performance considerations: The above method works reasonably well for datasets under 1 million rows, on commodity hardware. The issue is that the subsearch is blocking, thus the outer search needs to wait. If you have larger datasets to deal with, then alternative methods need to be employed to make this an efficient search. FYI, Splunk has a dedicated site where you can get answers to questions like this much faster: http://splunk-base.splunk.com/answers/
{ "language": "en", "url": "https://stackoverflow.com/questions/7536361", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: unix script - problem in making a text file I am writing a simple unix script as follows: #!/bin/bash mkdir tmp/temp1 cd tmp/temp1 echo "ab bc cj nn mm" > output.txt grep 'ab' output.txt > newoutput.txt I got following error message: grep : No such file or directory found output.txt but when I looked into the directory the text is created output.txt...but the type of the file was TXT....I am not sure what it is any help?? A: You probably have a stray '\r' (carriage return) on the line with the echo command. You're creating a file called "output.txt\r", and then trying to read a file called "output.txt" without the carriage return. Fix the script so it uses Unix-style line endings (\n rather than \r\n). You can use the unix2dos command for this. (Note that unix2dos, unlike most filters, overwrites its input file.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7536363", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Probably simple php regex Sorry for the simple question that I could research, but i crashed a database today, been here 12 hours, and want to go home. I am rotating recursively through files trying to extract city, phone number, and email address so that I can match the city and phone to my database entries and update the users email address. In theory, they could just login with their email and request to reset their password. heres what i need. my file contents look like this: > Address : 123 main street City : somecity State/Province : somestate > Zip/Postal Code : 12345 Country : United States Phone : 1231231234 Fax > : E-Mail : example@example.com ==== CUSTOMER SHIPPING INFORMATION === I should note that there is other info before and after the snippet I showed. Can someone please help me with a regex to remove the 3 items? Thanks. A: Try something like this, without regex.. $string = 'Address : 123 main street City : somecity State/Province : somestate Zip/Postal Code : 12345 Country : United States Phone : 1231231234 Fax : E-Mail : example@example.com ==== CUSTOMER SHIPPING INFORMATION ==='; $string = str_replace( array( ' ==== CUSTOMER SHIPPING INFORMATION ===', 'Address', 'City', 'State/Province', 'Zip/Postal Code', 'Country', 'Phone', 'Fax', 'E-Mail' ) , '', $string); $string = explode(' : ', $string); unset($string[0]); print_r($string); Result... Array ( [0] => [1] => 123 main street [2] => somecity [3] => somestate [4] => 12345 [5] => United States [6] => 1231231234 [7] => [8] => example@example.com ) If there are linebreaks, something like this... $string = explode("\n", $string); foreach($string as $value){ list(, $info) = explode(' : ', $value); echo $info . '<br />'; } Solution with regex.. $fields = array('City', 'Phone', 'E-mail'); foreach($fields as $field){ preg_match("#$field : (.*?) #is", $string, $matches); echo "$field : $matches[1]"; echo '<br />'; } Result: City : somecity Phone : 1231231234 E-mail : example@example.com A: Something like this: Address\s*:\s*(.*?)\s*City\s*:\s*(.*?)\s*State/Province\s*:\s*(.*?)\s*Zip/Postal Code\s*:\s*(.*?)\s*Country\s*:\s*(.*?)\s*Phone\s*:\s*(.*?)\s*Fax\s*:\s*(.*?)\s*E-Mail\s*:\s*(.*?)\s Will work if you rip out the > at the start of each line first. proof If you print_r that, you'll see the different components. Note the "dot matches all" modifier. Might be even easier if you rip out newlines too (after you take out the >). A: What about this $test = ' > Address : 123 main street City : somecity State/Province : somestate > Zip/Postal Code : 12345 Country : United States Phone : 1231231234 Fax > : E-Mail : example@example.com ==== CUSTOMER SHIPPING INFORMATION === '; preg_match('@.*City : (.+?) .*? Country : (.+?) Phone : (.+?) .*@si',$test,$res); var_dump($res); result array 0 => string ' > Address : 123 main street City : somecity State/Province : somestate > Zip/Postal Code : 12345 Country : United States Phone : 1231231234 Fax > : E-Mail : example@example.com ==== CUSTOMER SHIPPING INFORMATION === ' (length=217) 1 => string 'somecity' (length=8) 2 => string 'United States' (length=13) 3 => string '1231231234' (length=10)
{ "language": "en", "url": "https://stackoverflow.com/questions/7536366", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Faster Paint on Flex Mobile I am trying to build an app that tracks touchpoints and draws circles at those points using Flash Builder. The following works perfectly, but after a while, it begins to lag and the touch will be well ahead of the drawn circles. Is there a way of drawing the circles that does not produce lag as more and more of them are added? In declarations, I have: <fx:Component className="Circle"> <s:Ellipse> <s:stroke> <s:SolidColorStroke alpha="0"/> </s:stroke> </s:Ellipse> </fx:Component> And this is the drawing function: var c:Circle = new Circle(); c.x = somex; c.y = somey; c.fill = new SolidColor(somecolorint); c.height = somesize; c.width = somesize; c.alpha = 1; addElement(c); c = null; A: Try taking a look at doing a fullscreen Bitmap created with a BitmapData class. As the touch points are moved, update the bitmap data at the coordinates where the touch occured. Modifying and blitting a screen-sized bitmap is extremely fast and will probably work great for what you're trying to do. Another performance trade off often done is to make a series of lines instead of continuous circles. You create a new line segment only when a certain distance has been traveled, this lets you limit the number of nodes in the segment thereby keeping performance high.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536374", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I perform these animated view transitions? I am brand new to Core Animation, and I need to know how to do 2 animations: * *I need to switch XIBs by fading through black (fully releasing the the first view controller) *I need to mimic the UINavigationController's pushViewController animation (switching XIBs and releasing the first view controller) How can you achieve these animated view transitions? A: I've done both of these animations, but maybe not in the exact way you are looking for. * *Fade View to black, I took this the other way an instead added a new subview that covered the entire window that was Black and animated the Alpha from 0.0 to 1.0. Made for a nice effect. [UIView animateWithDuration:0.5 animations:^{ _easterEgg.alpha = 1.0; } completion:^(BOOL finished) { [self animateIndex:0]; }]; *Slide in a view like UINavigationController. I didn't do this exactly like UINavigationController since it does multiple animations, but I did have a new view slide the previous view off screen. This code sets the frame of the new view off screen to the right of the current view, builds a frame location that is off the screen to the left, and grabs the current visible frame. Finally it just animates the new view from off screen right into the visible frame, and the old view from the visible frame to off left. Then removes the old view. CGRect offRight = CGRectMake(_contentView.frame.size.width, 0, _contentView.frame.size.width, _contentView.frame.size.height); CGRect offLeft = CGRectMake(-_contentView.frame.size.width, 0, _contentView.frame.size.width, _contentView.frame.size.height); CGRect visibleFrame = CGRectMake(0, 0, _contentView.frame.size.width, _contentView.frame.size.height); [view setFrame:offRight]; UIView *currentView = [[_contentView subviews] lastObject]; [_contentView addSubview:view]; [UIView animateWithDuration:0.5 animations:^{ [currentView setFrame:offLeft]; [view setFrame:visibleFrame]; } completion:^(BOOL finished) { [currentView removeFromSuperview]; }];
{ "language": "en", "url": "https://stackoverflow.com/questions/7536375", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: android market - application update does not work I have a new version of my app on the market and an old one installed on tablet. I expect to see download/install option when I navigate to the application page on the market but instead I see "open" button as if the market version were already installed on the device. versionCode is incremented in market's version. What could be a reason for this? A: The version of your app installed using adb is probably not signed, or if it is the signature doesn't match the one on the app in the market. First need to uninstall the version that was installed using adb then the market version should install without a problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536379", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Need advice on how to design this. Composition or inheritance? I'm trying to design a client / server solution. Currently it contains three projects. The client, the server, and a library that each use (because they both require a lot of the same stuff). For example, both the client and the server (in this case) read incoming data in the exact same way. Because of this, both the client and the server have their own MessageReader object. The MessageReader will first read the first 4 bytes of incoming stream data to determine the length of the data and then read the rest. This is all performed asynchronously. When all the data is read the class raises its own MessageRead event or if there was an IOException while reading it raises its own ConnectionLost event. So this all works fine. What's the problem? Well, the client and the server are a bit different. For example, while they may read data in the same way, they do not write data in the same way. The server has a Dictionary of clients and has a Broadcast method to write to all clients. The client only has a single TcpClient and can only Write to the server. Currently all this behavior is within each respective WinForm and I want to move it to a Client and Server class but I'm having some problems. For example, remember earlier when I was talking about the MessageReader and how it can raise both a MessageRead event and a ConnectionLost event? Well, now there's a bit of a problem because in designing the Client class I have to capture these two events and re-raise them because the client form should not have access to the MessageReader class. It's a bit ugly and looks like this: class Client { private MessageReader messageReader = new MessageReader(); public delegate void MessageReceivedHandler(string message); public delegate void ConnectionLostHandler(string message); public event ConnectionLostHandler ConnectionLost; public event MessageReceivedHandler MessageReceived; public Client() { messageReader.ConnectionLost += messageReader_ConnectionLost; messageReader.MessageReceived += messageReader_MessageReceived; } private void messageReader_MessageReceived(string message) { if (ConnectionLost != null) { ConnectionLost(message); } } private void messageReader_ConnectionLost(string message) { if (MessageReceived != null) { MessageReceived(message); } } } This code is ugly because its basically duplicate code. When the MessageReader raises the MessageReceieved handler the Client has to capture it and basically re-raise its own version (duplicate code) because the client form should not have access to the message reader. Not really of a good way to solve it. I suppose both Client and Server could derive from an abstract DataReader but I don't think a client is a data reader, nor is the server. I feel like composition makes more logical sense but I can't figure out a way to do this without a lot of code duplication and confusing event handlers. Ouch, this question is getting a bit long.. I hope I don't scare anyone away with the length. It's probably a simple question but I'm not really sure what to do. Thanks for reading. A: Composition. I didn't even read your code or text. I find that the average developer (almost) never needs inheritance but they like to use it quite a bit. Inheritance is fragile. Inheritance is hard to get correct. It's harder to keep it in check with SOLID. Composition is easy to understand, easy to change, and easy to DI, Mock, and test. SOLID A: I ended up using inheritance for this even though the relationship wasn't strong. The code duplication it got rid of was worth it. Was able to place all the events both classes shared in to the base class.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536380", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Count users from table 2 in request to table 1 I have table with positions tbl_positions id position 1 Driver 2 Lobby 3 Support 4 Constructor and in other table i have users tbl_workers id name position status 1 John 2 3 2 Mike 3 2 3 Kate 2 3 4 Andy 1 0 i do request of positions Without status I select everything with this query . SELECT p.id, p.position, count(*) FROM tbl_positions as p inner join tbl_workers as w on w.position=p.id group by p.id, p.position But now i need output same query but also considers status, status 2=booked status, 3=placed. I need output like this in single query. Position booked placed Driver 0 0 Lobby 0 2 Support 1 0 Constructor 0 0 I tried add WHERE tbl_workers.status IN (2) for booked and WHERE tbl_workers.status IN (3) for placed and it works in two queries, but no luck joining this into one query A: Try this: SELECT p.id, p.position, SUM(CASE w.Status WHEN 2 THEN 1 ELSE 0 END) AS booked, SUM(CASE w.Status WHEN 3 THEN 1 ELSE 0 END) AS placed FROM tbl_positions AS p LEFT JOIN tbl_workers AS w ON w.position=p.id GROUP BY p.id, p.position A: Although you can do this with a single SQL query, it may be more straightforward to handle this using PHP. Use your current query and add status to the GROUP BY. SELECT p.id, p.position, w.status, count(*) FROM tbl_positions as p inner join tbl_workers as w on w.position=p.id group by p.id, p.position, w.status You'll get a result set like this: position status count Driver 2 0 Lobby 2 0 Support 2 1 Constructor 2 0 Driver 3 0 Lobby 3 2 Support 3 0 Constructor 3 0 Use PHP to logically determine 2 = booked and 3 = placed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536386", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why do we have to put an asterisk on method parameter types in Objective-C? I'm starting out Objective-C and I was wondering, why do we have to put asterisks in the method parameter type? e.g. - (void)myMethodThatTakesAString:(NSString*)string; Thanks in advance! A: The asterisk means that the parameter is a pointer to an NSString. You can't pass an NSString to a method, but rather you pass a pointer to it. Although you might get away with simply using pointers when you have objects and not really understanding them, it's probably a good idea to prioritize learning about pointers. A: Because that is what you are passing- a pointer - a memory location or reference to NSString. The notation for pointer, the * comes from C.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536393", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Rails Active Admin resource problem I recently have watched railscast 284 about active admin and wanted to implement it into my web app, however I am running into an issue when I add a resource. I get the following message every time I try to navigate to the created tab: NameError in Admin::LoadsController#index undefined local variable or method `per' for []:ActiveRecord::Relation Rails.root: /Users/thomascioppettini/rails_projects/want-freight Application Trace | Framework Trace | Full Trace Request Parameters: {"order"=>"id_desc"} Show session dump Show env dump Response Headers: None The only thing I can think of that may affect the application is adding a recaptcha to devise, which active admin depends on. A: For me, it looks like this is a pagination problem. What gem are you using? You should give as more details about your settup. Can you show us your resource file from admin directory? What version of rails and what ActiveAdmin are you using ? A: If you are using the will_paginate gem, set the version to 3.0.pre2. I was using ~>3.0.pre2, which auto-updated to 3.0.2 when I ran a bundle update Reverting fixed the issue. If you're using Bundler, the line is this: gem "will_paginate", "3.0.pre2" A: I agree with Dawaid. It is a pagiantion error. Add "Kaminari" gem to you Gemfile. According to active admin docs, it is using kaminari for pagination.. will_paginate will also work for you as swilliams described... A: As I understand active_admin doesn't support will_paginate anymore. But if you don't want to rewrite your pagination to Kaminari you can fix this problem with putting some code to initializers # config/initializers/will_paginate.rb if defined?(WillPaginate) module WillPaginate module ActiveRecord module RelationMethods alias_method :per, :per_page alias_method :num_pages, :total_pages end end end end module ActiveRecord class Relation alias_method :total_count, :count end end
{ "language": "en", "url": "https://stackoverflow.com/questions/7536399", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Deferred bcast wakeup for condition variables - is it valid? I'm implementing pthread condition variables (based on Linux futexes) and I have an idea for avoiding the "stampede effect" on pthread_cond_broadcast with process-shared condition variables. For non-process-shared cond vars, futex requeue operations are traditionally (i.e. by NPTL) used to requeue waiters from the cond var's futex to the mutex's futex without waking them up, but this is in general impossible for process-shared cond vars, because pthread_cond_broadcast might not have a valid pointer to the associated mutex. In a worst case scenario, the mutex might not even be mapped in its memory space. My idea for overcoming this issue is to have pthread_cond_broadcast only directly wake one waiter, and have that waiter perform the requeue operation when it wakes up, since it does have the needed pointer to the mutex. Naturally there are a lot of ugly race conditions to consider if I pursue this approach, but if they can be overcome, are there any other reasons such an implementation would be invalid or undesirable? One potential issue I can think of that might not be able to be overcome is the race where the waiter (a separate process) responsible for the requeue gets killed before it can act, but it might be possible to overcome even this by putting the condvar futex in the robust mutex list so that the kernel performs a wake on it when the process dies. A: There may be waiters belonging to multiple address spaces, each of which has mapped the mutex associated with the futex at a different address in memory. I'm not sure if FUTEX_REQUEUE is safe to use when the requeue point may not be mapped at the same address in all waiters; if it does then this isn't a problem. There are other problems that won't be detected by robust futexes; for example, if your chosen waiter is busy in a signal handler, you could be kept waiting an arbitrarily long time. [As discussed in the comments, these are not an issue] Note that with robust futexes, you must set the value of the futex & 0x3FFFFFFF to be the TID of the thread to be woken up; you must also set bit FUTEX_WAITERS on if you want a wakeup. This means that you must choose which thread to awaken from the broadcasting thread, or you will be unable to deal with thread death immediately after the FUTEX_WAKE. You'll also need to deal with the possibility of the thread dying immediately before the waker thread writes its TID into the state variable - perhaps having a 'pending master' field that is also registered in the robust mutex system would be a good idea. I see no reason why this can't work, then, as long as you make sure to deal with the thread exit issues carefully. That said, it may be best to simply define in the kernel an extension to FUTEX_WAIT that takes a requeue point and comparison value as an argument, and let the kernel handle this in a simple, race-free manner. A: I just don't see why you assume that the corresponding mutex might not be known. It is clearly stated The effect of using more than one mutex for concurrent pthread_cond_timedwait() or pthread_cond_wait() operations on the same condition variable is undefined; that is, a condition variable becomes bound to a unique mutex when a thread waits on the condition variable, and this (dynamic) binding shall end when the wait returns. So even for process shared mutexes and conditions this must hold, and any user space process must always have mapped the same and unique mutex that is associated to the condition. Allowing users to associate different mutexes to a condition at the same time is nothing that I would support.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536401", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: extjs4 - how to focus on a text field? I can't seem to be able to focus a field in a form in extjs 4. The doc lists a focus function for Text field (inherited from Component) but it doesn't do anything in terms of focusing to the input field. Here's a sample code from the docs Ext.create('Ext.form.Panel', { title: 'Contact Info', width: 300, bodyPadding: 10, renderTo: Ext.getBody(), items: [{ xtype: 'textfield', name: 'name', fieldLabel: 'Name', allowBlank: false }, { xtype: 'textfield', id:'email', name: 'email', fieldLabel: 'Email Address', vtype: 'email' }] }); If I call Ext.getCmp('email').focus() nothing visible happens. What's the correct way to focus a field in extjs 4? A: Sometimes a simple workaround is to slightly defer the focus call in case it's a timing issue with other code or even with the UI thread allowing the focus to take place. E.g.: Ext.defer(function(){ Ext.getCmp('email').focus(); }, 0); A: There isn't anything wrong with your code. I've made a jsfiddle for it and it works fine. Are you wrapping code in and Ext.onReady()? Also what browser are you using? A: Try this: Ext.getCmp('email').focus(false, 20); A: Rather than work around with a delay, look for what is getting focus instead. Look out for focusOnToFront property on the parent.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536407", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: (!IE) Problems with Blocking Code from IE I have (once again) been enhancing my template for a school site. However, I have run into another problem. I have noticed that the navigation bar does not render properly in any Internet Explorer version prior to IE9 (to be expected). I had seen the use of the !IE tag around the web and tried replicating it on my design. However, once implemented, every browser stopped showing that piece of code. <!--[if !IE]> <li><p>&nbsp;&nbsp;</p></li> <li><img src="vp-global-logo.gif" /> <![endif]--> I also tried: <!--[if gte IE 9]> <li><p>&nbsp;&nbsp;</p></li> <li><img src="vp-global-logo.gif" /> <![endif]--> How would I get this to work? Is there any alternative method without making the site too slow? A: You need to terminate the conditional comments with a special syntax: <!--[if !IE]><!--> <li><p>&nbsp;&nbsp;</p></li> <li><img src="vp-global-logo.gif" /> <!--<![endif]--> This prevents IE from displaying the HTML while other browsers get to see it, treating the if and else as regular HTML comments. A: You're commenting out the list items, try changing your code to this: <!--[if gte IE 9]--><!--> <li><p>&nbsp;&nbsp;</p></li> <li><img src="vp-global-logo.gif" /> <!--><![endif]-->
{ "language": "en", "url": "https://stackoverflow.com/questions/7536409", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Updating timestamps in mongoid How do I update/change the TimestampSequence on a Mongoid document in rails/ruby? If you dont know in Mongoid but know in MongoDB that will work as well. The class is Mongoid::TimestampSequence Thanks in advance A: Try this: Document.where(somecriteriahere: "criteriavaluehere").update_all( updated_at: Time.now.to_s)
{ "language": "en", "url": "https://stackoverflow.com/questions/7536411", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why calloc takes two arguments while malloc only one? IMO one is enough, why does calloc require to split it into two arguments? A: I'd guess that this is probably history and predates the times where C had prototypes for functions. At these times without a prototype the arguments basically had to be int, the typedef size_t probably wasn't even yet invented. But then INTMAX is the largest chunk you could allocate with malloc and splitting it up in two just gives you more flexibility and allows you to allocate really large arrays. Even at that times there were methods to obtain large pages from the system that where zeroed out by default, so efficiency was not so much a problem with calloc than for malloc. Nowadays, with size_t and the function prototype at hand, this is just a daily reminder of the rich history of C. A: The parameter names document it reasonably well: void *malloc(size_t size); void *calloc(size_t nelem, size_t elsize); The latter form allows for neat allocating of arrays, by providing the number of elements and element size. The same behavior can be achieved with malloc, by multiplying. However, calloc also initializes the allocated memory to 0. malloc does no init, so the value is undefined. malloc can be faster, in theory, due to not setting all the memory; this is only likely to be noted with large amounts. In this question, it is suggested that calloc is clear-alloc and malloc is mem-alloc.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536413", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Android Can I use C++ library via JNI interface and put my app in the marketplace? Thats it. I am looking to use a C/C++ Library in my Android app. So JNI to access the library functions. So 1) Can JNI be used inside an Android app. 2) Any restriction in putting my hybrid app Java/JNI android app into the android marketplace? Any restrictions on the inclusion of C/C++ libraries? Thanks A: You can use JNI all you want. There are no restrictions. I have an app with a JNI library in the market, no problemo. At some point, maybe you'll want to compile your JNI library for both ARM and x86. But not now, the few existing x86 Android devices do not get the "Google Experience" treatment.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536419", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Automatically generated property {get; set;} vs {get; private or protected set;} in C# I see a lot of code uses automatically generated property like {get; private set;} or {get; protected set;}. What's the advantage of this private or protected set? I tried this code, but it's the same when I have Foo{get; set;}. public class MyClass { public int Foo {get; private set;} public static void RunSnippet() { var x = new MyClass(); x.Foo = 30; Console.WriteLine(x.Foo); } ... } A: It makes a property read-only by external sources (i.e. classes that aren't MyClass and/or its subclasses). Or if you declared the property protected with a private set, it's read-only by its subclasses but writable by itself. It doesn't make a difference in your class because your setter is private to that class, so your class can still access it. However if you tried to instantiate MyClass from another class, you wouldn't be able to modify the Foo property's value if it had a private or protected setter. private and protected mean the same here as they do elsewhere: private restricts access only to that very class, while protected restricts access to that class and all its derived classes. A: It makes a difference when you have a class model that uses inheritance. If your MyClass methods are clients of your private fields and methods it makes no difference. That said, even if you don't anticipate your MyClass becoming a parent class in any sort of class hierarchy, it doesn't hurt to limit your field and method scope to the least visible scope that it requires. Encapsulate what you can with the least visible scope by default so that you don't have to refactor when subclasses start to access parent properties that they shouldn't be. The level of effort isn't any different from not doing so. A: If you specify no access modifiers on the get and set keywords, the property will be accessible according to the access modifier of the property itself. In your example, you would be able to get the value of Foo and set the value of Foo from anywhere in your program if you specify get instead of private get. In order to write robust code, you should try to always choose the most restrictive access modifier possible. It is a good idea to use properties to expose the state of your object, but not to change the state of your object from outside. If you want to change the state of your object, use method calls instead. A: Think of the get and set functions in terms of accessor and mutator methods (except that you don't have to explicitly write the method bodies out: private int foo; public int get_Foo() { return foo; } public /* or protected, or private */ void set_Foo(int value) { foo = value; } After you see it like that, know that the protected and private modifiers work the same on a setter as they do on any other sort of member.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536420", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: django's DateField model field and acceptable values I'm having a bit of trouble with django's DateField model field. Shouldn't it be able to accept fiveDaysLater as a valid date object? When I try to add fiveDaysLater into the database, I get an error saying cannot add null value to date. However, the second I change the date field to a regular CharField, the fiveDaysLater value is added to the database with no problem. fyi if I print fiveDaysLater, I get 2011-09-28 My view: def myView(): now = datetime.date.today() fiveDaysLater = now + datetime.timedelta(days=5) newDate = Speech(date = fiveDaysLater) newDate.save() My model class Speech(models.Model): date = models.DateField() A: "However, the second I change the date field to a regular CharField..." Just a suspicion but if you made this change in your code, make sure to delete and recreated the Speech table using syncdb, otherwise, sqlite will not be aware of this change. (or you could change the datatype using sqlite exporer for firefox or something like that...)
{ "language": "en", "url": "https://stackoverflow.com/questions/7536421", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: webforms vs asp.net mvc for single page application - which to choose? I'm building a single page application (e.g. like gmail) and I was wondering which asp.net framework would be better? asp.net mvc allows you full control and is easier with heavy ajax sites, but it isn't very good when it comes to partial views (or userControls in webforms). My page is divided into different "regions" which behave very much on their own, so being able to separate them is very much an issue. I know i can use PartialViews, but i'm not sure that MVC is in favor of them. on the other hand there's asp.net webforms which lends itself to userControls much easier, but is not as good when it comes to AJAX and heavy javaScript as much as MVC is. I've also seen people use webforms in an MVP kind of programming where everything is done in PageLoad and therefor has a lot of MVC's benefits. for a Single Page Application, which is more convenient? A: For rich single form applications I would start with ASP.NET MVC as there are fewer platform constraints to get in the way, and rendered HTML tends to be more lightweight than classic ASP.NET. You can design ASP.NET MVC applications in a highly modular fashion, as demonstrated by several MVC CMS' such as Orchard, http://orchardproject.net/. These highly modular frameworks are based entirely on ASP.NET MVC. ASP.NET MVC 3 makes the whole process quite easy. Convenience can mean many things. From a "you the developer" convenience perspective (assuming that you will be the only one developing the application, and assuming that only you will require the modularity to plug your own regions into your application), it will be more convenient for you to develop with whatever framework you are more proficient with. A: MVC 4 has a Single Page template that you should look at... Uses Knockout.js etc and provides exactly what you are asking for. Update:This is still in beta and will ship soon, but worth digging in to. It's amazing the amount of functionality and different approaches this caters for. Check it out at: http://www.asp.net/mvc/mvc4
{ "language": "en", "url": "https://stackoverflow.com/questions/7536422", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Rails - how does method access name fields with no call to a db and no form params? I'm a newbie watching a Lynda.com video about rails 3. The teacher creates a method like this to find a user def name "#{first_name} #{last_name}" end He says this will return first name and last name for this user, but I don't understand how this function accesses first_name last_name, since there is no call to a database or no form parameters. I know that without looking at the whole application it will be impossible for you to explain this, but you may be able to guess what this function might be dependent on. this is the whole AdminUser model require 'digest/sha1' class AdminUser < ActiveRecord::Base # To configure a different table name # set_table_name("admin_users") has_and_belongs_to_many :pages has_many :section_edits has_many :sections, :through => :section_edits attr_accessor :password EMAIL_REGEX = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i # standard validation methods # validates_presence_of :first_name # validates_length_of :first_name, :maximum => 25 # validates_presence_of :last_name # validates_length_of :last_name, :maximum => 50 # validates_presence_of :username # validates_length_of :username, :within => 8..25 # validates_uniqueness_of :username # validates_presence_of :email # validates_length_of :email, :maximum => 100 # validates_format_of :email, :with => EMAIL_REGEX # validates_confirmation_of :email # new "sexy" validations validates :first_name, :presence => true, :length => { :maximum => 25 } validates :last_name, :presence => true, :length => { :maximum => 50 } validates :username, :length => { :within => 8..25 }, :uniqueness => true validates :email, :presence => true, :length => { :maximum => 100 }, :format => EMAIL_REGEX, :confirmation => true # only on create, so other attributes of this user can be changed validates_length_of :password, :within => 8..25, :on => :create before_save :create_hashed_password after_save :clear_password scope :named, lambda {|first,last| where(:first_name => first, :last_name => last)} scope :sorted, order("admin_users.last_name ASC, admin_users.first_name ASC") attr_protected :hashed_password, :salt def name "#{first_name} #{last_name}" end def self.authenticate(username="", password="") user = AdminUser.find_by_username(username) if user && user.password_match?(password) return user else return false end end # The same password string with the same hash method and salt # should always generate the same hashed_password. def password_match?(password="") hashed_password == AdminUser.hash_with_salt(password, salt) end def self.make_salt(username="") Digest::SHA1.hexdigest("Use #{username} with #{Time.now} to make salt") end def self.hash_with_salt(password="", salt="") Digest::SHA1.hexdigest("Put #{salt} on the #{password}") end private def create_hashed_password # Whenever :password has a value hashing is needed unless password.blank? # always use "self" when assigning values self.salt = AdminUser.make_salt(username) if salt.blank? self.hashed_password = AdminUser.hash_with_salt(password, salt) end end def clear_password # for security and b/c hashing is not needed self.password = nil end end A: The method "name" is not finding a user from the database, however the variables inside it (first_name and last_name) are read from the corresponding database table fields. In this case assuming the usual rails conventions are followed you will find a database table called "AdminUsers" and inside it some fields of which one is first_name and another is second_name. How this all works and why it is so can be found in the Ruby on Rails documentation for ActiveRecord
{ "language": "en", "url": "https://stackoverflow.com/questions/7536423", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Prevent modification ("hacking") of hidden fields in form in rails3? So lets say I have a form for submitting a new post. The form has a hidden field which specify's the category_id. We are also on the show view for that very category. What I'm worried about, is that someone using something like firebug, might just edit the category id in the code, and then submit the form - creating a post for a different category. Obviously my form is more complicated and a different scenario - but the idea is the same. I also cannot define the category in the post's create controller, as the category will be different on each show view... Any solutions? EDIT: Here is a better question - is it possible to grab the Category id in the create controller for the post, if its not in a hidden field? A: pst is right- never trust the user. Double-check the value sent via the view in your controller and, if it does't match something valid, kick the user out (auto-logout) and send the admin an email. You may also want to lock the user's account if it keeps happening. A: Does your site have the concept of permissions / access control lists on the categories themselves? If the user would have access to the other category, then I'd say there's no worry here since there's nothing stopping them from going to that other category and doing the same. If your categories are restricted in some manner, then I'd suggest nesting your Post under a category (nested resource routes) and do a before_filter to ensure you're granted access to the appropriate category. config/routes.rb resources :categories do resources :posts end app/controllers/posts_controller before_filter :ensure_category_access def create @post = @category.posts.new(params[:post]) ... end private def ensure_category_access @category = Category.find(params[:category_id]) # do whatever you need to do. if you don't have to validate access, then I'm not sure I'd worry about this. # If the user wants to change their category in their post instead of # going to the other category and posting there, I don't think I see a concern? end URL would look like GET /categories/1/posts/new POST /categories/1/posts A: Never, ever trust the user, of course ;-) Now, that being said, it is possible to with a very high degree of confidence rely on hidden fields for temporal storage/staging (although this can generally also be handled entirely on the server with the session as well): ASP.NET follows this model and it has proven to be very secure against tampering if used correctly -- so what's the secret? Hash validation aka MAC (Message Authentication Code). The ASP.NET MAC and usage is discussed briefly this article. In short the MAC is a hash of the form data (built using a server -- and perhaps session -- secret key) which is embedded in the form as a hidden field. When the form submission occurs this MAC is re-calculated from the data and then compared with the original MAC. Because the secrets are known only to the server it is not (realistically) possible for a client to generate a valid MAC from the data itself. However, I do not use RoR or know what modules, if any, may implement security like this. I do hope that someone can provide more insight (in their own answer ;-) if such solutions exist, because it is a very powerful construct and easily allows safe per-form data association and validation. Happy coding.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536425", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How would one draw to the sub display of a ds as if it was a framebuffer? I need to draw raw pixel data to the Nintendo DS's "sub" screen, such as if I was drawing to the main screen in "framebuffer" mode or "Extended Rotation" mode. How can I do this with the current version of libnds (which seems to place restrictions on the use of VRAM_C)? A: #include <nds.h> int main(void) { int x, y; //set the mode to allow for an extended rotation background videoSetMode(MODE_5_2D); videoSetModeSub(MODE_5_2D); //allocate a vram bank for each display vramSetBankA(VRAM_A_MAIN_BG); vramSetBankC(VRAM_C_SUB_BG); //create a background on each display int bgMain = bgInit(3, BgType_Bmp16, BgSize_B16_256x256, 0,0); int bgSub = bgInitSub(3, BgType_Bmp16, BgSize_B16_256x256, 0,0); u16* videoMemoryMain = bgGetGfxPtr(bgMain); u16* videoMemorySub = bgGetGfxPtr(bgSub); //initialize it with a color for(x = 0; x < 256; x++) for(y = 0; y < 256; y++) { videoMemoryMain[x + y * 256] = ARGB16(1, 31, 0, 0); videoMemorySub[x + y * 256] = ARGB16(1, 0, 0, 31); } while(1) { swiWaitForVBlank(); } } Here is a simple example which creates a 16 bit frame buffer on the main and sub screens and fills each with either red or blue.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536434", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to box-shadow inset on just the Left, Bottom, Right -- not the top? I have the following box-shadow inset css3 styling: box-shadow: inset 0 0 10px 0 rgba(255, 255, 255, 1); The inset styling appears on all 4 sides of the box but I do not want styling on the top. How can I remove the styling from the top but keep the styling on the Left, Bottom, Right? Thanks A: You can't do that with just box-shadow so far, but you can composite box-shadow with other possibilities like overflow: hidden. For example, you can push the top shadow outside of parent element and hide that part with overflow: hidden. See this demo: http://jsfiddle.net/CatChen/Fty2N/3/ A: This is what you want: .right-left-bottom-shadow { box-shadow: 5px 0 5px -5px #CCC, 0 5px 5px -5px #CCC, -5px 0 5px -5px #CCC; } The first one is left, second bottom and last the shadow for the right side. This looks really nice if your border has color #CCC. A: No CSS method I know for this but following can be a work around (not a perfect solution) <div id="mydiv"> <div class="workaround"></div> </div> CSS #mydiv { background-color:#f00; height:100px; width:100px; box-shadow: inset 0 0 10px 0 rgba(255, 255, 255, 1); padding:0 2px; } #mydiv .workaround { background-color:#f00; width:100%; height:10px; } Check Fiddle http://jsfiddle.net/bZF48/17/
{ "language": "en", "url": "https://stackoverflow.com/questions/7536435", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: How would I parse this XML with Ruby? Currently, I have an XML document (called Food_Display_Table.xml) with data in a format like this: <Food_Display_Table> <Food_Display_Row> <Food_Code>12350000</Food_Code> <Display_Name>Sour cream dip</Display_Name> .... <Solid_Fats>105.64850</Solid_Fats> <Added_Sugars>1.57001</Added_Sugars> <Alcohol>.00000</Alcohol> <Calories>133.65000</Calories> <Saturated_Fats>7.36898</Saturated_Fats> </Food_Display_Row> ... </Food_Display_Table> I would like to print some of this information in human readable format. Like this: ----- Sour cream dip Calories: 133.65000 Saturated Fats: 7.36898 ----- So far, I have tried this, but it doesn't work: require 'rexml/document' include REXML data = Document.new File.new("Food_Display_Table.xml", "r") data.elements.each("*/*/*") do |foodcode, displayname, portiondefault, portionamount, portiondisplayname, factor, increments, multiplier, grains, wholegrains, orangevegetables, darkgreenvegetables, starchyvegetables, othervegetables, fruits, milk, meats, soy, drybeans, oils, solidfats, addedsugars, alcohol, calories, saturatedfats| puts "----" puts displayname puts "Calories: {calories}" puts "Saturated Fats: {saturatedfats}" puts "----" end A: Use Xpath. I tend to go with Nokogiri as I prefer the API. With the paths hard-coded: doc = Nokogiri::XML(xml_string) doc.xpath(".//Food_Display_Row").each do |node| puts "-"*5 puts "Name: #{node.xpath('.//Display_Name').text}" puts "Calories: #{node.xpath('.//Calories').text}" puts "Saturated Fats: #{node.xpath('.//Saturated_Fats').text}" puts "-"*5 end or for something a bit DRYer. nodes_to_display = ["Display_Name", "Calories", "Saturated_Fats"] doc = Nokogiri::XML(xml_string) doc.xpath(".//Food_Display_Row").each do |node| nodes_to_display.each do |node_name| if value = node.at_xpath(".//#{node_name}") puts "#{node_name}: #{value.text}" end end end A: I'd do it like this, with Nokogiri: require 'nokogiri' # gem install nokogiri doc = Nokogiri::XML(IO.read('Food_Display_Table.xml')) good_fields = %w[ Calories Saturated_Fats ] puts "-"*5 doc.search("Food_Display_Row").each do |node| puts node.at('Display_Name').text node.search(*good_fields).each do |node| puts "#{node.name.gsub('_',' ')}: #{node.text}" end puts "-"*5 end If I had to use REXML (which I used to love, but now love Nokogiri more), the following works: require 'rexml/document' doc = REXML::Document.new( IO.read('Food_Display_Table.xml') ) separator = "-"*15 puts separator desired = %w[ Calories Saturated_Fats ] doc.root.elements.each do |row| puts REXML::XPath.first( row, 'Display_Name' ).text desired.each do |node_name| REXML::XPath.each( row, node_name ) do |node| puts "#{node_name.gsub('_',' ')}: #{node.text}" end end puts separator end #=> --------------- #=> Sour cream dip #=> Calories: 133.65000 #=> Saturated Fats: 7.36898 #=> ---------------
{ "language": "en", "url": "https://stackoverflow.com/questions/7536437", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Casting a C++ long type to a JNI jlong I am using JNI to pass data between C++ and Java. I need to pass a 'long' type, and am doing so using something like: long myLongVal = 100; jlong val = (jlong)myLongVal; CallStaticVoidMethod(myClass, "(J)V", (jvalue*)val); However in Java, when the 'long' parameter is retrieved, it gets retrieved as some very large negative number. What am I doing wrong? A: CallStaticVoidMethod(myClass, "(J)V", (jvalue*)val); This is undefined behaviour. You are casting an integer to be a pointer. It is not a pointer. You need, at the very least, to pass the address. This code would on most platforms instantly crash. A: When you pass a jlong (which is 64 bit) as a pointer (which is, most likely, 32-bit) you necessarily lose data. I'm not sure what's the convention, but try either this: CallStaticVoidMethodA(myClass, "(J)V", (jvalue*)&val); //Note address-of! or this: CallStaticVoidMethod(myClass, "(J)V", val); It's ...A methods that take a jvalue array, the no-postfix methods take C equivalents to scalar Java types. The first snippet is somewhat unsafe; a better, if more verbose, alternative would be: jvalue jv; jv.j = val; CallStaticVoidMethodA(myClass, "(J)V", &jv); On some exotic CPU archtectures, the alignment requirements for jlong variables and jvalue unions might be different. When you declare a union explicitly, the compiler takes care of that. Also note that C++ long datatype is often 32-bit. jlong is 64 bits, on 32-bit platforms the nonstandard C equivalent is long long or __int64.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536439", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: MySQL Search Join Query I have a multiple input search form, that has 2 text boxes. One text box for "searchWords" and the other for "specificPeople". In the first text box, you may have "Dorchester Hotel London", and in the second, you may have "Brad Pitt/Angelina Jolie". Using ASP, I convert the second text box value to a format that my IN clause will accept, such as this ('Brad Pitt','Angelina Jolie'). SELECT photoSearch.photoID, Left(photoSearch.caption,25), photoSearch.allPeople, photoSearch.allKeywords FROM photoSearch JOIN ( photoPeople INNER JOIN people ON photoPeople.peopleID = people.peopleID) ON photoSearch.photoID = photoPeople.photoID AND people.people IN ('Brad Pitt','Angelina Jolie') WHERE MATCH (caption, allPeople, allKeywords) AGAINST ('+dorchester +hotel' IN BOOLEAN MODE) AND photoSearch.dateCreated BETWEEN '2011-07-21' AND '2011-10-23' ORDER BY photoSearch.dateCreated This works without errors but it's not producing records that have Brad and Angelina together. It shows records of Brad alone and records of Angelina alone. So this is where I first realised that an IN clause works like an OR. How is it possible to amend this query, to return rows that have both of these specific names, rather than either of them? My DB looks similar to this: photoSearch photoID INT / AUTO / INDEX caption VARCHAR(2500) / FULLTEXT allPeople VARCHAR(300) / FULLTEXT allKeywords VARCHAR(300) / FULLTEXT dateCreated DATETIME / INDEX photoPeople photoID INT / INDEX peopleID INT / INDEX people peopleID INT / INDEX people VARCHAR(100) / INDEX Any help gratefully received... as always :) An example of what is inside the tables: photoSearch photoID | caption | dateCreated 1900 Dorchester Hotel... 2011-10-03 'photoPeople' [photoID] | [peopleID] 1900 147 1900 148 'people' [peopleID] | [people] 147 Brad Pitt 148 Angelina Jolie A: Join to the photoPeople and people tables n times, where n is the number of people you are searching for: SELECT photoSearch.photoID, Left(photoSearch.caption,25), photoSearch.allPeople, photoSearch.allKeywords FROM photoSearch JOIN ( photoPeople AS pp1 JOIN people AS p1 ON pp1.peopleID = p1.peopleID) ON photoSearch.photoID = pp1.photoID AND p1.people = 'Brad Pitt' JOIN ( photoPeople AS pp2 JOIN people AS p2 ON pp2.peopleID = p2.peopleID) ON photoSearch.photoID = pp2.photoID AND p2.people = 'Angelina Jolie' WHERE MATCH (caption, allPeople, allKeywords) AGAINST ('+dorchester +hotel' IN BOOLEAN MODE) AND photoSearch.dateCreated BETWEEN '2011-07-21' AND '2011-10-23' ORDER BY photoSearch.dateCreated A: The problem is that the IN clause AND people.people IN ('Brad Pitt','Angelina Jolie') looks for exact matches, so the query is doing exactly what you are asking. If you had done AND (people.people LIKE '%Brad Pitt%' OR people.people LIKE '%Angelina Jolie%') you would get the results you want. If you want, you could use AND instr('/Brad Pitt/Angel Jolie/','/'+people.people+'/') > 0 you can get the results you expect.. Try this: SELECT photoSearch.photoID, Left(photoSearch.caption,25), photoSearch.allPeople, photoSearch.allKeywords FROM photoSearch ps JOIN photoPeople pp on pp.photoId=ps.photoId JOIN people on people.peopleId = pp.PeopleId WHERE MATCH (caption, allPeople, allKeywords) AGAINST ('+dorchester +hotel' IN BOOLEAN MODE) AND photoSearch.dateCreated BETWEEN '2011-07-21' AND '2011-10-23' AND people.people IN ('Brad Pitt','Angelina Jolie') ORDER BY photoSearch.dateCreated
{ "language": "en", "url": "https://stackoverflow.com/questions/7536444", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: C++ Windows link subsystem question When using the windows SDK to compile a program writen in C++, if I specify -subsystem:windows,6.1, the width of the window is smaller. If I don't, or do -subsystem:windows without the 6.1, the width is normal. I'm curious why this does this, and if there's a way to make it stay the same width regardless of what command line I pass to link. EDIT: So it's also height, height and width are both different. And if i look at it with Inspect.exe, it says the size is the same each time. EDIT2: Also it's a window application created with CreateWindow, not a console. EDIT3: Here's the full code that initializes my window: wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = WndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.hIcon = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(SMALL_ICON)); wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH); wcex.lpszMenuName = NULL; wcex.lpszClassName = g_szWindowClass; wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(SMALL_ICON)); g_hMainWnd = CreateWindow( g_szWindowClass, t_szWindowTitle, WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX, CW_USEDEFAULT, CW_USEDEFAULT, 392, 250, NULL, NULL, hInstance, NULL ); And I resize the window with this: SetWindowPos(hWnd, NULL, (GetSystemMetrics(SM_CXFULLSCREEN)/2)- (392/2), (GetSystemMetrics(SM_CYFULLSCREEN)/2) - (250/2), 392, 120, SWP_NOZORDER); A: I'm suspecting you are specifying some windows styles that are only supported in Windows7 (Win7 = 6.1). Post the full CreateWindow call with arguments and also try turning off Aero. The window border may be included in the width/height for example in one scenario.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536445", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: What Could Make PHP Code from One Directory Pick Up Behavior from Another Directory? I'm having a weird problem. I have two code bases on one server. One is cutting edge stuff in my home directory. The other is a more stable release in the /var/www/... directory. I have noticed that when I pull the code from git to my home directory, the other code base picks up some functionality of the fresh code. The about page stays the same, but new features are visible on the stable code base. The two codebases each have their own subdomain, sessions are stored in the databases, which are separate, and the cookies have unique names. It's not a browser cache issue - the code is server side and the sites have distinct colors and logos. There is no memcache, apc, or eaccellerator installed. Here's where it gets weirder. If I rename the cutting edge code directory in my home directory, and then rename it back, the stable code base goes back to behaving normally. (Unless I've made a database change. Then, I have to clear the model cache in the stable code's file system) The code in my home directory is a git clone. The code in the stable directory is a copy of the code in the home directory at some stable point in time (cp -av /home/foo /var/www/foo) Edit: The actual files in the /var/www/foo directory do not change. If I open one up in vi, the code is the proper code. A: Most likely candidate is you have some mod_rewrite rules, either in your Apache config files, or in .htaccess files.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536446", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Custom Logging for ServiceSecurityAuditBehavior in WCF 4.0? On my server, I would like to log security information to a database instead of the Windows Application or Security log. I am trying to figure out how to override or customize the ServiceSecurityAuditBehavior stuff to not just write to a Windows log. Is that possible? Thanks. A: You will not achieve that through ServiceSecurityAuditBehavior. This behavior doesn't add audit feature. The feature itself is hardcoded in DispatchRuntime and this behavior only expose its configuration. I think the default WCF implementation doesn't offer any hook to change audit mechanism because all classes using this auditing are internal and expect writing to event log and I'm not sure how big change you need to do to allow custom audit - default audit is handled during authentication, authorization and impersonation. You will have to hook or rewrite all of them.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536448", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Freeing malloc'ed memory from circular linked list I apologize in advance if this is an incredibly dumb question... Currently I have a circular linked list. The number of nodes is normally held static. When I want to add to it, I malloc a number of nodes (ex. 100000 or so) and splice it in. This part works fine when I malloc the nodes one by one. I want to attempt to allocate by blocks: NODE *temp_node = node->next; NODE *free_nodes = malloc( size_block * sizeof( NODE ) ); node->next = free_nodes; for ( i = 0; i < size_block - 1; i++ ) { free_nodes[i].src = 1; free_nodes[i].dst = 0; free_nodes[i].next = &free_nodes[i+1]; } free_nodes[size_block - 1].next = temp_node; The list works as long as I don't attempt to free anything ('glibc detected: double free or corruption' error). Intuitively, I think that is because freeing it doesn't free the single node, and looping through the normal way is attempting to free it multiple times (plus freeing the entire block probably screws up all the other pointers from the nodes that still exist?), but: * *Could somebody please explain to me explicitly what is happening? *Is there a way to allocate the nodes by blocks and not break things? The purpose of this is because I am calling malloc hundreds of thousands of times, and it would be nice if things were faster. If there is a better way around this, or I can't expect it to get faster, I would appreciate hearing that too. :) A: Could somebody please explain to me explicitly what is happening? Exactly what you said. You are allocating a single space of contiguous memory for all blocks. Then if you free it, all memory will be released. Is there a way to allocate the nodes by blocks and not break things? Allocate different memory segments for each block. In your code (that isn't complete) should be something like: for ( i = 0; i < size_block ; i++ ) { free_nodes[i] = malloc (sizeof( NODE )); } A: When you free a node you free the entire allocation that the node was allocated with. You must somehow arrange to free the entire group of nodes at once. Probably your best bet is to keep a list of "free" nodes and reuse those rather than allocating/freeing each node. And with some effort you can arrange to keep the nodes in blocks and allocate from the "most used" block first such that if an entire block goes empty you can free it. A: First, the way you allocated your nodes in blocks, you always have to free the whole block with exactly the same start address as you got from malloc. There is no way around this, malloc is designed like this. Putting up your own ways around this is complicated and usually not worth it. Modern run-times have quite efficient garbage collection behind malloc/free (for its buffers, not for user allocations) and it will be hard for you to achieve something better, better meaning more efficient but still guaranteeing the consistency of your data. Before losing yourself in such a project measure where the real bottlenecks of your program are. If the allocation part is a problem there is still another possibility that is more likely to be the cause, namely bad design. If you are using so many elements in your linked list such that allocation dominates, probably a linked list is just not the appropriate data structure. Think of using an array with a moving cursor or something like that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536449", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: jQuery Mobile footer not fixed when listview dynamically added I am dynamically building a list view when a page loads and have my footer set to fixed but it doesn't work when the listview is dynamically added. How can I fix this? http://www.blueshoemobile.com/preview/buzzoffbase/categories.html?cat_id=96&cat_title=Restaurants Thanks! A: Set $.mobile.autoInitializePage to false in the beginning of your script. After dynamically generating the DOM with the correct roles, call $.mobile.initializePage()
{ "language": "en", "url": "https://stackoverflow.com/questions/7536451", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Program to measure small changes in reaction-time I need some advice on writing a program that will be used as part of a psychology experiment. The program will track small changes in reaction time. The experimental subject will be asked to solve a series of very simple math problems (such as "2x4=" or "3+5="). The answer is always a single digit. The program will determine the time between the presentation of the problem and the keystroke that answers it. (Typical reaction times are on the order of 200-300 milliseconds.) I'm not a professional programmer, but about twenty years ago, I took some courses in PL/I, Pascal, BASIC, and APL. Before I invest the time in writing the program, I'd like to know whether I can get away with using a programming package that runs under Windows 7 (this would be the easiest approach for me), or whether I should be looking at a real-time operating system. I've encountered conflicting opinions on this matter, and I was hoping to get some expert consensus. I'm not relishing the thought of installing some sort of open-source Linux distribution that has real-time capabilities -- but if that's what it takes to get reliable data, then so be it. A: Affect seems like it could save you the programming: http://ppw.kuleuven.be/leerpsy/affect4/index2.php. Concerning accuracy on a windows machine, read this.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536452", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: RewriteRule to accept 3 parameters but 2nd & 3rd param are optional mydomain.com/MyFolder/parameter-1 I have this htaccess RewriteRule - RewriteRule ^([a-z0-9\-]+)/?$ index.php?c=$1 [NC,L] The htaccess file is inside [MyFolder] and this only accept a single parameter. How can do a RewriteRule to accept 3 parameters but the 2nd and 3rd parameters are optional so that the following 4 URLs are ALL possible mydomain.com/MyFolder/param-1/param-2/param-3 mydomain.com/MyFolder/param-1 mydomain.com/MyFolder/param-1/param-2 mydomain.com/MyFolder/param-1/param-3 Edit : Ill make it that PARAM3 always starts with the word [pop] Thanks A: RewriteRule ^([a-z0-9\-]+)/?([a-z0-9\-]+)?/?([a-z0-9\-]+)?/?$ index.php?c=$1&d=$2&e=$3 [NC,L] This would work for: mydomain.com/MyFolder/param-1/param-2/param-3 mydomain.com/MyFolder/param-1 mydomain.com/MyFolder/param-1/param-2 with $_GET[d] and $_GET[e] having as value '' in certain cases. Having: mydomain.com/MyFolder/param-1/param-2 mydomain.com/MyFolder/param-1/param-3 Seems impossible to me as is, how can you know if the second is param 2 or param 3 ?
{ "language": "en", "url": "https://stackoverflow.com/questions/7536454", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Importance of Cocos2D CCScenes? I recently followed Ray Wenderlich's Cocos2D tutorial for putting Cocos2D in a UIKit app. I am currently only using Cocos2D in only one of my UIViews. In the tutorial he uses a CCScene which is a specific .h and .m class in the project. In the scene is some code which I do not know the important of either. I must say that I am new to Cocos2D and I am wondering what is the point of a CCScene? Do I need to use it in my situation? And if so, how? Thanks! Edit1: Is this correct? I am also adding a simple game loop so should I do it in the way I am doing it below or should I use CADisplayLink? //Cocos2D methods -(id) init { if((self=[super init])) { CCScene *scene = [CCScene node]; CCLayer *layer = [CCLayer node]; [scene addChild:layer]; [[CCDirector sharedDirector] runWithScene:scene]; [self performSelector:@selector(cocosgameLoop:) withObject:nil afterDelay:1/60.0f]; } return self; } - (void)cocosgameLoop:(ccTime)dT { //Check for collisions here and add gravity, etc.... } - (void)viewDidUnload { [super viewDidUnload]; [[CCDirector sharedDirector] end]; } // A: CCScene is a root node in a scene graph. A node that have no parents. CCDirector operates with CCScenes only. Read this for more information: http://www.cocos2d-iphone.org/wiki/doku.php/prog_guide:lesson_3._menus_and_scenes ANSWER TO YOUR COMMENT Actually you don't have to understand how CCScene is implemented. But if you want something to be rendered with cocos2d you have to create a CCScene and pass it to CCDirector. The common way is: CCScene *scene = [CCScene node]; CCLayer *layer = [CCLayer node]; [scene addChild:layer]; [[CCDirector sharedDirector] runWithScene:scene]; Usually you have to subclass a CCLayer and reimplement init method to add your staff (sprites for example). Take a look at programming guide for more more detailed answer: http://www.cocos2d-iphone.org/wiki/doku.php/prog_guide:index
{ "language": "en", "url": "https://stackoverflow.com/questions/7536455", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: fancybox navigation arrows I've tried for hours to resolve this issue. I would sincerely appreciate some help. I'm trying to implement a jquery animation for the navigation arrows that appear once a [grouped] item is opened up in fancybox. The left or right navigation arrows appear after hovering over the #fancybox-left or #fancybox-right portion that divides the object. For instance, I've positioned the right arrow (defined as #fancybox-right-ico) by setting "right: -__px" under #fancybox-right:hover span so that the arrow is just outside of #fancyboxcontent. I want to use the jquery animation function so that the #fancybox-right-ico appears to slide out from under #fancyboxcontent instead of just appearing as it does by default. I've tried using this tutorial for reference. Where should I place the following code in the fancybox files and how should I label '#navigation a', '#navigation > li', and 'a'? $(function() { $('#navigation a').stop().animate({'marginLeft':'-85px'},1000); $('#navigation > li').hover( function () { $('a',$(this)).stop().animate({'marginLeft':'-2px'},200); }, function () { $('a',$(this)).stop().animate({'marginLeft':'-85px'},200); } ); }); Thanks so much. A: Try something like this (demo): $("a").fancybox({ onComplete: function() { $('#fancybox-left-ico, #fancybox-right-ico').css({ opacity: 0 }); $('#fancybox-left, #fancybox-right').hover(function(e) { var enter = (e.type === "mouseenter"), dir = ($(this).is('#fancybox-left')) ? { left : (enter) ? '-30px' : 0 }: { right: (enter) ? '-30px' : 0 }; dir.opacity = (enter) ? 1 : 0; $(this).find('span').stop().animate(dir, 400); }); } }); It doesn't slide out from under the image because the hoverable area needs to overlap it... if it was under, the hover wouldn't work.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536456", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Delphi TDBGrid How to change selected color when style is gdsGradient I'm just trying to use delphi XE, before that I've been a big fan of Delphi7. I see the new dbgrid allows to use themed and gradient styles. I'm using gradient and set rowselect, it has a property for gradient-start and -end for the column header. But where is the property to set the selected color ? It's strange because the color doesn't match, selected color is always a blue gradient. I can do it with customdraw, I just want to know if there is anyway to change it without custom drawing. A: The selected color comes from the OS. There it's coded as clHighlight. You cannot change it as such, but you can subclass the dbgrid and override the DrawCell method. Or even easier add a onDrawCell eventhandler. procedure TForm1.DBGrid1DrawCell(Sender: TObject, const Rect: TRect; Field: TField; State: TGridDrawState); var index: Integer; begin if not(gdSelected in State) then DefaultDrawCell(Rect, Field, State) else begin index := ARow * DBGrid1.ColCount + ACol; DBGrid1.Canvas.Brush.Color := clYellow; <<-- some color DBGrid1.Canvas.FillRect(Rect); if (gdFocused in State) then begin DBGrid1.Canvas.DrawFocusRect(Rect); end; ImageList1.Draw(DBGrid1.Canvas,Rect.Left,Rect.Top,index, True); end;
{ "language": "en", "url": "https://stackoverflow.com/questions/7536457", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: EF 4.1 and "Collection was modified; enumeration operation may not execute." exception This has been driving me nuts for the last 2 days. I have 3 pretty basic classes (well, reduced for readability) public class Employee { public string Name { set; get; } virtual public Employer Employer { set; get; } public Employee(string name) { this.Name = name; } } , // this basically ties Employee and his role in a company. public class EmployeeRole{ public int Id { set; get; } virtual public Employee Employee { set; get; } public string Role { set; get; } public EmployeeRole(Employee employee, string role){ this.Employee = employee; this.Role = role; } } and public class Employer{ public string Name { set; get; } List<EmployeeRole> employees = new List<EmployeeRole>(); virtual public List<EmployeeRole> Employees { get { return this.employees; } } public Employer(string name, Employee creator){ this.Name = name; this.Employees.Add(new EmployeeRole(creator, "Creator")); creator.Employer = this; } } Seems pretty simple. Not doing any specific configuration for those classes in DbContext. But, when I run following code using (DbContext db = DbContext.GetNewDbContext()){ Employee creator = new Employee("Bob"); db.Employees.Add(creator); db.SaveChanges(); Employer employer = new Employer("employer", creator); db.Employers.Add(employer); db.SaveChanges(); // I know I can call SaveChanges once (and it actually works in this case), // but I want to make sure this would work with saved entities. } It throws following exception: Collection was modified; enumeration operation may not execute. Stack trace: at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource) at System.Collections.Generic.List1.Enumerator.MoveNextRare() at System.Collections.Generic.List1.Enumerator.MoveNext() at System.Data.Objects.ObjectStateManager.PerformAdd(IList1 entries) at System.Data.Objects.ObjectStateManager.AlignChangesInRelationships(IList1 entries) at System.Data.Objects.ObjectStateManager.DetectChanges() at System.Data.Objects.ObjectContext.DetectChanges() at System.Data.Entity.Internal.InternalContext.DetectChanges(Boolean force) at System.Data.Entity.Internal.Linq.InternalSet1.ActOnSet(Action action, EntityState newState, Object entity, String methodName) at System.Data.Entity.Internal.Linq.InternalSet1.Add(Object entity) at System.Data.Entity.DbSet`1.Add(TEntity entity) Anyone has an idea what's going on and maybe how to fix it ? Thanks ! A: I've just recently come across this problem myself. What I found is that EF hates indirect circular references. In your case it seems Employer should own the relationship to employee. So take out the reference back to employer from the employee class. A: I had the same problem. It looks like a bug in EF. I changed my code to explicitly add the entity to EF context before setting it to any other entity property. A: For me this looks like a bug in Entity Framework. I've cooked down your example to a simpler one but with the same structure: public class TestA // corresponds to your Employee { public int Id { get; set; } public TestB TestB { get; set; } // your Employer } public class TestB // your Employer { public TestB() { TestCs = new List<TestC>(); } public int Id { get; set; } public ICollection<TestC> TestCs { get; set; } // your EmployeeRoles } public class TestC // your EmployeeRole { public int Id { get; set; } public TestA TestA { get; set; } // your Employee } These are three entities with cyclic relationships: TestA -> TestB -> TestC -> TestA If I use now a corresponding code with the same structure than yours I get the same exception: var testA = new TestA(); var testB = new TestB(); var testC = new TestC(); context.TestAs.Add(testA); testA.TestB = testB; testB.TestCs.Add(testC); testC.TestA = testA; context.ChangeTracker.DetectChanges(); Note that I have used DetectChanges instead of SaveChanges because the stack trace in the exception makes clear that actually DetectChanges causes the exception (which is called internally by SaveChanges). I also found that calling SaveChanges twice is not the problem. The problem here is only the "early" adding to the context before the whole object graph is completed. The collection which was modified (as the exception is complaining about) is not the TestB.TestCs collection in the model. It seems to be a collection of entries in the ObjectStateManager. I could verify this by replacing ICollection<TestC> TestCs with a single reference by TestC TestC in the TestB class. This way the model doesn't contain any collection at all but it still throws the same exception about a modified collection. (SaveChanges will fail though with three single references because EF doesn't know in which order to save the entities due to the cycle. But that is another problem.) I would consider it as a bug that EF change detection (DetectChanges) seems to modify its own internal collection it is just iterating through. Now, the fix to this problem is easy: Just Add entities to the context as your last step before you call SaveChanges: var testA = new TestA(); var testB = new TestB(); var testC = new TestC(); testA.TestB = testB; testB.TestCs.Add(testC); testC.TestA = testA; context.TestAs.Add(testA); context.ChangeTracker.DetectChanges(); EF will add the whole related object graph to the context. This code succeeds (also using SaveChanges instead of DetectChanges). Or your example: using (DbContext db = DbContext.GetNewDbContext()){ Employee creator = new Employee("Bob"); Employer employer = new Employer("employer", creator); db.Employees.Add(creator); db.SaveChanges(); } Edit This was the same exception: Entity Framework throws "Collection was modified" when using observable collection. Following the code in that example the situation was similar: Adding an entity to the context and then afterwards changing/adding relationships to that entity. Edit2 Interestingly this throws the same exception: var testA = context.TestAs.Find(1); // assuming there is already one in the DB var testB = new TestB(); var testC = new TestC(); testA.TestB = testB; testB.TestCs.Add(testC); testC.TestA = testA; context.SaveChanges(); // or DetectChanges, it doesn't matter So, I want to add relationships with new entities to the existing entity. A fix to this problem seems to be less obvious. A: I ran into the same issue this morning, in my case I had an "Employee-Manager" association defined with a circular relationship. For example: public class Employee { public string Name { set; get; } virtual public Employee Manager { set; get; } public Employee() { } } The app was crashing with the error above when setting the Manager property. At the end it turned out to be a bad implementation of the GetHashCode() method in the Employee class. It seemed that EF was not able to spot the modified entity since the comparison among the entities was failing; thus, EF was thinking the collection had been modified.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536459", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: Sql server ide for refactoring Is there an IDE for SQL Server that includes refactoring? For an example, if I have a composite primary key on a table and I change it, sql management studio will drop all foreign keys referencing to this primary key (it will warn first). Is there a tool that generates the DROP statements for the foreign keys and recreates them? A: I would look into the SQLDeveloper product from redgate. They offer some refactoring features in their SQL Prompt product. Also take a look at the SQL Compare tool. Both are worth every penny. A: I would recommend looking at the Database project type in VS2010, if you haven't already. It has a lot of features that make DB refactoring easier than working SQL Server Management Studio. For example it does a lot of build-time validation to make sure your database objects don't reference objects which no longer exist. For example if you rename a column, it will give you build errors for FKs that reference the old column name. Also, it has very handy "compare" feature which compares the DB project scripts & databases, generates a DIFF report, and generates the scripts to move selected changes between the two (either DB project to SQL Server, or vice versa). I'm not sure it will automatically handle your composite key example -- in other words, when you rename a column it won't fix up all references to that column throughout the project. However, since all of the database objects are kept in scripts within the project, things like column renames are just a search & replace operation. Also if you make a mistake you will get build errors when it validates the database structure. So at least makes it easy to find the places that you need to change. There are probably more powerful tools out there (I have heard good things about redgate) but the VS2010 support for the Database project type is fairly decent. A: The way your objects handle foreign key references is upon creation of the table/constraint. ON DELETE CASCADE would only be one option. You can also have it set to NULL or default. Unless I am misunderstanding your question, it is not the environment but the object parameters that dictate this.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536461", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there any way to perform a callback on a specified thread? I am writing a library, and would like to be able to fire a callback on a specified thread, so the end-user does not have to worry about thread-safety. I tried using ExecutionContext, but that didn't work out too well, it would fire in the specified context (a new thread), but not on the thread that originally called the function. The code should work like this: void Connect() { // This should be in the same thread .. SocketAsyncEventArgs.Completed += eventHandler; Socket.ConnectAsync(SocketAsyncEventArgs) } void eventHandler() { // .. as this } A: You can't just run your code on some existing thread. That thread is already executing other code. But, it can provide you some way to run your code on it. The main thread in a WPF application does this using Dispatcher.Invoke(). The main thread of a WinForms application uses Control.Invoke(). There is a more general way to do this: use Synchronization.Context.Current. This would work for the main thread of WPF or WinForms application, but would execute the callback on a thread pool thread otherwise. (Unless there is some sort of custom synchronization context, which I think is very rare.) But this is the best you can do. Like I said, you can't run your code on some other thread when you want. The code in that other thread has to allow you to do that. A: That's the thing about asynchronous functions -- you can't guarantee when you'll get called back, or what thread will be running your callback function. Consider that the cost of being able to "set it and forget it". There's usually no need for that much control anyway. If you "need" to have a specific thread run your callback, what you really need is to review why that's necessary. If it's something that needs to run on the UI thread, there's Control.Invoke. (The UI thread anticipates needing to be handed stuff to do, because of how the architecture works, so controls have a way to pass callbacks to run on that thread. You can't just up and do that with arbitrary threads -- they have to be expecting to be passed a callback like that.) Otherwise, if you have an issue with locks or something, chances are you're trying to use asynchronous functionality to do stuff that should really be done synchronously in a separate thread.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536462", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Create a 2D array with a nested loop The following code n = 3 matrix = [[0] * n] * n for i in range(n): for j in range(n): matrix[i][j] = i * n + j print(matrix) prints [[6, 7, 8], [6, 7, 8], [6, 7, 8]] but what I expect is [[0, 1, 2], [3, 4, 5], [6, 7, 8]] Why? A: Note this: >>> matrix = [[0] * 3] * 3 >>> [x for x in matrix] [[0, 0, 0], [0, 0, 0], [0, 0, 0]] >>> [id(x) for x in matrix] [32484168, 32484168, 32484168] >>> Three rows but only one object. See the docs especially Note 2 about the s * n operation. Fix: >>> m2= [[0] * 3 for i in xrange(5)] >>> [id(x) for x in m2] [32498152, 32484808, 32498192, 32499952, 32499872] >>> Update: Here are some samples of code that gets an answer simply (i.e. without iter()): >>> nrows = 2; ncols = 4 >>> zeroes = [[0 for j in xrange(ncols)] for i in xrange(nrows)] >>> zeroes [[0, 0, 0, 0], [0, 0, 0, 0]] >>> ap = [[ncols * i + j for j in xrange(ncols)] for i in xrange(nrows)] >>> ap [[0, 1, 2, 3], [4, 5, 6, 7]] >>> A: Try running matrix[0][0] = 0 after that. Notice it now becomes: [[0, 7, 8], [0, 7, 8], [0, 7, 8]] So it's changing all three at the same time. Read this: http://www.daniweb.com/software-development/python/threads/58916 That seems to explain it. A: >>> it = iter(range(9)) >>> [[next(it) for i in range(3)] for i in range(3)] [[0, 1, 2], [3, 4, 5], [6, 7, 8]] just replace 3 with n and 9 with n**2 Also (just answer the "why?"), you're making copies of the same list with multiplication and, therefore, modifying one of them will modify all of them.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536465", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Rails: How to insert a text_field without a form just to test the layout? I am just doing the layout for my app at the moment and I want to insert a text.field that does nothing just to see how it looks. How can I do this? A: There are a few ways that could do what you want. 1) just write the static HTML <input type="text" name="dummy" /> 2) Using text_field_tag <%= text_field_tag "dummy", nil %> 3) Building a dummy form using a form_for for a dummy object <%= form_for SomeModel.new do |f| %> <%= f.text_field :column_name %> <% end %>
{ "language": "en", "url": "https://stackoverflow.com/questions/7536466", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: MySQL Left Outer Join, MAX() and other columns I have one table which stores all outbound SMS text messages. The second table stores a number of delivery receipts for each message (between 1 and 20 delivery receipts per message). I have the following SQL: SELECT messages_sent.id, messages_sent.user_id, messages_sent.api_key, messages_sent.to, messages_sent.message, messages_sent.sender_id, messages_sent.route, messages_sent.submission_reference, messages_sent.unique_submission_reference, messages_sent.reason_code, messages_sent.timestamp, MAX(delivery_receipts.id) AS dlr_id, delivery_receipts.dlr_status FROM messages_sent LEFT OUTER JOIN delivery_receipts ON messages_sent.id = delivery_receipts.message_id WHERE message_id = '466182' GROUP BY messages_sent.id There are 2 delivery receipts for message #466182. The correct dlr_id is returned (the most recent one) however, the dlr_status that is returned is the first one. dlr_status should be 5 instead of 2. Any help would be very much appreciated. A: change to this: Select m.id, m.user_id, m.api_key, m.to, m.message, m.sender_id, m.route, m.submission_reference, m.unique_submission_reference, m.reason_code, m.timestamp, d.id dlr_id, d.dlr_status From messages_sent m Left Join delivery_receipts d On d.message_id = m.id And d.dlr_id = (Select Max(dlr_id) From delivery_receipts Where message_id = m.id) Where message_id = '466182' A: Just a minor tweak to your query should do: SELECT m.id, m.user_id, m.api_key, m.to, m.message, m.sender_id, m.route, m.submission_reference, m.unique_submission_reference, m.reason_code, m.timestamp, MAX(d.id) AS dlr_id, (select d1.dlr_status from delivery_receipts d1 where d1.id = max(d.id)) as dlr_status FROM messages_sent m LEFT OUTER JOIN delivery_receipts d ON m.id = d.message_id AND d.message_id = '466182' GROUP BY m.id Please check.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536469", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Quick C++ data to Java transfer I'm trying to transfer a stream of strings from my C++ program to my Java program in an efficient manner but I'm not sure how to do this. Can anyone post up links/explain the basic idea about how do implement this? I was thinking of writing my data into a text file and then reading the text file from my Java program but I'm not sure that this will be fast enough. I need it so that a single string can be transferred in 16ms so that we can get around 60 data strings to the C++ program in a second. A: Text files can easily be written to and read from upwards with 60 strings worth of content in merely a few milliseconds. Some alternatives, if you find that you are running into timing troubles anyway: Use socket programming. http://beej.us/guide/bgnet/output/html/multipage/index.html. Sockets should easily be fast enough. There are other alternatives, such as the tibco messaging service, which will be an order of magnitude faster than what you need: http://www.tibco.com/ Another alternative would be to use a mysql table to pass the data, and potentially just set an environment variable in order to indicate the table should be queried for the most recent entries. Or I suppose you could just use an environment variable itself to convey all of the info -- 60 strings isn't very much. The first two options are the more respectable solutions though. A: Serialization: protobuf or s11n A: Pretty much any way you do this will be this fast. A file is likely to be the slowest and it could be around 10ms total!. A Socket will be similar if you have to create a new connection as well (its the connect, not the data which will take most time) Using a socket has the advantage of the sender and receiver knowing how much data has been produced. If you use a file instead, you need another way to say, the file is complete now, you should read it. e.g. a socket ;) If the C++ and Java are in the same process, you can use a ByteBuffer to wrap a C array and import into Java in around 1 micro-second.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536470", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Guice injection and RequestFactory: Extending ServiceLayerDecorator I searched for a solution to use Guice Dependency injection together with RequestFactory. I stumbled upon this: https://github.com/etiennep It wasn't working for me so I changed the InjectedServiceLayerDecorator.java implementation to this: https://github.com/opncow/injected-requestfactory/blob/master/src/main/java/com/trycatchsoft/gwt/requestfactory/InjectedServiceLayerDecorator.java Now my questions are: Can something be done better regarding the caching mechanism of RequestFactory (Is it still working?)? What is getTop() and getNext() (in ServiceLayerDecorator) for? And is it correct / safe to use getTop() in this place? Sorry thought too complicated! It was as easy as: Class<?> serviceClazz = resolveServiceClass(requestContext); return injector.getInstance(serviceClazz); A: What is getTop() and getNext() (in ServiceLayerDecorator) for? ServiceLayer uses a chain of responsibility pattern: in cases your decorator has nothing specific to do, it should delegate to the next decorator in the chain (returned by getNext) by calling the same method with the same arguments. If your decorator changes the arguments, or needs to call another method, it should call it on getTop so the call is routed through all decorators, and not just the ones after itself in the chain. Your use of getTop is thus correct and safe (have a look at the LocatorServiceLayer from GWT, that's exactly what it does). But your code (and Etienne's one!) can actually be made simpler and better: simply override createServiceLocator to get an instance from your injector (same as createLocator).
{ "language": "en", "url": "https://stackoverflow.com/questions/7536477", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Retreving date from Hibernate TImestamp I have a field with temporal type as Timestamp to save both date and time to the database. @Temporal(TemporalType.TIMESTAMP) @Column(name="date", nullable=false) private Date date; But when displaying the value to the user, I just want to show date part and truncate time part. I tried this but I get ParseException probably because of the Nanosecond part of the Hibernate Timestamp. SimplDateFormat sd = new SimpleDateFormat("MM/dd/yyyy"); return sd.parse(date.toString()); So how do I retrieve just date from Hibernate Timestamp? Thanks A: Just format the date object. The toString method isn't guaranteed to give you a string in a format that can then be parsed. String dateStr = sd.format(date); That will give you a date string in MM/dd/yyyy format that you can then convert back into a Date. Date fancyNancy = sd.parse(dateStr); * EDIT * Run this code and verify it prints out the day, month and year with no time. try { Date d = new Date(); SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy"); System.out.println("Original Date: " + d); System.out.println("Formatted Date: " + df.parse(df.format(d))); } catch (Exception e) { e.printStackTrace(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7536479", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Calling an UnmanagedFunctionPointer in C# for custom calling conventions I have a function in a DLL: char __usercall MyUserCallFunction<al>(int arg1<esi>) Because I hate myself I'd like to call this from within C# using P/Invoke. Normally this can be done by getting a function delegate, a la: [UnmanagedFunctionPointer(CallingConvention.ThisCall, CharSet = CharSet.Auto, SetLastError = true)] public delegate char DMyUserCallFunction(IntPtr a1); And then invoking it by doing: var MyFunctionPointer = (DMyUserCallFunction)Marshal.GetDelegateForFunctionPointer(AddressOfFunction, typeof(DMyUserCallFunction)); MyFunctionPointer(IntPtr.Zero); For custom user calling conventions, however, this will cause the program to crash. Is there some sort of way I can do this using unsafe code or some sort of wrapper function that puts the delegates in place, but doesn't force me to write a C++ DLL? Thanks! Edit: As suggested by dtb, I created a very small C++ DLL which I use via P/Invoke to call the function. For anyone curious the function in C++ ends up looking like: extern "C" __declspec(dllexport) int __stdcall callUsercallFunction(int functionPointer, int arg1 ) { int retVal; _asm { mov esi, arg1 call functionPointer mov retVal, eax } //Fake returning al, the lower byte of eax return retVal & 0x000000FF; } A: There's no hope of implementing custom calling conventions in C#. You must do this in either a native DLL or a C++/CLI DLL.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536484", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: jQuery append() is broken in IE? Is jQuery 1.6.4 append() is broken in IE? This code works everywhere but IE6+ $('<xml></xml>').append('<test>hello world</test>'); Is there a way to fix that? A: From the docs: jQuery( html, [ownerDocument] ) html A string of HTML to create on the fly. Note that this parses HTML, not XML. The argument passed to jQuery is not HTML(there is no html-element xml) so there will be nothing to append something to. Take a look at MSDN for informations about creation of XML-Documents in IE<9
{ "language": "en", "url": "https://stackoverflow.com/questions/7536490", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Inheriting properties with accessibility modifier in C# I tried to inherit interface, and make some of the automatically generated set property as private. This is an example. public class MyClass { public interface A { int X {get; set;} } public interface B : A { int Y {get; set;} } public class C : A { public int X {get; private set;} } When I tried to compile it. I got an error 'MyClass.C' does not implement interface member 'MyClass.A.X.set'. 'MyClass.C.X.set' is not public.. I tried with private set; in iterface A, but I got this error again : 'MyClass.A.X.set': accessibility modifiers may not be used on accessors in an interface. Is this accessibility modifier not allowed in C#? A: I tried with private set; in iterface A, but I got this error again If your interface only requires that a property should be retrievable, you define it as: public interface A { int X {get;} // Leave off set entirely } A: The declaration of an interface defines the public set of members that the implementing type must have. So, if C implements A, it must have a public member for each member defined by the interface. A defines that any implementing type must have a public property X with a public getter and a public setter. C does not meet this requirement. A: You can think of an interface as the minimum functionality that your class must implement. If the interface specifies that a property exposes a get and a set clause, then you must implement a public get and set clause in your class, because only public methods and properties can implicitly implement interfaces. You can simply leave out the set keyword in the interface property definition if you don't want to expose a public mutator. Then you can make the implementation mutator either public or private. A: No it is not allowed. Remember, code which is using an instance of class C must be able to treat it as an interface A, which means that the contract is a public getter and setter for property X. This applies to class inheritance as well as interface inheritance -- you must follow the contract of the type you are derived from. If the intent of the code is that property X should not have a public setter, then the interface should be defined with just the { get; } A: I believe interface members must be public if the interface itself is public. Your implementation of the property is faulty because of that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536491", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: How do you write a no-op statement? What is the best way to write a no-op statement in Delphi? Take this code: if a=b then SomeOldStatement else AnotherStatement; And say that you temporarily want to rem out SomeOldStatement. Would you just go for this solution: if a=b then //SomeOldStatement else AnotherStatement; Personally I don't like the empty then section and would like to have something compilable in there... if a=b then NoOp //SomeOldStatement else AnotherStatement; A: In Delphi 2005 and subsequent versions, you can define a NoOp empty procedure and mark it as inline. This way no code is generated unless you define {$INLINE OFF} or set Code inlining control to Off in Compiler Options. procedure NoOp; inline; begin // do nothing end; The resulting code is very clean: if a=b then NoOp //SomeOldStatement else AnotherStatement; A: That's the best option. I use it extensively for debugging, because I can put a breakpoint there, does not depend on another unit, does not interfere with your program in any way, and also is much faster than conditional breakpoints. if a=b then asm nop end else AnotherStatement; A: You can possibly use something like a:=a but, to be honest, I find that even uglier than a non-statement - you should code so that those that come after you will understand what you intended, and the command a:=a doesn't really follow that guideline. Since this is only a temporary thing, I would just wear the fact that you have no executable code in there. If, as you say, Delphi still compiles it just fine, you have no issue. If you want some code in there for a breakpoint, and there's no better way of doing it, I would consider temporarily doing the a:=a thing. If it was going to be a more permanent change, you could instead consider the reversal of the condition so that you have no empty blocks at all: if not (a = b) then AnotherStatement; or, better yet: if a <> b then AnotherStatement; A: How about assignment, a := a? That's a no-op. (I don't know Delphi, so syntax for the assignment may be wrong, but hopefully you can get the idea and correct the syntax if needed) A: Not sure why you need anything there at all (e.g. I'm happy with "then else"). But if you want something compilable there, I would do this: if a=b then begin end //SomeOldStatement else AnotherStatement; An empty begin block is the best noop I know of in Delphi. It will produce no assembler code and thus no overhead. A: if a=b then SomeOldStatement else AnotherStatement; should be written as if a=b then begin SomeOldStatement; end else begin AnotherStatement; end; now, you can comment out SomeOldStatement; with exactly the effect you are after, the debugger more accurately follows the flow of the code AND you avoid bizarre side effects in code like if a=b then if b=c then statement1 else if c=d then statement2; else statement2 else statement3; screw up your indenting, get a semicolon wrong, document out a line for testing and holy crap, things get ugly fast. seriously, try figuring out if the code I just wrote there is even valid without a compiler pass. now, guess what happens with this: if a=b then if b=c then statement1 else if c=d then statement2; // else statement2 else statement3; also: if a=b then statement1; statement2; can often do strange things, and even stranger things when you do if a=b then // statement1; statement2; serious - just get in the habit of ALWAYS having begin ends in all your logic - it makes your code easier to follow, avoids side effects, avoids mental parsing errors, code parsing errors and commenting out side effects. Plus, an empty begin/end is the same as your no-op. A: If statements without a begin end block are a bug waiting to happen and in this case adding in a begin end block will allow you to comment out your line without changing any more code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536493", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to update Sample Data in C# I have this sample data. Right now it is defined in a seperate C# file like this: public class SampleData{ public static ObservableCollection<Product> GetSampleData(){ ObservableCollection<Product> teams = new ObservableCollection<Product>(); } } and I load the obsevableCollection inside GetSampleData(). It works and I am able to get the Sample-Data anywhere in my program. But how can I redesign this code so that I can create the sample data on the fly from outside the class? A: What you are trying to implement is called a singleton pattern. It allows you to store a single instance of an object. Basically your problem is that every time you call GetSampleData you are creating a new instance of the ObservableCollection<Product> so you can’t get the same data gain by calling the method again. Your actual sample I think is not what you meant because in it’s posted form it wouldn’t compile because you missed the return teams;. I am guessing you want something like this: public class SampleData { private static ObservableCollection<Product> _Instance; public static ObservableCollection<Product> Instance { get { // Create a new collection if required. if (SampleData._Instance == null) { // Cache instance in static field. SampleData._Instance = new ObservableCollection<Product>(); } // Return new or existing collection. return SampleData._Instance; } } } Basically we are creating the object instance on the first call so when you call the Instance property again you get the same instance. Use it like this: // Add the data to the ObservableCollection<Product>. SampleData.Instance.Add(new dataObjectOrWhatEver()); // Get index 0 from the collection. var someObject = SampleData.Instance[0]; A: public class SampleData{ static ObservableCollection<Product> teams = null; static public ObservableCollection<Product> Teams{ get{ if(teams == null) teams = GetSampleData(); return teams; } set{ teams = value; } } // make this one private private static ObservableCollection<Product> GetSampleData(){ ObservableCollection<Product> t = new ObservableCollection<Product>(); // fill t with your data return t; } } AND for the cunsumer: public class MyCunsumerClass{ // the method that uses the Team that provided by SampleData public void MyMethod(){ this.flatteningTreeView.ItemsSource = SampleData.Teams; } public void MyFillerMethod(){ var my_new_data = new ObservableCollection<Product>(); // or anything else you want to fill the Team with it. SampleData.Teams = my_new_data; // SampleData.Teams has new value you suplied! } public void MyChangerMethod(){ var t = SampleData.Team; t.AnyProperty = my_value; t.OtherProperty = my_value_2; // SampleData.Team's properties changed! } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7536494", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Question about UITableView and deleteRowsAtIndexPaths My first question on stackoverflow (<< n00b). I'm working on my first project involving UITableViews and plists, and I'm having an issue. The property list consists of a dictionary holding 3 sections/categories (each an array) and a number of entries in each of these. The lists load just fine. The problem doesn't occur until I try making it possible to delete individual entries from the list. Here's my code: - (void)tableView:(UITableView *)tableView commitEditingStyle: (UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { if (editingStyle == UITableViewCellEditingStyleDelete) { //make array of the objects and remove the selected object from that array. NSMutableArray *delArray = [faves objectForKey:[entries objectAtIndex:indexPath.section]]; [delArray removeObjectAtIndex:indexPath.row]; //set entries to the value of the array, now sans the removed object. self.entries = delArray; [delArray release]; //write the updated entries to the plist file. NSArray *rootPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *docsPath = [rootPath objectAtIndex:0]; NSString *plistFile = [docsPath stringByAppendingPathComponent:@"Data.plist"]; [faves writeToFile:plistFile atomically:YES]; //update the actual tableview. This is where things go awry. [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES]; //ends up trying to load the sections instead of the entries = wrong number of list items returned = crash! //[tableView reloadData]; //works if I only use this line, but the list updates wrong, showing each entry as a section header. } } The entry IS deleted from the plist correctly, but the table fails to update right and causes the app to crash. I've included the error code below. 2011-09-23 18:40:19.732 MyApp[10314:b303] *** Assertion failure in -[UITableView _endCellAnimationsWithContext:], /SourceCache/UIKit_Sim/UIKit-1448.89/UITableView.m:974 2011-09-23 18:40:19.734 MyApp[10314:b303] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of sections. The number of sections contained in the table view after the update (5) must be equal to the number of sections contained in the table view before the update (3), plus or minus the number of sections inserted or deleted (0 inserted, 0 deleted).' The first number (5) is consistent with how many records are supposed to be left in the affected category, but the second number (3) refers to the number of categories. Like I said above, the entry is deleted from the plist - just not the table. A: Considering the following two methods: - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return [entries count]; } -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { NSString *key = [entries objectAtIndex:section]; NSArray *sectionNames = [faves objectForKey:key]; return [sectionNames count]; } It appears that "entries" is an NSArray of key names (NSString) and that "faves" is an NSDictionary of section content (NSArrays). The problem is that you are replacing your array of key names (self.entries) with a single section's content array. I've expanded your code to make the logic error a little more obvious: // query for section key name by section index NSString * keyName = [entries objectAtIndex:indexPath.section]; // retrieve array of a section's datasource (array of rows) NSMutableArray * delArray = [faves objectForKey:keyName]; // remove row from a section's datasource [delArray removeObjectAtIndex:indexPath.row]; // ERROR: assign an array of rows to array used for section names self.entries = delArray; Changing your code to the following should remove the assertions generated by the UITableView: (void)tableView:(UITableView *)tableView commitEditingStyle: (UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { if (editingStyle == UITableViewCellEditingStyleDelete) { //make array of the objects and remove the selected object from that array. NSMutableArray *delArray = [faves objectForKey:[entries objectAtIndex:indexPath.section]]; [delArray removeObjectAtIndex:indexPath.row]; //write the updated entries to the plist file. NSArray *rootPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *docsPath = [rootPath objectAtIndex:0]; NSString *plistFile = [docsPath stringByAppendingPathComponent:@"Data.plist"]; [faves writeToFile:plistFile atomically:YES]; //update the actual tableview. This is where things go awry. [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES]; //ends up trying to load the sections instead of the entries = wrong number of list items returned = crash! //[tableView reloadData]; //works if I only use this line, but the list updates wrong, showing each entry as a section header. } A: If tableview delete when sourcing a array from plist file. Documents directory is the best choice.(Refer below) To delete a row and update the plist file again. In UITableViewCellEditingStyleDelete. in header @property (nonatomic, retain) NSMutableArray *arForTable; in CellForRowAtindexpath cell.textLabel.text=[[ self.arForTable objectAtIndex:indexPath.row] valueForKey:@"key"]; - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection (NSInteger)section { return [self.arForTable count]; } in - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { if (editingStyle == UITableViewCellEditingStyleDelete) { NSError *error; NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"data.plist"]; NSFileManager *fileManager = [NSFileManager defaultManager]; if (![fileManager fileExistsAtPath:dataPath]) { NSString *bundle = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"plist"]; [fileManager copyItemAtPath:bundle toPath:dataPath error:&error]; } [self.arForTable removeObjectAtIndex:indexPath.row]; [self.arForTable writeToFile:dataPath atomically:YES]; [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES]; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7536496", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: AJAX with HTML? I have a email system I am building for a company that they want to send emails with it. I have a custom HTML editor for it. What I am wanting to do it post the contents to a external PHP file and have it add to the database. function schedule_eblast (html) { var answer = confirm("Are you sure you want to start sending this E-blast?"); if (answer) { $.ajax({ type: "POST", url: "./../../../processes/eblast_schedule.php", data: {'html_text': html}, success: function(theRetrievedData) { if (theRetrievedData == "done") { alert("Your eblast has been successfully scheduled to send. To check it's status, go to the manage eblasts page."); } else { alert(theRetrievedData); } } }); return false; } And here is what I have for the header in the eblast_schedule.php file: <?php include('connect.php'); if ((isset($_POST['html_text'])) && (strlen(trim($_POST['html_text'])) > 0)) { $html_text = stripslashes(strip_tags($_POST['html_text'])); } else { $html_text = ""; } if ((isset($_POST['subject'])) && (strlen(trim($_POST['subject'])) > 0)) { $subject = stripslashes(strip_tags($_POST['subject'])); } else { $subject = ""; } ob_start(); And yes, it does get called. But when outputting html_text, it removes all the HTML. And when adding to the database, it doesn't show the HTML either. Help! Thanks. A: Remove those functions and add mysql_real_escape_string and it should work fine... include('connect.php'); if ((isset($_POST['html_text'])) && (strlen(trim($_POST['html_text'])) > 0)) { $html_text = mysql_real_escape_string($_POST['html_text']); } else { $html_text = ""; } if ((isset($_POST['subject'])) && (strlen(trim($_POST['subject'])) > 0)) { $subject = mysql_real_escape_string($_POST['subject']); } else { $subject = ""; } ob_start();
{ "language": "en", "url": "https://stackoverflow.com/questions/7536497", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: internal css will not work My internal css won't work with the little code I have. This seems like a really stupid question but nothing I do helps. <!DOCTYPE html> <html> <head> <meta http-equiv="content-type" content="text/html;charset=utf-8"/> <title>Ask Help</title> <style type = "text/css"> @font-face { font-family: "junction"; src: url("Junction_02.otf"); } html { background-image: linear-gradient(bottom, rgb(75,135,163) 2%, rgb(127,219,219) 54%); background-image: -o-linear-gradient(bottom, rgb(75,135,163) 2%, rgb(127,219,219) 54%); background-image: -webkit-linear-gradient(bottom, rgb(75,135,163) 2%, rgb(127,219,219) 54%); background-image: -ms-linear-gradient(bottom, rgb(75,135,163) 2%, rgb(127,219,219) 54%); background-image: -webkit-gradient(linear, left bottom, left top, color-stop(0.02, rgb(75,135,163)), color-stop(0.54, rgb(127,219,219)) } .menu { list-style-type: none; font-size: 25px; } h1 { font-family: junction; text-size: 60px; } </style> </head> <body> <nav> <ul class="menu"> <li><a href="index.html" title="Home">Home</a></li> <li><a href="about.html" title="About Us">About</a></li> <li><a href="past.html" title="iPod">Past Q&amp;A's</a></li> </ul> </nav> </body> </html> A: This line is missing a close parenthesis ) which is affecting your markup: background-image: -webkit-gradient(linear, left bottom, left top, color-stop(0.02, rgb(75,135,163)), color-stop(0.54, rgb(127,219,219)) Change it to this: background-image: -webkit-gradient(linear, left bottom, left top, color-stop(0.02, rgb(75,135,163)), color-stop(0.54, rgb(127,219,219))); You should look into using W3C's HTML and CSS validation tools to catch problems like these. The HTML validator isn't great about catching bad CSS, so you can copy-paste your embedded CSS into the CSS validator. Oh and might as well put a semi-colon at the end of that last background-image statement (I did it for you), since it'll save you grief if you add more lines in the future but forget to add the semi-colon to the previous line.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536498", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Maintaining data sync between UITableView cells and array of model objects I have a UITableView where each cell corresponds to a model object.The list of these model objects are kept in an array inside a singleton object that manages the model objects. The UITableViewController subclass holds a instance variable that references this singleton object. The model objects update their internal data asynchronously from the web. What's the best method for updating the table cells when the corresponding model object finishes reloading its data? Should the model objects send out a notification? Can the table cells use KVO to receive changes from the model objects? Is there another option? What is the best practice here? A: I found a solution by subclassing UITableViewCell. Each cell maintains a reference to the model object that it corresponds to and observes a boolean isLoading property of this object. When the loading state changes, the cell updates it's data. In other words, the cell (view) object observes the model object, then requests data to present upon the model object state changing. A: I'm not sure that is the best solution but in a previous project I was calling the message reloadRowsAtIndexPaths: NSArray* paths = [[NSArray alloc] initWithObjects:indexPath, nil]; [tableView reloadRowsAtIndexPaths:paths withRowAnimation:UITableViewRowAnimationMiddle];
{ "language": "en", "url": "https://stackoverflow.com/questions/7536501", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using custom keywords to set link in javascript The script implications are more advanced, but I've condensed it down to this following problem: In a nutshell I have some keyword variables set with javascript. These keyword variables contain URLs. What I need is when a person inputs a keyword he will be taken to a specific URL. I've created a sample page illustrating my problem: <a href="" class="link">LINK</a><br> <input type="text" class="text" value="hallo" /> <input type="button" onclick="check();" value="Click ME"> <script type="text/javascript"> function check() { var key1 = "some_link1.com"; var key2 = "some_link2.com"; var key3 = "some_link3.com"; var l = document.getElementsByClassName("link")[0]; var t = document.getElementsByClassName("text")[0]; if (t.value == "key1" || t.value == "key2" || t.value == "key3") { l.href = t.value; alert(t.value); } }</script> The problem lies between the ** because the script must recognize that the value corresponds to the variable and use thet value instead. However currently I'm only getting the inputted value. By the way I can't use a form or reload the page. It has to happen "live". Any thoughts? PS. the script is not meant to run, but to illustrate my point: http://jsfiddle.net/UhgKG/3/ A: <a href="" id="link">LINK</a><br> <input type="text" id="text" value="hallo" /> <input type="button" onclick="check();" value="Click ME"> <script type="text/javascript"> function check() { var key1 = "some_link1.com"; var key2 = "some_link2.com"; var key3 = "some_link3.com"; var l = document.getElementById("link"); var t = document.getElementById("text").value; if (t == "key1" || t == "key2" || t == "key3") { l.href = eval(t); // no risk as we run this line if and only if the value is one of the options defined in the if alert(t); } } </script> A: Partly because I avoid eval() when there are other ways, but also because it just seems cleaner, is more extensible and is less code, I'd do it like this with an object lookup rather than the separate variables, the multiple if tests and the eval: <a href="" id="link">LINK</a><br> <input type="text" id="text" value="hallo" /> <input type="button" onclick="check();" value="Click ME"> <script type="text/javascript"> function check() { var keys = { key1: "some_link1.com", key2: "some_link2.com", key3: "some_link3.com" }; var l = document.getElementById("link"); var t = document.getElementById("text").value; if (t in keys) { l.href = keys[t]; alert(t); } } </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/7536508", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I differentiate between Android and iPad with media query? In a page I'm making, I'm writing a secondary stylesheet for mobile devices that overwrites selected parts of the first stylesheet. I'm using media queries in the following way: <link rel="stylesheet" href="assets/ui.css"> <link media="only screen and (max-device-width: 480px)" rel="stylesheet" href="assets/ui_mobile.css" type="text/css"> This works for iPhone. My goal is to create a query that will activate if it's an iPhone or Android, and then let the iPad use the standard desktop styling. When I switch it to max-device-width: 800px, it triggers on the iPhone and Android, but also triggers on iPad. It should not be doing this, as the max-device-width of the iPad is allegedly 780px. But it is, for whatever reason. I've used many permutations of various widths, heights, and aspect ratios, but to no avail. Does anyone know a workable way of differentiating between these three? Any suggestions are appreciated. Thanks! A: When I switch it to max-device-width: 800px, it triggers on the iPhone and Android, but also triggers on iPad. It should not be doing this, as the max-device-width of the iPad is allegedly 780px. But it is, for whatever reason. I think you're misunderstanding how max-device-width works. Since the max-device-width of an iPad is 780px, it falls below the 800px limit just as validly as the iPhone does. A: Try using physical measurements rather than pixels - what you are trying to do is restrict to small screens, independent of resolution. Try max-device-width:12cm Which will only match physically small screens, like a phone (no matter how high resolution), but not larger ones like tablets, regardless how the resolutions change in the future.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536510", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Objective-C - C style string allocation leak? I have a very simple app. From the main screen I launch a new view ("learn view") that displays an image and a label. on the learn view there is a menu button and a next button. When the user taps the next button, the view updates the image and the label from char * array of C strings. However, when I do this, the instruments allocations shows a forever growing number of allocations that are not reduced when the view is destroyed by clicking the menu button. If I just display the learn view then click menu there is no problem, the allocations go up and then go back down to the prior level, but if I click next updating the label.text, then allocations are made that are not recovered. Instruments reports no leaks. here are relevant code snippets: LearnVC.h @interface LearnVC : UIViewController { IBOutlet UIImageView *imageView; IBOutlet UILabel *labelView1; NSInteger page; } @property (retain, nonatomic) UIImageView *imageView; @property (retain, nonatomic) UILabel *labelView1; @property NSInteger page; - (IBAction)handleNext; - (IBAction) gotoMenu; @end LearnVC.m #import ... char *states[] { "Alabama", "Alaska", "Arizona", ... }; #define maxStates 50 @implementation LearnVC @synthesize ... - (void)viewDidLoad { NSString *tstring; self.page = 0; //test!!!! tstring = [[NSString alloc] initWithCString:states[self.page] encoding:NSUTF8StringEncoding]; labelView1.text = tstring; [tstring release]; [super viewDidLoad]; } - (IBAction) handleNext { NSString *tstring; self.page++; if (self.page > maxStates-1) { self.page = 0; } //test!!!! tstring = [[NSString alloc] initWithCString:states[self.page] encoding:NSUTF8StringEncoding]; labelView1.text = tstring; [tstring release]; } - (void)dealloc { [imageView release]; [labelView1 release]; [super dealloc]; } This seems to occur anytime I update a view without removing (deallocating) it and re-adding it. Is there something with old C arrays that don't copy/release properly. Or some issue with UILabel.text properties that don't release memory? Any help is appreciated. Thanks beforehand, Neal I converted it to use NSArray - I added this to the .h file NSArray *statesArray; and @property (retain, nonatomic) NSArray *statesArray; then in the .m file in viewDidLoad NSArray *objects = [NSArray arrayWithObjects:@"Alabama", @"Montgomery", @"Alaska", @"Juneau" ,..., nil]; self.statesArray = objects; //I assume that since I didn't init it, I don't need to release objects. labelView1.text = [self.statesArray objectAtIndex:self.page];in dealloc [statesArray release]; Then in my handleNext labelView1.text = [self.statesArray objectAtIndex:self.page]; I run through the entire array, exit, reload, ect. and the allocations climb the first time through but stop climbing after I've been through the list once. This was not the case with the char * array, there must be something else going on, oh well, I'll just have to shed my old C ways and stick to NS/UI classes. This seems to have solved it. Now I'll work on the image loads and see if the it works the same. A: The initWithCString:encoding: method may make an internal copy of the C string you pass in, but is not guaranteed to free the copy during deallocation. Since the C strings you're passing are constant, and therefore can never be freed, you can instead use initWithBytesNoCopy:length:encoding:freeWhenDone: to avoid creating the extra copies. For example: NSString *s = [[NSString alloc] initWithBytesNoCopy:someCString length:strlen(someCString) encoding:NSUTF8StringEncoding freeWhenDone:NO]; A: Also, the system does a lot of caching, it acts like each control may cache the text it has used. I found that if I ran through the series a couple of times, then then allocations stopped rising, as if it had cached all it was going to. Allocations did not go down to the starting point when exiting learn view, but subsequent runs did not add anymore.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536520", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: JSON ajax and jquery, cannot get to work? I have the following script in my javascript... $.ajax({ type: 'POST', url: 'http://www.example.com/ajax', data: {email: val}, success: function(response) { alert(response); } }); And my php file looks like this... if ($_REQUEST['email']) { $q = $dbc -> prepare("SELECT email FROM accounts WHERE email = ?"); $q -> execute(array($_REQUEST['email'])); if (!$q -> rowCount()) { echo json_encode(error = false); } else { echo json_encode(error = true); } } I cannot get either the variable error of true or false out of the ajax call? Does it matter how I put the data into the ajax call? At the minute it is as above, where email is the name of the request, and val is a javascript variable of user input in a form. A: Try this instead. Your current code should give you a syntax error. if (!$q -> rowCount()) { echo json_encode(array('error' => false)); } else { echo json_encode(array( 'error' => true )) } A: In your code, the return parameter is json $.ajax({ type: 'POST', url: 'http://www.example.com/ajax', dataType: 'json', data: {email: val}, success: function(response) { alert(response); } }); PHP FILES if ($_REQUEST['email']) { $q = $dbc -> prepare("SELECT email FROM accounts WHERE email = ?"); $q -> execute(array($_REQUEST['email'])); if (!$q -> rowCount()) { echo json_encode(error = false); return json_encode(error = false); } else { echo json_encode(error = true); return json_encode(error = true); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7536525", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: can't seem to spot this error in BASH insists that there is a syntax error can't find the error here. when i run this program BASH comes up with "[ : 17: unexpected operator" i've tried it with a parameter ending in .c and with one in .java but neither seems to work. EXT=`echo $1 | cut -f2 -d"."` if [ "$EXT" == "c" ]; then NAME=`echo $1 | cut -f1 -d"."` gcc -Wall -o "$NAME" "$1" elif [ "$EXT" == "java" ]; then NAME=`echo $1 | cut -f1 -d"."` gcj -c -g -O $1 && gcj --main="$NAME" -o "$NAME" "${NAME}.o" else echo "hm... I don't seem to know what to do with that" fi A: test (aka [) doesn't have an == operator. String equality is = instead. Yes, that's a little bit weird. Also, case is nice for this: case "$1" in *.java) # java stuff here ;; *.c) # c stuff here ;; *) # otherwise... esac A: change all if [ "$EXT" == "c"/"java" ]; to if [ "$EXT" = "c"/"java" ];
{ "language": "en", "url": "https://stackoverflow.com/questions/7536528", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C#/Android Compatible Compression Algorithm I have a lot of plain-text content (English). I have a C# tool for creating the content, and it will be consumed in an Android app. I need, therefore, to know my options for compression algorithms. What library can I use to compress/decompress, where I can compress in C# and decompress in Java? I'm looking at probably 1-2MB of uncompressed text (at least), so it's definitely worth it to compress it. A: You should be able to zip in C# using something like this and unzip with this. GZIP format should do the trick.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536538", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PyGTK custom timing I need to have a custom timing for a component of my program (essentially i'm counting turns, at the rate of around 20 turns per second). Each turn i need to process some information. However, I have to do this so that it could work with PyGTK. Any ideas on how to accomplish this? A: The simplest solution is to use glib.timeout_add, which can periodically run code in the GLib main thread. If your calculation is time-consuming and needs to be run in a different thread, you can use Python's threading.Timer instead. When you're ready to update the GUI, use glib.idle_add.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536548", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: WCF Service Reference Support Files Not Updating I have a VS 2010 solution containing a WCF service project and a unit test project. The unit test project has a service reference to the WCF service. Web.config for the WCF service project sets a number of binding attributes to other-than-default values: web.config: (Specifically note maxBufferSize="20000000") <basicHttpBinding> <binding name="basicHttpBindingConfig" maxReceivedMessageSize="20000000" maxBufferSize="20000000" maxBufferPoolSize="20000000"> <readerQuotas maxDepth="32" maxArrayLength="200000000" maxStringContentLength="200000000"/> <security mode="TransportCredentialOnly"> <transport clientCredentialType="Ntlm"/> </security> </binding> </basicHttpBinding> While examining this issue, I came to realize that the unit test project's service reference support files do not contain the values I would expect (i.e. the values configured in the WCF service's web.config): configuration.svcinfo: (Specifically note maxBufferSize="65536") <binding hostNameComparisonMode="StrongWildcard" maxBufferSize="65536" messageEncoding="Text" name="BasicHttpBinding_IBishopService" textEncoding="utf-8" transferMode="Buffered"> <readerQuotas maxArrayLength="16384" maxBytesPerRead="4096" maxDepth="32" maxNameTableCharCount="16384" maxStringContentLength="8192" /> <security mode="None"> <message algorithmSuite="Default" clientCredentialType="UserName" /> <transport clientCredentialType="None" proxyCredentialType="None" realm="" /> </security> </binding> Deleting and re-creating the service reference or updating the service reference re-creates the files, but I still end up with the same values. Why? Update Here's the app.config of the client <binding name="BasicHttpBinding_IMyService" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="200000000" maxBufferPoolSize="200000000" maxReceivedMessageSize="200000000" messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true"> <readerQuotas maxDepth="32" maxStringContentLength="200000000" maxArrayLength="200000000" maxBytesPerRead="200000000" maxNameTableCharCount="200000000" /> <security mode="None"> <transport clientCredentialType="None" proxyCredentialType="None" realm="" /> <message clientCredentialType="UserName" algorithmSuite="Default" /> </security> </binding> A: That is correct behavior. Some information included in binding are specific to only one side of the configuration and both client and server can use completely different values. Also these values are defence against Denial of Service attach so service doesn't want to show them publicly. Those values affects only processing of incoming messages so service configures how it will handle incoming requests and client configures how it will handle incoming responses. Requests and responses can have different characteristics and different configuration. There is no need for service to be configured to accept 1MB requests if it always receives only few KB requests and returns 1MB responses. Btw. this is WCF specific feature not related to general web services and because of that there is no standardized way to describe this in WSDL. A: Same issue here and no solution after half a day messing about with config files... Changing automatically generated files is usually frowned upon, so my feeling says that "there has got to be a better way, Dennis". UPDATE: I got my problem fixed by removing the name attribute in the binding configuration. So your current web.config is looking like this <basicHttpBinding> <binding name="basicHttpBindingConfig" maxReceivedMessageSize="20000000" maxBufferSize="20000000" maxBufferPoolSize="20000000"> <readerQuotas maxDepth="32" maxArrayLength="200000000" maxStringContentLength="200000000"/> <security mode="TransportCredentialOnly"> <transport clientCredentialType="Ntlm"/> </security> </binding> </basicHttpBinding> would become <basicHttpBinding> <binding maxReceivedMessageSize="20000000" maxBufferSize="20000000" maxBufferPoolSize="20000000"> <readerQuotas maxDepth="32" maxArrayLength="200000000" maxStringContentLength="200000000"/> <security mode="TransportCredentialOnly"> <transport clientCredentialType="Ntlm"/> </security> </binding> </basicHttpBinding> I think you only need to this at the client-side. By removing the name attribute, you essentially change the default basicHttpBinding configuration for your app, as far as I understand it. Credits for this solution here. Another update: if you name your service configuration correctly (including the namespace) it will pick up the binding configuration. So instead of <service name="ServiceName"> you need <service name="My.Namespace.ServiceName">
{ "language": "en", "url": "https://stackoverflow.com/questions/7536550", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Accessing Data inside of a .jar I am currently putting a program into a .jar, and have difficulties telling it where to get its data from. The data was inside of a file in the project, and I am sure that it is located in the jar as well. But I have no clue on how to get a path into a jar. I found the getClass().getClassLoader().getResourceAsStream() method online to get an input stream into the jar, but since I used FileReaders all the time, I dont know what to do with it as well.. I`d be very thankful for any help. Edit: Here is a picture of how the directory is organized: My command window shows what happens if I run the .jar. Nullpointer in line 30. I tried it with and without .getClassLoader(), it just wont find it. Here is the inside of the jar: again, app is where the class files are in. Hence, via class.getResource.. I should be able to search in DataPackeg. Man, this is wearing me out. A: A key concept to understand is that files don't exist inside of jars. You must instead get your data as a read-only resource, and you will need to use a path that is relative to path of your class files. If you're still stuck, you may need to tell us more specifics about your current program, its structure, what type of data you're trying to get, where it's located in the jar file, and how you're trying to use it. For instance, say your package structure looked like this: So the class file is located in the codePackage package (this is Eclipse so the class files live in a universe parallel to the java files), and the resource's location is in the codePackage.images package, but relative to the class file it is the images directory, you could use the resource like so: package codePackage; import java.awt.image.*; import java.io.*; import javax.imageio.*; import javax.swing.*; public class ClassUsesResources { private JLabel label = new JLabel(); public ClassUsesResources() { try { BufferedImage img = ImageIO.read(getClass().getResourceAsStream( "images/img001s.jpg")); ImageIcon icon = new ImageIcon(img); label.setIcon(icon); JOptionPane.showMessageDialog(null, label); } catch (IOException e) { e.printStackTrace(); System.exit(-1); } } public static void main(String[] args) { new ClassUsesResources(); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7536553", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: calling php function to delete a record from database doesn't work can you please have a look at these codes and let me know why mysql query doesn't work? in a php file I add a check box to my page with following code echo "<input type=checkbox name=box[] onClick=\"deleteLink('$ClickedWord','$rLinks');\"'>"; then in another php file "deleteLink" function exists and its code is: function deleteLink($clword,$DltLinks) { <?php session_start(); // start up your PHP session! $u= $_SESSION['Unit']; $f= $_SESSION['file']; mysql_query("DELETE FROM links WHERE ((Unit_Code='$u') && (File_Name='$f')&& (Word='$clword')&& (Link_Add='$DltLinks'))") or die(mysql_error()); ?> } I am sure that this file executes but doesn't delete the record. I did some tests to find the problem but no result!!! A: I think you're missing something here. I'm pretty sure you can't directly call a php function with an onClick handler. You'd have to write a javascript function that creates and AJAX request to pass the values to the php page with the function. I think the reason that you think it's being called is that you're actually calling it as you're creating the page.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536556", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Facebook Development - Simple question on best approach I am a PHP developer, but completely new to this Facebook stuff and am getting all confused. The whole Apps vs Pages vs Fan Pages terminology is driving me nuts. Please help! My client's requirements: 1) Display Like button on a single web page 2) When Like button is clicked, content on the page is unlocked and displayed (PHP) 3) Future visits to the page detects that visitor already likes the page, and content remains unlocked (PHP) 4) All updates to web page profile on FB will show on Likers' news feed My understanding is that the cleanest way of doing (3) above is to use the PHP SDK. But to do this, I need to create an app (to get the App ID). So I created an App. I 'liked' the App from my FB profile. Updates to my app are posted to my news feed. So far, so good. However when I try and implement the PHP SDK, it only works if I authorize the App to my account first. Is there a way of avoiding this authorization step just for a simple "Like" (I ask because I didn't have to authorize anything when liking the app within FB)? If this authorization is unavoidable, are there any alternatives to Apps that would allow me to achieve the above requirements? Ideally, I'd like to use just "Pages" to do this, and not Apps, but I believe I cannot achieve (2) and (3) with pages, correct (remembering everything needs to be server side, so no JavaScript showing and hiding layers etc)? I would be grateful for any guidance. Thanks. A: So I'm assuming what we are talking about here is a Facebook tab - the 520 pixel wide applications that can go in Fan pages? If not, you will not be able to make this happen without permissions. It sounds like that is what you're talking about, though. Here's an example of an Facebook tab on the Coca Cola fan page: In a tab, the PHP SDK will tell you if the user is a fan of the page (not of the app, of the page). You'll need to read the signed request - there will be a parameter there called Page, which tells you if the user is already a fan (see https://developers.facebook.com/docs/authentication/signed_request/). You get this without having to authorize. I usually read all this and store whether the user is a fan in a boolean variable. Then later in my page I'll do something like this: <?php if ($isFan):?> Content for fans here <?php else:?> Content for non-fans here <?php endif;?> Keep in mind that it is only telling you if the user is a fan OF THAT PAGE - if you set up your app on a test page, for instance, it'll tell you if the user is a fan of that test page or not, NOT if the user is a fan of your app. A: In order to read what a facebook user likes using the PHP SDK, you will need the user_likes permission. You may however, be able to hack something together by rendering a like button on your page somewhere and detecting the color of the button, meaning the user has liked the page. This may be problematic because of cross domain issues considering the like button is rendered as an iframe. Best of luck! A: For some things, you need an app. Like restricting access to content if the user has "Liked" something. You need custom code to do that. You don't need an app for a basic "Like" button, but you really can't get any stats on the Likes. You can link an app to a website, so that you can report on the content and referrals. If you go to http://www.facebook.com/insights/ you can link the app with a website so the insights/reporting are combined. Just click on the "Insights for your Website" button. It does require validation. That said, your confusion is the norm. Apps, Pages and Fan Pages are almost the same thing. They are all referenced through numerical ID. There are subtle feature differences between Pages and App Pages. An app can be added to any Page if it is configured to do so. But you can't add a Page to another Page. You can use FQL to query if a user is a fan of your app, instead of the Page you are currently on. Facebook controls what gets shown in the news feed. Just because you post to the feed, doesn't mean it will show. However, if you are an admin of the Page and/or App, posts will always show in your feed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536557", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to parse content with ? I am using jsoup to parse a number of things. I am trying to parse this tag <pre>HEllo Worl<pre> But just cant get it to work. How would i parse this using jsoup?\ Document jsDoc = null; jsDoc = Jsoup.connect(url).get(); Elements titleElements = jsDoc.getElementsByTag("pre"); Here is what i have so far. A: Works fine for me with latest Jsoup: String html = "<p>lorem ipsum</p><pre>Hello World</pre><p>dolor sit amet</p>"; Document document = Jsoup.parse(html); Elements pres = document.select("pre"); for (Element pre : pres) { System.out.println(pre.text()); } Result: Hello World If you get nothing, then the HTML which you're parsing simply doesn't contain any <pre> element. Check it yourself by System.out.println(document.html()); Perhaps the URL is wrong. Perhaps there's some JavaScript which alters the HTML DOM with new elements (Jsoup doesn't interpret nor execute JS). Perhaps the site expects a real browser instead of a bot (change the user agent then). Perhaps the site requires a login (you'd need to maintain cookies). Who knows. You can figure this all out with a real webbrowser like Firefox or Chrome.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536564", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using Data.Typeable's cast with a locally defined data type I have a data type which I'm using to represent a wxAny object in wxHaskell, currently I only support wxAnys which contain a String or an Int, thus: data Any = IsString String | IsInt Int | IsUndefined I need a function (a -> Any) and I'm wondering if I can do it elegantly using Data.Typeable, or if anyone can suggest another approach? A: You can do it relatively simply by combining the cast function with pattern guards: f :: Typeable a => a -> Any f x | Just s <- cast x = IsString s | Just n <- cast x = IsInt n | otherwise = IsUndefined That does require that the input be an instance of Typeable, but most standard types have a deriving Typeable clause so it's usually not a problem. A: You could use a type-class for this: class ToAny a where toAny :: a -> Any instance ToAny Int where toAny = IsInt instance ToAny String where toAny = IsString For the other case, you could just not call the function on values of other types - it would be less code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536567", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: JQuery script not working despite working in the console I am attempting to make the entire div of a Nivo slider on this site clickable so the visitor can navigate to a featured article. I developed the following script within Chrome's console to work out the bugs. var $j = jQuery.noConflict(); $j(function(){ $j( '.nivo-slice' ).click(function(){ window.location = $j('.nivo-html-caption').find('a:first').attr('href'); }); }); This script works perfectly when entered via the console, however when inserted into a js file (custom.js) and included in the footer, it doesn't work at all. If you view the page source, the file shows up correctly in the markup and Chrome's inspector flags no errors. I'm confused, anyone have ideas? Thanks! A: Well, the error that i see in the console Chrome gives:[jquery.form] terminating; zero elements found by selector Comes from this line $('div.wpcf7 > form').ajaxForm This is located in your scripts.js file. It cant find div.wpcf7 > form hence, throws that error. As far as your code goes, i don't see an element with class .nivo-slice. A: There is no argument for the delay: when you call the slider. It is just blank. It needs a value.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536572", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Some sort of “different auto-increment indexes” per a primary key values I have got a table which has an id (primary key with auto increment), uid (key refering to users id for example) and something else which for my question won’t matter. I want to make, lets call it, different auto-increment keys on id for each uid entry. So, I will add an entry with uid 10, and the id field for this entry will have a 1 because there were no previous entries with a value of 10 in uid. I will add a new one with uid 4 and its id will be 3 because I there were already two entried with uid 4. ...Very obvious explanation, but I am trying to be as explainative an clear as I can to demonstrate the idea... clearly. * *What SQL engine can provide such a functionality natively? (non Microsoft/Oracle based) *If there is none, how could I best replicate it? Triggers perhaps? *Does this functionality have a more suitable name? *In case you know about a non SQL database engine providing such a functioality, name it anyway, I am curious. Thanks. A: MySQL's MyISAM engine can do this. See their manual, in section Using AUTO_INCREMENT: For MyISAM tables you can specify AUTO_INCREMENT on a secondary column in a multiple-column index. In this case, the generated value for the AUTO_INCREMENT column is calculated as MAX(auto_increment_column) + 1 WHERE prefix=given-prefix. This is useful when you want to put data into ordered groups. The docs go on after that paragraph, showing an example. The InnoDB engine in MySQL does not support this feature, which is unfortunate because it's better to use InnoDB in almost all cases. You can't emulate this behavior using triggers (or any SQL statements limited to transaction scope) without locking tables on INSERT. Consider this sequence of actions: * *Mario starts transaction and inserts a new row for user 4. *Bill starts transaction and inserts a new row for user 4. *Mario's session fires a trigger to computes MAX(id)+1 for user 4. You get 3. *Bill's session fires a trigger to compute MAX(id). I get 3. *Bill's session finishes his INSERT and commits. *Mario's session tries to finish his INSERT, but the row with (userid=4, id=3) now exists, so Mario gets a primary key conflict. In general, you can't control the order of execution of these steps without some kind of synchronization. The solutions to this are either: * *Get an exclusive table lock. Before trying an INSERT, lock the table. This is necessary to prevent concurrent INSERTs from creating a race condition like in the example above. It's necessary to lock the whole table, since you're trying to restrict INSERT there's no specific row to lock (if you were trying to govern access to a given row with UPDATE, you could lock just the specific row). But locking the table causes access to the table to become serial, which limits your throughput. *Do it outside transaction scope. Generate the id number in a way that won't be hidden from two concurrent transactions. By the way, this is what AUTO_INCREMENT does. Two concurrent sessions will each get a unique id value, regardless of their order of execution or order of commit. But tracking the last generated id per userid requires access to the database, or a duplicate data store. For example, a memcached key per userid, which can be incremented atomically. It's relatively easy to ensure that inserts get unique values. But it's hard to ensure they will get consecutive ordinal values. Also consider: * *What happens if you INSERT in a transaction but then roll back? You've allocated id value 3 in that transaction, and then I allocated value 4, so if you roll back and I commit, now there's a gap. *What happens if an INSERT fails because of other constraints on the table (e.g. another column is NOT NULL)? You could get gaps this way too. *If you ever DELETE a row, do you need to renumber all the following rows for the same userid? What does that do to your memcached entries if you use that solution? A: SQL Server should allow you to do this. If you can't implement this using a computed column (probably not - there are some restrictions), surely you can implement it in a trigger. MySQL also would allow you to implement this via triggers. A: In a comment you ask the question about efficiency. Unless you are dealing with extreme volumes, storing an 8 byte DATETIME isn't much of an overhead compared to using, for example, a 4 byte INT. It also massively simplifies your data inserts, as well as being able to cope with records being deleted without creating 'holes' in your sequence. If you DO need this, be careful with the field names. If you have uid and id in a table, I'd expect id to be unique in that table, and uid to refer to something else. Perhaps, instead, use the field names property_id and amendment_id. In terms of implementation, there are generally two options. 1). A trigger Implementations vary, but the logic remains the same. As you don't specify an RDBMS (other than NOT MS/Oracle) the general logic is simple... * *Start a transaction (often this is Implicitly already started inside triggers) *Find the MAX(amendment_id) for the property_id being inserted *Update the newly inserted value with MAX(amendment_id) + 1 *Commit the transaction Things to be aware of are... - multiple records being inserted at the same time - records being inserted with amendment_id being already populated - updates altering existing records 2). A Stored Procedure If you use a stored procedure to control writes to the table, you gain a lot more control. * *Implicitly, you know you're only dealing with one record. *You simply don't provide a parameter for DEFAULT fields. *You know what updates / deletes can and can't happen. *You can implement all the business logic you like without hidden triggers I personally recommend the Stored Procedure route, but triggers do work. A: It is important to get your data types right. What you are describing is a multi-part key. So use a multi-part key. Don't try to encode everything into a magic integer, you will poison the rest of your code. If a record is identified by (entity_id,version_number) then embrace that description and use it directly instead of mangling the meaning of your keys. You will have to write queries which constrain the version number but that's OK. Databases are good at this sort of thing. version_number could be a timestamp, as a_horse_with_no_name suggests. This is quite a good idea. There is no meaningful performance disadvantage to using timestamps instead of plain integers. What you gain is meaning, which is more important. You could maintain a "latest version" table which contains, for each entity_id, only the record with the most-recent version_number. This will be more work for you, so only do it if you really need the performance.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536573", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Constructing Strings using Regular Expressions and Boolean logic || How do I construct strings with exactly one occurrence of 111 from a set E* consisting of all possible combinations of elements in the set {0,1}? A: You can generate the set of strings based on following steps: Some chucks of numbers and their legal position are enumerated: Start: 110 Must have one, anywhere: 111 Anywhere: 0, 010, 0110 End: 011 Depend on the length of target string (the length should be bigger than 3) Condition 1: Length = 3 : {111} Condition 2: 6 > Length > 3 : (Length-3) = 1x + 3y + 4z For example, if length is 5: answer is (2,1,0) and (1,0,1) (2,1,0) -> two '0' and one '010' -> ^0^010^ or ^010^0^ (111 can be placed in any one place marked as ^) (1,0,1) -> one '0' and one '0110' ... Condition 3: If 9 > Length > 6, you should consider the solution of two formulas: Comments: length – 3 : the length exclude 111 x: the times 0 occurred y: the times 010 occurred z: the times 0110 occurred Finding all solutions {(x,y,z) | 1x + 3y + 4z = (Length - 3)} ----(1) For each solution, you can generate one or more qualified string. For example, if you want to generate strings of length 10. One solution of (x,y,z) is (0,2,1), that means '010' should occurred twice and '0110' should occurred once. Based on this solution, the following strings can be generated: 0: x0 times 010: x 2 times 0110: x1 times 111: x1 times (must have) Finding the permutations of elements above. 010-0110-010-111 or 111-010-010-0110 … (Length - 6) = 1x + 3y + 4z ---(2) Similar as above case, find all permutations to form an intermediate string. Finally, for each intermediate string Istr, Istr + 011 or 110 + Istr are both qualified. For example, (10-6) = 1*0 + 3*0 + 4*1 or = 1*1 + 3*1 + 4*0 The intermediate string can be composed by one '0110' for answer(0,0,1): Then ^0110^011 and 110^0110^ are qualified strings (111 can be placed in any one place marked as ^) Or the intermediate string can also be composed by one '0' and one '010' for answer (1,1,0) The intermediate string can be 0 010 or 010 0 Then ^0010^011 and 110^0100^ are qualified strings (111 can be placed in any one place marked as ^) Condition 4: If Length > 9, an addition formula should be consider: (Length – 9) = 1x + 3y + 4z Similar as above case, find all permutations to form an intermediate string. Finally, for each intermediate string Istr, 110 + Istr + 011 is qualified. Explaination: The logic I use is based on Combinatorial Mathematics. A target string is viewed as a combination of one or more substrings. To fulfill the constraint ('111' appears exactly one time in target string), we should set criteria on substrings. '111' is definitely one substring, and it can only be used one time. Other substrings should prevent to violate the '111'-one-time constraint and also general enough to generate all possible target string. Except the only-one-111, other substrings should not have more than two adjacent '1'. (Because if other substring have more than two adjacent 1, such as '111', '1111', '11111,' the substring will contain unnecessary '111'). Except the only-one-111, other substrings should not have more than two consecutive '1'. Because if other substring have more than two consecutive 1, such as '111', '1111', '11111,' the substring will contain unnecessary '111' . However, substrings '1' and '11' cannot ensure the only-one-111 constraint. For example, '1'+'11,' '11'+'11' or '1'+'1'+'1' all contain unnecessary '111'. To prevent unnecessary '111,' we should add '0' to stop more adjacent '1'. That results in three qualified substring '0', '010' and '0110'. Any combined string made from three qualified substring will contain zero times of '111'. Above three qualified substring can be placeed anywhere in the target string, since they 100% ensure no additional '111' in target string. If the substring's position is in the start or end, they can use only one '0' to prevent '111'. In start: 10xxxxxxxxxxxxxxxxxxxxxxxxxxxx 110xxxxxxxxxxxxxxxxxxxxxxxxxxx In end: xxxxxxxxxxxxxxxxxxxxxxxxxxx011 xxxxxxxxxxxxxxxxxxxxxxxxxxxx01 These two cases can also ensure no additional '111'. Based on logics mentioned above. We can generate any length of target string with exactly one '111'. A: Your question could be clearer. For one thing, does "1111" contain one occurrence of "111" or two? If so, you want all strings that contain "111" but do not contain either "1111" or "111.*111". If not, omit the test for "1111". If I understand you correctly, you're trying to construct an infinite subset of the infinite set of sequences of 0s and 1s. How you do that is probably going to depend on the language you're using (most languages don't have a way of representing infinite sets). My best guess is that you want to generate a sequence of all sequences of 0s and 1s (which shouldn't be too hard) and select the ones that meet your criteria.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536574", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Android MediaStore won't set file name I am trying to get Android's MediaStore to write an image to the SD card with a specific file name. It does write the file, but does not use the title parameter passed with MediaStore.Images.Media.insertImage(cr, source, title, description) Here is my relevant code: PictureCallback myPictureCallback_JPG = new PictureCallback(){ public void onPictureTaken(byte[] arg0, Camera arg1) { Bitmap bitmapPicture = BitmapFactory.decodeByteArray(arg0, 0, arg0.length); int year = Calendar.getInstance().getTime().getYear(); int month = Calendar.getInstance().getTime().getMonth(); int day = Calendar.getInstance().getTime().getDay(); int hour = Calendar.getInstance().getTime().getHours(); int minute = Calendar.getInstance().getTime().getMinutes(); int seconds = Calendar.getInstance().getTime().getSeconds(); String imgName = "IMG_" + Integer.toString(year) + Integer.toString(month) +Integer.toString(day) + "_" + Integer.toString(hour) + Integer.toString(minute) + Integer.toString(seconds) + ".jpg"; MediaStore.Images.Media.insertImage(getContentResolver(), bitmapPicture, imgName, imgName); camera.startPreview(); inPreview=true; }}; It successfully stores the picture, but the file name appears to be time since the Unix epoch (i.e. 13168297...16.jpg) A: I didn't get MediaStore to work, but I did use the File class and FileOutputStream to get the job done: ByteArrayOutputStream bytes = new ByteArrayOutputStream(); bitmapPicture.compress(Bitmap.CompressFormat.JPEG, 100, bytes); File imageDirectory = new File(Environment.getExternalStorageDirectory() + File.separator + "DropPic 64"); imageDirectory.mkdirs(); File f = new File(Environment.getExternalStorageDirectory() + File.separator + "DropPic 64" + File.separator + currentPicture.fileName); try { f.createNewFile(); FileOutputStream fo = new FileOutputStream(f); fo.write(arg0); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7536576", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Using color as the 3rd dimension I have 3 dimensions that I want to plot, and I want the third dimension to be color. This will be in R by the way. For instance, my data looks like this x = [1,2,3,4,1,5,6,3,4,7,8,9] y = [45,32,67,32,32,47,89,91,10,12,43,27] z = [1,2,3,4,5,6,7,8,9,10,11,12] I am trying to use filled.contour, but it giving me an error saying x and y must be in increasing order. But I'm not really sure how to arrange my data such that that is true. Because if I arrange x in increasing order, then y will not be in increasing order. It is also feasible for me to do a non-filled contour method where it is just data points that are colored. How can I do this in R. Any suggested packages? Please use specific examples. Thanks! A: jet.colors <- colorRampPalette(c("#00007F", "blue", "#007FFF", "cyan", "#7FFF7F", "yellow", "#FF7F00", "red", "#7F0000")) plot(x,y, col=jet.colors(12)[z], ylim=c(0,100), pch=20, cex=2) legend(8.5,90, col = jet.colors(12)[z], legend=z, pch=15) And if you want to check the coloring you can label the points with the z value: text(x, y+2, labels=z) #offset vertically to see the colors Another option is to use package:akima which does interpolations on irregular (non)-grids: require(akima) require(lattice) ak.interp <- interp(x,y,z) pdf(file="out.pdf") levelplot(ak.interp$z, main="Output of akima plotted with lattice::levelplot", contour=TRUE) dev.off()
{ "language": "en", "url": "https://stackoverflow.com/questions/7536577", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to alter these functions so that they recursively find the solution This is a question about Project Euler problem #67. (Find the maximum path down a triangle) I know it may be in bad taste to ask for help on these. I have these functions: def chooseBest(rowOfTriangle): if len(rowOfTriangle) == 1: return rowOfTriangle return list(max(element) for element in zip(rowOfTriangle[0:-1],rowOfTriangle[1:])) and: def consolidatePath(rowOfTriangle , bestPath): return list(sum(element) for element in zip(rowOfTriangle,bestPath)) which work on a data set formatted like this: triangle = [[1], [2, 3], [4, 5, 6], [7, 8, 9, 10]] where the solution for this triangle would look like: consolidatePath(triangle[0],chooseBest(consolidatePath(triangle[1],chooseBest(consolidatePath(triangle[2],chooseBest(triangle[3])))))) This outputs (correctly): [20] Writing out each nested function call is far from optimal, and is going to be impossible when I scale up to the problem's hundred rows. How do I alter consolidatePath and chooseBest to call each other where appropriate? EDIT: Figured it out. A: Something like this? def max_path(triangle, idx=0, total=0): if triangle: row = triangle[0] next = max(row[idx:idx+2]) return max_path(triangle[1:], row.index(next), total+next) return total
{ "language": "en", "url": "https://stackoverflow.com/questions/7536583", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-4" }
Q: What is the maximum addressable space of virtual memory? Saw this questions asked many times. But couldn't find a reasonable answer. What is actually the limit of virtual memory? Is it the maximum addressable size of CPU? For example if CPU is 32 bit the maximum is 4G? Also some texts relates it to hard disk area. But I couldn't find it is a good explanation. Some says its the CPU generated address. All the address we see are virtual address? For example the memory locations we see when debugging a program using GDB. The historical reason behind the CPU generating virtual address? Some texts interchangeably use virtual address and logical address. How does it differ? A: Unfortunately, the answer is "it depends". You didn't mention an operating system, but you implied linux when you mentioned GDB. I will try to be completely general in my answer. There are basically three different "address spaces". The first is logical address space. This is the range of a pointer. Modern (386 or better) have memory management units that allow an operating system to make your actual (physical) memory appear at arbitrary addresses. For a typical desktop machine, this is done in 4KB chunks. When a program accesses memory at some address, the CPU will lookup where what physical address corresponds to that logical address, and cache that in a TLB (translation lookaside buffer). This allows three things: first it allows an operating system to give each process as much address space as it likes (up to the entire range of a pointer - or beyond if there are APIs to allow programs to map/unmap sections of their address space). Second it allows it to isolate different programs entirely, by switching to a different memory mapping, making it impossible for one program to corrupt the memory of another program. Third, it provides developers with a debugging aid - random corrupt pointers may point to some address that hasn't been mapped at all, leading to "segmentation fault" or "invalid page fault" or whatever, terminology varies by OS. The second address space is physical memory. It is simply your RAM - you have a finite quantity of RAM. There may also be hardware that has memory mapped I/O - devices that LOOK like RAM, but it's really some hardware device like a PCI card, or perhaps memory on a video card, etc. The third type of address is virtual address space. If you have less physical memory (RAM) than the programs need, the operating system can simulate having more RAM by giving the program the illusion of having a large amount of RAM by only having a portion of that actually being RAM, and the rest being in a "swap file". For example, say your machine has 2MB of RAM. Say a program allocated 4MB. What would happen is the operating system would reserve 4MB of address space. The operating system will try to keep the most recently/frequently accessed pieces of that 4MB in actual RAM. Any sections that are not frequently/recently accessed are copied to the "swap file". Now if the program touches a part of that 4MB that isn't actually in memory, the CPU will generate a "page fault". THe operating system will find some physical memory that hasn't been accessed recently and "page in" that page. It might have to write the content of that memory page out to the page file before it can page in the data being accessed. THis is why it is called a swap file - typically, when it reads something in from the swap file, it probably has to write something out first, effectively swapping something in memory with something on disk. Typical MMU (memory management unit) hardware keeps track of what addresses are accessed (i.e. read), and modified (i.e. written). Typical paging implementations will often leave the data on disk when it is paged in. This allows it to "discard" a page if it hasn't been modified, avoiding writing out the page when swapping. Typical operating systems will periodically scan the page tables and keep some kind of data structure that allows it to intelligently and quickly choose what piece of physical memory has not been modified, and over time builds up information about what parts of memory change often and what parts don't. Typical operating systems will often gently page out pages that don't change often (gently because they don't want to generate too much disk I/O which would interfere with your actual work). This allows it to instantly discard a page when a swapping operation needs memory. Typical operating systems will try to use all the "unused" memory space to "cache" (keep a copy of) pieces of files that are accessed. Memory is thousands of times faster than disk, so if something gets read often, having it in RAM is drastically faster. Typically, a virtual memory implementation will be coupled with this "disk cache" as a source of memory that can be quickly reclaimed for a swapping operation. Writing an effective virtual memory manager is extremely difficult. It needs to dynamically adapt to changing needs. Typical virtual memory implementations feel awfully slow. When a machine starts to use far more memory that it has RAM, overall performance gets really, really bad.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536587", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Need help in GPS location on android I need a simple code snippet which can do the following. I need a function which can do the following. * *check if GPS is enabled. If not enabled, then enable it. *check for the current location, i.e get longitude and latitude *Disable the GPS. I don't need the continuous location update like LocationListener. Just once in 15 mins is ok. can anybody provide me working code snippet for this? A: For enabling GPS: private void turnGPSOn(){ String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED); if(!provider.contains("gps")){ //if gps is disabled final Intent poke = new Intent(); poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider"); poke.addCategory(Intent.CATEGORY_ALTERNATIVE); poke.setData(Uri.parse("3")); sendBroadcast(poke); } } For disabling GPS private void turnGPSOff(){ String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED); if(provider.contains("gps")){ //if gps is enabled final Intent poke = new Intent(); poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider"); poke.addCategory(Intent.CATEGORY_ALTERNATIVE); poke.setData(Uri.parse("3")); sendBroadcast(poke); } } To check GPS is on or not. if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) { buildAlertMessageNoGps(); } For getting current location. public void getCurrentLocation() { LocationManager locationManager; String context = Context.LOCATION_SERVICE; locationManager = (LocationManager) getSystemService(context); Criteria crta = new Criteria(); crta.setAccuracy(Criteria.ACCURACY_FINE); crta.setAltitudeRequired(false); crta.setBearingRequired(false); crta.setCostAllowed(true); crta.setPowerRequirement(Criteria.POWER_LOW); String provider = locationManager.getBestProvider(crta, true); locationManager.requestLocationUpdates(provider, 1000, 0, new LocationListener() { @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { } @Override public void onLocationChanged(Location location) { if (location != null) { double lat = location.getLatitude(); double lng = location.getLongitude(); if (lat != 0.0 && lng != 0.0) { System.out.println("WE GOT THE LOCATION"); System.out.println(lat); System.out.println(lng); getAddress(); } } } }); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7536588", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: lastchild.appendchild in Firefox and Chrome The following code var descriptdiv = document.createElement("div"); document.body.lastChild.appendChild(descriptdiv); works in IE, but doesn't work in FireFox and Chrome. How can I get it to work in those browsers too? A: What you're most likely seeing is Firefox/Chrome returning text nodes as lastChild. This is because these browsers will return any whitespace/newlines at the end of your code as text nodes. Since you can't append a div to a text node, the code fails. IE on the other hand will ignore the whitespace/newlines and return the last element, which you can successfully append to. You can use a function like the following to get the last element: function getLastChild(n) { var x = n.lastChild; // noteType == 1 is an element node - keep searching until we find one while (x && x.nodeType != 1){ x = x.previousSibling; } // don't allow a non element node to be returned. if(x && x.nodeType != 1){ x = null; } return x; } A: You cannot add a block element to an img, br, hr and many others, and there are some you can that you won't ever need to. You probably have some idea of the container you want. function addaBlocktothelastChild(block, rx){ var next, elements= document.body.getElementsByTagName('*'), L= elements.length, count= L; rx= rx || /^(DIV|P|TD|LI|DT|DD)$/i; while(L && !rx.test(elements[--L].tagName)); if(L>= 0){ return elements[L].appendChild(block); } return document.body.appendChild(block); } var block= document.createElement('div'); block.id= 'Zed'; addaBlocktothelastChild(block); alert(document.getElementById('Zed').parentNode) /^(DIV|P|TD|LI|DT|DD|BLOCKQUOTE|FORM|ARTICLE|ASIDE|FOOTER|HEADER|NAV|SECTION)/i
{ "language": "en", "url": "https://stackoverflow.com/questions/7536592", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Ajaxful-rating confirmation when casting vote - ruby on rails I'm running an app that uses Ajaxful-rating with Rails 3 right now, but several users have commented that it is tough to tell if you've actually voted. Ideally I'd like a small growl-ish window to appear that says "Thanks!" or "rated!" or something like that when a user votes, however I cannot make this work. Any ideas? Here's the controller code for rating: def rate @idea = Idea.find(params[:id]) @idea.rate(params[:stars], current_user, params[:dimension]) average = @idea.rate_by(current_user, :quality).stars width = average.to_f / @idea.class.max_stars * 100 render :json => { :id => @idea.wrapper_dom_id(params), :average => average, :width => width } end Thanks in advance. A: You say you "cannot make this work" but it's unclear what you've tried. Does your controller method work? What does your client-side code look like? If you're successfully making the Ajax call then all you need to do is, on the client side, handle the Ajax response you get and show your message. As for a "small Growl-ish window" there are lots of libraries out there that do this kind of thing, or you could roll your own.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536593", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Good example of application that uses rails and backbone.js that handles authentication through backbone Does anybody know of a good example I could look at as to how to go about implementing authentication through backbone with rails? I haven't been able to find anything.. A: You have several possibilities. First you can log in normally, with plain html. That login would guide you to your backbone.js application. Another possibility is within your backbone.js app you have a login form that takes advantage of backbone.js's ":authentication_token". When your backbone.js app sends the login info it will get a token back. From then on you are able make ajax calls and receive responses with that token. EDIT: see this post for an example of working with the token: http://www.hyperionreactor.net/blog/token-based-authentication-rails-3-and-rails-2 A: What you are looking about rails integration with client-side, except ajax queries and authentication/authorization? Use the demo app to see how backbone.js is working: http://documentcloud.github.com/backbone/examples/todos/index.html A: Found one example app. Trying to figure out what is what atm myself. But might be worth looking: https://github.com/diaspora/diaspora
{ "language": "en", "url": "https://stackoverflow.com/questions/7536598", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: MFC: how to erase a just drawn rectangle Could somebody tell me how to erase a rectangle that has just been drawn on an image? In the application, I have an image displayed on a document (MDI application). The user can select a portion of the image. I implemented this feature as letting the user start the selection with a CRectTrackerColor (derived from CRectTracker) object. The selection works fine: a user is able select a rectangle using the mouse. A rubber band rectangle is shown as a feedback. After the user releases the left mouse, the rectangle is colored based on my pen color. Then I present a dialog for OK/Cancel. Upon Cancel, I would like the rectangle to disappear. How should I go about doing that? Thanks. A: Just invalidate that rectangle so it'll get redrawn normally.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536599", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Silverlight How to pass a selected row of datagrid to view model I have a datagrid within a view <Grid x:Name="LayoutRoot" Background="White" Width="600" MaxHeight="150"> <sdk:DataGrid x:Name="grid1" ItemsSource="{Binding Persons}" SelectedItem="{Binding MyList, Mode=TwoWay}"> </sdk:DataGrid> </Grid> Within my ViewModel I have the following code private ObservableCollection<string> myList; public ObservableCollection<string> MyList { get { return myList; } set { myList = value; NotifyPropertyChanged(vm => vm.MyList); } And for the DG private ObservableCollection<Person> person; public ObservableCollection<Person> Persons { get { return person; } set { person = value; NotifyPropertyChanged(vm => vm.Persons); } } I was hoping from the View I could bind the selected item(row) of the datagrid to the MyList collection within my view model (Maybe IList vs OC?). I only need one value from the selected row such as address or zip. But do I need to pass the entire collection of can I get just one cell value into the view model another way? For example here is the class I am using to populate the data grid public void CreateList() { Person p = new Person(); p.FirstName = "Bob"; p.LastName = "Jones"; p.Address = "123 Main Street"; p.City = "Wilmington"; p.State = "NC"; p.Zip = "12345"; Person p1 = new Person(); p1.FirstName = "Sue"; p1.LastName = "Smith"; p1.Address = "1222 Main Street"; p1.City = "Tampa"; p1.State = "FL"; p1.Zip = "12345"; Person p2 = new Person(); p2.FirstName = "Chris"; p2.LastName = "Jones"; p2.Address = "234 Water Street"; p2.City = "Dallas"; p2.State = "TX"; p2.Zip = "22222"; Person p3 = new Person(); p3.FirstName = "Andy"; p3.LastName = "Jones"; p3.Address = "434 Main Street"; p3.City = "Columbia"; p3.State = "SC"; p3.Zip = "12345"; ObservableCollection<Person> Result = new ObservableCollection<Person>(); Result.Add(p); Result.Add(p1); Result.Add(p2); Result.Add(p3); Persons = Result; } This class is fired when the view model is loaded. I would like to be able to select the third row of data and only pass the address value back to the VM. My inital thought was to pass the entire selected row back to the vm and then extract the address from that collection. Using the selectedItem Binding does not work, selecting a row never triggers the inotify event in the vm so I know the collection is not being updated unless I click in the DG and then outside of it which only passes a null value. Secondly, is there a more effient way to do this vs. using the code behind to pull a value and then pass it to the VM? I had thought of using selection changed event within view and then set the column value to a bound field that is passed to the vm but this seems hacky. Thanks for any suggestions or ideas. -cheers A: It think you've thrown in a bit of a curve ball with this MyList property to which you want to "bind the selected item". Everywhere else, including your own solution, you refer to binding to a single item. So why have a property to receive it be a list type? It seems to me that what you need is to drop the MyList and simply have:- private Person mySelectedItem; public Person SelectedItem { get { return mySelectedItem; } set { mySelectedItem = value; NotifyPropertyChanged("SelectedItem"); } } Now your binding on the DataGrid would make sense:- <sdk:DataGrid x:Name="grid1" ItemsSource="{Binding Persons}" SelectedItem="{Binding SelectedItem, Mode=TwoWay}"> And your TextBlock would look something like:- <TextBlock x:Name="textholder" Text="{Binding SelectedItem.FirstName}" /> A: Update The current approach I am taking for this is within the code behind of the view I have the following private void grid1_SelectionChanged(object sender, SelectionChangedEventArgs e) { Person selectedPerson = grid1.SelectedItem as Person; textholder.Text = selectedPerson.Address; } Then within the view I have a text field <TextBlock x:Name="textholder" Text="{Binding SelectedID, Mode=TwoWay}"/> Which is bound to the SelectedID property within the VM This works and gets the value to the VM. This just seems wierd in implementation (but it is a lot less code that using commands and command parameters :) ) . I'd welcome any other ideas. -cheers
{ "language": "en", "url": "https://stackoverflow.com/questions/7536600", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I get this rotated anchor to be positioned against right side? What I'm attempting to do is place a slide-out panel jQuery thing to display some ancillary information about a selected recipe on my website. I used this example as a starting point for the slide-out panel. But the anchor that triggers the sliding panel takes up more screen real estate than I'd like so I wanted to rotate it 90 degrees and place it against the right side of the page. I looked at this site for an example of how to do the rotation. Essentially what I end up with is something like this: <a class="trigger" href="#">Nutrition</a> and some css that looks like this: a.trigger{ position: absolute; text-decoration: none; top: 100px; right: 0; font-size: 16px; letter-spacing:-1px; font-family: verdana, helvetica, arial, sans-serif; color:#fff; padding: 20px 40px 20px 15px; font-weight: 700; background:#333333; border:1px solid #444444; -moz-border-radius-topright: 20px; -webkit-border-top-right-radius: 20px; -moz-border-radius-bottomright: 20px; -webkit-border-bottom-right-radius: 20px; -moz-border-radius-bottomleft: 0px; -webkit-border-bottom-left-radius: 0px; display: block; -webkit-transform: rotate(90deg); -moz-transform: rotate(90deg); filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=1); } And what results is this: So, that right:0 jazz in the CSS doesn't seem to fix things. It's not against the right side. It seems like it's offset by the original width, like it is rotated with the lower left-hand corner of the rectangle being the origin. (This is in IE by the way - and that's generally what we use in-house.) I didn't see an offset argument or a way to specify where the origin is. Might be that I've just missed the page in my searching that explains exactly how to do that - if so, I'd be interested in the link to it or if you've got ideas how to solve this, I'd appreciate hearing how to do it or perhaps a different way to accomplish what I want to do. A: Absolute positioned elements will only work relative to their parent container, make sure that the main container that houses your anchor has a position:relative; attribute added to it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536601", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Custom Button - Background Doesn't Change I'm trying to make a custom button, my only problem is that the background doesn't change. I am aware that i need to set the background value as {TemplateBinding Background} but i cannot seem to find the right spot. I tried at but it just doesn't work. The button was created in expression blend, so any weird thing you might see may come from there, i believe. <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <Style x:Key="DEHRButton" TargetType="{x:Type Button}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type Button}"> <Grid> <VisualStateManager.VisualStateGroups> <VisualStateGroup x:Name="CommonStates"> <VisualStateGroup.Transitions> <VisualTransition GeneratedDuration="0:0:0.1"/> </VisualStateGroup.Transitions> <VisualState x:Name="Normal"/> <VisualState x:Name="MouseOver"> <Storyboard> <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(Shape.StrokeThickness)" Storyboard.TargetName="path"> <EasingDoubleKeyFrame KeyTime="0" Value="2"/> </DoubleAnimationUsingKeyFrames> </Storyboard> </VisualState> <VisualState x:Name="Pressed"> <Storyboard> <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(Shape.StrokeThickness)" Storyboard.TargetName="path"> <EasingDoubleKeyFrame KeyTime="0" Value="3"/> </DoubleAnimationUsingKeyFrames> </Storyboard> </VisualState> <VisualState x:Name="Disabled"> <Storyboard> <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Opacity)" Storyboard.TargetName="path"> <EasingDoubleKeyFrame KeyTime="0" Value="0.7"/> </DoubleAnimationUsingKeyFrames> <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Visibility)" Storyboard.TargetName="path"> <DiscreteObjectKeyFrame KeyTime="0" Value="{x:Static Visibility.Visible}"/> </ObjectAnimationUsingKeyFrames> </Storyboard> </VisualState> </VisualStateGroup> </VisualStateManager.VisualStateGroups> <Path Fill="{TemplateBinding Background}"/> <Path x:Name="path" Data="M14.666499,0.5 L14.833,0.94661933 14.833,0.5 67.170002,0.5 81.166,0.5 95.502998,0.5 81.336502,38.5 81.166,38.042648 81.166,38.5 28.833,38.5 14.833,38.5 0.5,38.5 z" Stretch="Fill" Stroke="{TemplateBinding BorderBrush}"> <Path.Fill> <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0"> <GradientStop Color="Black" Offset="0"/> <GradientStop Color="White" Offset="1"/> </LinearGradientBrush> </Path.Fill> </Path> <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/> </Grid> <ControlTemplate.Triggers> <Trigger Property="IsFocused" Value="True"/> <Trigger Property="IsDefaulted" Value="True"/> <Trigger Property="IsMouseOver" Value="True"/> <Trigger Property="IsPressed" Value="True"/> <Trigger Property="IsEnabled" Value="False"/> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> <!-- Resource dictionary entries should be defined here. --> Thanks for the help in advance. A: The problem you have there is that the Fill property is bound two time (once to the Background, and once to your default style of Black and White). Here is how you solve your problem: <Style x:Key="DEHRButton" TargetType="{x:Type Button}"> <Setter Property="Background"> <Setter.Value> <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0"> <GradientStop Color="Black" Offset="0"/> <GradientStop Color="White" Offset="1"/> </LinearGradientBrush> </Setter.Value> </Setter> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type Button}"> <Grid> <VisualStateManager.VisualStateGroups> <VisualStateGroup x:Name="CommonStates"> <VisualStateGroup.Transitions> <VisualTransition GeneratedDuration="0:0:0.1"/> </VisualStateGroup.Transitions> <VisualState x:Name="Normal"/> <VisualState x:Name="MouseOver"> <Storyboard> <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(Shape.StrokeThickness)" Storyboard.TargetName="path"> <EasingDoubleKeyFrame KeyTime="0" Value="2"/> </DoubleAnimationUsingKeyFrames> </Storyboard> </VisualState> <VisualState x:Name="Pressed"> <Storyboard> <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(Shape.StrokeThickness)" Storyboard.TargetName="path"> <EasingDoubleKeyFrame KeyTime="0" Value="3"/> </DoubleAnimationUsingKeyFrames> </Storyboard> </VisualState> <VisualState x:Name="Disabled"> <Storyboard> <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Opacity)" Storyboard.TargetName="path"> <EasingDoubleKeyFrame KeyTime="0" Value="0.7"/> </DoubleAnimationUsingKeyFrames> <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Visibility)" Storyboard.TargetName="path"> <DiscreteObjectKeyFrame KeyTime="0" Value="{x:Static Visibility.Visible}"/> </ObjectAnimationUsingKeyFrames> </Storyboard> </VisualState> </VisualStateGroup> </VisualStateManager.VisualStateGroups> <Path x:Name="path" Fill="{TemplateBinding Background}" Data="M14.666499,0.5 L14.833,0.94661933 14.833,0.5 67.170002,0.5 81.166,0.5 95.502998,0.5 81.336502,38.5 81.166,38.042648 81.166,38.5 28.833,38.5 14.833,38.5 0.5,38.5 z" Stretch="Fill" Stroke="{TemplateBinding BorderBrush}"> </Path> <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/> </Grid> <ControlTemplate.Triggers> <Trigger Property="IsFocused" Value="True"/> <Trigger Property="IsDefaulted" Value="True"/> <Trigger Property="IsMouseOver" Value="True"/> <Trigger Property="IsPressed" Value="True"/> <Trigger Property="IsEnabled" Value="False"/> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> You define the default look as a Setter to the Background property, and you Template Bind the Fill to the Background. This allows you to have some default value for the Background, but also enables you to set your own background directly from the control like this: <Button Background="Azure" Style="{StaticResource DEHRButton}" Height="20" Width="100"/> Here is more about the Visual Tree in WPF. One of the seniors I worked with once said that you first need to understand the concept of Visual Tree and Logical Tree before starting to program in XAML, else you will start to hate it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536615", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Unable to cast transparent proxy in a dll when called from PowerShell, but successful in C# console app I'm attempting to create an open source library that spawn a new AppDomain and runs a PowerShell script in it. I have a static method that takes the name of the powershell file and the name of the AppDomain. The method executes successfully when called from a C# console app, but not PowerShell. I know the dll is being loaded in the second app domain because of this entry in the fusionlog. The class declaraton and constructor looks like this. public class AppDomainPoshRunner : MarshalByRefObject{ public AppDomainPoshRunner (){ Console.WriteLine("Made it here."); } } That message in the constructor gets output when I call CreateInstanceFromAndUnwrap whether I run the dll from a C# console app or from the PowerShell app. The failure occurs when I cast the value returned by CreateInstanceFromAndUnwrap to AppDomainPoshRunner in the static method below. public static string[] RunScriptInAppDomain(string fileName, string appDomainName = "Unamed") { var assembly = Assembly.GetExecutingAssembly(); var setupInfo = new AppDomainSetup { ApplicationName = appDomainName, // TODO: Perhaps we should setup an even handler to reload the AppDomain similar to ASP.NET in IIS. ShadowCopyFiles = "true" }; var appDomain = AppDomain.CreateDomain(string.Format("AppDomainPoshRunner-{0}", appDomainName), null, setupInfo); try { var runner = appDomain.CreateInstanceFromAndUnwrap(assembly.Location, typeof(AppDomainPoshRunner).FullName); if (RemotingServices.IsTransparentProxy(runner)) Console.WriteLine("The unwrapped object is a proxy."); else Console.WriteLine("The unwrapped object is not a proxy!"); Console.WriteLine("The unwrapped project is a {0}", runner.GetType().FullName); /* This is where the error happens */ return ((AppDomainPoshRunner)runner).RunScript(fileName); } finally { AppDomain.Unload(appDomain); } } When running that in PowerShell I get an InvalidCastExcception with the message Unable to cast transparent proxy to type JustAProgrammer.ADPR.AppDomainPoshRunner. What am I doing wrong? A: I had the same problem: I created sandbox with Execute only permissions (the min one can have) to execute untrusted code in very restricted environment. All worked great in C# application, but did not work (the same cast exception) when starting point was vbs script creating .NET COM object. I think PowerShell also uses COM. I found workaround using AppDomain.DoCallBack, which avoids getting proxy from the appdomain. This is the code. If you find a better option, please post. Registering in GAC is not a good solution for me... class Test { /* create appdomain as usually */ public static object Execute(AppDomain appDomain, Type type, string method, params object[] parameters) { var call = new CallObject(type, method, parameters); appDomain.DoCallBack(call.Execute); return call.GetResult(); } } [Serializable] public class CallObject { internal CallObject(Type type, string method, object[] parameters) { this.type = type; this.method = method; this.parameters = parameters; } [PermissionSet(SecurityAction.Assert, Unrestricted = true)] public void Execute() { object instance = Activator.CreateInstance(this.type); MethodInfo target = this.type.GetMethod(this.method); this.result.Data = target.Invoke(instance, this.parameters); } internal object GetResult() { return result.Data; } private readonly string method; private readonly object[] parameters; private readonly Type type; private readonly CallResult result = new CallResult(); private class CallResult : MarshalByRefObject { internal object Data { get; set; } } } A: It sounds very much like a loading context issue. Type identity isn't just about the physical assembly file; it's also about how and where it was loaded. Here's an old blog post from Suzanne Cook that you'll probably have to read fifteen times until you can begin to make sense of your problem. Choosing a Binding Context http://blogs.msdn.com/b/suzcook/archive/2003/05/29/57143.aspx Before you say "but it works in a console app," remember that when running it from powershell, you have an entirely different kettle of fish as regards the calling appdomain's context, probing paths, identity etc. Good luck!
{ "language": "en", "url": "https://stackoverflow.com/questions/7536619", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: OS X & Python 3: Behavior while executing bash command in new terminal? I've seen similar questions (e.g. Running a command in a new Mac OS X Terminal window ) but I need to confirm this command and its expected behavior in a mac (which I don't have). If anyone can run the following in Python 3 Mac: import subprocess, os def runcom(bashCommand): sp = subprocess.Popen(['osascript'], stdin=subprocess.PIPE, stderr=subprocess.PIPE) sp.communicate('''tell application "Terminal"\nactivate\ndo script with command "{0} $EXIT"\nend tell'''.format(bashCommand)) runcom('''echo \\"This is a test\\n\\nThis should come two lines later; press any key\\";read throwaway''') runcom('''echo \\"This is a test\\"\n\necho \\"This should come one line later; press any key\\";read throwaway''') runcom('''echo \\"This is testing whether I can have you enter your sudo pw on separate terminal\\";sudo ls;\necho \\"You should see your current directory; press any key\\";read throwaway''') Firstly, and most basically, is the "spawn new terminal and execute" command correct? (For reference, this version of the runcom function came from this answer below, and is much cleaner than my original.) As for the actual tests: the first one tests that internal double escaped \\n characters really work. The second tests that we can put (unescaped) newlines into the "script" and still have it work just like semicolon. Finally, the last one tests whether you can call a sudo process in a separate terminal (my ultimate goal). In all cases, the new terminal should disappear as soon as you "press any key". Please also confirm this. If one of these doesn't work, a correction/diagnosis would be most appreciated. Also appreciated: is there a more pythonic way of spawning a terminal on Mac then executing a (sudo, extended) bash commands on it? Thanks! A: I don't have Python 3, but I edited your runcom function a little and it should work: def runcom(bashCommand): sp = subprocess.Popen(['osascript'], stdin=subprocess.PIPE, stderr=subprocess.PIPE) sp.communicate('''tell application "Terminal"\nactivate\ndo script with command "{0} $EXIT"\nend tell'''.format(bashCommand)) A: [...] its expected behavior [...] This is hard to answer, since those commands do what I expect them to do, which might not be what you expect them to do. As for the actual tests: the first one tests that internal double escaped \n characters really work. The \\n with the doubled backslash does indeed work correctly in that it causes echo to emit a newline character. However, no double quotes are emitted by echo. The second tests that we can put (unescaped) newlines into the "script" and still have it work just like semicolon. That works also. Finally, the last one tests whether you can call a sudo process in a separate terminal (my ultimate goal). There is no reason why this should not work also, and indeed it does. In all cases, the new terminal should disappear as soon as you "press any key". Please also confirm this. That will not work because of several reasons: * *read in bash will by default read a whole line, not just one character *after the script you supply is executed, there is no reason for the shell within the terminal to exit *even if the shell would exit, the user can configure Terminal.app not to close a window after the shell exits (this is even the default setting) Other problems: * *the script you supply to osascript will appear in the terminal window before it is executed. in the examples above, the user will see every "This is a test [...]" twice. *I cannot figure out what $EXIT is supposed to do *The ls command will show the user "the current directory" only in the sense that the current working directory in a new terminal window will always be the user's home directory *throwaway will not be available after the script bashCommand exits Finally, this script will not work at all under Python 3, because it crashes with a TypeError: communicate() takes a byte string as argument, not a string. Also appreciated: is there a more pythonic way of spawning a terminal on Mac [...] You should look into PyObjC! It's not necessarily more pythonic, but at least you would eliminate some layers of indirection.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536623", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Animate CSS value left and opacity doesn't work with jQuery? Here is the code. I can't make opacity animate as well. <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title></title> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script> <style type="text/css"> body{ background: #000; color: #fff; font-family: Arial, sans-serif; } .menu{ position: absolute; top: 10px; left: 0px; z-index: 11; width: 700px; height: 60px; } .menu a{ background-color: #808080; margin-bottom: 2px; display: inline; width: 150px; height: 60px; color: #fff; line-height: 60px; text-align: center; text-transform: uppercase; outline: none; } .menu a:hover{ color: #000; background-color: #fff; } #main-wrapper{ position: absolute; left: 1000px; top: 10px; width: 900px; height: 380px; background-color: #000; opacity: 0.1; filter: alpha(opacity=10); -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=10)"; filter: alpha(opacity=10); z-index: 9999; zoom: 1; color: #fff; } #main-wrapper .active{ display: block; } .id-two{ padding: 10px; display: none; } .id-three{ padding: 10px; display: none; } .id-four{ padding: 10px; display: none; } #slider_window{ position: relative; left: 110px; width: 85%; height: 400px; background-color: #8ae234; overflow: hidden; top: 120px; } </style> <script type="text/javascript"> jQuery(document).ready(function($){ var current_elem_class; var close_active_page = function(current_id){ if(current_id != current_elem_class){ var left_position = '1000px'; $("#main-wrapper").stop().animate({ opacity : 0.1, left : left_position }, { "duration": 700, //"easing": "easeInOutBack", complete: function(){ //alert('complete'); if(typeof current_elem_class != 'undefined'){ $("div." + current_elem_class).removeClass('active'); current_elem_class = current_id; if(current_id != 'id-one'){ open_non_active_page("div." + current_elem_class); } }else{ current_elem_class = current_id; if(current_id != 'id-one'){ open_non_active_page("div." + current_elem_class); } } } }); } } var open_non_active_page = function(elem){ var left_position = '10px'; $(elem).addClass('active'); $("#main-wrapper").stop().animate({ opacity : 0.6, left: left_position },{ "duration": 700, //"easing": "easeInOutBack", complete: function(){ $("#main-wrapper").stop().animate({ opacity : 1.0, left: left_position },{ "duration": 1000 }); } }); } $("a.button").bind('click',function(){ close_active_page($(this).attr('id')); }); }) </script> </head> <body> <div id="menu" class="menu"> <a href="#" id="id-one" class="button close_all">Close all</a> <a href="#" id="id-two" class="button">Close all - Open Two</a> <a href="#" id="id-three" class="button">Close all - Open Three</a> <a href="#" id="id-four" class="button">Close all - Open Four</a> </div> <div id="slider_window"> <div id="main-wrapper" class=""> <div class="id-two"> <p><h2>Two</h2><br />Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent adipiscing, magna a porttitor consequat, libero augue gravida lacus, vitae blandit elit eros sed sem. Pellentesque convallis aliquam ante at pretium. Nam at semper ligula. Integer blandit tellus in libero accumsan eleifend. Maecenas hendrerit ante velit. Aenean ultricies vehicula iaculis. Aliquam id orci et lacus egestas elementum. Aliquam erat volutpat. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Aliquam viverra sollicitudin tortor, at ultricies enim mollis ut. Etiam facilisis vulputate justo, sed venenatis justo ullamcorper porta.</p> </div> <div class="id-three"> <p><h2>Three</h2><br />Aliquam id orci et lacus egestas elementum. Aliquam erat volutpat. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Aliquam viverra sollicitudin tortor, at ultricies enim mollis ut. Etiam facilisis vulputate justo, sed venenatis justo ullamcorper porta.</p> </div> <div class="id-four"> <p><h2>Four</h2><br />Lorem ipsum dolor sit amet, consectetur adipiscing elit lacus, cula iaculis. Aliquam id orci et lacus egestas elementum. Aliquam erat volutpat. Vestibulum ante ipsum primis in faucibutor, at ultricies enim mollis ut. Etiam faci</p> </div> </div> </div> </body> </html> A: You need left : "+=" + left_position or left : "-=" + left_position A: You don't have to use stop() function on open_non_active_page. In this chain of events when close_active_page is called it will stop any opening animation. var open_non_active_page = function(elem) { var left_position = '10px'; $(elem).addClass('active'); $("#main-wrapper").animate({ opacity: 0.6, left: left_position }, 700, function() { $("#main-wrapper").animate({ opacity: 1.0, left: left_position }, { queue: false, duration: 1000 }); }); } http://jsfiddle.net/ywre2/5/
{ "language": "en", "url": "https://stackoverflow.com/questions/7536624", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SQL Backup not working with PHP Script I am using the script found at this blog post. What I am trying to do is output the SQL Code onto the screen and then using file_get_contents from my local web server to get the SQL Query and mysql_query it to my local database. The problem is when I do this it gives me an error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INSERT INTO... If I copy and paste the SQL Code from the screen it's executed perfectly fine. I know this is quite a weird request but if someone could help me find the problem it'll be great. A: well i used this $file = file_get_contents("db-backup-1316832550-6f1ed002ab5595859014ebf0951522d9.sql"); foreach(explode(';', $file) as $value => $key) { if($key == ''){continue;} echo $key; mysql_query($key) or die(mysql_error()); } of course the file is example one there's seems to be a problem with the delimiter = ";"
{ "language": "en", "url": "https://stackoverflow.com/questions/7536627", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to insert date and time in oracle? Im having trouble inserting a row in my table. Here is the insert statement and table creation. This is part of a uni assignment hence the simplicity, what am i doing wrong? Im using oracle SQL developer Version 3.0.04.' The problem i am having is that it is only inserting the dd/mon/yy but not the time. How do i get it to insert the time as well? INSERT INTO WORKON (STAFFNO,CAMPAIGNTITLE,DATETIME,HOURS) VALUES ('102','Machanic Summer Savings',TO_DATE('22/April/2011 8:30:00AM','DD/MON/YY HH:MI:SSAM'),'3') ; CREATE TABLE WorkOn ( StaffNo NCHAR(4), CampaignTitle VARCHAR(50), DateTime DATE, Hours VARCHAR(2) ) ; Thanks for the help. EDIT: This is making no sense, i enter just a time in the field to test if time is working and it outputs a date WTF? This is really weird i may not use a date field and just enter the time in, i realise this will result in issues manipulating the data but this is making no sense... A: Try this: ...(to_date('2011/04/22 08:30:00', 'yyyy/mm/dd hh24:mi:ss')); A: You can use insert into table_name (date_field) values (TO_DATE('2003/05/03 21:02:44', 'yyyy/mm/dd hh24:mi:ss')); Hope it helps. A: Just use TO_DATE() function to convert string to DATE. For Example: create table Customer( CustId int primary key, CustName varchar(20), DOB date); insert into Customer values(1,'Vishnu', TO_DATE('1994/12/16 12:00:00', 'yyyy/mm/dd hh:mi:ss')); A: You are doing everything right by using a to_date function and specifying the time. The time is there in the database. The trouble is just that when you select a column of DATE datatype from the database, the default format mask doesn't show the time. If you issue a alter session set nls_date_format = 'dd/MON/yyyy hh24:mi:ss' or something similar including a time component, you will see that the time successfully made it into the database. A: create table Customer( CustId int primary key, CustName varchar(20), DOB date); insert into Customer values(1,'kingle', TO_DATE('1994-12-16 12:00:00', 'yyyy-MM-dd hh:mi:ss'));
{ "language": "en", "url": "https://stackoverflow.com/questions/7536628", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "53" }
Q: Adding html class tag under in Html.DropDownList I've been looking for answers on how to add an HTML class tag on my html.dropdownlist. here is the code <%: Html.DropDownList("PackageId", new SelectList(ViewData["Packages"] as IEnumerable, "PackageId", "Name", Model.PackageId))%> I want to add classes for options under the select element so that I can use this chained select : <select id="category"> <option value="1">One</option> <option value="2">Two</option> </select> <select id="package"> <option value="1" class="1">One - package1</option> <option value="2" class="1">One - package2</option> <option value="3" class="2">Two - package1</option> <option value="4" class="2">Two - package2</option> </select> $("#series").chained("#mark"); A: This is not possible with the DropDownList helper that is built into ASP.NET MVC. As a consequence you will have to write your own helper if you need to do that. You could take a look at the source code of ASP.NET MVC which uses TagBuilder to generate the options and you could append any attributes in your custom implementation. Another less elegant solution is to manually loop through the dataset in the view and generate individual option elements. A: I've done this for the DropDownlistFor extension method, not the DropDownList you use, but you can probably figure that out yourself. This stuff is mostly copy/paste from the MVC sources. You can find the sources here. public class ExtendedSelectListItem : SelectListItem { public object htmlAttributes { get; set; } } public static partial class HtmlHelperExtensions { public static MvcHtmlString ExtendedDropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<ExtendedSelectListItem> selectList, string optionLabel, object htmlAttributes) { return SelectInternal(htmlHelper, optionLabel, ExpressionHelper.GetExpressionText(expression), selectList, false /* allowMultiple */, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes)); } private static MvcHtmlString SelectInternal(this HtmlHelper htmlHelper, string optionLabel, string name, IEnumerable<ExtendedSelectListItem> selectList, bool allowMultiple, IDictionary<string, object> htmlAttributes) { string fullName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name); if (String.IsNullOrEmpty(fullName)) throw new ArgumentException("No name"); if (selectList == null) throw new ArgumentException("No selectlist"); object defaultValue = (allowMultiple) ? GetModelStateValue(htmlHelper, fullName, typeof(string[])) : GetModelStateValue(htmlHelper, fullName, typeof(string)); // If we haven't already used ViewData to get the entire list of items then we need to // use the ViewData-supplied value before using the parameter-supplied value. if (defaultValue == null) defaultValue = htmlHelper.ViewData.Eval(fullName); if (defaultValue != null) { IEnumerable defaultValues = (allowMultiple) ? defaultValue as IEnumerable : new[] { defaultValue }; IEnumerable<string> values = from object value in defaultValues select Convert.ToString(value, CultureInfo.CurrentCulture); HashSet<string> selectedValues = new HashSet<string>(values, StringComparer.OrdinalIgnoreCase); List<ExtendedSelectListItem> newSelectList = new List<ExtendedSelectListItem>(); foreach (ExtendedSelectListItem item in selectList) { item.Selected = (item.Value != null) ? selectedValues.Contains(item.Value) : selectedValues.Contains(item.Text); newSelectList.Add(item); } selectList = newSelectList; } // Convert each ListItem to an <option> tag StringBuilder listItemBuilder = new StringBuilder(); // Make optionLabel the first item that gets rendered. if (optionLabel != null) listItemBuilder.Append(ListItemToOption(new ExtendedSelectListItem() { Text = optionLabel, Value = String.Empty, Selected = false })); foreach (ExtendedSelectListItem item in selectList) { listItemBuilder.Append(ListItemToOption(item)); } TagBuilder tagBuilder = new TagBuilder("select") { InnerHtml = listItemBuilder.ToString() }; tagBuilder.MergeAttributes(htmlAttributes); tagBuilder.MergeAttribute("name", fullName, true /* replaceExisting */); tagBuilder.GenerateId(fullName); if (allowMultiple) tagBuilder.MergeAttribute("multiple", "multiple"); // If there are any errors for a named field, we add the css attribute. ModelState modelState; if (htmlHelper.ViewData.ModelState.TryGetValue(fullName, out modelState)) { if (modelState.Errors.Count > 0) { tagBuilder.AddCssClass(HtmlHelper.ValidationInputCssClassName); } } tagBuilder.MergeAttributes(htmlHelper.GetUnobtrusiveValidationAttributes(name)); return MvcHtmlString.Create(tagBuilder.ToString(TagRenderMode.Normal)); } internal static string ListItemToOption(ExtendedSelectListItem item) { TagBuilder builder = new TagBuilder("option") { InnerHtml = HttpUtility.HtmlEncode(item.Text) }; if (item.Value != null) { builder.Attributes["value"] = item.Value; } if (item.Selected) { builder.Attributes["selected"] = "selected"; } builder.MergeAttributes(HtmlHelper.AnonymousObjectToHtmlAttributes(item.htmlAttributes)); return builder.ToString(TagRenderMode.Normal); } } A: First thing that comes to my mind is JQuery here. You can do this with following code easily : $("#bla").find("option").addClass("poo"); A: Here's a little improved version of @john-landheer's solution. Things improved: * *problem with GetModelStateValue() fixed *DropDownList() extension method added *unobtrusive validation attributes will be rendered just like they should using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Web; using System.Web.Mvc; namespace App.Infrastructure.Helpers { public class ExtendedSelectListItem : SelectListItem { public object HtmlAttributes { get; set; } } public static class ExtendedSelectExtensions { internal static object GetModelStateValue(this HtmlHelper htmlHelper, string key, Type destinationType) { System.Web.Mvc.ModelState modelState; if (htmlHelper.ViewData.ModelState.TryGetValue(key, out modelState)) { if (modelState.Value != null) { return modelState.Value.ConvertTo(destinationType, null /* culture */); } } return null; } public static MvcHtmlString ExtendedDropDownList(this HtmlHelper htmlHelper, string name, IEnumerable<ExtendedSelectListItem> selectList) { return ExtendedDropDownList(htmlHelper, name, selectList, (string)null, (IDictionary<string, object>)null); } public static MvcHtmlString ExtendedDropDownList(this HtmlHelper htmlHelper, string name, IEnumerable<ExtendedSelectListItem> selectList, string optionLabel, IDictionary<string, object> htmlAttributes) { return ExtendedDropDownListHelper(htmlHelper, null, name, selectList, optionLabel, htmlAttributes); } public static MvcHtmlString ExtendedDropDownListHelper(this HtmlHelper htmlHelper, ModelMetadata metadata, string expression, IEnumerable<ExtendedSelectListItem> selectList, string optionLabel, IDictionary<string, object> htmlAttributes) { return SelectInternal(htmlHelper, metadata, optionLabel, expression, selectList, false, htmlAttributes); } public static MvcHtmlString ExtendedDropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<ExtendedSelectListItem> selectList, string optionLabel, object htmlAttributes) { if (expression == null) throw new ArgumentNullException("expression"); ModelMetadata metadata = ModelMetadata.FromLambdaExpression<TModel, TProperty>(expression, htmlHelper.ViewData); return SelectInternal(htmlHelper, metadata, optionLabel, ExpressionHelper.GetExpressionText(expression), selectList, false /* allowMultiple */, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes)); } private static MvcHtmlString SelectInternal(this HtmlHelper htmlHelper, ModelMetadata metadata, string optionLabel, string name, IEnumerable<ExtendedSelectListItem> selectList, bool allowMultiple, IDictionary<string, object> htmlAttributes) { string fullName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name); if (String.IsNullOrEmpty(fullName)) throw new ArgumentException("No name"); if (selectList == null) throw new ArgumentException("No selectlist"); object defaultValue = (allowMultiple) ? htmlHelper.GetModelStateValue(fullName, typeof(string[])) : htmlHelper.GetModelStateValue(fullName, typeof(string)); // If we haven't already used ViewData to get the entire list of items then we need to // use the ViewData-supplied value before using the parameter-supplied value. if (defaultValue == null) defaultValue = htmlHelper.ViewData.Eval(fullName); if (defaultValue != null) { IEnumerable defaultValues = (allowMultiple) ? defaultValue as IEnumerable : new[] { defaultValue }; IEnumerable<string> values = from object value in defaultValues select Convert.ToString(value, CultureInfo.CurrentCulture); HashSet<string> selectedValues = new HashSet<string>(values, StringComparer.OrdinalIgnoreCase); List<ExtendedSelectListItem> newSelectList = new List<ExtendedSelectListItem>(); foreach (ExtendedSelectListItem item in selectList) { item.Selected = (item.Value != null) ? selectedValues.Contains(item.Value) : selectedValues.Contains(item.Text); newSelectList.Add(item); } selectList = newSelectList; } // Convert each ListItem to an <option> tag StringBuilder listItemBuilder = new StringBuilder(); // Make optionLabel the first item that gets rendered. if (optionLabel != null) listItemBuilder.Append( ListItemToOption(new ExtendedSelectListItem() { Text = optionLabel, Value = String.Empty, Selected = false })); foreach (ExtendedSelectListItem item in selectList) { listItemBuilder.Append(ListItemToOption(item)); } TagBuilder tagBuilder = new TagBuilder("select") { InnerHtml = listItemBuilder.ToString() }; tagBuilder.MergeAttributes(htmlAttributes); tagBuilder.MergeAttribute("name", fullName, true /* replaceExisting */); tagBuilder.GenerateId(fullName); if (allowMultiple) tagBuilder.MergeAttribute("multiple", "multiple"); // If there are any errors for a named field, we add the css attribute. System.Web.Mvc.ModelState modelState; if (htmlHelper.ViewData.ModelState.TryGetValue(fullName, out modelState)) { if (modelState.Errors.Count > 0) { tagBuilder.AddCssClass(HtmlHelper.ValidationInputCssClassName); } } tagBuilder.MergeAttributes(htmlHelper.GetUnobtrusiveValidationAttributes(fullName, metadata)); return MvcHtmlString.Create(tagBuilder.ToString(TagRenderMode.Normal)); } internal static string ListItemToOption(ExtendedSelectListItem item) { TagBuilder builder = new TagBuilder("option") { InnerHtml = HttpUtility.HtmlEncode(item.Text) }; if (item.Value != null) { builder.Attributes["value"] = item.Value; } if (item.Selected) { builder.Attributes["selected"] = "selected"; } builder.MergeAttributes(HtmlHelper.AnonymousObjectToHtmlAttributes(item.HtmlAttributes)); return builder.ToString(TagRenderMode.Normal); } } } A: A simple solution : When you add @Html.DropDownList("someID", new SelectList(Model.selectItems),"--Select--",new { @class= "select-ddl" }) Add one more class in your css as .select-ddl option {} This class will be applied to all your option tags in HTML. A: I wrote a wrapper that simply modifies the html: public static MvcHtmlString DisableFirstItem(MvcHtmlString htmlString) { return new MvcHtmlString( htmlString.ToString() .Replace("<option value=\"Unknown\">", "<option disabled value=\"Unknown\">") ); } and then I wrapped my DropDownListFor with this helper function: @Html.Raw(MyHtmlHelpers.DisableFirstItem( Html.DropDownListFor(m => m.Instrument, new SelectList(ReflectionHelpers.GenerateEnumDictionary<OrderInstrument>(true), "Key", "Value", Model.Instrument), new { @class = "form-control" }) )) You could obviously make the helper function more sophisticated if you want. A: I modified @Alexander Puchkov answer in order to automatically create an ExtendedSelectList that contains a collection of ExtendedSelectListItems that is automatically generated from the properties of the Items being passed into it without having to specify the attributes for each SelectListItem manually. It creates the attributes as "data-*". You can exclude some properties using the function parms or by having them listed in excludedProperties. using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Text; using System.Web; using System.Web.Mvc; using System.Web.UI; namespace App.Infrastructure.Helpers.Extensions { public class ExtendedSelectList : SelectList { static readonly string[] excludedProperties = new string[] { "DateInsert", "DateUpdate" }; // Write here properties you want to exclude for every ExtendedSelectList public ICollection<ExtendedSelectListItem> ExtendedSelectListItems { get; set; } public ExtendedSelectList(IEnumerable items, string dataValueField, string dataTextField, object selectedValue, params string[] exclude) : base(items, dataValueField, dataTextField, selectedValue) { ExtendedSelectListItems = new List<ExtendedSelectListItem>(); exclude = exclude.Concat(new string[] { dataValueField, dataTextField }).ToArray(); exclude = exclude.Concat(excludedProperties).ToArray(); foreach (var selectListItem in this.AsEnumerable()) { var extendedItem = new ExtendedSelectListItem() { Value = selectListItem.Value, Text = selectListItem.Text, Selected = selectListItem.Selected, Disabled = selectListItem.Disabled, Group = selectListItem.Group }; var htmlAttributes = new Dictionary<string, object>(); var item = items.Cast<object>().FirstOrDefault(x => { string valueItem = DataBinder.Eval(x, DataValueField).ToString(); string valueSelectListItem = DataBinder.Eval(selectListItem, "Value").ToString(); return valueItem == valueSelectListItem; }); foreach (PropertyInfo property in item.GetType().GetProperties()) { if (!property.CanRead || (property.GetIndexParameters().Length > 0) || (exclude != null && exclude.Contains(property.Name))) continue; htmlAttributes.Add("data-" + property.Name.ToLower(), property.GetValue(item)); } extendedItem.HtmlAttributesDict = htmlAttributes; ExtendedSelectListItems.Add(extendedItem); } } } public class ExtendedSelectListItem : SelectListItem { public object HtmlAttributes { get; set; } public Dictionary<string, object> HtmlAttributesDict { get; set; } } public static class ExtendedSelectExtensions { internal static object GetModelStateValue(this HtmlHelper htmlHelper, string key, Type destinationType) { System.Web.Mvc.ModelState modelState; if (htmlHelper.ViewData.ModelState.TryGetValue(key, out modelState)) { if (modelState.Value != null) { return modelState.Value.ConvertTo(destinationType, null /* culture */); } } return null; } public static MvcHtmlString ExtendedDropDownList(this HtmlHelper htmlHelper, string name, IEnumerable<ExtendedSelectListItem> selectList) { return ExtendedDropDownList(htmlHelper, name, selectList, (string)null, (IDictionary<string, object>)null); } public static MvcHtmlString ExtendedDropDownList(this HtmlHelper htmlHelper, string name, IEnumerable<ExtendedSelectListItem> selectList, string optionLabel, IDictionary<string, object> htmlAttributes) { return ExtendedDropDownListHelper(htmlHelper, null, name, selectList, optionLabel, htmlAttributes); } public static MvcHtmlString ExtendedDropDownListHelper(this HtmlHelper htmlHelper, ModelMetadata metadata, string expression, IEnumerable<ExtendedSelectListItem> selectList, string optionLabel, IDictionary<string, object> htmlAttributes) { return SelectInternal(htmlHelper, metadata, optionLabel, expression, selectList, false, htmlAttributes); } public static MvcHtmlString ExtendedDropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<ExtendedSelectListItem> selectList, string optionLabel, object htmlAttributes) { if (expression == null) throw new ArgumentNullException("expression"); ModelMetadata metadata = ModelMetadata.FromLambdaExpression<TModel, TProperty>(expression, htmlHelper.ViewData); return SelectInternal(htmlHelper, metadata, optionLabel, ExpressionHelper.GetExpressionText(expression), selectList, false /* allowMultiple */, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes)); } private static MvcHtmlString SelectInternal(this HtmlHelper htmlHelper, ModelMetadata metadata, string optionLabel, string name, IEnumerable<ExtendedSelectListItem> selectList, bool allowMultiple, IDictionary<string, object> htmlAttributes) { string fullName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name); if (String.IsNullOrEmpty(fullName)) throw new ArgumentException("No name"); if (selectList == null) throw new ArgumentException("No selectlist"); object defaultValue = (allowMultiple) ? htmlHelper.GetModelStateValue(fullName, typeof(string[])) : htmlHelper.GetModelStateValue(fullName, typeof(string)); // If we haven't already used ViewData to get the entire list of items then we need to // use the ViewData-supplied value before using the parameter-supplied value. if (defaultValue == null) defaultValue = htmlHelper.ViewData.Eval(fullName); if (defaultValue != null) { IEnumerable defaultValues = (allowMultiple) ? defaultValue as IEnumerable : new[] { defaultValue }; IEnumerable<string> values = from object value in defaultValues select Convert.ToString(value, CultureInfo.CurrentCulture); HashSet<string> selectedValues = new HashSet<string>(values, StringComparer.OrdinalIgnoreCase); List<ExtendedSelectListItem> newSelectList = new List<ExtendedSelectListItem>(); foreach (ExtendedSelectListItem item in selectList) { item.Selected = (item.Value != null) ? selectedValues.Contains(item.Value) : selectedValues.Contains(item.Text); newSelectList.Add(item); } selectList = newSelectList; } // Convert each ListItem to an <option> tag StringBuilder listItemBuilder = new StringBuilder(); // Make optionLabel the first item that gets rendered. if (optionLabel != null) listItemBuilder.Append( ListItemToOption(new ExtendedSelectListItem() { Text = optionLabel, Value = String.Empty, Selected = false })); foreach (ExtendedSelectListItem item in selectList) { listItemBuilder.Append(ListItemToOption(item)); } TagBuilder tagBuilder = new TagBuilder("select") { InnerHtml = listItemBuilder.ToString() }; tagBuilder.MergeAttributes(htmlAttributes); tagBuilder.MergeAttribute("name", fullName, true /* replaceExisting */); tagBuilder.GenerateId(fullName); if (allowMultiple) tagBuilder.MergeAttribute("multiple", "multiple"); // If there are any errors for a named field, we add the css attribute. System.Web.Mvc.ModelState modelState; if (htmlHelper.ViewData.ModelState.TryGetValue(fullName, out modelState)) { if (modelState.Errors.Count > 0) { tagBuilder.AddCssClass(HtmlHelper.ValidationInputCssClassName); } } tagBuilder.MergeAttributes(htmlHelper.GetUnobtrusiveValidationAttributes(fullName, metadata)); return MvcHtmlString.Create(tagBuilder.ToString(TagRenderMode.Normal)); } internal static string ListItemToOption(ExtendedSelectListItem item) { TagBuilder builder = new TagBuilder("option") { InnerHtml = HttpUtility.HtmlEncode(item.Text) }; if (item.Value != null) { builder.Attributes["value"] = item.Value; } if (item.Selected) { builder.Attributes["selected"] = "selected"; } var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(item.HtmlAttributes); builder.MergeAttributes(attributes); if (item.HtmlAttributesDict != null) { foreach (var attribute in item.HtmlAttributesDict) { var key = attribute.Key.ToLower(); // We call ToLower to keep the same naming convention used by MVC's HtmlHelper.AnonymousObjectToHtmlAttributes var value = attribute.Value?.ToString() ?? ""; builder.Attributes[key] = value; } } return builder.ToString(TagRenderMode.Normal); } } } To use it in Razor you do: @{ var availableLocations = new ExtendedSelectList(Model.AvailableLocations, "Id", "Value", Model.LocationId); } @Html.ExtendedDropDownListFor(m => Model.LocationId, availableLocations.ExtendedSelectListItems, null, new { id = "ddLocation" }) Notice the "availableLocations.ExtendedSelectListItems" because you can't use the Enumerable items directly as they are simple SelectListItem
{ "language": "en", "url": "https://stackoverflow.com/questions/7536631", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "39" }
Q: OCaml: Pattern matching vs If/else statements So, I'm totally new to OCaml and am moving pretty slowly in getting my first functions implemented. One thing I'm having trouble understanding is when to use pattern matching abilities like let foo = [] -> true | _ -> false;; vs using the if else structure like let foo a = if a = [] then true else false;; When should I use each? A: As far as I know the signifincant difference is that the expression at the guards in the match statement is a pattern which means you can do things that allow you to break apart the shape (destruct) the matched expression, as Nicolas showed in his answer. The other implication of this is that code like this: let s = 1 in let x = 2 in match s with x -> Printf.printf "x does not equal s!!\n" x | _ -> Printf.printf "x = %d\n" x; won't do what you expect. This is because x in the match statement does not refer to the x in the let statement above it but it's a name of the pattern. In cases like these you'd need to use if statements. A: I don't think there's a clear cut answer to that question. First, the obvious case of pattern matching is when you need destructing, e.g.: let rec sum = function | [] -> 0 | head :: tail -> head + sum tail;; Another obvious case is when you're defining a recursive function, pattern matching make the edge condition clearer, e.g.: let rec factorial = function | 0 -> 1 | n -> n * factorial(n - 1);; instead of: let rec factorial = function n -> if n = 0 then 1 else n * factorial(n-1);; That might not be a great example, just use your imagination to figure out more complex edge conditions! ;-) In term of regular (say C like) languages, I could say that you should use pattern matching instead of switch/case and if in place of the ternary operator. For everything else it's kind of a grey zone but pattern matching is usually preferred in the ML family of languages. A: For me if..then..else is equivalent to match .. with | true -> .. | false -> .., but there's a syntax sugar if you are facing cases with nested pattern matching, using if..else in an interlace way can help you avoiding to use begin...end to separate different level of patterns match .. with | true -> if .. then match .. with | true -> .. | false -> .. else ... | false -> ... is more compact than match .. with | true -> begin match .. with | true -> begin match .. with | true -> .. | false -> .. end | false -> ... end | false -> ... A: Pattern matching allows for deconstruction of compound data types, and in general, the ability to match pattern within a given data structure, rather than using conditionals like the if.. then structure. Pattern matching can also be used for boolean equality cases using the |x when (r == n) type construct. I should also add pattern matching is a lot more efficient than if... then.. constructs, so use it liberally!
{ "language": "en", "url": "https://stackoverflow.com/questions/7536633", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: ggplot heatmap legend doesn't represent negative numbers I'm trying to make a heat map for a data set that includes negative numbers: Ne BR Error 10000 0.00001 1.62 10000 0.000001 -1.03 10000 0.0000001 -0.124 100000 0.00001 36.73 100000 0.000001 5.86 100000 0.0000001 -0.79 1000000 0.00001 -8.335 1000000 0.000001 39.465 1000000 0.0000001 2.59 I've used this code: library(ggplot2) data = read.csv('full_path') (p <- ggplot(data[1:9,], aes(Ne, BR)) + geom_tile(aes(fill=Error), colour="white") + scale_fill_gradient(low="white", high="black") + scale_x_log('Ne') + scale_y_log('Birth Rate') + opts(axis.ticks = theme_blank())) This produces a fine heatmap, but the legend doesn't account for the negative numbers. The colors appear to correctly reflect the negative values, but the legend stops at zero, which is light grey. How can I get a legend out of this that covers the full range of the data in the 'Error' column of my dataframe? A: Try this: ggplot(dat, aes(Ne, BR)) + geom_tile(aes(fill=Error), colour="white") + scale_fill_gradient(low="white", high="black",breaks = seq(min(dat$Error),max(dat$Error),length.out = 5)) + scale_x_log('Ne') + scale_y_log('Birth Rate') + opts(axis.ticks = theme_blank()) ggplot is just trying to pick 'nice' breaks in the scale for you, similarly to how axis tick marks are chosen. (I changed your data frame name to dat, as data is a commonly used function in R. It's not a huge deal, but it avoids confusion.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7536639", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How are a java Runnable object's other methods called? I am given some skeletons of classes that I must implement (I personally don't really agree with the design of the program but I am not at mercy to change it :( ) and they work in this manner: I have a Game class which implements Runnable and represents a chess game. A Server class will have a list of multiple Game classes that it keeps track of. Ok this makes sense, Game implements Runnable so the Server can put each game in its own thread. I am a bit confused at how java's threads work. What I know is the following: After tying my Runnable class to a thread and calling the .start() method, the Runnable class's run() method is called. However, I have some other methods inside my Game class such as: capturePiece() playerMakesMove() etc In the current design, it is up to the Server to handle game actions. When a player wants to capture a piece, the Server will call game.capturePiece(). In this case, is capturePiece() being run on the Game thread, or the Server's thread? (the caller's thread or the callee's thread) In this case, what would run() even do? A: Any method, in any programming language, executes in the same thread as the caller. When you call Thread.start() it runs in the same thread that called it. Now, you know that the run() method of a Thread does not execute in the same thread as start. But that is because start does not itself call run. You will have to read up more on threads to get the complete picture but just imagine that start only crates a new thread with some data structure (the Runnable) and the newly created thread looks at that data structure, identifies the Runnable and executes its run method. And that is really the only way control passes from one thread to another: one thread generates some data and other thread picks it up and processes it. Control does not pass from one thread to another, it is inter-thread communication and co-ordination. If the methods of Game are called by Server then the threads are not going to have anything to do, are they? But instead, if the Server does not call the method directly but instead represents the action as data then Game.run() can pick the action and perform it, in its own thread. Now the only question is where can Server put the data such that each Game.run(), running in its own thread knows to pick it up from. One option is to use BlockingQueue. The Server can put these Action objects in the queue and the Game thread can pick it up. How will the two know to use the same queue? There many different ways, one is for server to create the game with a queue and store a map on its side. As in the skeleton below: class Server { Map<Game, BlockingQueue> games = ....; void createGame() { BlockingQueue queue = ....; Game game = new Game(queue); games.put(game, queue); } void foo() { Game game = ....; Action action = ....; // identify the Game map.get(g).add(action); } } class Game { BlockingQueue _queue; Game(BlockingQueue queue) { _queue = queue; } void run() { while (true) { Action nextAction = _queue.take(); // perform the action } } } A: @Razor, as per other discussion, if a class implements Runnable and the run method is tied up with a long running process, you can still call other methods of the class. And this can be tested like this: public class TestThreads { public static void main(String[] args) { TestGame testGame = new TestGame(); new Thread(testGame).start(); for (int i = 0; i < 10; i++) { testGame.otherMethod(); try { Thread.sleep(1000); } catch (InterruptedException e) {} } System.out.println("done"); System.exit(0); } } class TestGame implements Runnable { @Override public void run() { try { Thread.sleep(100 * 1000); } catch (InterruptedException e) {} } public void otherMethod() { System.out.println("in other method"); } } A: In this case, is capturePiece() being run on the Game thread, or the Server's thread? capturePiece will run on the Game thread, where the method has been called. In this case, what would run() even do? If it always the Server who calls method on Game threads, then you could do the same with a single thread. Threads will be useful if the actions were triggered by each Game thread that independently call Server to notify the result.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536641", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to reverse the order of displaying content of a list? Let's say I have a list of integers. var myList = new List<int>(); 1, 2, 3, 4, 5, ..., 10 Is there any function that allows me to display them in reverse order, i.e. 10, 9, 8, ..., 1 EDIT public List<Location> SetHierarchyOfLocation(Location location) { var list = new List<Location>(7); var juridiction = location.Juridiction; if (juridiction > 0) { while (juridiction > 0) { var loc = repository.GetLocationByID(juridiction); list.Add(loc); juridiction = loc.Juridiction; } } return list; } Since the list contains location by location, I want to be able to display it by reversed order as well. Now, when I write return list.Reversed(), I get the error. Thanks for helping A: Is there any function that allows me to display them in reverse order, i.e. It depends if you want to reverse them in place, or merely produce a sequence of values that is the reverse of the underlying sequence without altering the list in place. If the former, just use List<T>.Reverse. // myList is List<int> myList.Reverse(); Console.WriteLine(String.Join(", ", myList)); If the latter, the key is Enumerable.Reverse: // myList is List<int> Console.WriteLine( String.Join( ", ", myList.AsEnumerable().Reverse() ) ); for a beautiful one-liner. Be sure you have using System.Linq;. A: var reversed = myList.Reverse() should do the trick. EDIT: Correction- as the OP found out, List.Reverse works in-place, unlike Enumerable.Reverse. Thus, the answer is simply myList.Reverse(); - you don't assign it to a new variable. A: To do a foreach loop in a List<Location> reversely you should use: foreach (Location item in myList.Reverse().ToList()) { // do something ... } The .Reverse() is an in-place reverse; it doesn't return a new list. The .ToList() after the .Reverse() do the trick.
{ "language": "en", "url": "https://stackoverflow.com/questions/7536644", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Matlab dependency management I am looking to apply dependency management to a large-scale Matlab project. This project imports a large number of java libraries, as well as some compiled C++ code, to the extent that some software best practices are now becoming more essential. Is anyone aware of something along the lines of Maven/Ivy for use with Matlab? A: I'm not very familiar with Matlab, but sounds like your issue is that you're trying to put a large set of binary files under some sort of version control? If those files are available in Maven Central, you can use my ant2ivy script to generate a starting set of ivy.xml and ivysettings.xml files. One of the great things about ivy is that it can be run stand-alone as follows: java -jar ivy.jar -retrieve "lib/[artifact].[ext]" -ivy ivy.xml -settings ivysettings.xml This will download the jars and place them into a "lib" directory (Or whatever directory Matlab uses). A: matlab isn't really made for large-scale projects. You'll have to come up with your own code to check for all necessary dependencies. A: I created a simple maven based dependency management for matlab projects using jitpack.io and zip as release format. Sample project - https://github.com/ragavsathish/mmockito Simple archetype can be found in https://github.com/ragavsathish/matlab-simple-archetype Please provide your comments on what can be improved further
{ "language": "en", "url": "https://stackoverflow.com/questions/7536645", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }