Search Results

Search found 10298 results on 412 pages for 'self teaching'.

Page 10/412 | < Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >

  • Model self referential collections in Rails

    - by Najitaka
    I have written an application for an online clothing store in Rails 2.3.5. I want to show related Products when a customer views the Product Detail page. For example, if the customer views the detail page for a suit, I'd like to display the accessory products that match the dress such as a vest, shoes, and belt. I have named the related products an Ensemble. However, the vest, shoes, and belts are also Products which is what has me struggling. I have it working as follows but I know it's not the Rails way. I have a Products table for all of the products. Not important here but I also have a ProductDetails table. I have an Ensembles table that has the following columns: product_id - the main or origination product, the one displayed on the detail page outfit_id - the related or accessory product In setting up the data, on the Products list, for each Product I have an Ensemble link. This link takes you to the index action in the Ensembles controller. Using the id from the "main" Product, I find all of the associated Ensemble rows by product_id or I create a new ensemble and assign the id from the main product as the product_id. I'd like to just be able to do @product.related_products to get an Ensemble collection. Also on the index page I list the columns of the main product so the user can be sure their main product was the one they selected from the list. I also have a select list of the other products, with an Add to Ensemble action. Finally on the same index page, I have a table that displays the products that are already in the ensemble and in that list each row has a destroy link to remove a particular product from the ensemble. It would be nice if given a single Ensemble row @ensemble I could do @ensemble.product to get the Product related to the outfit_id of the ensemble row. I've got it working without associations but I have to run queries in the controller to build my own @product, @ensemble, and @ensembles collections. Also the only way I found to destroy an ensemble row is by Ensemble.connection.delete(sql to delete), simple @ensemble.destroy doesn't work. Anyone know how I would set up the associations or have a link to a site explaining a similar setup. None of the examples I found use the same table. They have A related to B through C. I want A related to other A through B.

    Read the article

  • How to stop a QDialog from executing while still in the __init__ statement(or immediatly after)?

    - by Jonathan
    I am wondering how I can go about stopping a dialog from opening if certain conditions are met in its __init__ statement. The following code tries to call the 'self.close()' function and it does, but (I'm assuming) since the dialog has not yet started its event loop, that it doesn't trigger the close event? So is there another way to close and/or stop the dialog from opening without triggering an event? Example code: from PyQt4 import QtCore, QtGui class dlg_closeInit(QtGui.QDialog): ''' Close the dialog if a certain condition is met in the __init__ statement ''' def __init__(self): QtGui.QDialog.__init__(self) self.txt_mytext = QtGui.QLineEdit('some text') self.btn_accept = QtGui.QPushButton('Accept') self.myLayout = QtGui.QVBoxLayout(self) self.myLayout.addWidget(self.txt_mytext) self.myLayout.addWidget(self.btn_accept) self.setLayout(self.myLayout) # Connect the button self.connect(self.btn_accept,QtCore.SIGNAL('clicked()'), self.on_accept) self.close() def on_accept(self): # Get the data... self.mydata = self.txt_mytext.text() self.accept() def get_data(self): return self.mydata def closeEvent(self, event): print 'Closing...' if __name__ == '__main__': import sys app = QtGui.QApplication(sys.argv) dialog = dlg_closeInit() if dialog.exec_(): print dialog.get_data() else: print "Failed"

    Read the article

  • Python Locking Implementation (with threading module)

    - by Matty
    This is probably a rudimentary question, but I'm new to threaded programming in Python and am not entirely sure what the correct practice is. Should I be creating a single lock object (either globally or being passed around) and using that everywhere that I need to do locking? Or, should I be creating multiple lock instances in each of the classes where I will be employing them. Take these 2 rudimentary code samples, which direction is best to go? The main difference being that a single lock instance is used in both class A and B in the second, while multiple instances are used in the first. Sample 1 class A(): def __init__(self, theList): self.theList = theList self.lock = threading.Lock() def poll(self): while True: # do some stuff that eventually needs to work with theList self.lock.acquire() try: self.theList.append(something) finally: self.lock.release() class B(threading.Thread): def __init__(self,theList): self.theList = theList self.lock = threading.Lock() self.start() def run(self): while True: # do some stuff that eventually needs to work with theList self.lock.acquire() try: self.theList.remove(something) finally: self.lock.release() if __name__ == "__main__": aList = [] for x in range(10): B(aList) A(aList).poll() Sample 2 class A(): def __init__(self, theList,lock): self.theList = theList self.lock = lock def poll(self): while True: # do some stuff that eventually needs to work with theList self.lock.acquire() try: self.theList.append(something) finally: self.lock.release() class B(threading.Thread): def __init__(self,theList,lock): self.theList = theList self.lock = lock self.start() def run(self): while True: # do some stuff that eventually needs to work with theList self.lock.acquire() try: self.theList.remove(something) finally: self.lock.release() if __name__ == "__main__": lock = threading.Lock() aList = [] for x in range(10): B(aList,lock) A(aList,lock).poll()

    Read the article

  • Which is the best Linux C/C++ debugger (or front-end to gdb) to help teaching programming?

    - by omer.gimenez
    I teach a sort of "lite" C++ programming course to novices ("lite" meaning no pointers, no classes, just plain old C, plus references and STL string and vectors). Students have no previous experience in programming, so I believe that using an interactive debugger would help them understand program flow, variables, and recursion. The course is taught in Linux. Teaching them to use gdb is just overkill (they will not use nor understand most features). I just need something simple but easy to use: to see at which line the program is now, what is in the stack (local variables, previous calls, etc.). I look something similar to old Turbo Pascal or Turbo C++ Borland's debugger, or Visual Studio debugger. Thank you,

    Read the article

  • Experiences teaching or learning map/reduce/etc before recursion?

    - by Jay
    As far as I can see, the usual (and best in my opinion) order for teaching iterting constructs in functional programming with Scheme is to first teach recursion and maybe later get into things like map, reduce and all SRFI-1 procedures. This is probably, I guess, because with recursion the student has everything that's necessary for iterating (and even re-write all of SRFI-1 if he/she wants to do so). Now I was wondering if the opposite approach has ever been tried: use several procedures from SRFI-1 and only when they are not enough (for example, to approximate a function) use recursion. My guess is that the result would not be good, but I'd like to know about any past experiences with this approach.

    Read the article

  • Software and/(x)or Hardware Projects for Pre-School Kids

    - by haylem
    I offered to participate at my kid's pre-school for various activities (yes, I'm crazy like that), and one of them is to help them discover extra-curricular (big word for a pre-school, but by lack of a better one... :)) hobbies, which may or may not relate to a professional activity. At first I thought that it wouldn't be really easy to have pre-schoolers relate to programming or the internal workings of a computer system in general (and I'm more used to teaching middle-school to university-level students), but then I thought there must be a way. So I'm trying to figure out ways to introduce very young kids (3yo) to computer systems in a fun and preferably educational way. Of course, I don't expect them to start smashing the stack for fun and profit right away (or at least not voluntarily, though I could use the occasion for some toddler tests...), but I'm confident there must be ways to get them interested in both: using the systems, becoming curious about understanding what they do, interacting with the systems to modify them. I guess this setting is not really relevant after all, it's pretty much the same as if you were aiming to achieve the same for your own kids at home. Ideas Considering we're talking 3yo pre-schoolers here, and that at this age some kids are already quite confident using a mouse (some even a keyboard, if not for typing, at least to press some buttons they've come to associate with actions) while others have not yet had any interaction with computers of any kind, it needs to be: rather basic, demonstrated and played with in less then 5 or 10 minutes, doable in in groups or alone, scalable and extendable in complexity to accommodate their varying abilities. The obvious options are: basic smallish games to play with, interactive systems like LOGO, Kojo, Squeak and clones (possibly even simpler than that), or thngs like Lego Systems. I guess it can be a thing to reflect on both at the software and the hardware levels: it could be done with a desktop or laptop machine, a tablet, a smartphone (or a crap-phone, for that matter, as long as you can modify it), or even get down to building something from scratch (Raspberry Pi and Arduino being popular options at the moment). I can probably be in the form of games, funny visualizations (which are pretty much games) w/ Prototype, virtual worlds to explore. I also thought on the moment (and I hope this won't offend anyone) that some approaches to teaching pets could work (reward systems, haptic feedback and such things could quickly point a kid in the right direction to understanding how things work, in a similar fashion - I'm not suggesting to shock the kids!). Hmm, Is There an Actual Question in There? What type of systems do you think might be a good fit, both in terms of hardware and software? Do you have seen such systems, or have anything in mind to work on? Are you aware of some research in this domain, with tangible results? Any input is welcome. It's not that I don't see options: there are tons, but I have a harder time pinpointing a more concrete and definite type of project/activity, so I figure some have valuable ideas or existing ones. Note: I am not advocating that every kid should learn to program, be interested in computer systems, or that all of them in a class would even care enough to follow such an introduction with more than a blank stare. I don't buy into the "everybody would benefit from learning to program" thing. Wouldn't hurt, but not necessary in any way. But if I can walk out of there with a few of them having smiled using the thing (or heck, cried because others took them away from them), that'd be good enough. Related Questions I've seen and that seem to complement what I'm looking for, but not exactly for the same age groups or with the same goals: Teaching Programming to Kids Recommendations for teaching kids math concepts & skills for programming?

    Read the article

  • Manager Self Service at your Fingertips

    - by Elaine Clement
    Last week we released new and improved Manager Self Service capabilities in PeopleSoft HCM 9.1. We delivered a new Manager Dashboard, streamlined many Manager Self Service transactions, provided new Pivot Grid capabilities, and implemented one-click Related Actions accessible from multiple places – all with the goal of improving every Manager’s self service experience. Manager Dashboard These new capabilities have the potential to significantly impact an organization’s bottom line, and here is why. Increased Efficiency The Manager Dashboard provides a ‘one-stop shop’ for your Managers with all of the key data they need consolidated into a single view. Alerts notifying managers of important tasks are immediately viewable and actionable. Administrators can configure the dashboard to include the most important pagelets needed for their organization, and Managers can personalize it to fit within their personal way of conducting their tasks. The Related Actions feature further improves the ease with which Managers get their work done by providing one-click access to Manager Self Service transactions.  Increased Job Satisfaction The streamlined Manager transactions, related actions, and the new Manager Dashboard provide an enhanced user experience. Managers are able to quickly get in, get the information they need, complete their transactions, and get out. Managers can spend their time focusing on getting the business results they need instead of their day to day HR tasks. Enhanced Decision Support Administrators can ensure the information and analytics they want their Managers to use are available from the Manager Dashboard, establishing best business practices. Additional pivot grids relevant to your own organization can be added to the Manager Dashboard. With this easy access to the relevant information in an easily understood format, Managers can make the right business decisions needed to improve their team and their team’s productivity. For more details on the Manager Dashboard and some of the other newly posted features, such as a new Talent Summary, check out this video and others: Oracle PeopleSoft Webcasts

    Read the article

  • custom tabbars and make them circulate

    - by pengwang
    i want to custom tabbars and want to circulate slide,default tab bar only have 5 items show at the same time,it not meet me,i have 11 items,so i want to make 3 tabbars ,every have 5 items,for example A(0-4)--B(5-9)--C(10)--A--B--C--A. at print i only finish A(0-4)--B(5-9)--C(10),how to make them circulate? my code : .h file #import <UIKit/UIKit.h> @protocol InfiniTabBarDelegate; @interface InfiniTabBar : UIScrollView <UIScrollViewDelegate, UITabBarDelegate> { __weak id <InfiniTabBarDelegate> infiniTabBarDelegate; NSMutableArray *tabBars; UITabBar *aTabBar; UITabBar *bTabBar; } @property (nonatomic, weak) id infiniTabBarDelegate; @property (strong,nonatomic) NSMutableArray *tabBars; @property (strong,nonatomic) UITabBar *aTabBar; @property (strong,nonatomic) UITabBar *bTabBar; - (id)initWithItems:(NSArray *)items; - (void)setBounces:(BOOL)bounces; // Don't set more items than initially - (void)setItems:(NSArray *)items animated:(BOOL)animated; - (int)currentTabBarTag; - (int)selectedItemTag; - (BOOL)scrollToTabBarWithTag:(int)tag animated:(BOOL)animated; - (BOOL)selectItemWithTag:(int)tag; @end @protocol InfiniTabBarDelegate <NSObject> - (void)infiniTabBar:(InfiniTabBar *)tabBar didScrollToTabBarWithTag:(int)tag; - (void)infiniTabBar:(InfiniTabBar *)tabBar didSelectItemWithTag:(int)tag; @end .m file @implementation InfiniTabBar @synthesize infiniTabBarDelegate; @synthesize tabBars; @synthesize aTabBar; @synthesize bTabBar; - (id)initWithItems:(NSArray *)items { self = [super initWithFrame:CGRectMake(0.0, 411.0, 320.0, 49.0)]; // TODO: //self = [super initWithFrame:CGRectMake(self.superview.frame.origin.x + self.superview.frame.size.width - 320.0, self.superview.frame.origin.y + self.superview.frame.size.height - 49.0, 320.0, 49.0)]; // Doesn't work. self is nil at this point. if (self) { self.pagingEnabled = YES; self.delegate = self; self.tabBars = [[NSMutableArray alloc] init]; float x = 0.0; for (double d = 0; d < ceil(items.count / 5.0); d ++) { UITabBar *tabBar = [[UITabBar alloc] initWithFrame:CGRectMake(x, 0.0, 320.0, 49.0)]; tabBar.delegate = self; int len = 0; for (int i = d * 5; i < d * 5 + 5; i ++) if (i < items.count) len ++; tabBar.items = [items objectsAtIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(d * 5, len)]]; // NSLog(@"####%@",NSMakeRange(d * 5, len)); [self.tabBars addObject:tabBar]; [self addSubview:tabBar]; x += 320.0; } self.contentSize = CGSizeMake(x, 49.0); } return self; } - (void)setBounces:(BOOL)bounces { if (bounces) { int count = self.tabBars.count; if (count > 0) { if (self.aTabBar == nil) self.aTabBar = [[UITabBar alloc] initWithFrame:CGRectMake(-320.0, 0.0, 320.0, 49.0)]; [self addSubview:self.aTabBar]; if (self.bTabBar == nil) self.bTabBar = [[UITabBar alloc] initWithFrame:CGRectMake(count * 320.0, 0.0, 320.0, 49.0)]; [self addSubview:self.bTabBar]; } } else { [self.aTabBar removeFromSuperview]; [self.bTabBar removeFromSuperview]; } [super setBounces:bounces]; } - (void)setItems:(NSArray *)items animated:(BOOL)animated { for (UITabBar *tabBar in self.tabBars) { int len = 0; for (int i = [self.tabBars indexOfObject:tabBar] * 5; i < [self.tabBars indexOfObject:tabBar] * 5 + 5; i ++) if (i < items.count) len ++; [tabBar setItems:[items objectsAtIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange([self.tabBars indexOfObject:tabBar] * 5, len)]] animated:animated]; } self.contentSize = CGSizeMake(ceil(items.count / 5.0) * 320.0, 49.0); } - (int)currentTabBarTag { return self.contentOffset.x / 320.0; } - (int)selectedItemTag { for (UITabBar *tabBar in self.tabBars) if (tabBar.selectedItem != nil) return tabBar.selectedItem.tag; // No item selected return 0; } - (BOOL)scrollToTabBarWithTag:(int)tag animated:(BOOL)animated { for (UITabBar *tabBar in self.tabBars) if ([self.tabBars indexOfObject:tabBar] == tag) { UITabBar *tabBar = [self.tabBars objectAtIndex:tag]; [self scrollRectToVisible:tabBar.frame animated:animated]; if (animated == NO) [self scrollViewDidEndDecelerating:self]; return YES; } return NO; } - (BOOL)selectItemWithTag:(int)tag { for (UITabBar *tabBar in self.tabBars) for (UITabBarItem *item in tabBar.items) if (item.tag == tag) { tabBar.selectedItem = item; [self tabBar:tabBar didSelectItem:item]; return YES; } return NO; } - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView { [infiniTabBarDelegate infiniTabBar:self didScrollToTabBarWithTag:scrollView.contentOffset.x / 320.0]; } - (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView { [self scrollViewDidEndDecelerating:scrollView]; } - (void)tabBar:(UITabBar *)cTabBar didSelectItem:(UITabBarItem *)item { // Act like a single tab bar for (UITabBar *tabBar in self.tabBars) if (tabBar != cTabBar) tabBar.selectedItem = nil; [infiniTabBarDelegate infiniTabBar:self didSelectItemWithTag:item.tag]; } @end

    Read the article

  • Self-signed certificates for a known community

    - by costlow
    Recently announced changes scheduled for Java 7 update 51 (January 2014) have established that the default security slider will require code signatures and the Permissions Manifest attribute. Code signatures are a common practice recommended in the industry because they help determine that the code your computer will run is the same code that the publisher created. This post is written to help users that need to use self-signed certificates without involving a public Certificate Authority. The role of self-signed certificates within a known community You may still use self-signed certificates within a known community. The difference between self-signed and purchased-from-CA is that your users must import your self-signed certificate to indicate that it is valid, whereas Certificate Authorities are already trusted by default. This works for known communities where people will trust that my certificate is mine, but does not scale widely where I cannot actually contact or know the systems that will need to trust my certificate. Public Certificate Authorities are widely trusted already because they abide by many different requirements and frequent checks. An example would be students in a university class sharing their public certificates on a mailing list or web page, employees publishing on the intranet, or a system administrator rolling certificates out to end-users. Managed machines help this because you can automate the rollout, but they are not required -- the major point simply that people will trust and import your certificate. How to distribute self-signed certificates for a known community There are several steps required to distribute a self-signed certificate to users so that they will properly trust it. These steps are: Creating a public/private key pair for signing. Exporting your public certificate for others Importing your certificate onto machines that should trust you Verify work on a different machine Creating a public/private key pair for signing Having a public/private key pair will give you the ability both to sign items yourself and issue a Certificate Signing Request (CSR) to a certificate authority. Create your public/private key pair by following the instructions for creating key pairs.Every Certificate Authority that I looked at provided similar instructions, but for the sake of cohesiveness I will include the commands that I used here: Generate the key pair.keytool -genkeypair -alias erikcostlow -keyalg EC -keysize 571 -validity 730 -keystore javakeystore_keepsecret.jks Provide a good password for this file. The alias "erikcostlow" is my name and therefore easy to remember. Substitute your name of something like "mykey." The sigalg of EC (Elliptical Curve) and keysize of 571 will give your key a good strong lifetime. All keys are set to expire. Two years or 730 days is a reasonable compromise between not-long-enough and too-long. Most public Certificate Authorities will sign something for one to five years. You will be placing your keys in javakeystore_keepsecret.jks -- this file will contain private keys and therefore should not be shared. If someone else gets these private keys, they can impersonate your signature. Please be cautious about automated cloud backup systems and private key stores. Answer all the questions. It is important to provide good answers because you will stick with them for the "-validity" days that you specified above.What is your first and last name?  [Unknown]:  First LastWhat is the name of your organizational unit?  [Unknown]:  Line of BusinessWhat is the name of your organization?  [Unknown]:  MyCompanyWhat is the name of your City or Locality?  [Unknown]:  City NameWhat is the name of your State or Province?  [Unknown]:  CAWhat is the two-letter country code for this unit?  [Unknown]:  USIs CN=First Last, OU=Line of Business, O=MyCompany, L=City, ST=CA, C=US correct?  [no]:  yesEnter key password for <erikcostlow>        (RETURN if same as keystore password): Verify your work:keytool -list -keystore javakeystore_keepsecret.jksYou should see your new key pair. Exporting your public certificate for others Public Key Infrastructure relies on two simple concepts: the public key may be made public and the private key must be private. By exporting your public certificate, you are able to share it with others who can then import the certificate to trust you. keytool -exportcert -keystore javakeystore_keepsecret.jks -alias erikcostlow -file erikcostlow.cer To verify this, you can open the .cer file by double-clicking it on most operating systems. It should show the information that you entered during the creation prompts. This is the file that you will share with others. They will use this certificate to prove that artifacts signed by this certificate came from you. If you do not manage machines directly, place the certificate file on an area that people within the known community should trust, such as an intranet page. Import the certificate onto machines that should trust you In order to trust the certificate, people within your known network must import your certificate into their keystores. The first step is to verify that the certificate is actually yours, which can be done through any band: email, phone, in-person, etc. Known networks can usually do this Determine the right keystore: For an individual user looking to trust another, the correct file is within that user’s directory.e.g. USER_HOME\AppData\LocalLow\Sun\Java\Deployment\security\trusted.certs For system-wide installations, Java’s Certificate Authorities are in JAVA_HOMEe.g. C:\Program Files\Java\jre8\lib\security\cacerts File paths for Mac and Linux are included in the link above. Follow the instructions to import the certificate into the keystore. keytool -importcert -keystore THEKEYSTOREFROMABOVE -alias erikcostlow -file erikcostlow.cer In this case, I am still using my name for the alias because it’s easy for me to remember. You may also use an alias of your company name. Scaling distribution of the import The easiest way to apply your certificate across many machines is to just push the .certs or cacerts file onto them. When doing this, watch out for any changes that people would have made to this file on their machines. Trusted.certs: When publishing into user directories, your file will overwrite any keys that the user has added since last update. CACerts: It is best to re-run the import command with each installation rather than just overwriting the file. If you just keep the same cacerts file between upgrades, you will overwrite any CAs that have been added or removed. By re-importing, you stay up to date with changes. Verify work on a different machine Verification is a way of checking on the client machine to ensure that it properly trusts signed artifacts after you have added your signing certificate. Many people have started using deployment rule sets. You can validate the deployment rule set by: Create and sign the deployment rule set on the computer that holds the private key. Copy the deployment rule set on to the different machine where you have imported the signing certificate. Verify that the Java Control Panel’s security tab shows your deployment rule set. Verifying an individual JAR file or multiple JAR files You can test a certificate chain by using the jarsigner command. jarsigner -verify filename.jar If the output does not say "jar verified" then run the following command to see why: jarsigner -verify -verbose -certs filename.jar Check the output for the term “CertPath not validated.”

    Read the article

  • Python: nonblocking read from stdout of threaded subprocess

    - by sberry2A
    I have a script (worker.py) that prints unbuffered output in the form... 1 2 3 . . . n where n is some constant number of iterations a loop in this script will make. In another script (service_controller.py) I start a number of threads, each of which starts a subprocess using subprocess.Popen(stdout=subprocess.PIPE, ...); Now, in my main thread (service_controller.py) I want to read the output of each thread's worker.py subprocess and use it to calculate an estimate for the time remaining till completion. I have all of the logic working that reads the stdout from worker.py and determines the last printed number. The problem is that I can not figure out how to do this in a non-blocking way. If I read a constant bufsize then each read will end up waiting for the same data from each of the workers. I have tried numerous ways including using fcntl, select + os.read, etc. What is my best option here? I can post my source if needed, but I figured the explanation describes the problem well enough. Thanks for any help here. EDIT Adding sample code I have a worker that starts a subprocess. class WorkerThread(threading.Thread): def __init__(self): self.completed = 0 self.process = None self.lock = threading.RLock() threading.Thread.__init__(self) def run(self): cmd = ["/path/to/script", "arg1", "arg2"] self.process = subprocess.Popen(cmd, stdout=subprocess.PIPE, bufsize=1, shell=False) #flags = fcntl.fcntl(self.process.stdout, fcntl.F_GETFL) #fcntl.fcntl(self.process.stdout.fileno(), fcntl.F_SETFL, flags | os.O_NONBLOCK) def get_completed(self): self.lock.acquire(); fd = select.select([self.process.stdout.fileno()], [], [], 5)[0] if fd: self.data += os.read(fd, 1) try: self.completed = int(self.data.split("\n")[-2]) except IndexError: pass self.lock.release() return self.completed I then have a ThreadManager. class ThreadManager(): def __init__(self): self.pool = [] self.running = [] self.lock = threading.Lock() def clean_pool(self, pool): for worker in [x for x in pool is not x.isAlive()]: worker.join() pool.remove(worker) del worker return pool def run(self, concurrent=5): while len(self.running) + len(self.pool) > 0: self.clean_pool(self.running) n = min(max(concurrent - len(self.running), 0), len(self.pool)) if n > 0: for worker in self.pool[0:n]: worker.start() self.running.extend(self.pool[0:n]) del self.pool[0:n] time.sleep(.01) for worker in self.running + self.pool: worker.join() and some code to run it. threadManager = ThreadManager() for i in xrange(0, 5): threadManager.pool.append(WorkerThread()) threadManager.run() I have stripped out a log of the other code in hopes to try to pinpoint the issue.

    Read the article

  • How to teach computer science ?

    - by proferikson
    I am just starting to teach computer science. It's just the basic level. I'm finding that I sometimes don't know how to approach topics in a way that lets students easily understand. I've found that the best thing is to use analogies. A terrible one, that worked well, was presenting recursion by using the process of eating a burger. (You eat one bite, then you eat the rest). Interesting real world examples do wonders here. I'd like to know the techniques you have used for teaching, or teachers you've had have used that proved particularly effective. I'd also like to know your best analogies and examples for topics in CS101, especially for those harder to grasp topics. I'm teaching the class in Java (as required).

    Read the article

  • C# Toolbox: Debug-able, Self-Installable Windows Service Template Redux

    - by James Michael Hare
    I had written a pair of posts before about creating a debug-able and self-installing windows service template in C#.  This is a template I began creating to ease creating windows services and to take some of the mundane tasks out of the coding effort.  The original posts were here: C# Windows Services (1 of 2) - Debug-able Windows Services C# Windows Services (2 of 2) - Self-Installing Windows Services But at the time, though I gave the code samples I didn't have a downloadable for of the template on the blog.  After getting many requests for the actual source, I zipped it up and am posting it with this blog entry.  Click on the link below to download the archive.  The password on the archive is, imaginatively enough, password.  Hope you enjoy and please feel free to comment and suggest changes! Debug-able, Self-Installing Windows Service Template download Enjoy! Tweet Technorati Tags: C#,Windows Service,Toolbox

    Read the article

  • What are some good, simple examples for queues?

    - by Michael Ekstrand
    I'm teaching CS2 (Java and data structures), and am having some difficulty coming up with good examples to use when teaching queues. The two major applications I use them for are multithreaded message passing (but MT programming is out of scope for the course), and BFS-style algorithms (and I won't be covering graphs until later in the term). I also want to avoid contrived examples. Most things that I think of, if I were actually going to solve them in a single-threaded fashion I would just use a list rather than a queue. I tend to only use queues when processing and discovery are interleaved (e.g. search), or in other special cases like length-limited buffers (e.g. maintaining last N items). To the extent practical, I am trying to teach my students good ways to actually do things in real programs, not just toys to show off a feature. Any suggestions of good, simple algorithms or applications of queues that I can use as examples but that require a minimum of other prior knowledge?

    Read the article

  • Can I avoid a threaded UDP socket in Python dropping data?

    - by 666craig
    First off, I'm new to Python and learning on the job, so be gentle! I'm trying to write a threaded Python app for Windows that reads data from a UDP socket (thread-1), writes it to file (thread-2), and displays the live data (thread-3) to a widget (gtk.Image using a gtk.gdk.pixbuf). I'm using queues for communicating data between threads. My problem is that if I start only threads 1 and 3 (so skip the file writing for now), it seems that I lose some data after the first few samples. After this drop it looks fine. Even by letting thread 1 complete before running thread 3, this apparent drop is still there. Apologies for the length of code snippet (I've removed the thread that writes to file), but I felt removing code would just prompt questions. Hope someone can shed some light :-) import socket import threading import Queue import numpy import gtk gtk.gdk.threads_init() import gtk.glade import pygtk class readFromUDPSocket(threading.Thread): def __init__(self, socketUDP, readDataQueue, packetSize, numScans): threading.Thread.__init__(self) self.socketUDP = socketUDP self.readDataQueue = readDataQueue self.packetSize = packetSize self.numScans = numScans def run(self): for scan in range(1, self.numScans + 1): buffer = self.socketUDP.recv(self.packetSize) self.readDataQueue.put(buffer) self.socketUDP.close() print 'myServer finished!' class displayWithGTK(threading.Thread): def __init__(self, displayDataQueue, image, viewArea): threading.Thread.__init__(self) self.displayDataQueue = displayDataQueue self.image = image self.viewWidth = viewArea[0] self.viewHeight = viewArea[1] self.displayData = numpy.zeros((self.viewHeight, self.viewWidth, 3), dtype=numpy.uint16) def run(self): scan = 0 try: while True: if not scan % self.viewWidth: scan = 0 buffer = self.displayDataQueue.get(timeout=0.1) self.displayData[:, scan, 0] = numpy.fromstring(buffer, dtype=numpy.uint16) self.displayData[:, scan, 1] = numpy.fromstring(buffer, dtype=numpy.uint16) self.displayData[:, scan, 2] = numpy.fromstring(buffer, dtype=numpy.uint16) gtk.gdk.threads_enter() self.myPixbuf = gtk.gdk.pixbuf_new_from_data(self.displayData.tostring(), gtk.gdk.COLORSPACE_RGB, False, 8, self.viewWidth, self.viewHeight, self.viewWidth * 3) self.image.set_from_pixbuf(self.myPixbuf) self.image.show() gtk.gdk.threads_leave() scan += 1 except Queue.Empty: print 'myDisplay finished!' pass def quitGUI(obj): print 'Currently active threads: %s' % threading.enumerate() gtk.main_quit() if __name__ == '__main__': # Create socket (IPv4 protocol, datagram (UDP)) and bind to address socketUDP = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) host = '192.168.1.5' port = 1024 socketUDP.bind((host, port)) # Data parameters samplesPerScan = 256 packetsPerSecond = 1200 packetSize = 512 duration = 1 # For now, set a fixed duration to log data numScans = int(packetsPerSecond * duration) # Create array to store data data = numpy.zeros((samplesPerScan, numScans), dtype=numpy.uint16) # Create queue for displaying from readDataQueue = Queue.Queue(numScans) # Build GUI from Glade XML file builder = gtk.Builder() builder.add_from_file('GroundVue.glade') window = builder.get_object('mainwindow') window.connect('destroy', quitGUI) view = builder.get_object('viewport') image = gtk.Image() view.add(image) viewArea = (1200, samplesPerScan) # Instantiate & start threads myServer = readFromUDPSocket(socketUDP, readDataQueue, packetSize, numScans) myDisplay = displayWithGTK(readDataQueue, image, viewArea) myServer.start() myDisplay.start() gtk.gdk.threads_enter() gtk.main() gtk.gdk.threads_leave() print 'gtk.main finished!'

    Read the article

  • Can I avoid a threaded UDP socket in Pyton dropping data?

    - by 666craig
    First off, I'm new to Python and learning on the job, so be gentle! I'm trying to write a threaded Python app for Windows that reads data from a UDP socket (thread-1), writes it to file (thread-2), and displays the live data (thread-3) to a widget (gtk.Image using a gtk.gdk.pixbuf). I'm using queues for communicating data between threads. My problem is that if I start only threads 1 and 3 (so skip the file writing for now), it seems that I lose some data after the first few samples. After this drop it looks fine. Even by letting thread 1 complete before running thread 3, this apparent drop is still there. Apologies for the length of code snippet (I've removed the thread that writes to file), but I felt removing code would just prompt questions. Hope someone can shed some light :-) import socket import threading import Queue import numpy import gtk gtk.gdk.threads_init() import gtk.glade import pygtk class readFromUDPSocket(threading.Thread): def __init__(self, socketUDP, readDataQueue, packetSize, numScans): threading.Thread.__init__(self) self.socketUDP = socketUDP self.readDataQueue = readDataQueue self.packetSize = packetSize self.numScans = numScans def run(self): for scan in range(1, self.numScans + 1): buffer = self.socketUDP.recv(self.packetSize) self.readDataQueue.put(buffer) self.socketUDP.close() print 'myServer finished!' class displayWithGTK(threading.Thread): def __init__(self, displayDataQueue, image, viewArea): threading.Thread.__init__(self) self.displayDataQueue = displayDataQueue self.image = image self.viewWidth = viewArea[0] self.viewHeight = viewArea[1] self.displayData = numpy.zeros((self.viewHeight, self.viewWidth, 3), dtype=numpy.uint16) def run(self): scan = 0 try: while True: if not scan % self.viewWidth: scan = 0 buffer = self.displayDataQueue.get(timeout=0.1) self.displayData[:, scan, 0] = numpy.fromstring(buffer, dtype=numpy.uint16) self.displayData[:, scan, 1] = numpy.fromstring(buffer, dtype=numpy.uint16) self.displayData[:, scan, 2] = numpy.fromstring(buffer, dtype=numpy.uint16) gtk.gdk.threads_enter() self.myPixbuf = gtk.gdk.pixbuf_new_from_data(self.displayData.tostring(), gtk.gdk.COLORSPACE_RGB, False, 8, self.viewWidth, self.viewHeight, self.viewWidth * 3) self.image.set_from_pixbuf(self.myPixbuf) self.image.show() gtk.gdk.threads_leave() scan += 1 except Queue.Empty: print 'myDisplay finished!' pass def quitGUI(obj): print 'Currently active threads: %s' % threading.enumerate() gtk.main_quit() if __name__ == '__main__': # Create socket (IPv4 protocol, datagram (UDP)) and bind to address socketUDP = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) host = '192.168.1.5' port = 1024 socketUDP.bind((host, port)) # Data parameters samplesPerScan = 256 packetsPerSecond = 1200 packetSize = 512 duration = 1 # For now, set a fixed duration to log data numScans = int(packetsPerSecond * duration) # Create array to store data data = numpy.zeros((samplesPerScan, numScans), dtype=numpy.uint16) # Create queue for displaying from readDataQueue = Queue.Queue(numScans) # Build GUI from Glade XML file builder = gtk.Builder() builder.add_from_file('GroundVue.glade') window = builder.get_object('mainwindow') window.connect('destroy', quitGUI) view = builder.get_object('viewport') image = gtk.Image() view.add(image) viewArea = (1200, samplesPerScan) # Instantiate & start threads myServer = readFromUDPSocket(socketUDP, readDataQueue, packetSize, numScans) myDisplay = displayWithGTK(readDataQueue, image, viewArea) myServer.start() myDisplay.start() gtk.gdk.threads_enter() gtk.main() gtk.gdk.threads_leave() print 'gtk.main finished!'

    Read the article

  • I'm making a simulated tv

    - by Jam
    I need to make a tv that shows the user the channel and the volume, and shows whether or not the television is on. I have the majority of the code made, but for some reason the channels won't switch. I'm fairly unfamiliar with how properties work, and I think that's what my problem here is. Help please. class Television(object): def __init__(self, __channel=1, volume=1, is_on=0): self.__channel=__channel self.volume=volume self.is_on=is_on def __str__(self): if self.is_on==1: print "The tv is on" print self.__channel print self.volume else: print "The television is off." def toggle_power(self): if self.is_on==1: self.is_on=0 return self.is_on if self.is_on==0: self.is_on=1 return self.is_on def get_channel(self): return channel def set_channel(self, choice): if self.is_on==1: if choice>=0 and choice<=499: channel=self.__channel else: print "Invalid channel!" else: print "The television isn't on!" channel=property(get_channel, set_channel) def raise_volume(self, up=1): if self.is_on==1: self.volume+=up if self.volume>=10: self.volume=10 print "Max volume!" else: print "The television isn't on!" def lower_volume(self, down=1): if self.is_on==1: self.volume-=down if self.volume<=0: self.volume=0 print "Muted!" else: print "The television isn't on!" def main(): tv=Television() choice=None while choice!="0": print \ """ Television 0 - Exit 1 - Toggle Power 2 - Change Channel 3 - Raise Volume 4 - Lower Volume """ choice=raw_input("Choice: ") print if choice=="0": print "Good-bye." elif choice=="1": tv.toggle_power() tv.__str__() elif choice=="2": change=raw_input("What would you like to change the channel to?") tv.set_channel(change) tv.__str__() elif choice=="3": tv.raise_volume() tv.__str__() elif choice=="4": tv.lower_volume() tv.__str__() else: print "\nSorry, but", choice, "isn't a valid choice." main() raw_input("Press enter to exit.")

    Read the article

  • What are the disadvantages of self-encapsulation?

    - by Dave Jarvis
    Background Tony Hoare's billion dollar mistake was the invention of null. Subsequently, a lot of code has become riddled with null pointer exceptions (segfaults) when software developers try to use (dereference) uninitialized variables. In 1989, Wirfs-Brock and Wikerson wrote: Direct references to variables severely limit the ability of programmers to re?ne existing classes. The programming conventions described here structure the use of variables to promote reusable designs. We encourage users of all object-oriented languages to follow these conventions. Additionally, we strongly urge designers of object-oriented languages to consider the effects of unrestricted variable references on reusability. Problem A lot of software, especially in Java, but likely in C# and C++, often uses the following pattern: public class SomeClass { private String someAttribute; public SomeClass() { this.someAttribute = "Some Value"; } public void someMethod() { if( this.someAttribute.equals( "Some Value" ) ) { // do something... } } public void setAttribute( String s ) { this.someAttribute = s; } public String getAttribute() { return this.someAttribute; } } Sometimes a band-aid solution is used by checking for null throughout the code base: public void someMethod() { assert this.someAttribute != null; if( this.someAttribute.equals( "Some Value" ) ) { // do something... } } public void anotherMethod() { assert this.someAttribute != null; if( this.someAttribute.equals( "Some Default Value" ) ) { // do something... } } The band-aid does not always avoid the null pointer problem: a race condition exists. The race condition is mitigated using: public void anotherMethod() { String someAttribute = this.someAttribute; assert someAttribute != null; if( someAttribute.equals( "Some Default Value" ) ) { // do something... } } Yet that requires two statements (assignment to local copy and check for null) every time a class-scoped variable is used to ensure it is valid. Self-Encapsulation Ken Auer's Reusability Through Self-Encapsulation (Pattern Languages of Program Design, Addison Wesley, New York, pp. 505-516, 1994) advocated self-encapsulation combined with lazy initialization. The result, in Java, would resemble: public class SomeClass { private String someAttribute; public SomeClass() { setAttribute( "Some Value" ); } public void someMethod() { if( getAttribute().equals( "Some Value" ) ) { // do something... } } public void setAttribute( String s ) { this.someAttribute = s; } public String getAttribute() { String someAttribute = this.someAttribute; if( someAttribute == null ) { setAttribute( createDefaultValue() ); } return someAttribute; } protected String createDefaultValue() { return "Some Default Value"; } } All duplicate checks for null are superfluous: getAttribute() ensures the value is never null at a single location within the containing class. Efficiency arguments should be fairly moot -- modern compilers and virtual machines can inline the code when possible. As long as variables are never referenced directly, this also allows for proper application of the Open-Closed Principle. Question What are the disadvantages of self-encapsulation, if any? (Ideally, I would like to see references to studies that contrast the robustness of similarly complex systems that use and don't use self-encapsulation, as this strikes me as a fairly straightforward testable hypothesis.)

    Read the article

  • Atom feed validator keeps showing Self reference doesn't match document location

    - by Dino
    I am creating an atom feed, but when I validate it I keep getting: Self reference doesn't match document location and the specific line that is causing the error is: <link rel="self" type="application/atom+xml" href="http://www.example.com/test.rss"/> Please can anyone advise what the error is? Ps. I noticed an up arrow just at the end of that line. (presumably something to do with that bbut not sure)

    Read the article

  • rhythmbox plugin code for hot key not working

    - by Bunny Rabbit
    def activate(self,shell): self.shell = shell self.copy_selected() self.action = gtk.Action ('foo','bar','baz',None) self.activate_id = self.action.connect ('activate', self.call_bk_fn,self.shell) self.action_group = gtk.ActionGroup ('hot_key_action_group') self.action_group.add_action_with_accel (self.action, "<control>E") uim = shell.get_ui_manager () uim.insert_action_group (self.action_group, 0) uim.ensure_update () def call_bk_fn(): print('hello world') i am using the above code in a plugin for rhythmbox ,and here i am trying to register the key ctr+e so that the call_bk_fn gets called whenever the key combination is pressed , but its not working why is that so ?

    Read the article

  • Strange Flash AS3 xml Socket behavior

    - by Rnd_d
    I have a problem which I can't understand. To understand it I wrote a socket client on AS3 and a server on python/twisted, you can see the code of both applications below. Let's launch two clients at the same time, arrange them so that you can see both windows and press connection button in both windows. Then press and hold any button. What I'm expecting: Client with pressed button sends a message "some data" to the server, then the server sends this message to all the clients(including the original sender) . Then each client moves right the button 'connectButton' and prints a message to the log with time in the following format: "min:secs:milliseconds". What is going wrong: The motion is smooth in the client that sends the message, but in all other clients the motion is jerky. This happens because messages to those clients arrive later than to the original sending client. And if we have three clients (let's name them A,B,C) and we send a message from A, the sending time log of B and C will be the same. Why other clients recieve this messages later than the original sender? By the way, on ubuntu 10.04/chrome all the motion is smooth. Two clients are launched in separated chromes. windows screenshot Can't post linux screenshot, need more than 10 reputation to post more hyperlinks. Listing of log, four clients simultaneously: [16:29:33.280858] 62.140.224.1 >> some data [16:29:33.280912] 87.249.9.98 << some data [16:29:33.280970] 87.249.9.98 << some data [16:29:33.281025] 87.249.9.98 << some data [16:29:33.281079] 62.140.224.1 << some data [16:29:33.323267] 62.140.224.1 >> some data [16:29:33.323326] 87.249.9.98 << some data [16:29:33.323386] 87.249.9.98 << some data [16:29:33.323440] 87.249.9.98 << some data [16:29:33.323493] 62.140.224.1 << some data [16:29:34.123435] 62.140.224.1 >> some data [16:29:34.123525] 87.249.9.98 << some data [16:29:34.123593] 87.249.9.98 << some data [16:29:34.123648] 87.249.9.98 << some data [16:29:34.123702] 62.140.224.1 << some data AS3 client code package { import adobe.utils.CustomActions; import flash.display.Sprite; import flash.events.DataEvent; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.KeyboardEvent; import flash.events.MouseEvent; import flash.events.SecurityErrorEvent; import flash.net.XMLSocket; import flash.system.Security; import flash.text.TextField; public class Main extends Sprite { private var socket :XMLSocket; private var textField :TextField = new TextField; private var connectButton :TextField = new TextField; public function Main():void { if (stage) init(); else addEventListener(Event.ADDED_TO_STAGE, init); } private function init(event:Event = null):void { socket = new XMLSocket(); socket.addEventListener(Event.CONNECT, connectHandler); socket.addEventListener(DataEvent.DATA, dataHandler); stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler); addChild(textField); textField.y = 50; textField.width = 780; textField.height = 500; textField.border = true; connectButton.selectable = false; connectButton.border = true; connectButton.addEventListener(MouseEvent.MOUSE_DOWN, connectMouseDownHandler); connectButton.width = 105; connectButton.height = 20; connectButton.text = "click here to connect"; addChild(connectButton); } private function connectHandler(event:Event):void { textField.appendText("Connect\n"); textField.appendText("Press and hold any key\n"); } private function dataHandler(event:DataEvent):void { var now:Date = new Date(); textField.appendText(event.data + " time = " + now.getMinutes() + ":" + now.getSeconds() + ":" + now.getMilliseconds() + "\n"); connectButton.x += 2; } private function keyDownHandler(event:KeyboardEvent):void { socket.send("some data"); } private function connectMouseDownHandler(event:MouseEvent):void { var connectAddress:String = "ep1c.org"; var connectPort:Number = 13250; Security.loadPolicyFile("xmlsocket://" + connectAddress + ":" + String(connectPort)); socket.connect(connectAddress, connectPort); } } } Python server code from twisted.internet import reactor from twisted.internet.protocol import ServerFactory from twisted.protocols.basic import LineOnlyReceiver import datetime class EchoProtocol(LineOnlyReceiver): ##### name = "" id = 0 delimiter = chr(0) ##### def getName(self): return self.transport.getPeer().host def connectionMade(self): self.id = self.factory.getNextId() print "New connection from %s - id:%s" % (self.getName(), self.id) self.factory.clientProtocols[self.id] = self def connectionLost(self, reason): print "Lost connection from "+ self.getName() del self.factory.clientProtocols[self.id] self.factory.sendMessageToAllClients(self.getName() + " has disconnected.") def lineReceived(self, line): print "[%s] %s >> %s" % (datetime.datetime.now().time(), self, line) if line=="<policy-file-request/>": data = """<?xml version="1.0"?> <!DOCTYPE cross-domain-policy SYSTEM "http://www.adobe.com/xml/dtds/cross-domain-policy.dtd"> <!-- Policy file for xmlsocket://ep1c.org --> <cross-domain-policy> <allow-access-from domain="*" to-ports="%s" /> </cross-domain-policy>""" % PORT self.send(data) else: self.factory.sendMessageToAllClients( line ) def send(self, line): print "[%s] %s << %s" % (datetime.datetime.now().time(), self, line) if line: self.transport.write( str(line) + chr(0)) else: print "Nothing to send" def __str__(self): return self.getName() class ChatProtocolFactory(ServerFactory): protocol = EchoProtocol def __init__(self): self.clientProtocols = {} self.nextId = 0 def getNextId(self): id = self.nextId self.nextId += 1 return id def sendMessageToAllClients(self, msg): for client in self.clientProtocols: self.clientProtocols[client].send(msg) def sendMessageToClient(self, id, msg): self.clientProtocols[id].send(msg) PORT = 13250 print "Starting Server" factory = ChatProtocolFactory() reactor.listenTCP(PORT, factory) reactor.run()

    Read the article

  • Self-Executing Anonymous Function vs Prototype

    - by Robotsushi
    In Javascript there are a few clearly prominent techniques for create and manage classes/namespaces in javascript. I am curious what situations warrant using one technique vs. the other. I want to pick one and stick with it moving forward. I write enterprise code that is maintained and shared across multiple teams, and I want to know what is the best practice when writing maintainable javascript ? I tend to prefer Self-Executing Anonymous Functions however I am curious what the community vote is on these techniques. Prototype : function obj() { } obj.prototype.test = function() { alert('Hello?'); }; var obj2 = new obj(); obj2.test(); Self-Closing Anonymous Function : //Self-Executing Anonymous Function (function( skillet, $, undefined ) { //Private Property var isHot = true; //Public Property skillet.ingredient = "Bacon Strips"; //Public Method skillet.fry = function() { var oliveOil; addItem( "\t\n Butter \n\t" ); addItem( oliveOil ); console.log( "Frying " + skillet.ingredient ); }; //Private Method function addItem( item ) { if ( item !== undefined ) { console.log( "Adding " + $.trim(item) ); } } }( window.skillet = window.skillet || {}, jQuery )); //Public Properties console.log( skillet.ingredient ); //Bacon Strips //Public Methods skillet.fry(); //Adding Butter & Fraying Bacon Strips //Adding a Public Property skillet.quantity = "12"; console.log( skillet.quantity ); //12 //Adding New Functionality to the Skillet (function( skillet, $, undefined ) { //Private Property var amountOfGrease = "1 Cup"; //Public Method skillet.toString = function() { console.log( skillet.quantity + " " + skillet.ingredient + " & " + amountOfGrease + " of Grease" ); console.log( isHot ? "Hot" : "Cold" ); }; }( window.skillet = window.skillet || {}, jQuery )); //end of skillet definition try { //12 Bacon Strips & 1 Cup of Grease skillet.toString(); //Throws Exception } catch( e ) { console.log( e.message ); //isHot is not defined } I feel that I should mention that the Self-Executing Anonymous Function is the pattern used by the jQuery team. Update When I asked this question I didn't truly see the importance of what I was trying to understand. The real issue at hand is whether or not to use new to create instances of your objects or to use patterns which do not require constructors of the use of the new keyword. I added my own answer, because in my opinion we should make use of patterns which don't use the new keyword. For more information please see my answer.

    Read the article

  • Rhythmbox plugin code for hot key not working - why?

    - by Bunny Rabbit
    def activate(self,shell): self.shell = shell self.copy_selected() self.action = gtk.Action ('foo','bar','baz',None) self.activate_id = self.action.connect ('activate', self.call_bk_fn,self.shell) self.action_group = gtk.ActionGroup ('hot_key_action_group') self.action_group.add_action_with_accel (self.action, "<control>E") uim = shell.get_ui_manager () uim.insert_action_group (self.action_group, 0) uim.ensure_update () def call_bk_fn(): print('hello world') I am using the above code in a plugin for Rhythmbox and here I am trying to register the key Ctrl+E so that the call_bk_fn gets called whenever the key combination is pressed but its not working. Why is that so ?

    Read the article

  • Implementing touch-based rotation in cocoa touch

    - by ewoo
    I am wondering what is the best way to implement rotation-based dragging movements in my iPhone application. I have a UIView that I wish to rotate around its centre, when the users finger is touch the view and they move it. Think of it like a dial that needs to be adjusted with the finger. The basic question comes down to: 1) Should I remember the initial angle and transform when touchesBegan is called, and then every time touchesMoved is called apply a new transform to the view based on the current position of the finger, e.g., something like: - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *touch = [touches anyObject]; CGPoint currentPoint = [touch locationInView:self]; //current position of touch if (([touch view] == self) && [Utility getDistance:currentPoint toPoint:self.middle] <= ROTATE_RADIUS //middle is centre of view && [Utility getDistance:currentPoint toPoint:self.middle] >= MOVE_RADIUS) { //will be rotation gesture //remember state of view at beginning of touch CGPoint top = CGPointMake(self.middle.x, 0); self.initialTouch = currentPoint; self.initialAngle = angleBetweenLines(self.middle, top, self.middle, currentPoint); self.initialTransform = self.transform; } } - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{ UITouch *touch = [touches anyObject]; CGPoint currentPoint = [touch locationInView:self]; //current position of touch if (([touch view] == self) && [Utility getDistance:currentPoint toPoint:self.middle] <= ROTATE_RADIUS && [Utility getDistance:currentPoint toPoint:self.middle] >= MOVE_RADIUS) { //a rotation gesture //rotate tile float newAngle = angleBetweenLines(self.middle, CGPointMake(self.middle.x, 0), self.middle, currentPoint); //touch angle float angleDif = newAngle - self.initialAngle; //work out dif between angle at beginning of touch and now. CGAffineTransform newTransform = CGAffineTransformRotate(self.initialTransform, angleDif); //create new transform self.transform = newTransform; //apply transform. } OR 2) Should I simply remember the last known position/angle, and rotate the view based on the difference in angle between that and now, e.g.,: - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *touch = [touches anyObject]; CGPoint currentPoint = [touch locationInView:self]; //current position of touch if (([touch view] == self) && [Utility getDistance:currentPoint toPoint:self.middle] <= ROTATE_RADIUS && [Utility getDistance:currentPoint toPoint:self.middle] >= MOVE_RADIUS) { //will be rotation gesture //remember state of view at beginning of touch CGPoint top = CGPointMake(self.middle.x, 0); self.lastTouch = currentPoint; self.lastAngle = angleBetweenLines(self.middle, top, self.middle, currentPoint); } } - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{ UITouch *touch = [touches anyObject]; CGPoint currentPoint = [touch locationInView:self]; //current position of touch if (([touch view] == self) && [Utility getDistance:currentPoint toPoint:middle] <= ROTATE_RADIUS && [Utility getDistance:currentPoint toPoint:middle] >= MOVE_RADIUS) { //a rotation gesture //rotate tile float newAngle = angleBetweenLines(self.middle, CGPointMake(self.middle.x, 0), self.middle, currentPoint); //touch angle float angleDif = newAngle - self.lastAngle; //work out dif between angle at beginning of touch and now. CGAffineTransform newTransform = CGAffineTransformRotate(self.transform, angleDif); //create new transform self.transform = newTransform; //apply transform. self.lastTouch = currentPoint; self.lastAngle = newAngle; } The second option makes more sense to me, but it is not giving very pleasing results (jaggy updates and non-smooth rotations). Which way is best (if any), in terms of performance? Cheers!

    Read the article

  • How to teach Exception Handling for New Programmers?

    - by Kanini
    How do you go about teaching Exception Handling to Programmers. All other things are taught easily - Data Structures, ASP.NET, WinForms, WPF, WCF - you name it, everything can be taught easily. With Exception Handling, teaching them try-catch-finally is just the syntactic nature of Exception Handling. What should be taught however is - What part of your code do you put in the try block? What do you do in the catch block? Let me illustrate it with an example. You are working on a Windows Forms Project (a small utility) and you have designed it as below with 3 different projects. UILayer BusinessLayer DataLayer If an Exception (let us say of loading an XDocument throws an exception) is raised at DataLayer (the UILayer calls BusinessLayer which in turns calls the DataLayer), do you just do the following //In DataLayer try { XDocument xd_XmlDocument = XDocument.Load("systems.xml"); } catch(Exception ex) { throw ex; } which gets thrown again in the BusinessLayer and which is caught in UILayer where I write it to the log file? Is this how you go about Exception Handling?

    Read the article

< Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >