i am trying to initialize a basic stack - with push, and pop function.
the problems comes in while testing. you will notice in the code that i have pushed 2 times, so a print of the stack should display [5,5] whereas it is displaying None. I could tinker with the code to make it work eventually, but then i will not fully understand the underlying concepts and the error of my ways. so i ask for advice and pointers.
please check out these codes and tell me what i am doing wrong.
this is the code with the class with all it's functions, it is named stack_class:
class Stack:
def __init__(self):
self._values = []
print ('Stack initialized...')
return
def push(self, var):
ok = self._values.append(var)
return ok
def pop(self):
self.stack.pop()
def __str__(self):
output = "{0}".format(self.ok)
return output
this is the testing code:
from stack_class import Stack
ob_1 = Stack()
ob_1.push(5)
print(ob_1.push(5))
What happens is that append method doesn't return anything.
print [].append(1)
>>> None
It does its job, but doesn't return anything, that's why you are getting None in variable ok. I think you want to return the _values instead:
def push(self, var):
self._values.append(var)
return self._values
Output:
Stack initialized...
[5, 5]
Also, it's the first time I read about empty return convention. It's not necessary.
Related
I'm new to Kotlin/Native! I'd like to create an array of CPointers to pass it around, but having hard time creating one.
In C/C++ void* a[] = {test} is enough. But I'm not able to do the same in K/N.
I've tried val a: CValuesRef<out COpaquePointerVar> = cValuesOf(test)
But it results in the following error:
Tried looking at docs and find it on the web, but none of them answered correctly.
Any help is appreciated!!
So I basically did what I wanted using a StableRef
on_exit(staticCFunction { _, argsPtr ->
val argsStableRef = argsPtr!!.asStableRef<List<COpaquePointer>>()
val args = argsStableRef.get()
// Cleanup code
argsStableRef.dispose()
}, StableRef.create(listOf(/* All the pointers */)).asCPointer())
Basically transforming the List<COpaquePointer> to a StableRef and extracting pointer out of it, then when required deref it via the asStableRef and after that dispose it to ensure memory have been freed.
I have a class which has BaseScheduler as an attribute, nothing fancy, no frameworks etc.
class MyClass(object):
def __init__(self, ...):
...
self.Scheduler = BackgroundScheduler()
...
Later on I define methods that a) schedule jobs based on a schedule definition passed as kwargs, and b) handle the jobs when they are triggered:
def _schedule_Events(self, *args, **kwargs):
try:
Schedule_Def = kwargs.copy()
Schedule_Def['func'] = self._handle_scheduled_Event
job = self.Scheduler.add_job(**Schedule_Def)
self.Scheduled_Events.append(job)
except Exception as e:
self.Logger.exception('%s: exception in schedule_Events, details: %s' %(self.Name, e))
def _handle_scheduled_Event(self, Event_Action):
""" Callback function for scheduled jobs """
try:
.... do stuff ....
However, adding jobs with _schedule_Events fails with:
File "/usr/local/lib/python3.4/dist-packages/apscheduler/util.py", line 381, in check_callable_args
', '.join(unsatisfied_args))
ValueError: The following arguments have not been supplied: Event_Action
The reason is apparently that the 'func' argument must be globally callable, ie. not within a class instance scope. I also don't see how using a 'textual reference' as described in the documentation will help.
If I replace the 'func' callable with a function defined at the module level then it works, but I need to make it call a method within my instance object. Any ideas how to make this work ? Custom trigger ? Wrapping APS Scheduler inside another class and pass the callback ? Other ideas ?
Many thanks in advance.
I’ve come across some annoying problems when using asserts where there is either
no good information available: why did it fails, and what the assert was about
the assert information is buried under a sea of unneeded information like too many layers of scala functions.
I’ve kept these issues in the back of my head and, now that new scala macros are available , I plan to go on Stack Overflow and create a high-value question and answer pair for each issue. That way, the next person who has the problem won’t have to slog through so much misinformation. I might even learn some more about the various issues that plagued us if other experts chime in with their own knowledge.
This is a simple scala macro example.
Here is a solution giving more in depths details about assert failure and eliminating all scala layers of internal functions when throwing the exception:
def assert2(c: Context)(act: c.Expr[Any],exp: c.Expr[Any]): c.Expr[Unit] = {
import c.universe._
val actm = act.tree.toString
val expm = exp.tree.toString
reify({
if(act.splice!=exp.splice) {
try {
throw new Exception("AssertionError: "+c.Expr[String](Literal(Constant(actm))).splice+"["+act.splice+"]==["+exp.splice+"]"+c.Expr[String](Literal(Constant(expm))).splice)
} catch {
case unknown: Throwable => System.err.println(""+unknown+unknown.getStackTrace.toList.filter(_.toString.indexOf("scala.")!=0).mkString("\n ","\n ","\n ")); exit
}
}
})
}
def myAssert2(act: Any, exp: Any) = macro assert2
I have a class file myClass.m in a package folder +myPack that's on the path. A simple example of the class file is:
classdef myClass
properties
prop
end
methods
function obj = myClass(x)
obj.prop = x;
end
end
end
Now if I directly call the method and access the property using the full package name, i.e.:
x = myPack.myClass(2).prop;
returns x = 2 correctly. Now, if I try the same by importing this class (and not use the package name):
import myPack.myClass
y = myClass(2).prop
it gives me the following error:
Static method or constructor invocations cannot be indexed.
Do not follow the call to the static method or constructor with
any additional indexing or dot references.
Why does this work in the first case and not the second? As far as I understood, importing a class mainly allowed one to use the class name without the long package name (among other considerations). What is the difference in these two that causes this error and how can I work around it?
Here is some more weird for you: the behavior is different if you are running in the command window, from a script, or from a function!
1) command prompt (1st: ok, 2nd: error)
This is what you've already shown
>> x = myPack.myClass(2).prop
x =
2
>> import myPack.myClass; y = myClass(2).prop
Static method or constructor invocations cannot be indexed.
Do not follow the call to the static method or constructor with
any additional indexing or dot references.
2) Script (1st: error, 2nd: error)
testMyClassScript.m
x = myPack.myClass(2).prop
import myPack.myClass; y = myClass(2).prop
and
>> testMyClassScript
Static method or constructor invocations cannot be indexed.
Do not follow the call to the static method or constructor with
any additional indexing or dot references.
Error in testMyClassScript (line 1)
x = myPack.myClass(2).prop
(the second line would also throw the same error)
3) Function (1st: ok, 2nd: ok)
testMyClassFunction.m
function testMyClassFunction()
x = myPack.myClass(2).prop
import myPack.myClass; y = myClass(2).prop
end
and
>> testMyClassFunction
x =
2
y =
2
I would definitely call that a bug :) The expected behavior is to give an error in all cases.
I am calling a scraping class from Flask and the second time I instantiate a new Webkit() class (QApplication), it exits my Flask app.
How can I re-run a Qt GUI app multiple times and have it contained so it does not shut down the "outer" app?
Further clarification, Qt is event drive and calling QApplication.quit() closes not only the event loop but Python as well. Not calling quit() though never continues executing the rest of the code.
class Webkit():
...
def __run(self, url, method, dict=None):
self.qapp = QApplication(sys.argv) # FAIL here the 2nd time round
req = QNetworkRequest()
req.setUrl(QUrl(url))
self.qweb = QWebView()
self.qweb.setPage(self.Page())
self.qweb.loadFinished.connect(self.finished_loading)
self.qweb.load(req)
self.qapp.exec_()
def finished_loading(self):
self.qapp.quit()
The only (hacky!) solution so far is for me is to add this to the WebKit() class:
if __name__ == '__main__':
....
and then parse the result from the Flask app with this:
return os.popen('python webkit.py').read()