Search Results

Search found 312 results on 13 pages for 'invalidate'.

Page 8/13 | < Previous Page | 4 5 6 7 8 9 10 11 12 13  | Next Page >

  • Invalidating UITableView contents

    - by Roman
    I have an application with several UITableViewControllers. Now, the user is allowed to change "Data source". In that case I need to invalidate (reset) data in the relevant UITableViews. I figured out, that I can use NSNotificationCenter and add these controllers as observers to events which will be generated when the data source changes. The question is, how do I reset the underlying tables? I can, of course, set some boolean flag, and call UITableView:reloadData in viewWillAppear or viewDidAppear, but I was wondering, if there's a cleaner way of doing it. Or perhaps I'm completely missing the point, and I don't need NSNotificationCenter altogether. Thank you very much in advance.

    Read the article

  • fade effect in blackberry (os 4.5 ) application.

    - by Vivart
    in my blackberry application i have to create a effect in which fullscreen bitmap is slowly disappearing and ui screen is coming up. protected void paint(Graphics g) { g.setGlobalAlpha(globalAlpha);//starting value of globalAlpha is 255. g.drawBitmap(0, 0, getWidth(), getHeight(), _bitmap, 0, 0); g.setGlobalAlpha(255 - globalAlpha); globalAlpha--; super.paint(g); } This code is just for giving demo that what i want. super.paint(g) is calling 255 times because of that its a poor code. in one timer task i am calling invalidate(); So any suggestions how to implement this?

    Read the article

  • MyLocationOverlay dissappears, is not there onResume.

    - by Paul
    I have a mapView to which I add a MyLocationOverlay. It displays fine when the app starts from scratch (goes through onCreate). If I exit the app (back button) and then start it again (onResume), the overlay is gone. I have tried to fix this for 10+ hours. All sorts of messing with re-adding the overlay. Resetting the overlays. Changing the maps location so it's forced to redraw. Trying to manually invalidate or force a redraw of the overlay. NOTHING has worked. From the way the code looks, the Overlay object exists and everything is working fine - but it's just not on the map. Is anybody else having this problem? (Droid Incredible, 2.2)

    Read the article

  • how to kill an older jsonp request?

    - by pfg
    I have a cross-domain long polling request using getJSON with a callback that looks something like this: $.getJSON("http://long-polling.com/some.fcgi?jsoncallback=?" function(data){ if(data.items[0].rval == 1) { // update data in page } }); The problem is the request to the long-polling service might take a while to return, and another getJSON request might be made in the meantime and update the page even though it is a stale response. Req1: h**p://long-polling.com/some.fcgi at 10:00 AM Req2: h**p://long-polling.com/some.fcgi? at 10:01 AM Req1 returns and updates the data on the page 10:02 AM I want a way to invalidate the return from Req1 if Req2 has already been made. Thanks!

    Read the article

  • How can i call NStimer form one viewcontroller from unother viewcontroller?

    - by Bala
    At first time i call the timer like this in Third viewcontroller timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(targetMethod) userInfo:nil repeats:NO]; Then timer called the targetMethod -(void)targetMethod { First * sVC = [[First alloc] initWithNibName:@"First" bundle:[NSBundle mainBundle]]; [self presentModalViewController:sVC animated:YES]; [sVC release]; [timer invalidate]; } First viewcontroller opened.. In First viewcontroller had one button.In button action i wrote (IBAction) Action:(id)sender { [self dismissModalViewControllerAnimated:YES]; Third *BVC=[[Third alloc]init]; [Bvc TimerStart]; Timestart is function i start timer in this function.. i want to call Third viewcontroller timer function this place } timer started..But view didn't open (first )viewcontroller....... Please help me......

    Read the article

  • Android: How can we change the view in the tabs?

    - by achie
    I want to provide a clickthrough on the list in a tab which opens another view. I need to open the new view within the same tab. I then need to provide a back button on the changed layout to change the view to original view. I have tried this. Intent intentA = new Intent(this, AView.class); Now I am trying to access the tabSpec from main activity class[MainTabView] and set the intent as follows. MainTabView.tabSpec1.setContent(intentA); MainTabView.mTabHost.setCurrentTab(0); MainTabView.mTabHost.invalidate(); But this does not change the view immediately but changes it when I go to another tab and come to the starting tab. How can I make it to refresh it as soon as the content has been changed to another intent?

    Read the article

  • django-avatar: cant save thumbnail

    - by Znack
    I'm use django-avatar app and can't make it to save thumbnails. The original image save normally in my media dir. Using the step execution showed that error occurred here image.save(thumb, settings.AVATAR_THUMB_FORMAT, quality=quality) I found this line in create_thumbnail: def create_thumbnail(self, size, quality=None): # invalidate the cache of the thumbnail with the given size first invalidate_cache(self.user, size) try: orig = self.avatar.storage.open(self.avatar.name, 'rb') image = Image.open(orig) quality = quality or settings.AVATAR_THUMB_QUALITY w, h = image.size if w != size or h != size: if w > h: diff = int((w - h) / 2) image = image.crop((diff, 0, w - diff, h)) else: diff = int((h - w) / 2) image = image.crop((0, diff, w, h - diff)) if image.mode != "RGB": image = image.convert("RGB") image = image.resize((size, size), settings.AVATAR_RESIZE_METHOD) thumb = six.BytesIO() image.save(thumb, settings.AVATAR_THUMB_FORMAT, quality=quality) thumb_file = ContentFile(thumb.getvalue()) else: thumb_file = File(orig) thumb = self.avatar.storage.save(self.avatar_name(size), thumb_file) except IOError: return # What should we do here? Render a "sorry, didn't work" img? maybe all I need is just some library? Thanks

    Read the article

  • Audio File continues to play even on leaving the view

    - by Swastik
    What I am doing is -(void)viewWillAppear:(BOOL)animated{ [NSTimer scheduledTimerWithTimeInterval:0.3 target:self selector:@selector(clickEvent:) userInfo:nil repeats:YES]; } -(void)clickEvent:(NSTimer *)aTimer{ NSDate* finishDate = [NSDate date]; if([finishDate timeIntervalSinceDate: self.startDate] 11 && touched == NO){ NSString *mp3Path = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"test.mp3"]; [self playMusicFile:mp3Path]; NSLog(@"Timer from First Page"); [aTimer invalidate]; //[touchCheckTimer release]; aTimer = nil; } else{ } -(void)playMusicFile:(NSString *)mp3Path{ NSURL *mp3Url = [NSURL fileURLWithPath:mp3Path]; NSError *err; AVAudioPlayer *audPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:mp3Url error:&err]; [self setAudioPlayer1:audPlayer]; if(audioPlayer1) [audioPlayer1 play]; [audPlayer release]; } Now, on pushing another view this audio file keeps playing in the background. Please help!

    Read the article

  • Problem using GDI+ with multiple threads (VB.NET)

    - by Joe B
    I think it would be best if I just copy and pasted the code (it's very trivial). Private Sub Main() Handles MyBase.Shown timer.Interval = 10 timer.Enabled = True End Sub Private Sub Form1_Paint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint e.Graphics.DrawImage(image, 0, 0) End Sub Private Sub tick() Handles timer.Elapsed Using g = Graphics.FromImage(image) g.Clear(Color.Transparent) g.DrawLine(Pens.Red, 0 + i, 0 + i, Me.Width - i, Me.Height - i) End Using Me.Invalidate() End Sub An exception, "The object is currently in use elsewhere", is raised during the tick event. Could someone tell me why this happens and how to solve it? Thanks.

    Read the article

  • Fusion Table Layer Caching issue

    - by user1854791
    I have created a series of fusion table layers and apply filtering to one of the layers in response to checkbox click events. The base layer of the map contains a gradient applied over county boundaries. When the base layer is unchecked, the filtered layer loses it's styling. I have added unique timestamps to all queries to avoid caching, however I get the feeling that these image tiles are still be cached for this situation. Is there any way to force the google fusion tables api to invalidate a cached image? Test site here: http://map.inquestmarketing.com/new.html Unchecking the Other - Consumer Prospects checkbox reproduces the issue. This is a pure client app, all of the source is in the single page.

    Read the article

  • how to get the properties of a bitmap?

    - by BlueMonster
    How would i grab a bitmap's copyright date? I've been googling around for some pointers in the right direction, can't seem to find much though. Any ideas? private void toolStripMenuItemLoadImage_Click(object sender, EventArgs e) { using (OpenFileDialog ofd = new OpenFileDialog()) { ofd.Title = "Load Image"; if (ofd.ShowDialog() == DialogResult.OK) { firstLoaded = new Bitmap(ofd.FileName); String details = //Grab the copyright date of the image here; this.Invalidate(); } } isLoaded = true; }

    Read the article

  • UI updates not happening in the expected order

    - by allonym
    I have a Panel which hosts a number of child controls in a grid layout. The child controls each consist of a Panel with a PictureBox and a Label. When one of these child controls is clicked it becomes "selected" (which basically entails changing its background to a different color) and an event is fired. In the handler for this event, an image is displayed in a PictureBox on a separate form. In code, the background of the child control is definitely changed before firing the event, but for some reason it never updates at runtime until after the image has updated in the other Form. I've tried to Invalidate() and Refresh() the child control before firing the event, without effect. Why is this happening, and what can I do to set it right?

    Read the article

  • C# method contents validation

    - by user258651
    I need to validate the contents of a C# method. I do not care about syntax errors that do not affect the method's scope. I do care about characters that will invalidate parsing of the rest of the code. For example: method() { /* valid comment */ /* <-- bad for (i..) { } for (i..) { <-- bad } I need to validate/fix any non-paired characters. This includeds /* */, { }, and maybe others. How should I go about this? My first thought was Regex, but that clearly isn't going to get the job done.

    Read the article

  • Working with EO composition associations via ADF BC SDO web services

    - by Chris Muir
    ADF Business Components support the ability to publish the underlying Application Modules (AMs) and View Objects (VOs) as web services through Service Data Objects (SDOs).  This blog post looks at a minor challenge to overcome when using SDOs and Entity Objects (EOs) that use a composition association. Using the default ADF BC EO association behaviour ADF BC components allow you to work with VOs that are based on EOs that are a part of a parent-child composition association.  A composition association enforces that you cannot create records for the child outside the context of the parent.  As example when creating invoice-lines you want to enforce the individual lines have a relating parent invoice record, it just simply doesn't make sense to save invoice-lines without their parent invoice record. In the following screenshot using the ADF BC Tester it demonstrates the correct way to create a child Employees record as part of a composition association with Departments: And the following screenshot shows you the wrong way to create an Employee record: Note the error which is enforced by the composition association: (oracle.jbo.InvalidOwnerException) JBO-25030: Detail entity Employees with row key null cannot find or invalidate its owning entity.  Working with composition associations via the SDO web services  Shay Shmeltzer recently recorded a good video which demonstrates how to expose your ADF Business Components through the SDO interface. On exposing the VOs you get a choice of operation to publish including create, update, delete and more: For example through the SDO test interface we can see that the create operation will request the attributes for the VO exposed, in this case EmployeesView1: In this specific case though, just like the ADF BC Tester, an attempt to create this record will fail with JBO-25030, the composition association is still enforced: The correct way to to do this is through the create operation on the DepartmentsView1 which also lets you create employees record in context of the parent, thus satisfying the composition association rule: Yet at issue here is the create operation will always create both the parent Departments and Employees records.  What do we do if we've already previously created the parent Departments records, and we just want to create additional Employees records for that Department?  The create method of the EmployeeView1 as we saw previously doesn't allow us to do that, the JBO-3050 error will be raised. The solution is the "merge" operation on the parent Departments record: In this case for the Departments record you just need to supply the DepartmentId of the Department you want the Employees record to be associated with, as well as the new Employees record.  When invoked only the Employees record is created, and the supply of the DepartmentId of the Departments record satisfies the composition association without actually creating or updating the associated Department record that already exists in the database. Be warned however if you supply any more attributes for the Department record, it will result in a merge (update) of the associated Departments record too. 

    Read the article

  • A Simple Entity Tagger

    - by Elton Stoneman
    In the REST world, ETags are your gateway to performance boosts by letting clients cache responses. In the non-REST world, you may also want to add an ETag to an entity definition inside a traditional service contract – think of a scenario where a consumer persists its own representation of your entity, and wants to keep it in sync. Rather than load every entity by ID and check for changes, the consumer can send in a set of linked IDs and ETags, and you can return only the entities where the current ETag is different from the consumer’s version.  If your entity is a projection from various sources, you may not have a persistent ETag, so you need an efficient way to generate an ETag which is deterministic, so an entity with the same state always generates the same ETag. I have an implementation for a generic ETag generator on GitHub here: EntityTagger code sample. The essence is simple - we get the entity, serialize it and build a hash from the serialized value. Any changes to either the state or the structure of the entity will result in a different hash. To use it, just call SetETag, passing your populated object and a Func<> which acts as an accessor to the ETag property: EntityTagger.SetETag(user, x => x.ETag); The implementation is all in at 80 lines of code, which is all pretty straightforward: var eTagProperty = AsPropertyInfo(eTagPropertyAccessor); var originalETag = eTagProperty.GetValue(entity, null); try { ResetETag(entity, eTagPropertyAccessor); string json; var serializer = new DataContractJsonSerializer(entity.GetType()); using (var stream = new MemoryStream()) { serializer.WriteObject(stream, entity); json = Encoding.UTF8.GetString(stream.GetBuffer(), 0, (int)stream.Length); } var guid = GetDeterministicGuid(json); eTagProperty.SetValue(entity, guid.ToString(), null); //... There are a couple of helper methods to check if the object has changed since the ETag value was last set, and to reset the ETag. This implementation uses JSON to do the serializing rather than XML. Benefit - should be marginally more efficient as your hashing a much smaller serialized string; downside, JSON doesn't include namespaces or class names at the root level, so if you have two classes with the exact same structure but different names, then instances which have the same content will have the same ETag. You may want that behaviour, but change to use the XML DataContractSerializer if you think that will be an issue. If you can persist the ETag somewhere, it will save you server processing to load up the entity, but that will only apply to scenarios where you can reliably invalidate your ETag (e.g. if you control all the entry points where entity contents can be updated, then you can calculate and persist the new ETag with each update).

    Read the article

  • What's the best way to cache a growing database table for html generation?

    - by McLeopold
    I've got a database table which will grow in size by about 5000 rows a hour. For a key that I would be querying by, the query will grow in size by about 1 row every hour. I would like a web page to show the latest rows for a key, 50 at a time (this is configurable). I would like to try and implement memcache to keep database activity low for reads. If I run a query and create a cache result for each page of 50 results, that would work until a new entry is added. At that time, the page of latest results gets new result and the oldest results drops off. This cascades down the list of cached pages causing me to update every cache result. It seems like a poor design. I could build the cache pages backwards, then for each page requested I should get the latest 2 pages and truncate to the proper length of 50. I'm not sure if this is good or bad? Ideally, the mechanism I use to insert a new row would also know how to invalidate the proper cache results. Has someone already solved this problem in a widely acceptable way? What's the best method of doing this? EDIT: If my understanding of the MYSQL query cache is correct, it has table level granularity in invalidation. Given the fact that I have about 5000 updates before a query on a key should need to be invalidated, it seems that the database query cache would not be used. MS SQL caches execution plans and frequently accessed data pages, so it may do better in this scenario. My query is not against a single table with TOP N. One version has joins to several tables and another has sub-selects. Also, since I want to cache the html generated table, I'm wondering if a cache at the web server level would be appropriate? Is there really no benefit to any type of caching? Is the best advice really to just allow a website site query to go through all the layers and hit the database every request?

    Read the article

  • Setting Up Apache as a Forward Proxy with Cahcing

    - by Karl
    I am trying to set up Apache as a forward proxy with caching, but it does not seem to be working correctly. Getting Apache working as a forward proxy was no problem, but no matter what I do it is not caching anything, to disk or memory. I already checked to make sure nothing is conflicting in the mods_enabled directory with mod_cache (ended up commenting it all out) and also I tried moving all of the caching related fields to the configuration file for mod_cache. In addition I set up logging for caching requests, but nothing is being written to those logs. Below is my Apache config, any help would be greatly appreciated!! <VIRTUALHOST *:8080> ProxyRequests On ProxyVia On #ErrorLog "/var/log/apache2/proxy-error.log" #CustomLog "/var/log/apache2/proxy-access.log" common CustomLog "/var/log/apache2/cached-requests.log" common env=cache-hit CustomLog "/var/log/apache2/uncached-requests.log" common env=cache-miss CustomLog "/var/log/apache2/revalidated-requests.log" common env=cache-revalidate CustomLog "/var/log/apache2/invalidated-requests.log" common env=cache-invalidate LogFormat "%{cache-status}e ..." # This path must be the same as the one in /etc/default/apache2 CacheRoot /var/cache/apache2/mod_disk_cache # This will also cache local documents. It usually makes more sense to # put this into the configuration for just one virtual host. CacheEnable disk / #CacheHeader on CacheDirLevels 3 CacheDirLength 5 ##<IfModule mod_mem_cache.c> # CacheEnable mem / # MCacheSize 4096 # MCacheMaxObjectCount 100 # MCacheMinObjectSize 1 # MCacheMaxObjectSize 2048 #</IfModule> <Proxy *> Order deny,allow Deny from all Allow from x.x.x.x #IP above hidden for this post <filesMatch "\.(xml|txt|html|js|css)$"> ExpiresDefault A7200 Header append Cache-Control "proxy-revalidate" </filesMatch> </Proxy> </VIRTUALHOST> Thank you once again!

    Read the article

  • How do I log back into a Windows Server 2003 guest OS after Hyper-V integration services installs and breaks my domain logins?

    - by Warren P
    After installing Hyper-V integration services, I appear to have a problem with logging in to my Windows Server 2003 virtual machine. Incorrect passwords and logins give the usual error message, but a correct login/password gives me this message: Windows cannot connect to the domain, either because the domain controller is down or otherwise unavailable, or because your computer account was not found. Please try again later. If this message continues to appear, contact your system administrator for assistance. Nothing pleases me more than Microsoft telling me (the ersatz system administrator) to contact my system administrator for help, when I suspect that I'm hooped. The virtual machine has a valid network connection, and has decided to invalidate all my previous logins on this account, so I can't log in and remotely fix anything, and I can't remotely connect to it from outside either. This appears to be a catch 22. Unfortunately I don't know any non-domain local logins for this virtual machine, so I suspect I am basically hooped, or that I need ophcrack. is there any alternative to ophcrack? Second and related question; I used Disk2VHD to do the conversion, and I could log in fine several times, until after the Hyper-V integration services were installed, then suddenly this happens and I can't log in now - was there something I did wrong? I can't get networking working inside the VM BEFORE I install integration services, and at the very moment that integration services is being installed, I'm getting locked out like this. I probably should always know the local login of any machine I'm upgrading so I don't get stuck like this in the future.... great. Now I am reminded again of this.

    Read the article

  • Why does lighttpd keep static files in cache, even when modified on disk ?

    - by Pixelastic
    I am using lighttpd to serve static files. I have a bunch of images in a dir that I regularly update. This will change the file content (and filesize) as well as the modification date, but not their filename. When I access the files through http, the updates are not taken into account and lighty serves the old file. I can manually rename the file to something different, then lighttpd will return a 404 error, and if I rename my file back, I will get the correct updated version. Seems like lightty is using some kind of cache mechanism of its own (which is fine) to return static files. Unfortunatly, it seems that this mechanism doesn't update itself when files are modified. I checked through Wireshark, and my browser is really doing a request to the file, this is not a browser caching issue. It returns a 200 OK when requesting it from an empty cache, and a 304 Not Modified otherwise, as expected. But the file is returned with a wrong Last-Modified header that do not reflect the real last modification date. Maybe there is some config directive that I am not aware of ? I would like the files returned by lighty to reflect the changes made on disk directly, or at least being able to invalidate its cache.

    Read the article

  • How do I prevent lighttpd from caching static files, even when modified on disk?

    - by Pixelastic
    I am using lighttpd to serve static files. I have a bunch of images in a dir that I regularly update. This will change the file content (and filesize) as well as the modification date, but not their filename. When I access the files through http, the updates are not taken into account and lighty serves the old file. I can manually rename the file to something different, then lighttpd will return a 404 error, and if I rename my file back, I will get the correct updated version. Seems like lightty is using some kind of cache mechanism of its own (which is fine) to return static files. Unfortunatly, it seems that this mechanism doesn't update itself when files are modified. I checked through Wireshark, and my browser is really doing a request to the file, this is not a browser caching issue. It returns a 200 OK when requesting it from an empty cache, and a 304 Not Modified otherwise, as expected. But the file is returned with a wrong Last-Modified header that do not reflect the real last modification date. Maybe there is some config directive that I am not aware of ? I would like the files returned by lighty to reflect the changes made on disk directly, or at least being able to invalidate its cache.

    Read the article

  • Collision problems with drag-n-drop puzzle game.

    - by Amplify91
    I am working on an Android game similar to the Rush Hour/Traffic Jam/Blocked puzzle games. The board is a square containing rectangular pieces. Long pieces may only move horizontally, and tall pieces may only move vertically. The object is to free the red piece and move it out of the board. This game is only my second ever programming project in any language, so any tips or best practices would be appreciated along with your answer. I have a class for the game pieces called Pieces that describes how they are sized and drawn to the screen, gives them drag-and-drop functionality, and detects and handles collisions. I then have an activity class called GameView which creates my layout and creates Pieces objects to add to a RelativeLayout called Board. I have considered making Board its own class, but haven't needed to yet. Here's what my work in progress looks like: My Question: Most of this works perfectly fine except for my collision handling. It seems to be detecting collisions well but instead of pushing the pieces outside of each other when there is a collision, it frantically snaps back and forth between (what seems to be) where the piece is being dragged to and where it should be. It looks something like this: Another oddity: when the dragged piece collides with a piece to its left, the collision handling seems to work perfectly. Only piece above, below, and to the right cause problems. Here's the collision code: @Override public boolean onTouchEvent(MotionEvent event){ float eventX = event.getX(); float eventY = event.getY(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: //check if touch is on piece if (eventX > x && eventX < (x+width) && eventY > y && eventY < (y+height)){ initialX=x; initialY=y; break; }else{ return false; } case MotionEvent.ACTION_MOVE: //determine if piece should move horizontally or vertically if(width>height){ for (Pieces piece : aPieces) { //if object equals itself in array, skip to next object if(piece==this){ continue; } //if next to another piece, //do not allow to move any further towards said piece if(eventX<x&&(x==piece.right+1)){ return false; }else if(eventX>x&&(x==piece.x-width-1)){ return false; } //move normally if no collision //if collision, do not allow to move through other piece if(collides(this,piece)==false){ x = (eventX-(width/2)); }else if(collidesLeft(this,piece)){ x = piece.right+1; break; }else if(collidesRight(this,piece)){ x = piece.x-width-1; break; } } break; }else if(height>width){ for (Pieces piece : aPieces) { if(piece==this){ continue; }else if(collides(this,piece)==false){ y = (eventY-(height/2)); }else if(collidesUp(this,piece)){ y = piece.bottom+1; break; }else if(collidesDown(this,piece)){ y = piece.y-height-1; break; } } } invalidate(); break; case MotionEvent.ACTION_UP: // end move if(this.moves()){ GameView.counter++; } initialX=x; initialY=y; break; } // parse puzzle invalidate(); return true; } This takes place during onDraw: width = sizedBitmap.getWidth(); height = sizedBitmap.getHeight(); right = x+width; bottom = y+height; My collision-test methods look like this with different math for each: private boolean collidesDown(Pieces piece1, Pieces piece2){ float x1 = piece1.x; float y1 = piece1.y; float r1 = piece1.right; float b1 = piece1.bottom; float x2 = piece2.x; float y2 = piece2.y; float r2 = piece2.right; float b2 = piece2.bottom; if((y1<y2)&&(y1<b2)&&(b1>=y2)&&(b1<b2)&&((x1>=x2&&x1<=r2)||(r1>=x2&&x1<=r2))){ return true; }else{ return false; } } private boolean collides(Pieces piece1, Pieces piece2){ if(collidesLeft(piece1,piece2)){ return true; }else if(collidesRight(piece1,piece2)){ return true; }else if(collidesUp(piece1,piece2)){ return true; }else if(collidesDown(piece1,piece2)){ return true; }else{ return false; } } As a second question, should my x,y,right,bottom,width,height variables be ints instead of floats like they are now? Also, any suggestions on how to implement things better would be greatly appreciated, even if not relevant to the question! Thanks in advance for the help and for sitting through such a long question! Update: I have gotten it working almost perfectly with the following code (this doesn't include the code for vertical pieces): @Override public boolean onTouchEvent(MotionEvent event){ float eventX = event.getX(); float eventY = event.getY(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: //check if touch is on piece if (eventX > x && eventX < (x+width) && eventY > y && eventY < (y+height)){ initialX=x; initialY=y; break; }else{ return false; } case MotionEvent.ACTION_MOVE: //determine if piece should move horizontally or vertically if(width>height){ for (Pieces piece : aPieces) { //if object equals itself in array, skip to next object if(piece==this){ continue; } //check if there the possibility for a horizontal collision if(this.isAllignedHorizontallyWith(piece)){ //check for and handle collisions while moving left if(this.isRightOf(piece)){ if(eventX>piece.right+(width/2)){ x = (int)(eventX-(width/2)); //move normally }else{ x = piece.right+1; } } //check for and handle collisions while moving right if(this.isLeftOf(piece)){ if(eventX<piece.x-(width/2)){ x = (int)(eventX-(width/2)); }else{ x = piece.x-width-1; } } break; }else{ x = (int)(eventX-(width/2)); } The only problem with this code is that it only detects collisions between the moving piece and one other (with preference to one on the left). If there is a piece to collide with on the left and another on the right, it will only detect collisions with the one on the left. I think this is because once it finds a possible collision, it handles it without finishing looping through the array holding all the pieces. How do I get it to check for multiple possible collisions at the same time?

    Read the article

  • [Silverlight] How to watermark a WriteableBitmap with a text

    - by Benjamin Roux
    Hello, In my current project, I needed to watermark a WriteableBitmap with a text. As I couldn’t find anything I decided to create a small extension method to do so. public static class WriteableBitmapEx { /// <summary> /// Creates a watermark on the specified image /// </summary> /// <param name="input">The image to create the watermark from</param> /// <param name="watermark">The text to watermark</param> /// <param name="color">The color - default is White</param> /// <param name="fontSize">The font size - default is 50</param> /// <param name="opacity">The opacity - default is 0.25</param> /// <param name="hasDropShadow">Specifies if a drop shadow effect must be added - default is true</param> /// <returns>The watermarked image</returns> public static WriteableBitmap Watermark(this WriteableBitmap input, string watermark, Color color = default(Color), double fontSize = 50, double opacity = 0.25, bool hasDropShadow = true) { var watermarked = GetTextBitmap(watermark, fontSize, color == default(Color) ? Colors.White : color, opacity, hasDropShadow); var width = watermarked.PixelWidth; var height = watermarked.PixelHeight; var result = input.Clone(); var position = new Rect(input.PixelWidth - width - 20 /* right margin */, input.PixelHeight - height, width, height); result.Blit(position, watermarked, new Rect(0, 0, width, height)); return result; } /// <summary> /// Creates a WriteableBitmap from a text /// </summary> /// <param name="text"></param> /// <param name="fontSize"></param> /// <param name="color"></param> /// <param name="opacity"></param> /// <param name="hasDropShadow"></param> /// <returns></returns> private static WriteableBitmap GetTextBitmap(string text, double fontSize, Color color, double opacity, bool hasDropShadow) { TextBlock txt = new TextBlock(); txt.Text = text; txt.FontSize = fontSize; txt.Foreground = new SolidColorBrush(color); txt.Opacity = opacity; if (hasDropShadow) txt.Effect = new DropShadowEffect(); WriteableBitmap bitmap = new WriteableBitmap((int)txt.ActualWidth, (int)txt.ActualHeight); bitmap.Render(txt, null); bitmap.Invalidate(); return bitmap; } } For this code to run, you need the WritableBitmapEx library. As you can see, it’s quite simple. You just need to call the Watermark method and pass it the text you want to add in your image. You can also pass optional parameters like the color, the opacity, the fontsize or if you want a drop shadow effect. I could have specify other parameters like the position or the the font family but you can change the code if you need to. Here’s what it can give Hope this helps.

    Read the article

  • OpenXML SDK: Make Excel recalculate formula

    - by chiccodoro
    I update some cells of an Excel spreadsheet through the Microsoft Office OpenXML SDK 2.0. Changing the values makes all cells containing formula that depend on the changed cells invalid. However, due to the cached values Excel does not recalculate the formular, even if the user clicks on "Calculate now". What is the best way to invalidate all dependent cells of the whole workbook through the SDK? So far, I've found the following code snippet at http://cdonner.com/introduction-to-microsofts-open-xml-format-sdk-20-with-a-focus-on-excel-documents.htm: public static void ClearAllValuesInSheet (SpreadsheetDocument spreadSheet, string sheetName) { WorksheetPart worksheetPart = GetWorksheetPartByName(spreadSheet, sheetName); foreach (Row row in worksheetPart.Worksheet. GetFirstChild().Elements()) { foreach (Cell cell in row.Elements()) { if (cell.CellFormula != null && cell.CellValue != null) { cell.CellValue.Remove(); } } } worksheetPart.Worksheet.Save(); } Besides the fact that this snippet does not compile for me, it has two limitations: It only invalidates a single sheet, although other sheets might contain dependent formula It does not take into account any dependencies. I am looking for a way that is efficient (in particular, only invalidates cells that depend on a certain cell's value), and takes all sheets into account. Update: In the meantime I have managed to make the code compile & run, and to remove the cached values on all sheets of the workbook. (See answers.) Still I am interested in better/alternative solutions, in particular how to only delete cached values of the cells that actually depend on the updated cell.

    Read the article

  • Help: Android paint/canvas issue; drawing smooth curves

    - by Wrapper
    How do I get smooth curves instead of dots or circles, when I draw with my finger on the touch screen, in Android? I am using the following code- public class DrawView extends View implements OnTouchListener { private static final String TAG = "DrawView"; List<Point> points = new ArrayList<Point>(); Paint paint = new Paint(); public DrawView(Context context) { super(context); setFocusable(true); setFocusableInTouchMode(true); this.setOnTouchListener(this); paint.setColor(Color.WHITE); paint.setAntiAlias(true); } @Override public void onDraw(Canvas canvas) { for (Point point : points) { canvas.drawCircle(point.x, point.y, 5, paint); // Log.d(TAG, "Painting: "+point); } } public boolean onTouch(View view, MotionEvent event) { // if(event.getAction() != MotionEvent.ACTION_DOWN) // return super.onTouchEvent(event); Point point = new Point(); point.x = event.getX(); point.y = event.getY(); points.add(point); invalidate(); Log.d(TAG, "point: " + point); return true; } } class Point { float x, y; @Override public String toString() { return x + ", " + y; } }

    Read the article

  • How can I validate the result in an ASP.NET MVC editor template?

    - by Morten Christiansen
    I have created an editor template for representing selecting from a dynamic dropdown list and it works as it should except for validation, which I have been unable to figure out. If the model has the [Required] attribute set, I want that to invalidate if the default option is selected. The view model object that must be represented as the dropdown list is Selector: public class Selector { public int SelectedId { get; set; } public IEnumerable<Pair<int, string>> Choices { get; private set; } public string DefaultValue { get; set; } public Selector() { //For binding the object on Post } public Selector(IEnumerable<Pair<int, string>> choices, string defaultValue) { DefaultValue = defaultValue; Choices = choices; } } The editor template looks like this: <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %> <select class="template-selector" id="<%= ViewData.ModelMetadata.PropertyName %>.SelectedId" name="<%= ViewData.ModelMetadata.PropertyName %>.SelectedId"> <% var model = ViewData.ModelMetadata.Model as QASW.Web.Mvc.Selector; if (model != null) { %> <option><%= model.DefaultValue %></option><% foreach (var choice in model.Choices) { %> <option value="<%= choice.Value1 %>"><%= choice.Value2 %></option><% } } %> </select> I sort of got it to work by calling it from the view like this (where Category is a Selector): <%= Html.ValidationMessageFor(n => n.Category.SelectedId)%> But it shows the validation error for not supplying a proper number and it does not care if I set the Required attribute.

    Read the article

< Previous Page | 4 5 6 7 8 9 10 11 12 13  | Next Page >