How to modify the code so that i do not have to uninstall pycharm? - exception

I have run the code as part of exception handling in python, during a session on Plural-sight but now even if a write a incorrect code the result is OK.
For example : hello world without print statement gives me exit code 0
Could you please advice on it?
code :
try:
import msvcrt
def getkey():
return msvcrt.getch()
except ImportError:
import sys
import tty
import termios
def getkey():
fd=sys.stdin.fileno()
original_attributes =termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, original_attributes)
return ch

You need to make sure that the indentation of your code is correct first.
For example get_key function should be defined in both: the try case and in the catch, in the catch case you indented it correctly under the catch statement, but for the try case you made it on the same level of indentation as the try itself, for the interpreter it means that the function definition is not related to the try you wrote, therefore it throws an error as you should not add code after between the try and catch statement.
a rewrite of your program
try:
import msvcrt
def getkey():
return msvcrt.getch()
except ImportError:
import sys
import tty
import termios
def getkey():
fd=sys.stdin.fileno()
original_attributes =termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, original_attributes)
return ch
This code says now, if we tried to import the library msvcrt and succeeded, then we will define a function get_key using the library, if failed; then we will define it again without using the library.

Related

Can't write to a csv file from a class in kotlin

Im trying to write a class to csv. And I need or at least prefer a class that I could call that could both retrieve and eventually save the class objects as csv.
I have tried every imaginable way I can find to write files. Everytime it works flawlessly in the main activity .kt, but soon as I move any of it to a dedicated class I get:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.FileOutputStream android.content.Context.openFileOutput(java.lang.String, int)' on a null object reference
or I get told thats is a read only file system.
Heres a copy of a class that ive tried and gotten the error.
package com.example.jobndays
import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.PrintWriter
class DryTest: AppCompatActivity() {
fun main() {
var fileInputStream: FileOutputStream? = null
fileInputStream = openFileOutput("bobbin.csv", MODE_PRIVATE)
val bob = "fella"
fileInputStream.write(bob.toByteArray())
}
}
I believe I've found an answer. Apparently in order to write files you need 'context', not entirely sure why, but just ask for it and stick infront of stuff that says they're unresolved.

SQLModel: sqlalchemy.exc.ArgumentError: Column expression or FROM clause expected,

