Search Results

Search found 161 results on 7 pages for 'callable'.

Page 1/7 | 1 2 3 4 5 6 7  | Next Page >

  • On reference_wrapper and callable objects

    - by Nicola Bonelli
    Given the following callable object: struct callable : public std::unary_function &lt;void, void&gt; { void operator()() const { std::cout << "hello world" << std::endl; } }; a std::tr1::reference_wrapper< calls through it: callable obj; std::tr1::ref(obj)(); Instead, when the operator() accepts an argument: struct callable : public std::unary_function &lt;int, void&gt; { void operator()(int n) const { std::cout << n << std::endl; } }; std::tr1::bind accepts a reference_wrapper to it as a callable wrapper... callable obj; std::tr1::bind( std::tr1::ref(obj), 42 )(); but what's wrong with this? std::tr1::ref(obj)(42);

    Read the article

  • 'int' object is not callable

    - by Oscar Reyes
    I'm trying to define a simply Fraction class And I'm getting this error: python fraction.py Traceback (most recent call last): File "fraction.py", line 20, in <module> f.numerator(2) TypeError: 'int' object is not callable The code follows: class Fraction(object): def __init__( self, n=0, d=0 ): self.numerator = n self.denominator = d def get_numerator(self): return self.numerator def get_denominator(self): return self.denominator def numerator(self, n): self.numerator = n def denominator( self, d ): self.denominator = d def prints( self ): print "%d/%d" %(self.numerator, self.denominator) if __name__ == "__main__": f = Fraction() f.numerator(2) f.denominator(5) f.prints() I thought it was because I had numerator(self) and numerator(self, n) but now I know Python doesn't have method overloading ( function overloading ) so I renamed to get_numerator but that's not the problems. What could it be?

    Read the article

  • Why is MaybeChannelBound callable?

    - by William Payne
    The Queue class in the python kombu library inherits from MaybeChannelBound, which in turn implements the call method (making it callable). The call() method itself is a thin wrapper around the bind() method. It is not clear why this was done, as calling the bind() method seems (to my simple mind, at least) to be clearer and more descriptive of the intent of the function. Why would somebody use the call() method in a situation like this?

    Read the article

  • Synchronizing issue: I want the main thread to be run before another thread but it sometimes doesn´t

    - by Rox
    I have done my own small concurrency framework (just for learning purposes) inspired by the java.util.concurrency package. This is about the Callable/Future mechanism. My code below is the whole one and is compilable and very easy to understand. My problem is that sometimes I run into a deadlock where the first thread (the main thread) awaits for a signal from the other thread. But then the other thread has already notified the main thread before the main thread went into waiting state, so the main thread cannot wake up. FutureTask.get() should always be run before FutureTask.run() but sometimes the run() method (which is called by new thread) runs before the get() method (which is called by main thread). I don´t know how I can prevent that. This is a pseudo code of how I want the two threads to be run. //From main thread: Executor.submit().get() (in get() the main thread waits for new thread to notify) ->submit() calls Executor.execute(FutureTask object) -> execute() starts new thread -> new thread shall notify `main thread` I cannot understand how the new thread can start up and run faster than the main thread that actually starts the new thread. Main.java: public class Main { public static void main(String[] args) { new ExecutorServiceExample(); } public Main() { ThreadExecutor executor = new ThreadExecutor(); Integer i = executor.submit(new Callable<Integer>() { @Override public Integer call() { return 10; } }).get(); System.err.println("Value: "+i); } } ThreadExecutor.java: public class ThreadExecutor { public ThreadExecutor() {} protected <V> RunnableFuture<V> newTaskFor(Callable c) { return new FutureTask<V>(c); } public <V> Future<V> submit(Callable<V> task) { if (task == null) throw new NullPointerException(); RunnableFuture<V> ftask = newTaskFor(task); execute(ftask); return ftask; } public void execute(Runnable r) { new Thread(r).start(); } } FutureTask.java: import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; import java.util.logging.Level; import java.util.logging.Logger; public class FutureTask<V> implements RunnableFuture<V> { private Callable<V> callable; private volatile V result; private ReentrantLock lock = new ReentrantLock(); private Condition condition = lock.newCondition(); public FutureTask(Callable callable) { if (callable == null) throw new NullPointerException(); this.callable = callable; } @Override public void run() { acquireLock(); System.err.println("RUN"+Thread.currentThread().getName()); V v = this.callable.call(); set(v); condition.signal(); releaseLock(); } @Override public V get() { acquireLock(); System.err.println("GET "+Thread.currentThread().getName()); try { condition.await(); } catch (InterruptedException ex) { Logger.getLogger(FutureTask.class.getName()).log(Level.SEVERE, null, ex); } releaseLock(); return this.result; } public void set(V v) { this.result = v; } private void acquireLock() { lock.lock(); } private void releaseLock() { lock.unlock(); } } And the interfaces: public interface RunnableFuture<V> extends Runnable, Future<V> { @Override void run(); } public interface Future<V> { V get(); } public interface Callable<V> { V call(); }

    Read the article

  • Callable objects on ActionScript?

    - by CodexDraco
    Hi, is it posible to have callable objects on ActionScript? For example: class Foo extends EventDispatcher { Foo() { super(); } call(world:String):String { return "Hello, " + world; } } And later... var foo:Foo = new Foo(); trace( foo("World!") ); // Will NOT work

    Read the article

  • str is not callable error in python .

    - by mekasperasky
    import sys import md5 from TOSSIM import * from RadioCountMsg import * t = Tossim([]) #The Tossim object is defined here m = t.mac()#The mac layer is defined here , in which the communication takes place r = t.radio()#The radio communication link object is defined here , as the communication needs Rf frequency to transfer t.addChannel("RadioCountToLedsC", sys.stdout)# The various channels through which communication will take place t.addChannel("LedsC", sys.stdout) #The no of nodes that would be required in the simulation has to be entered here print("enter the no of nodes you want ") n=input() for i in range(0, n): m = t.getNode(i) m.bootAtTime((31 + t.ticksPerSecond() / 10) * i + 1) #The booting time is defined so that the time at which the node would be booted is given f = open("topo.txt", "r") #The topography is defined in topo.txt so that the RF frequencies of the transmission between nodes are are set lines = f.readlines() for line in lines: s = line.split() if (len(s) > 0): if (s[0] == "gain"): r.add(int(s[1]), int(s[2]), float(s[3])) #The topogrography is added to the radio object noise = open("meyer-heavy.txt", "r") #The noise model is defined for the nodes lines = noise.readlines() for line in lines: str = line.strip() if (str != ""): val = int(str) for i in range(0, 4): t.getNode(i).addNoiseTraceReading(val) for i in range (0, n): t.getNode(i).createNoiseModel() #The noise model is created for each node for i in range(0,n): t.runNextEvent() fk=open("key.txt","w") for i in range(0,n): if i ==0 : key=raw_input() fk.write(key) ak=key key=md5.new() key.update(str(ak)) ak=key.digest() fk.write(ak) fk.close() fk=open("key.txt","w") plaint=open("pt.txt") for i in range(0,n): msg = RadioCountMsg() msg.set_counter(7) pkt = t.newPacket()#A packet is defined according to a certain format print("enter message to be transported") ms=raw_input()#The message to be transported is taken as input #The RC5 encryption has to be done here plaint.write(ms) pkt.setData(msg.data) pkt.setType(msg.get_amType()) pkt.setDestination(i+1)#The destination to which the packet will be sent is set print "Delivering " + " to" ,i+1 pkt.deliver(i+1, t.time() + 3) fk.close() print "the key to be displayed" ki=raw_input() fk=open("key.txt") for i in range(0,n): if i==ki: ms=fk.readline() for i in range(0,n): msg=RadioCountMsg() msg.set_counter(7) pkt=t.newPacket() msg.data=ms pkt.setData(msg.data) pkt.setType(msg.get_amType()) pkt.setDestination(i+1) pkt.deliver(i+1,t.time()+3) #The key has to be broadcasted here so that the decryption can take place for i in range(0, n): t.runNextEvent(); this code gives me error here key.update(str(ak)) . when i run a similar code on the python terminal there is no such error but this code pops up an error . why so?

    Read the article

  • Django: TypeError: 'str' object is not callable, referer: http://xxx

    - by user705415
    I've been wondering why when I set the settings.py of my django project 'arvindemo' debug = Flase and deploy it on Apache with mod_wsgi, I got the 500 Internal Server Error. Env: Django 1.4.0 Python 2.7.2 mod_wsgi 2.8 OS centOS Here is the recap: Visit the homepage, go to sub page A/B/C/D, and fill some forms, then submit it to the Apache server. Once click 'submit' button, I will get the '500 Internal Server Error', and the error_log listed below(Traceback): [Tue Apr 10 10:07:20 2012] [error] [client 122.198.133.250] Traceback (most recent call last): [Tue Apr 10 10:07:20 2012] [error] [client 122.198.133.250] File "/opt/python2.7/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 241, in __call__ [Tue Apr 10 10:07:20 2012] [error] [client 122.198.133.250] response = self.get_response(request) [Tue Apr 10 10:07:20 2012] [error] [client 122.198.133.250] File "/opt/python2.7/lib/python2.7/site-packages/django/core/handlers/base.py", line 179, in get_response [Tue Apr 10 10:07:20 2012] [error] [client 122.198.133.250] response = self.handle_uncaught_exception(request, resolver, sys.exc_info()) [Tue Apr 10 10:07:20 2012] [error] [client 122.198.133.250] File "/opt/python2.7/lib/python2.7/site-packages/django/core/handlers/base.py", line 224, in handle_uncaught_exception [Tue Apr 10 10:07:20 2012] [error] [client 122.198.133.250] if resolver.urlconf_module is None: [Tue Apr 10 10:07:20 2012] [error] [client 122.198.133.250] File "/opt/python2.7/lib/python2.7/site-packages/django/core/urlresolvers.py", line 323, in urlconf_module [Tue Apr 10 10:07:20 2012] [error] [client 122.198.133.250] self._urlconf_module = import_module(self.urlconf_name) [Tue Apr 10 10:07:20 2012] [error] [client 122.198.133.250] File "/opt/python2.7/lib/python2.7/site-packages/django/utils/importlib.py", line 35, in import_module [Tue Apr 10 10:07:20 2012] [error] [client 122.198.133.250] __import__(name) [Tue Apr 10 10:07:20 2012] [error] [client 122.198.133.250] File "/opt/web/django/arvindemo/arvindemo/../arvindemo/urls.py", line 23, in <module> [Tue Apr 10 10:07:20 2012] [error] [client 122.198.133.250] url(r'^submitPage$', name=submitPage), [Tue Apr 10 10:07:20 2012] [error] [client 122.198.133.250] TypeError: url() takes at least 2 arguments (2 given) When using django runserver, I set arvindemo.settings debug = True, everything is OK. But things changed once I set debug = Flase. Here is my views.py from django.http import HttpResponseRedirect from django.http import HttpResponse, HttpResponseServerError from django.shortcuts import render_to_response import datetime, string from user_info.models import * from django.template import Context, loader, RequestContext import settings def hello(request): return HttpResponse("hello girl") def helpPage(request): return render_to_response('kktHelp.html') def server_error(request, template_name='500.html'): return render_to_response(template_name, context_instance = RequestContext(request) ) def page404(request): return render_to_response('404.html') def submitPage(request): post = request.POST Mall = 'goodsName' Contest = 'ojs' Presentation = 'addr' WeatherReport = 'city' Habit = 'task' if Mall in post: return submitMall(request) elif Contest in post: return submitContest(request) elif Presentation in post: return submitPresentation(request) elif Habit in post: return submitHabit(request) elif WeatherReport in post: return submitWeather(request) else: return HttpResponse(request.POST) return HttpResponseRedirect('404') def submitXXX(): ..... def xxxx(): .... Here comes the urls.py from django.conf.urls import patterns, include, url from views import * from django.conf import settings handler500 = 'server_error' urlpatterns = patterns('', url(r'^hello/$', hello), # hello world url(r'^$', homePage), url(r'^time/$', getTime), url(r'^time/plus/(\d{1,2})/$', hoursAhead), url(r'^Ttime/$', templateGetTime), url(r'^Mall$', templateMall), url(r'^Contest$', templateContest), url(r'^Presentation$', templatePresentation), url(r'^Habit$', templateHabit), url(r'^Weather$', templateWeather), url(r'^Help$', helpPage), url(r'^404$', page404), url(r'^500$', server_error), url(r'^submitPage$', submitPage), url(r'^submitMall$', submitMall), url(r'^submitContest$', submitContest), url(r'^submitPresentation$', submitPresentation), url(r'^submitHabit$', submitHabit), url(r'^submitWeather$', submitWeather), url(r'^terms$', terms), url(r'^privacy$', privacy), url(r'^thanks$', thanks), url(r'^about$', about), url(r'^static/(?P<path>.*)$','django.views.static.serve',{'document_root':settings.STATICFILES_DIRS}), ) I'm sure there is no syntax error in my django project,cause when I use django runserver, everything is fine. Anyone can help ? Best regards

    Read the article

  • Python "callable" attribute (pseudo-property)

    - by mgilson
    In python, I can alter the state of an instance by directly assigning to attributes, or by making method calls which alter the state of the attributes: foo.thing = 'baz' or: foo.thing('baz') Is there a nice way to create a class which would accept both of the above forms which scales to large numbers of attributes that behave this way? (Shortly, I'll show an example of an implementation that I don't particularly like.) If you're thinking that this is a stupid API, let me know, but perhaps a more concrete example is in order. Say I have a Document class. Document could have an attribute title. However, title may want to have some state as well (font,fontsize,justification,...), but the average user might be happy enough just setting the title to a string and being done with it ... One way to accomplish this would be to: class Title(object): def __init__(self,text,font='times',size=12): self.text = text self.font = font self.size = size def __call__(self,*text,**kwargs): if(text): self.text = text[0] for k,v in kwargs.items(): setattr(self,k,v) def __str__(self): return '<title font={font}, size={size}>{text}</title>'.format(text=self.text,size=self.size,font=self.font) class Document(object): _special_attr = set(['title']) def __setattr__(self,k,v): if k in self._special_attr and hasattr(self,k): getattr(self,k)(v) else: object.__setattr__(self,k,v) def __init__(self,text="",title=""): self.title = Title(title) self.text = text def __str__(self): return str(self.title)+'<body>'+self.text+'</body>' Now I can use this as follows: doc = Document() doc.title = "Hello World" print (str(doc)) doc.title("Goodbye World",font="Helvetica") print (str(doc)) This implementation seems a little messy though (with __special_attr). Maybe that's because this is a messed up API. I'm not sure. Is there a better way to do this? Or did I leave the beaten path a little too far on this one? I realize I could use @property for this as well, but that wouldn't scale well at all if I had more than just one attribute which is to behave this way -- I'd need to write a getter and setter for each, yuck.

    Read the article

  • TypeError: object not callable when making instance

    - by TSM
    I've searched around other threads with similar questions, but I'm not finding the answer. Basically, I have a class: import Android_Class class Android_Revision(object): def __init__(self): # dict for storing the classes in this revision # (format {name : classObject}): self.Classes = {} self.WorkingClass = Android_Class() self.RevisionNumber = '' def __call__(self): print "Called" def make_Class(self, name): newClass = Android_Class(name) self.Classes.update({name : newClass}) self.WorkingClass = newClass def set_Class(self, name): if not(self.Classes.has_key(name)): newClass = Android_Class(name) self.Classes.update({name : newClass}) self.WorkingClass = self.Classes.get(name) I'm trying to make an instance of this class: Revision = Android_Revision() and that's when I'm getting the error. I'm confused because I have another situation where I'm doing almost the exact same thing, and it's working fine. I can't figure out what differences between the two would lead to this error. Thanks.

    Read the article

  • Java - SwingWorker - problem

    - by Yatendra Goel
    I am developing a Java Desktop Application. This app executes the same task public class MyTask implements Callable<MyObject> { in multiple thread simultaneously. Now, when a user clicks on a "start" button, I have created a SwingWorker myWorker and have executed it. Now, this myWorker creates multiple instances of MyTask and submits them to an ExecutorService. Each MyTask instance has a loop and generates an intermediate result at every iteration. Now, I want to collect these intermediate results from each MyTask instances as soon as they are generated. Then after collecting these intermediate results from every MyTask instance, I want to publish it through SwingWorker.publish(MyObject) so that the progress is shown on the EDT. Q1. How can I implement this? Should I make MyTask subclass of SwingWorker instead of Callable to get intermediate results also, because I think that Callable only returns final result. Q2. If the answer of Q1. is yes, then can you give me a small example to show how can I get those intermediate results and aggregate them and then publish them from main SwingWorker? Q3. If I can't use SwingWorker in this situation, then how can I implement this?

    Read the article

  • Filling SWT table object using a separated thread class ...

    - by erlord
    Hi all I've got a code snippet by the swt team that does exactly what I need. However, there is a part I want to separate into another class, in particular, the whole inline stuff. In response to my former question, it has been suggested that Callable should be used in order to implement threaded objects. It is suggested to make use of an implementation of runnable or better callable, since I do need some kind of return. However, I don't get it. My problems are: In the original code, within the inline implementation of the method run, some of the parents objects are called. How would I do this when the thread is separated? Pass the object via the C'tor's parameter? In the original code, another runnable object is nested within the runnable implementation. What is it good for? How to implement this when having separated the code? Furthermore, this nested runnable again calls objects created by the main method. Please, have mercy with me, but I am still quite a beginner and my brain is near collapsing :-( All I want is to separate all the threaded stuff into another class and make the program do just the same thing as it already does. Help please! Again thank you very much in advance for any useful suggestions, hints, examples etc... Regs Me

    Read the article

  • When does the call() method get called in a Java Executor using Callable objects?

    - by MalcomTucker
    This is some sample code from an example. What I need to know is when call() gets called on the callable? What triggers it? public class CallableExample { public static class WordLengthCallable implements Callable { private String word; public WordLengthCallable(String word) { this.word = word; } public Integer call() { return Integer.valueOf(word.length()); } } public static void main(String args[]) throws Exception { ExecutorService pool = Executors.newFixedThreadPool(3); Set<Future<Integer>> set = new HashSet<Future<Integer>>(); for (String word: args) { Callable<Integer> callable = new WordLengthCallable(word); Future<Integer> future = pool.submit(callable); //**DOES THIS CALL call()?** set.add(future); } int sum = 0; for (Future<Integer> future : set) { sum += future.get();//**OR DOES THIS CALL call()?** } System.out.printf("The sum of lengths is %s%n", sum); System.exit(sum); } }

    Read the article

  • Value gets changed upon comiting. | CallableStatements

    - by Triztian
    Hello, I having a weird problem with a DAO class and a StoredProcedure, what is happening is that I use a CallableStatement object which takes 15 IN parameters, the value of the field id_color is retrieved correctly from the HTML forms it even is set up how it should in the CallableStatement setter methods, but the moment it is sent to the database the id_color is overwriten by the value 3 here's the "context": I have the following class DAO.CoverDAO which handles the CRUD operations of this table CREATE TABLE `cover_details` ( `refno` int(10) unsigned NOT NULL AUTO_INCREMENT, `shape` tinyint(3) unsigned NOT NULL , `id_color` tinyint(3) unsigned NOT NULL ', `reversefold` bit(1) NOT NULL DEFAULT b'0' , `x` decimal(6,3) unsigned NOT NULL , `y` decimal(6,3) unsigned NOT NULL DEFAULT '0.000', `typecut` varchar(10) NOT NULL, `cornershape` varchar(20) NOT NULL, `z` decimal(6,3) unsigned DEFAULT '0.000' , `othercornerradius` decimal(6,3) unsigned DEFAULT '0.000'', `skirt` decimal(5,3) unsigned NOT NULL DEFAULT '7.000', `foamTaper` varchar(3) NOT NULL, `foamDensity` decimal(2,1) unsigned NOT NULL , `straplocation` char(1) NOT NULL ', `straplength` decimal(6,3) unsigned NOT NULL, `strapinset` decimal(6,3) unsigned NOT NULL, `spayear` varchar(20) DEFAULT 'Not Specified', `spamake` varchar(20) DEFAULT 'Not Specified', `spabrand` varchar(20) DEFAULT 'Not Specified', PRIMARY KEY (`refno`) ) ENGINE=MyISAM AUTO_INCREMENT=143 DEFAULT CHARSET=latin1 $$ The the way covers are being inserted is by a stored procedure, which is the following: CREATE DEFINER=`root`@`%` PROCEDURE `putCover`( IN shape TINYINT, IN color TINYINT(3), IN reverse_fold BIT, IN x DECIMAL(6,3), IN y DECIMAL(6,3), IN type_cut VARCHAR(10), IN corner_shape VARCHAR(10), IN cutsize DECIMAL(6,3), IN corner_radius DECIMAL(6,3), IN skirt DECIMAL(5,3), IN foam_taper VARCHAR(7), IN foam_density DECIMAL(2,1), IN strap_location CHAR(1), IN strap_length DECIMAL(6,3), IN strap_inset DECIMAL(6,3) ) BEGIN INSERT INTO `dbre`.`cover_details` (`dbre`.`cover_details`.`shape`, `dbre`.`cover_details`.`id_color`, `dbre`.`cover_details`.`reversefold`, `dbre`.`cover_details`.`x`, `dbre`.`cover_details`.`y`, `dbre`.`cover_details`.`typecut`, `dbre`.`cover_details`.`cornershape`, `dbre`.`cover_details`.`z`, `dbre`.`cover_details`.`othercornerradius`, `dbre`.`cover_details`.`skirt`, `dbre`.`cover_details`.`foamTaper`, `dbre`.`cover_details`.`foamDensity`, `dbre`.`cover_details`.`strapLocation`, `dbre`.`cover_details`.`strapInset`, `dbre`.`cover_details`.`strapLength` ) VALUES (shape,color,reverse_fold, x,y,type_cut,corner_shape, cutsize,corner_radius,skirt,foam_taper,foam_density, strap_location,strap_inset,strap_length); END As you can see basically it just fills each field, now, the CoverDAO.create(CoverDTO cover) method which creates the cover is like so: public void create(CoverDTO cover) throws DAOException { Connection link = null; CallableStatement query = null; try { link = MySQL.getConnection(); link.setAutoCommit(false); query = link.prepareCall("{CALL putCover(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}"); query.setLong(1,cover.getShape()); query.setInt(2,cover.getColor()); query.setBoolean(3, cover.getReverseFold()); query.setBigDecimal(4,cover.getX()); query.setBigDecimal(5,cover.getY()); query.setString(6,cover.getTypeCut()); query.setString(7,cover.getCornerShape()); query.setBigDecimal(8, cover.getZ()); query.setBigDecimal(9, cover.getCornerRadius()); query.setBigDecimal(10, cover.getSkirt()); query.setString(11, cover.getFoamTaper()); query.setBigDecimal(12, cover.getFoamDensity()); query.setString(13, cover.getStrapLocation()); query.setBigDecimal(14, cover.getStrapLength()); query.setBigDecimal(15, cover.getStrapInset()); query.executeUpdate(); link.commit(); } catch (SQLException e) { throw new DAOException(e); } finally { close(link, query); } } The CoverDTO is made of accessesor methods, the MySQL object basically returns the connection from a pool. Here is the pset Query with dummy but appropriate data: putCover(1,10,0,80.000,80.000,'F','Cut',0.000,0,15.000,'4x2',1.5,'A',10.000,5.000) As you can see everything is fine just when I write to the DB instead of 10 in the second parameter a 3 is written. I have done the following: Traced the id_color value to the create method, still got replaced by a 3 Hardcoded the value in the DAO create method, still got replaced by a 3 Called the procedure from the MySQL Workbench, it worked fined so I assume something is happening in the create method, any help is really appreciated.

    Read the article

  • Is there a good digraph layout library callable from C++?

    - by Steve314
    The digraphs represent finite automata. Up until now my test program has been writing out dot files for testing. This is pretty good both for regression testing (keep the verified output files in subversion, ask it if there has been a change) and for visualisation. However, there are some problems... Basically, I want something callable from C++ and which plans a layout for my states and transitions but leaves the drawing to me - something that will allow me to draw things however I want and draw on GUI (wxWidgets) windows. I also want a license which will allow commercial use - I don't need that at present, and I may very well release as open source, but I don't want to limit my options ATM. The problems with GraphViz are (1) the warnings about building from source on Windows, (2) all the unnecessary dependencies for rendering and parsing, and (3) the (presumed) lack of a documented API specifically and purely for layout. Basically, I want to be able to specify my states (with bounding rectangle sizes) and transitions, and read out positions for the states and waypoints for each transition, then draw based on those co-ordinates myself. I haven't really figured out how annotations on transitions should be handled, but there should be some kind of provision for specifying bounding-box-sizes for those, associating them with transitions, and reading out positions. Does anyone know of a library that can handle those requirements? I'm not necessarily against implementing something for myself, but in this case I'd rather avoid it if possible.

    Read the article

  • Screen Snip/Capture Utility callable from API or command line?

    - by Raymond
    I am looking for a screen capture tool that is controllable from the command line. Ideally I would pass the filename, and possibly some options (capture mouse pointer or not, etc..), then it would take control, allow the user to select a region of the screen, and then save it to the specified file and disappear. screensnip.exe /output c:\users\public\pictures\screenshot.png /hidecursor user draws rectangle on screen control passes back to batch file, script, etc....

    Read the article

  • Java: design for using many executors services and only few threads

    - by Guillaume
    I need to run in parallel multiple threads to perform some tests. My 'test engine' will have n tests to perform, each one doing k sub-tests. Each test result is stored for a later usage. So I have n*k processes that can be ran concurrently. I'm trying to figure how to use the java concurrent tools efficiently. Right now I have an executor service at test level and n executor service at sub test level. I create my list of Callables for the test level. Each test callable will then create another list of callables for the subtest level. When invoked a test callable will subsequently invoke all subtest callables test 1 subtest a1 subtest ...1 subtest k1 test n subtest a2 subtest ...2 subtest k2 call sequence: test manager create test 1 callable test1 callable create subtest a1 to k1 testn callable create subtest an to kn test manager invoke all test callables test1 callable invoke all subtest a1 to k1 testn callable invoke all subtest an to kn This is working fine, but I have a lot of new treads that are created. I can not share executor service since I need to call 'shutdown' on the executors. My idea to fix this problem is to provide the same fixed size thread pool to each executor service. Do you think it is a good design ? Do I miss something more appropriate/simple for doing this ?

    Read the article

  • Why are ASP.Net MVC2 area controller actions callable without including the area in the url path?

    - by Nathan Ridley
    I've just installed Visual Studio 2010 and have created a new MVC2 project so that I can learn about the changes and updates and have discovered an issue with areas that I'm not sure what to make of. I created a new EMPTY MVC2 project I right clicked the project and, from the context menu, added a new area called "Test" In the new test area, I added a controller called "Data". The code is: public class DataController : Controller { // // GET: /Test/Data/ public ActionResult Index() { Response.Write("Hi"); return new EmptyResult(); } } Now, I compile and call this address: http://localhost/mytest/test/data and get the output: Hi All good. Now I call this: http://localhost/mytest/data and get the same response! I thought routing was supposed to take care of this? Am I overlooking something? Or has the default project setup for MVC2 overlooked something?

    Read the article

  • Tying PyQt4 QAction triggered() to local class callable doesn't seem to work. How to debug this?

    - by Jon Watte
    I create this object when I want to create a QAction. I then add this QAction to a menu: class ActionObject(object): def __init__(self, owner, command): action = QtGui.QAction(command.name, owner) self.action = action self.command = command action.setShortcut(command.shortcut) action.setStatusTip(command.name) QtCore.QObject.connect(action, QtCore.SIGNAL('triggered()'), self.triggered) def triggered(self): print("got triggered " + self.command.id + " " + repr(checked)) Unfortunately, when the menu item is selected, the 'triggered' function is not called. QtCore.QObject.connect() returns True. Nothing is printed on the console to indicate that anything is wrong, and no exception is thrown. How can I debug this? (or, what am I doing wrong?)

    Read the article

  • uWSGI cannot find "application" using Flask and Virtualenv

    - by skyler
    Using uWSGI to serve a simple wsgi app, (a simple "Hello, World") my configuration works, but when I try to run a Flask app, I get this in uWSGI's error logs: current working directory: /opt/python-env/coefficient/lib/python2.6/site-packages writing pidfile to /var/run/uwsgi.pid detected binary path: /opt/uwsgi/uwsgi setuid() to 497 your memory page size is 4096 bytes detected max file descriptor number: 1024 lock engine: pthread robust mutexes uwsgi socket 0 bound to TCP address 127.0.0.1:3031 fd 3 Python version: 2.6.6 (r266:84292, Jun 18 2012, 14:18:47) [GCC 4.4.6 20110731 (Red Hat 4.4.6-3)] Set PythonHome to /opt/python-env/coefficient/ *** Python threads support is disabled. You can enable it with --enable-threads *** Python main interpreter initialized at 0xbed3b0 your server socket listen backlog is limited to 100 connections *** Operational MODE: single process *** added /opt/python-env/coefficient/lib/python2.6/site-packages/ to pythonpath. unable to find "application" callable in file /var/www/coefficient/flask.py unable to load app 0 (mountpoint='') (callable not found or import error) *** no app loaded. going in full dynamic mode *** *** uWSGI is running in multiple interpreter mode ***` Note in particular this part of the log: unable to find "application" callable in file /var/www/coefficient/flask.py unable to load app 0 (mountpoint='') (callable not found or import error) **no app loaded. going in full dynamic mode** This is my Flask app: from flask import Flask app = Flask(__name__) @app.route("/") def hello(): return "Hello, World, from Flask!" Before I added my Virtualenv's pythonpath to my configuration file, I was getting an ImportError for Flask. I solved this though, I believe (I'm not receiving errors about it anymore) and here is my complete configuration file: uwsgi: #socket: /tmp/uwsgi.sock socket: 127.0.0.1:3031 daemonize: /var/log/uwsgi.log pidfile: /var/run/uwsgi.pid master: true vacuum: true #wsgi-file: /var/www/coefficient/coefficient.py wsgi-file: /var/www/coefficient/flask.py processes: 1 virtualenv: /opt/python-env/coefficient/ pythonpath: /opt/python-env/coefficient/lib/python2.6/site-packages This is how I start uWSGI, from an rc script: /opt/uwsgi/uwsgi --yaml /etc/uwsgi/conf.yaml --uid uwsgi And if I try to view the Flask program in a browser, I get this: **uWSGI Error** Python application not found Any help is appreciated.

    Read the article

  • What is the fastest cyclic synchronization in Java (ExecutorService vs. CyclicBarrier vs. X)?

    - by Alex Dunlop
    Which Java synchronization construct is likely to provide the best performance for a concurrent, iterative processing scenario with a fixed number of threads like the one outlined below? After experimenting on my own for a while (using ExecutorService and CyclicBarrier) and being somewhat surprised by the results, I would be grateful for some expert advice and maybe some new ideas. Existing questions here do not seem to focus primarily on performance, hence this new one. Thanks in advance! The core of the app is a simple iterative data processing algorithm, parallelized to the spread the computational load across 8 cores on a Mac Pro, running OS X 10.6 and Java 1.6.0_07. The data to be processed is split into 8 blocks and each block is fed to a Runnable to be executed by one of a fixed number of threads. Parallelizing the algorithm was fairly straightforward, and it functionally works as desired, but its performance is not yet what I think it could be. The app seems to spend a lot of time in system calls synchronizing, so after some profiling I wonder whether I selected the most appropriate synchronization mechanism(s). A key requirement of the algorithm is that it needs to proceed in stages, so the threads need to sync up at the end of each stage. The main thread prepares the work (very low overhead), passes it to the threads, lets them work on it, then proceeds when all threads are done, rearranges the work (again very low overhead) and repeats the cycle. The machine is dedicated to this task, Garbage Collection is minimized by using per-thread pools of pre-allocated items, and the number of threads can be fixed (no incoming requests or the like, just one thread per CPU core). V1 - ExecutorService My first implementation used an ExecutorService with 8 worker threads. The program creates 8 tasks holding the work and then lets them work on it, roughly like this: // create one thread per CPU executorService = Executors.newFixedThreadPool( 8 ); ... // now process data in cycles while( ...) { // package data into 8 work items ... // create one Callable task per work item ... // submit the Callables to the worker threads executorService.invokeAll( taskList ); } This works well functionally (it does what it should), and for very large work items indeed all 8 CPUs become highly loaded, as much as the processing algorithm would be expected to allow (some work items will finish faster than others, then idle). However, as the work items become smaller (and this is not really under the program's control), the user CPU load shrinks dramatically: blocksize | system | user | cycles/sec 256k 1.8% 85% 1.30 64k 2.5% 77% 5.6 16k 4% 64% 22.5 4096 8% 56% 86 1024 13% 38% 227 256 17% 19% 420 64 19% 17% 948 16 19% 13% 1626 Legend: - block size = size of the work item (= computational steps) - system = system load, as shown in OS X Activity Monitor (red bar) - user = user load, as shown in OS X Activity Monitor (green bar) - cycles/sec = iterations through the main while loop, more is better The primary area of concern here is the high percentage of time spent in the system, which appears to be driven by thread synchronization calls. As expected, for smaller work items, ExecutorService.invokeAll() will require relatively more effort to sync up the threads versus the amount of work being performed in each thread. But since ExecutorService is more generic than it would need to be for this use case (it can queue tasks for threads if there are more tasks than cores), I though maybe there would be a leaner synchronization construct. V2 - CyclicBarrier The next implementation used a CyclicBarrier to sync up the threads before receiving work and after completing it, roughly as follows: main() { // create the barrier barrier = new CyclicBarrier( 8 + 1 ); // create Runable for thread, tell it about the barrier Runnable task = new WorkerThreadRunnable( barrier ); // start the threads for( int i = 0; i < 8; i++ ) { // create one thread per core new Thread( task ).start(); } while( ... ) { // tell threads about the work ... // N threads + this will call await(), then system proceeds barrier.await(); // ... now worker threads work on the work... // wait for worker threads to finish barrier.await(); } } class WorkerThreadRunnable implements Runnable { CyclicBarrier barrier; WorkerThreadRunnable( CyclicBarrier barrier ) { this.barrier = barrier; } public void run() { while( true ) { // wait for work barrier.await(); // do the work ... // wait for everyone else to finish barrier.await(); } } } Again, this works well functionally (it does what it should), and for very large work items indeed all 8 CPUs become highly loaded, as before. However, as the work items become smaller, the load still shrinks dramatically: blocksize | system | user | cycles/sec 256k 1.9% 85% 1.30 64k 2.7% 78% 6.1 16k 5.5% 52% 25 4096 9% 29% 64 1024 11% 15% 117 256 12% 8% 169 64 12% 6.5% 285 16 12% 6% 377 For large work items, synchronization is negligible and the performance is identical to V1. But unexpectedly, the results of the (highly specialized) CyclicBarrier seem MUCH WORSE than those for the (generic) ExecutorService: throughput (cycles/sec) is only about 1/4th of V1. A preliminary conclusion would be that even though this seems to be the advertised ideal use case for CyclicBarrier, it performs much worse than the generic ExecutorService. V3 - Wait/Notify + CyclicBarrier It seemed worth a try to replace the first cyclic barrier await() with a simple wait/notify mechanism: main() { // create the barrier // create Runable for thread, tell it about the barrier // start the threads while( ... ) { // tell threads about the work // for each: workerThreadRunnable.setWorkItem( ... ); // ... now worker threads work on the work... // wait for worker threads to finish barrier.await(); } } class WorkerThreadRunnable implements Runnable { CyclicBarrier barrier; @NotNull volatile private Callable<Integer> workItem; WorkerThreadRunnable( CyclicBarrier barrier ) { this.barrier = barrier; this.workItem = NO_WORK; } final protected void setWorkItem( @NotNull final Callable<Integer> callable ) { synchronized( this ) { workItem = callable; notify(); } } public void run() { while( true ) { // wait for work while( true ) { synchronized( this ) { if( workItem != NO_WORK ) break; try { wait(); } catch( InterruptedException e ) { e.printStackTrace(); } } } // do the work ... // wait for everyone else to finish barrier.await(); } } } Again, this works well functionally (it does what it should). blocksize | system | user | cycles/sec 256k 1.9% 85% 1.30 64k 2.4% 80% 6.3 16k 4.6% 60% 30.1 4096 8.6% 41% 98.5 1024 12% 23% 202 256 14% 11.6% 299 64 14% 10.0% 518 16 14.8% 8.7% 679 The throughput for small work items is still much worse than that of the ExecutorService, but about 2x that of the CyclicBarrier. Eliminating one CyclicBarrier eliminates half of the gap. V4 - Busy wait instead of wait/notify Since this app is the primary one running on the system and the cores idle anyway if they're not busy with a work item, why not try a busy wait for work items in each thread, even if that spins the CPU needlessly. The worker thread code changes as follows: class WorkerThreadRunnable implements Runnable { // as before final protected void setWorkItem( @NotNull final Callable<Integer> callable ) { workItem = callable; } public void run() { while( true ) { // busy-wait for work while( true ) { if( workItem != NO_WORK ) break; } // do the work ... // wait for everyone else to finish barrier.await(); } } } Also works well functionally (it does what it should). blocksize | system | user | cycles/sec 256k 1.9% 85% 1.30 64k 2.2% 81% 6.3 16k 4.2% 62% 33 4096 7.5% 40% 107 1024 10.4% 23% 210 256 12.0% 12.0% 310 64 11.9% 10.2% 550 16 12.2% 8.6% 741 For small work items, this increases throughput by a further 10% over the CyclicBarrier + wait/notify variant, which is not insignificant. But it is still much lower-throughput than V1 with the ExecutorService. V5 - ? So what is the best synchronization mechanism for such a (presumably not uncommon) problem? I am weary of writing my own sync mechanism to completely replace ExecutorService (assuming that it is too generic and there has to be something that can still be taken out to make it more efficient). It is not my area of expertise and I'm concerned that I'd spend a lot of time debugging it (since I'm not even sure my wait/notify and busy wait variants are correct) for uncertain gain. Any advice would be greatly appreciated.

    Read the article

  • how to pass a parameter to method with php's is_callable

    - by fayer
    i have to create a variable that is callable with php's is_callable i have done this: $callable = array(new MyClass, 'methodName'); but i want to pass a parameter to the method. how can i do that? cause using symfony's event dispatcher component will be like: $sfEventDispatcher->connect('log.write', array(new IC_Log('logfile.txt'), 'write')); the first parameter is just a event name, the second is the callable variable. but i can only call the write method, i want to pass a parameter to it. could someone help me out. thanks

    Read the article

  • A problem with assertRaises function in Python

    - by anton.k.
    Hello,guys! I am trying to run the following test self.assertRaises(Exception,lambda: unit_test.testBasic()) where test.testBasic() is class IsPrimeTest(unittest.TestCase): def assertRaises(self,exception,callable,*args,**kwargs): print('dfdf') temp = callable super().assertRaises(exception,temp,*args,**kwargs) def testBasic_helper(self): self.failIf(is_prime(2)) self.assertTrue(is_prime(1)) where prime is a function,and but in self.assertRaises(Exception,lambda: unit_test.testBasic()) the lambda function doesnt throws an exception after the test def testBasic_helper(self): self.failIf(is_prime(2)) self.assertTrue(is_prime(1)) fails Can somebody offers a solution to the problem?

    Read the article

1 2 3 4 5 6 7  | Next Page >