Search Results

Search found 2328 results on 94 pages for 'callback'.

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

  • How to make Dajax callback into scoped object

    - by BozoJoe
    I cant seem to find a way to make django-dajaxice have its callback inside same scoped object from which made the initial call. MyViewport = Ext.extend(MyViewportUi, { initComponent: function() { MyViewport.superclass.initComponent.call(this); }, LoadRecordsCallback: function(data){ if(data!='DAJAXICE_EXCEPTION') { alert(data); } else { alert('DAJAXICE_EXCEPTION'); } }, LoadRecords: function(){ Dajaxice.Console.GetUserRecords(this.LoadRecordsCallback); } }); var blah = new MyViewport(); blah.LoadRecords(); I'm on django, and like the calling syntax to django-dajaxice. I'm using Extjs 3.2 and tried passing a Ext.createCallback but Dajax's returning eval seems to only want a string for the callback.

    Read the article

  • Android Camera takePicture function does not call Callback function

    - by Tomáš 'Guns Blazing' Frcek
    I am working on a custom Camera activity for my application. I was following the instruction from the Android Developers site here: http://developer.android.com/guide/topics/media/camera.html Everything seems to works fine, except the Callback function is not called and the picture is not saved. Here is my code: public class CameraActivity extends Activity { private Camera mCamera; private CameraPreview mPreview; private static final String TAG = "CameraActivity"; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.camera); // Create an instance of Camera mCamera = getCameraInstance(); // Create our Preview view and set it as the content of our activity. mPreview = new CameraPreview(this, mCamera); FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview); preview.addView(mPreview); Button captureButton = (Button) findViewById(R.id.button_capture); captureButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Log.v(TAG, "will now take picture"); mCamera.takePicture(null, null, mPicture); Log.v(TAG, "will now release camera"); mCamera.release(); Log.v(TAG, "will now call finish()"); finish(); } }); } private PictureCallback mPicture = new PictureCallback() { @Override public void onPictureTaken(byte[] data, Camera camera) { Log.v(TAG, "Getting output media file"); File pictureFile = getOutputMediaFile(); if (pictureFile == null) { Log.v(TAG, "Error creating output file"); return; } try { FileOutputStream fos = new FileOutputStream(pictureFile); fos.write(data); fos.close(); } catch (FileNotFoundException e) { Log.v(TAG, e.getMessage()); } catch (IOException e) { Log.v(TAG, e.getMessage()); } } }; private static File getOutputMediaFile() { String state = Environment.getExternalStorageState(); if (!state.equals(Environment.MEDIA_MOUNTED)) { return null; } else { File folder_gui = new File(Environment.getExternalStorageDirectory() + File.separator + "GUI"); if (!folder_gui.exists()) { Log.v(TAG, "Creating folder: " + folder_gui.getAbsolutePath()); folder_gui.mkdirs(); } File outFile = new File(folder_gui, "temp.jpg"); Log.v(TAG, "Returnng file: " + outFile.getAbsolutePath()); return outFile; } } After clicking the Button, I get logs: "will now take picture", "will now release camera" and "will now call finish". The activity finishes succesfully, but the Callback function was not called during the mCamera.takePicture(null, null, mPicture); function (There were no logs from the mPicture callback or getMediaOutputFile functions) and there is no file in the location that was specified. Any ideas? :) Much thanks!

    Read the article

  • C#: How to force "calling" a method from the main thread by signaling in some way from another thread

    - by Fire-Dragon-DoL
    Sorry for long title, I don't know even the way on how to express the question I'm using a library which run a callback from a different context from the main thread (is a C Library), I created the callback in C# and when gets called I would like to just raise an event. However because I don't know what will be inside the event, I would like to find a way to invoke the method without the problem of locks and so on (otherwise the third party user will have to handle this inside the event, very ugly) Are there any way to do this? I can be totally on the wrong way but I'm thinking about winforms way to handle different threads (the .Invoke thing) Otherwise I can send a message to the message loop of the window, but I don't know a lot about message passing and if I can send "custom" messages like this Example: private uint lgLcdOnConfigureCB(int connection, System.IntPtr pContext) { OnConfigure(EventArgs.Empty); return 0U; } this callback is called from another program which I don't have control over, I would like to run OnConfigure method in the main thread (the one that handles my winform), how to do it? Or in other words, I would like to run OnConfigure without the need of thinking about locks

    Read the article

  • SystemStackError in Rails::ActiveSupport::Callbacks

    - by coreyward
    I'm building a Rails app that connects to Dropbox and syncs with a folder to update a personal site. I'm using Rails 3.0.3, Ruby 1.9.2, and the Dropbox gem. Right now I have a DropboxAccounts Controller, and two models: DropboxSession, which wraps calls to the gem with application-specific functionality, and DropboxAccount, which stores the session and settings in the database. After the user authorizes their account with Dropbox they're redirected back over and the DropboxAccount is saved with the authorized session. That all works just fine. My problem is that when I try to call Dropbox::API#create_folder(any path) I end up with a SystemStackError in lib/activesupport/callbacks.rb:421 which refers to the code below. If I remove the call to create the folder, it works. If I call create folder from another request, it works. I doubled the stack size to 16K to no avail. # This is called the first time a callback is called with a particular # key. It creates a new callback method for the key, calculating # which callbacks can be omitted because of per_key conditions. # def __create_keyed_callback(name, kind, object, &blk) #:nodoc: @_keyed_callbacks ||= {} @_keyed_callbacks[name] ||= begin str = send("_#{kind}_callbacks").compile(name, object) class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1 def #{name}() #{str} end # THIS IS LINE 421 protected :#{name} RUBY_EVAL true end end I'm not very familiar with Rails yet, and I'm not sure what the intention of the code above is or why it would cause a stack overflow. I'm not using any method_missing/ghost method magic in my code. I suspected it was something with a callback serialize :files but commenting it out did nothing. My DropboxAccount model contains only a call to belongs_to :user, and DropboxSession is just a handful of methods, none of which contain callbacks. Bypassing them and using the Dropbox::Session methods directly doesn't help. I hope someone on StackOverflow can help me with this stack overflow. ;)

    Read the article

  • FMOD.net streaming, callback and exinfo parameters

    - by Tesserex
    I posted a question on gamedev about how to play nsf files (NES console music) in FMOD. It didn't get any results, but since then I made some progress. I decided that the easiest method was just to compile an existing player into a dll and then call it from C# to populate my buffer. The problem now is getting it to sound right, and making sure all my paremeters are correct. Here are the facts so far: The nsf dll is dealing with shorts, so the data is PCM16. The sample nsf I'm using has a playback rate of 60 Hz. Just for playing around now, I'm using a frequency of 48000. Based on 2 and 3, the dll calculates a necessary buffer size of 48000 / 60hz = 800. This means it will render 800 shorts worth of buffer for every simulated NES frame. I've so far got my C# code to play the nsf, at the correct pitch and tempo, but it's very grainy / fuzzy, which I'm attributing to the fact that the FMOD read callback is giving a data length of 1600, whereas I should be expecting 800. I've tried playing around with all the numbers and it either crashes, or the music changes pitch, tempo, or both. Here's some of my C# code: uint channels = 1, frequency = 48000; FMOD.MODE mode = (FMOD.MODE.DEFAULT | FMOD.MODE.OPENUSER | FMOD.MODE.LOOP_NORMAL); FMOD.Sound sound = new FMOD.Sound(); FMOD.CREATESOUNDEXINFO ex = new FMOD.CREATESOUNDEXINFO(); ex.cbsize = Marshal.SizeOf(ex); ex.fileoffset = 0; ex.format = FMOD.SOUND_FORMAT.PCM16; // does this even matter? It doesn't change my results as long as it's long enough for one update ex.length = frequency; ex.numchannels = (int)channels; ex.defaultfrequency = (int)frequency; ex.pcmreadcallback = pcmreadcallback; ex.dlsname = null; // eventually I will calculate this with frequency / nsf hz, but I'm just testing for now ex.decodebuffersize = 800; // from the dll load_nsf_file("file.nsf", 8, (int)frequency); // 8 is the track number to play var result = system.createSound( (string)null, (mode | FMOD.MODE.CREATESTREAM), ref ex, ref sound); channel = new FMOD.Channel(); result = system.playSound(FMOD.CHANNELINDEX.FREE, sound, false, ref channel); private FMOD.RESULT PCMREADCALLBACK(IntPtr soundraw, IntPtr data, uint datalen) { // from the dll process_buffer(data, (int)800); // if I use datalen, it usually crashes (I can't get datalen to = 800 safely) return FMOD.RESULT.OK; } So here are some of my questions: What is the relationship between exinfo.decodebuffersize, frequency, and the datalen parameter of the read callback? With this code sample, it's coming in as 3200. I don't know where that factor of 4 between it and the decodebuffersize comes from. Is datalen in the callback referring to number of bytes, or shorts? The process_buffer function takes a short array and its length. I would expect fmod is talking about shorts as well because I told it PCM16. Maybe my playback quality is bad for some totally different reason. If so I have no idea where to begin solving that. Any ideas there?

    Read the article

  • Safely defining variables for public callback functions in javascript

    - by djreed
    I am working with the YouTube iFrame API to embed a number of videos on a page. Documentation here: https://developers.google.com/youtube/iframe_api_reference#Requirements In summary, you load the API asynchronously using the following snippet: var tag = document.createElement('script'); tag.src = "http://www.youtube.com/player_api"; var firstScriptTag = document.getElementsByTagName('script')[0]; firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); Once loaded, the API fires the predefined callback function onYouTubePlayerAPIReady. For additional context: I am defining a library file for this in Google Closure. I am providing a namespace: goog.provide('yt.video'); I then use goog.exportSymbol so that the API can find the function. That all works fine. My challenge is that I would like to pass 2 variables to the callback function. Is there any way to do this without defining these 2 variables in the context of the window object? goog.provide('yt.video'); goog.require('goog.dom'); yt.video = function(videos, locales) { this.videos = videos; this.captionLocales = locales; this.init(); }; yt.video.prototype.init = function() { var tag = document.createElement('script'); tag.src = "http://www.youtube.com/player_api"; var firstScriptTag = document.getElementsByTagName('script')[0]; firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); }; /* * Callback function fired when YT API is ready * This is exported using goog.exportSymbol in another file and * is being fired by the API properly. */ yt.video.prototype.onPlayerReady = function(videos, locales) { window.console.log('this :' + this); //logs window window.console.log('this.videos : ' + this.videos); //logs undefined /* * Video settings from Django variable */ for(i=0; i<this.videos.length; i++) { var playerEvents = {}; var embedVars = {}; var el = this.videos[i].el; var playerVid = this.videos[i].vid; var playerWidth = this.videos[i].width; var playerHeight = this.videos[i].height; var captionLocales = this.videos[i].locales; if(this.videos[i].playerVars) var embedVars = this.videos[i].playerVars; } if(this.videos[i].events) { var playerEvents = this.videos[i].events; } /* * Show captions by default */ if(goog.array.indexOf(captionLocales, 'es') >= 0) { embedVars.cc_load_policy = 1; }; new YT.Player(el, { height: playerHeight, width: playerWidth, videoId: playerVid, events: playerEvents, playerVars: embedVars }); }; }; To intialize this, I am currently using the following within a self-executing anonymous function: var videos = [ {"vid": "video_id", "el": "player-1", "width": 640, "height": 390, "locales": ["es", "fr"], "events": {"onStateChange": stateChanged}}, {"vid": "video_id", "el": "player-2", "locales": ["es", "fr"], "width": 640, "height": 390} ]; var locales = ['es']; var videoTemplate = new yt.video(videos, locales);

    Read the article

  • Settings variable values in a Moq Callback() call

    - by Adam Driscoll
    I think I may be a bit confused on the syntax of the Moq Callback methods. When I try to do something like this: IFilter filter = new Filter(); List<IFoo> objects = new List<IFoo> { new Foo(), new Foo() }; IQueryable myFilteredFoos = null; mockObject.Setup(m => m.GetByFilter(It.IsAny<IFilter>())).Callback( (IFilter filter) => myFilteredFoos = filter.FilterCollection(objects)).Returns(myFilteredFoos.Cast<IFooBar>()); This throws a exception because myFilteredFoos is null during the Cast<IFooBar>() call. Is this not working as I expect? I would think FilterCollection would be called and then myFilteredFoos would be non-null and allow for the cast. FilterCollection is not capable of returning a null which draws me to the conclusion it is not being called. Also, when I declare myFilteredFoos like this: Queryable myFilteredFoos; The Return call complains that myFilteredFoos may be used before it is initialized.

    Read the article

  • Can't Change The Content of a Ajax Control After CallBack

    - by Kubi
    public void RaiseCallbackEvent(String eventArgument) { // Processes a callback event on the server using the event // argument from the client. //Response.Write(eventArgument); printAlternativesFromAirport(eventArgument); } public void printAlternativesFromAirport(string airport) { List<TravelPlan> alternatives = fit.Code.TextDataHelper.GetAllTravelPlansFromCity(airport); AlternativesAcc.Panes.Clear(); AjaxControlToolkit.AccordionPane p = new AjaxControlToolkit.AccordionPane(); Label header = new Label(); header.Text = airport; Label content = new Label(); content.Text = airport; p.HeaderContainer.Controls.Add(header); p.ContentContainer.Controls.Add(content); AlternativesAcc.Panes.Add(p); ... Hi, printAlternativesFromAirport method should change an accordion panel after the callback but it doesn't. Is there anything that i could set to fix this problem ? There should be stg with the page lifecycle but i can't figure it out ! Thanks

    Read the article

  • wcf callback exception after updating to .net 4.0

    - by James
    I have a wcf service that uses callbacks with DualHttpBindings. The service pushes back a datatable of search results the client (for a long running search) as it finds them. This worked fine in .Net 3.5. Since I updated to .Net 4.0, it bombs out with a System.Runtime.FatalException that actually kills the IIS worker process. I have no idea how to even go about starting to fix this. Any recommendations appreciated. The info from the resulting event log is pasted below. An unhandled exception occurred and the process was terminated. Application ID: /LM/W3SVC/2/ROOT/CP Process ID: 5284 Exception: System.Runtime.FatalException Message: Object reference not set to an instance of an object. StackTrace: at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc& rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage31(MessageRpc& rpc) at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet) at System.ServiceModel.Dispatcher.ChannelHandler.DispatchAndReleasePump(RequestContext request, Boolean cleanThread, OperationContext currentOperationContext) at System.ServiceModel.Dispatcher.ChannelHandler.HandleRequest(RequestContext request, OperationContext currentOperationContext) at System.ServiceModel.Dispatcher.ChannelHandler.AsyncMessagePump(IAsyncResult result) at System.Runtime.Fx.AsyncThunk.UnhandledExceptionFrame(IAsyncResult result) at System.Runtime.AsyncResult.Complete(Boolean completedSynchronously) at System.Runtime.InputQueue1.AsyncQueueReader.Set(Item item) at System.Runtime.InputQueue1.Dispatch() at System.ServiceModel.Channels.ReliableDuplexSessionChannel.ProcessDuplexMessage(WsrmMessageInfo info) at System.ServiceModel.Channels.ReliableDuplexSessionChannel.HandleReceiveComplete(IAsyncResult result) at System.ServiceModel.Channels.ReliableDuplexSessionChannel.OnReceiveCompletedStatic(IAsyncResult result) at System.Runtime.Fx.AsyncThunk.UnhandledExceptionFrame(IAsyncResult result) at System.Runtime.AsyncResult.Complete(Boolean completedSynchronously) at System.ServiceModel.Channels.ReliableChannelBinder1.InputAsyncResult1.OnInputComplete(IAsyncResult result) at System.Runtime.Fx.AsyncThunk.UnhandledExceptionFrame(IAsyncResult result) at System.Runtime.AsyncResult.Complete(Boolean completedSynchronously) at System.Runtime.InputQueue1.AsyncQueueReader.Set(Item item) at System.Runtime.InputQueue1.Dispatch() at System.Runtime.IOThreadScheduler.ScheduledOverlapped.IOCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped) at System.Runtime.Fx.IOCompletionThunk.UnhandledExceptionFrame(UInt32 error, UInt32 bytesRead, NativeOverlapped* nativeOverlapped) at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP) InnerException: * System.NullReferenceException* Message: Object reference not set to an instance of an object. StackTrace: at System.Web.HttpApplication.ThreadContext.Enter(Boolean setImpersonationContext) at System.Web.HttpApplication.OnThreadEnterPrivate(Boolean setImpersonationContext) at System.Web.AspNetSynchronizationContext.CallCallbackPossiblyUnderLock(SendOrPostCallback callback, Object state) at System.Web.AspNetSynchronizationContext.CallCallback(SendOrPostCallback callback, Object state) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc& rpc)

    Read the article

  • Designing a fluid Javascript interface to hide callback asynchrony

    - by Anurag
    How would I design an API to hide the asynchronous nature of AJAX and HTTP requests, or basically delay it to provide a fluid interface. To show an example from Twitter's new Anywhere API: // get @ded's first 20 statuses, filter only the tweets that // mention photography, and render each into an HTML element T.User.find('ded').timeline().first(20).filter(filterer).each(function(status) { $('div#tweets').append('<p>' + status.text + '</p>'); }); function filterer(status) { return status.text.match(/photography/); } vs this (asynchronous nature of each call is clearly visible) T.User.find('ded', function(user) { user.timeline(function(statuses) { statuses.first(20).filter(filterer).each(function(status) { $('div#tweets').append('<p>' + status.text + '</p>'); }); }); }); It finds the user, gets their tweet timeline, filters only the first 20 tweets, applies a custom filter, and ultimately uses the callback function to process each tweet. I am guessing that a well designed API like this should work like a query builder (think ORMs) where each function call builds the query (HTTP URL in this case), until it hits a looping function such as each/map/etc., the HTTP call is made and the passed in function becomes the callback. An easy development route would be to make each AJAX call synchronous, but that's probably not the best solution. I am interested in figuring out a way to make it asynchronous, and still hide the asynchronous nature of AJAX.

    Read the article

  • Javascript callback not firing when AJAX operation complete

    - by MisterJames
    Given the following code on an ASP.NET MVC View: <% using (Ajax.BeginForm("AddCommunity", new AjaxOptions { UpdateTargetId = "community-list", OnSuccess = "BindCommunityHover" })) { %> Add Community: <input type="text" id="communityName" name="communityName" /> <input type="submit" value="Add" /> <% } %> And the following JavaScript method in the file: function BindCommunityHover() { $(".community-item-li").hover( function () { $(this).addClass("communityHover"); }, function () { $(this).removeClass("communityHover"); } ); }; Is there any reason why BindCommunityHover is not being called when the AJAX result comes back? The community-list div is properly updated (the action returns a partial view). I have also tried setting OnComplete (instead of OnSuccess) to no avail. The BindCommunityHover method is called in a $(function(){...}); block when the page first loads, and for all existing .community-item-li elements, it works. The partial result from my controller replaces all items in that div with more of the same class. The OnSuccess method is supposed to fire after the document is updated. Update: k...this gets weird. I added the following to the BindCommunityHover method: alert($(".community-item-li").size()); I'm getting 240 in the alert when the page loads and when the callback fires. So, the callback IS firing, jQuery is matching the elements but not applying the styles...

    Read the article

  • Authentication using cookie key with asynchronous callback

    - by greg
    I need to write authentication function with asynchronous callback from remote Auth API. Simple authentication with login is working well, but authorization with cookie key, does not work. It should checks if in cookies present key "lp_login", fetch API url like async and execute on_response function. The code almost works, but I see two problems. First, in on_response function I need to setup secure cookie for authorized user on every page. In code user_id returns correct ID, but line: self.set_secure_cookie("user", user_id) does't work. Why it can be? And second problem. During async fetch API url, user's page has loaded before on_response setup cookie with key "user" and the page will has an unauthorized section with link to login or sign on. It will be confusing for users. To solve it, I can stop loading page for user who trying to load first page of site. Is it possible to do and how? Maybe the problem has more correct way to solve it? class BaseHandler(tornado.web.RequestHandler): @tornado.web.asynchronous def get_current_user(self): user_id = self.get_secure_cookie("user") user_cookie = self.get_cookie("lp_login") if user_id: self.set_secure_cookie("user", user_id) return Author.objects.get(id=int(user_id)) elif user_cookie: url = urlparse("http://%s" % self.request.host) domain = url.netloc.split(":")[0] try: username, hashed_password = urllib.unquote(user_cookie).rsplit(',',1) except ValueError: # check against malicious clients return None else: url = "http://%s%s%s/%s/" % (domain, "/api/user/username/", username, hashed_password) http = tornado.httpclient.AsyncHTTPClient() http.fetch(url, callback=self.async_callback(self.on_response)) else: return None def on_response(self, response): answer = tornado.escape.json_decode(response.body) username = answer['username'] if answer["has_valid_credentials"]: author = Author.objects.get(email=answer["email"]) user_id = str(author.id) print user_id # It returns needed id self.set_secure_cookie("user", user_id) # but session can's setup

    Read the article

  • Twitter O-Auth Callback url

    - by jtymann
    I am having a problem with Twitter's oauth authentication and using a callback url. I am coding in php and using the sample code referenced by the twitter wiki, http://github.com/abraham/twitteroauth I got that code, and tried a simple test and it worked nicely. However I want to programatically specify the callback url, and the example did not support that. So I quickly modified the getRequestToken() method to take in a parameter and now it looks like this: function getRequestToken($params = array()) { $r = $this->oAuthRequest($this->requestTokenURL(), $params); $token = $this->oAuthParseResponse($r); $this->token = new OAuthConsumer($token['oauth_token'], $token['oauth_token_secret']); return $token; } and my call looks like this $tok = $to->getRequestToken(array('oauth_callback' => 'http://127.0.0.1/twitter_prompt/index.php')); This is the only change I made, and the redirect works like a charm, however I am getting an error when I then try and use my newly granted access to try and make a call. I get a "Could not authenticate you" error. Also the application never actually gets added to the users authorized connections. Now I read the specs and I thought all I had to do was specify the parameter when getting the request token. Could someone a little more seasoned in oauth and twitter possibly give me a hand? Thank You

    Read the article

  • Chrome extension sendRequest from async callback not working?

    - by Eugene
    Can't figure out what's wrong. onRequest not triggered on call from async callback method, the same request from content script works. The sample code below. background.js ============= ... makeAsyncRequest(); ... chrome.extension.onRequest.addListener(function(request, sender, sendResponse) { switch (request.id) { case "from_content_script": // This works console.log("from_content_script"); sendResponse({}); // clean up break; case "from_async": // Not working! console.log("from_async"); sendResponse({}); // clean up break; } }); methods.js ========== makeAsyncRequest = function() { ... var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState == 4) { ... // It works console.log("makeAsyncRequest callback"); chrome.extension.sendRequest({id: "from_async"}, function(response) { }); } } ... }; UPDATE: manifest configuration file. Don't no what's wrong here. { "name": "TestExt", "version": "0.0.1", "icons": { "48": "img/icon-48-green.gif" }, "description": "write it later", "background_page": "background.html", "options_page": "options.html", "browser_action": { "default_title": "TestExt", "default_icon": "img/icon-48-green.gif" }, "permissions": [ "tabs", "http://*/*", "https://*/*", "file://*/*", "webNavigation" ] }

    Read the article

  • efficient sort with custom comparison, but no callback function

    - by rob
    I have a need for an efficient sort that doesn't have a callback, but is as customizable as using qsort(). What I want is for it to work like an iterator, where it continuously calls into the sort API in a loop until it is done, doing the comparison in the loop rather than off in a callback function. This way the custom comparison is local to the calling function (and therefore has access to local variables, is potentially more efficient, etc). I have implemented this for an inefficient selection sort, but need it to be efficient, so prefer a quick sort derivative. Has anyone done anything like this? I tried to do it for quick sort, but trying to turn the algorithm inside out hurt my brain too much. Below is how it might look in use. // the array of data we are sorting MyData array[5000], *firstP, *secondP; // (assume data is filled in) Sorter sorter; // initialize sorter int result = sortInit (&sorter, array, 5000, (void **)&firstP, (void **)&secondP, sizeof(MyData)); // loop until complete while (sortIteration (&sorter, result) == 0) { // here's where we do the custom comparison...here we // just sort by member "value" but we could do anything result = firstP->value - secondP->value; }

    Read the article

  • Drupal 6 Validation for Form Callback Function

    - by Wade
    I have a simple form with a select menu on the node display page. Is there an easy way to validate the form in my callback function? By validation I don't mean anything advanced, just to check that the values actually existed in the form array. For example, without ajax, if my select menu has 3 items and I add a 4th item and try to submit the form, drupal will give an error saying something similar to "an illegal choice was made, please contact the admin." With ajax this 4th item you created would get saved into the database. So do I have to write validation like if ($select_item > 0 && $select_item <= 3) { //insert into db } Or is there an easier way that will check that the item actually existed in the form array? I'm hoping there is since without ajax, drupal will not submit the form if it was manipulated. Thanks. EDIT: So I basically need this in my callback function? $form_state = array('storage' => NULL, 'submitted' => FALSE); $form_build_id = $_POST['form_build_id']; $form = form_get_cache($form_build_id, $form_state); $args = $form['#parameters']; $form_id = array_shift($args); $form_state['post'] = $form['#post'] = $_POST; $form['#programmed'] = $form['#redirect'] = FALSE; drupal_process_form($form_id, $form, $form_state); To get $_POST['form_build_id'], I sent it as a data param, is that right? Where I use form_get_cache, looks like there is no data. Kind of lost now.

    Read the article

  • Stopping a MATLAB GUI callback

    - by leonhart88
    Dear All, I have a START and STOP button. When I hit START, i run a bunch of code in my callback. It's basically a sequential "script" that opens valves, dispenses water and then closes the valves...there is no while() loop and it doesn't repeat. I want to be able to stop this process at any time using the STOP button. Most of the related answers I've seen are in the cases where a while() loop is used. Some people have also suggested to periodically check if the STOP button was pressed (using a variable or handle variable). Since I do not have a while loop, I can't solve it that way. Also, I'd like to be able to exit immediately, without having to periodically check (because checking multiple times in my code would be ugly and confusing). Is there a way to terminate the callback which was interrupted by the STOP button? If not, is it possible to have the START button run a .m file and then have the STOP button terminate that .m file? The worst case scenario would be to check a variable periodically. UPDATE: Well, looks like the worst case scenario is what is suggested by MATLAB... http://www.mathworks.com/support/solutions/en/data/1-33IK85/index.html?product=ML&solution=1-33IK85 Thanks.

    Read the article

  • Programming pattern to flatten deeply nested ajax callbacks?

    - by chiborg
    I've inherited JavaScript code where the success callback of an Ajax handler initiates another Ajax call where the success callback may or may not initiate another Ajax call. This leads to deeply nested anonymous functions. Maybe there is a clever programming pattern that avoids the deep-nesting and is more DRY. jQuery.extend(Application.Model.prototype, { process: function() { jQuery.ajax({ url:myurl1, dataType:'json', success:function(data) { // process data, then send it back jQuery.ajax({ url:myurl2, dataType:'json', success:function(data) { if(!data.ok) { jQuery.ajax({ url:myurl2, dataType:'json', success:mycallback }); } else { mycallback(data); } } }); } }); } });

    Read the article

  • C++: Dependency injection, circular dependency and callbacks

    - by Jonathan
    Consider the (highly simplified) following case: class Dispatcher { public: receive() {/*implementation*/}; // callback } class CommInterface { public: send() = 0; // call } class CommA : public CommInterface { public: send() {/*implementation*/}; } Various classes in the system send messages via the dispatcher. The dispatcher uses a comm to send. Once an answer is returned, the comm relays it back to the dispatcher which dispatches it back to the appropriate original sender. Comm is polymorphic and which implementation to choose can be read from a settings file. Dispatcher has a dependency on the comm in order to send. Comm has a dependency on dispatcher in order to callback. Therefor there's a circular dependency here and I can't seem to implement the dependency injection principle (even after encountering this nice blog post).

    Read the article

  • Passing methods/functions as args in Objective C

    - by Baishampayan Ghose
    Hello, I am new to Objective C and I am trying to implement an async library which works with callbacks. I need to figure out a way to pass callback methods as args to my async methods so that the callback can be invoked when the task is finished. What is the best way to achieve this in Objective C? In Python, for example I could easily pass a function, but in Objective C it seems selectors are the way to go(?). Can anyone point me to an example from where I can get some ideas? Thanks in advance.

    Read the article

  • Disabling model's after_find only when called from certain controllers

    - by Lynn C
    I have an after_find callback in a model, but I need to disable it in a particular controller action e.g. def index @people = People.find(:all) # do something here to disable after_find()? end def show @people = People.find(:all) # after_find() should still be called here! end What is the best way to do it? Can I pass something in to .find to disable all/particular callbacks? Can I somehow get the controller name in the model and not execute the callback based on the controller name (I don't like this)..? Help!

    Read the article

  • paperclip callbacks or simple processor?

    - by holden
    I wanted to run the callback after_post_process but it doesn't seem to work in Rails 3.0.1 using Paperclip 2.3.8. It gives an error: undefined method `_post_process_callbacks' for #<Class:0x102d55ea0> I want to call the Panda API after the file has been uploaded. I would have created my own processor for this, but as Panda handles the processing, and it can upload the files as well, and queue itself for an undetermined duration I thought a callback would do fine. But the callbacks don't seem to work in Rails3. after_post_process :panda_create def panda_create video = Panda::Video.create(:source_url => mp3.url.gsub(/[?]\d*/,''), :profiles => "f4475446032025d7216226ad8987f8e9", :path_format => "blah/1234") end I tried require and include for paperclip in my model but it didn't seem to matter. Anyideas?

    Read the article

  • C++ Win32 Unhandled Exception Handler

    - by uray
    currently I used SetUnhandledExceptionFilter() to provide callback to get information when an unhandled exception was occurred, that callback will provides me with EXCEPTION_RECORD which provides ExceptionAddress. [1]what is actually ExceptionAddress is? does it the address of function / code that gives exception, or the memory address that some function tried to access? [2]is there any better mechanism that could give me better information when unhandled exception occured? (I can't use debug mode or add any code that affect runtime performance, since crash is rare and only on release build when code run as fast as possible) [3]is there any way for me to get several callstack address when unhandled exception occured. [4]suppose ExceptionAddress has address A, and I have DLL X loaded and executed at base address A-x, and some other DLL Y at A+y, is it good to assume that crash was PROBABLY caused by code on DLL X?

    Read the article

  • Using Interfaces in JNI

    - by lhw
    I am trying to use (*env)->RegisterNatives to add methods to a defined class which I then add to a callback list. The callback sender of course expects my class to implement a certain interface which I do not. And is failing on execution. If I add the keyword "implements Listener" to my class in Java the javac expects to have the methods definition in Java or with native keyword which I try to avoid here, as I'd like to register the methods within the JNI_OnLoad and execute one of them afterwards. The question now is: Can I implement the interface in JNI or avoid the error message in Java?

    Read the article

  • External class-calling

    - by anonymous
    Hi guys i have a bit of a problem with a few classes, and i would be very grateful if someone can help me out. So i have: Already compiled executable (for whom i don't have the source) A class in that program that i want to call The program doesn't have export for the class, and that's my problem i don't have definition for this class, so is there a way to get a callback to this class? Example: In the compiled executable: foo::bar (example) { printf(example); } My app: CALLBACK(foo::bar, "this text must be passed as argument") Or in other words i want to call a class in other executable (without having its source) and pass arguments to its function.

    Read the article

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