I am using the SQLModel library to do a simple select() like described on their official website. However I am getting Column expression or FROM clause expected error message
from typing import Optional
from sqlmodel import Field, Session, SQLModel, create_engine, select
from models import Hero
sqrl = f"mysql+pymysql:///roo#asdf:localhost:3306/datab"
engine = create_engine(sqrl, echo=True)
def create_db_and_tables():
SQLModel.metadata.create_all(engine)
def select_heroes():
with Session(engine) as session:
statement = select(Hero)
results = session.exec(statement)
for hero in results:
print(hero)
def main():
select_heroes()
if __name__ == "__main__":
main()
this is my models/Hero.py code:
from datetime import datetime, date, time
from typing import Optional
from sqlmodel import Field, SQLModel
class Hero(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
secret_name: str
age: Optional[int] = None
created: datetime
lastseen: time
when I run app.py I get the sqlalchemy.exc.ArgumentError: Column expression or FROM clause expected, got <module 'models.Hero' from '/Users/dev/test/models/Hero.py'>. message
The error message <Column expression or FROM clause expected, got module 'models.Hero' from '/Users/dev/test/models/Hero.py'> tells us:
SQLModel / SQLAlchemy unexpectedly received a module object named models.Hero
that you have a module named Hero.py
The import statement from models import Hero only imports the module Hero. Either
change the import to import the model*
from models.Hero import Hero
change the code in select_heroes to reference the model†
statement = select(Hero.Hero)
* It's conventional to use all lowercase for module names; following this convention will help you distinguish between modules and models.
† This approach is preferable in my opinion: accessing the object via the module namespace eliminates the possibility of name collisions (of course it can be combined with lowercase module names).

Call up a function from another module

I am making a project where I need several modules which are imported into one main module. I have decided to move the interaction to a single Tkinter window. Instead of using input() I use tkinter.Entry(), for example. I have functions for each step of the interaction.
When I get past the last function of the first module, the configured button has a command to go to a function in the second module. I get an error saying that the command is not defined.
I seem unable to import the configured button variable into the next module, and anything else I tried gave no result. It simply doesn't go to the next module after the first module is done.
I have made the main Tkinter window in the main module and have it that it will mainloop after importing the other modules. Shouldn't the function I want to call upon be defined? How can I get from one function to the next if the latter is in a separate module?
Here is a minimal example:
main_script.py
import tkinter
mainwindow = tkinter.Tk()
# here i set the window to a certain size etc.
import mod1
import mod2
mainwindow.mainloop()
mod1.py
import tkinter
def button1():
label.destroy()
button1.destroy()
button2.config(text = "continue", command = func2)
def button2():
label.destroy()
button1.destroy()
button2.config(text = "continue", command = func2)
label = tkinter.Label(text = "example label")
button1 = tkinter.Button(text = "button1", command = button1)
button2 = tkinter.Button(text = "button2", command = button2)
label.pack()
button1.pack()
button2.pack()
mod2.py
def func2():
button2.destroy()
print ("haha it works...")
Importing a module has no effect on what the module you import can see. If you want to use mod1 contents in mod2 and mod2 contents in mod1, you need to have them import each other and refer to each other's contents with the appropriate module:
# mod1
import mod2
...
button2.config(text = "continue", command = mod2.func2)
# mod2
import mod1
def func2():
mod1.button2.destroy()
Circular imports cause nasty initialization order issues, though, so imports like this are a bad idea. When dividing your code into modules, try to do so in such a way that import loops like this aren't necessary.

Check if object is an sqlalchemy model instance

I want to know how to know, given an object, if it is an instance of an sqlalchemy mapped model.
Normally, I would use isinstance(obj, DeclarativeBase). However, in this scenario, I do not have the DeclarativeBase class used available (since it is in a dependency project).
I would like to know what is the best practice in this case.
class Person(DeclarativeBase):
__tablename__ = "Persons"
p = Person()
print isinstance(p, DeclarativeBase)
#prints True
#However in my scenario, I do not have the DeclarativeBase available
#since the DeclarativeBase will be constructed in the depending web app
#while my code will act as a library that will be imported into the web app
#what are my alternatives?
You can use class_mapper() and catch the exception.
Or you could use _is_mapped_class, but ideally you should not as it is not a public method.
from sqlalchemy.orm.util import class_mapper
def _is_sa_mapped(cls):
try:
class_mapper(cls)
return True
except:
return False
print _is_sa_mapped(MyClass)
# #note: use this at your own risk as might be removed/renamed in the future
from sqlalchemy.orm.util import _is_mapped_class
print bool(_is_mapped_class(MyClass))
for instances there is the object_mapper(), so:
from sqlalchemy.orm.base import object_mapper
def is_mapped(obj):
try:
object_mapper(obj)
except UnmappedInstanceError:
return False
return True
the complete mapper utilities are documented here: http://docs.sqlalchemy.org/en/rel_1_0/orm/mapping_api.html
Just a consideration: since specific errors are raised by SQLAlchemy (UnmappedClassError for calsses and UnmappedInstanceError for instances) why not catch them rather than a generic exception? ;)

Serializing and unserializing case classes with lift-json

I'm attempting basic serialization/hydration with lift-json, but without success. As near as I can tell from the package readme, this should work. Help?
I'm using Scala 2.8.0 and Lift 2.2 cross-built for 2.8 with sbt ("net.liftweb" %% "lift-json" % "2.2").
import net.liftweb.json._
import net.liftweb.json.Serialization.{read, write}
implicit val formats = Serialization.formats(NoTypeHints)
case class Route(title: String)
val rt = new Route("x277a1")
val ser = write(rt)
// ser: String = {} ...
val deser = read[Route]("""{"title":"Some Title"}""")
// net.liftweb.json.MappingException: Parsed JSON values do not match with class constructor
Lift JSON's serialization does not work for case classes defined in REPL (paranamer can't find the bytecode to read the type metadata). Compile Route with scalac and then the above example works.
The same problem applies every time when the (de)serialuzed class is not on the classpath. In such case, paranamer can't read the parameter names. It is necessary to provide a custom ParameterNameReader.
Such problem applies for e.g.:
REPL (as mentioned) - unless you define the class outside the REPL and add via classpath.
Play Framework - unless you provide a simple custom ParameterNameReader (see below) or load the (de)serialized class as a Maven/Play/... dependency
Feel free to add another situation (you can edit this post).
The PlayParameterNameReader:
import net.liftweb.json.ParameterNameReader
import java.lang.reflect.Constructor
import play.classloading.enhancers.LocalvariablesNamesEnhancer
import scala.collection.JavaConversions._
object PlayParameterReader extends ParameterNameReader{
def lookupParameterNames(constructor: Constructor[_]) = LocalvariablesNamesEnhancer.lookupParameterNames(constructor)
}