Importing a deck in anki python - python

I am working on an addon, for anki, which requires me to import a new deck using its python API. I found the function called test_apkg which seems to have parts which do that. I tried implimenting that below, I am getting no errors, however the deck does not get imported. How do I make my testFunction() import a deck for anki?
from aqt import mw
from aqt.utils import showInfo, qconnect
from aqt.qt import *
from anki.importing import *
import os
from anki.collection import Collection as aopen
#from anki.pylib.tests.shared import getEmptyCol
from .shared import getEmptyCol
def testFunction() -> None:
file = "flashcards.apkg"
col = getEmptyCol()
apkg = r"path_to_file/flashcards.apkg"
imp = AnkiPackageImporter(col, apkg)
imp.run()
# create a new menu item, "test"
action = QAction("Import", mw)
# set it to call testFunction when it's clicked
qconnect(action.triggered, testFunction)
# and add it to the tools menu
mw.form.menuTools.addAction(action)

Related

Is this the right way to "publish" msg to the topic?

Currently learning ROS with LGSVL Simulator. I want to publish to "/move_base_simple/goal" topic.
In main code just showing important "import" and the end of the code
import rospy
import roslibpy
from rospy import rostime
import lgsvl
import logging
from environs import Env
from geometry_msgs.msg import PoseStamped
import publisher
### LGSVL SETUP ###
...
###################
ego.set_destination(publisher.GoalPublisher.publish_2d_nav_goal(self=publisher.GoalPublisher,pose_x=9425.16015625, pose_y=9823.15527344, pose_z=0.0))
ros = roslibpy.Ros(host='localhost', port=9090)
ros.run()
sim.run()
This is my publisher
import rospy
import rospkg
import std_msgs
from geometry_msgs.msg import PoseStamped
class GoalPublisher():
def __init__(self):
rospy.init_node('webapp', disable_signals=True)
self.goal_publisher = rospy.Publisher("move_base_simple/goal", PoseStamped, queue_size=10)
def publish_2d_nav_goal(self, pose_x, pose_y, pose_z):
goal = PoseStamped()
goal.header.stamp = rospy.Time.now()
goal.header.frame_id = "map"
goal.pose.position.x = pose_x
goal.pose.position.y = pose_y
goal.pose.position.z = pose_z
goal.pose.orientation.x = 0.0
goal.pose.orientation.y = 0.0
goal.pose.orientation.z = -0.663932738254
goal.pose.orientation.w = 0.747792296747
self.goal_publisher.publish(goal)
When i am trying to start my main code, i get this error:rospy.exceptions.ROSInitException: time is not initialized. Have you called init_node()?
Do i need to add "rospy.init_node(...)" in the main code ? Or how can i fix this issue ?
You need to call rospy.init_node() for every ros node you create. You can call it wherever you want in the node, however, it must be called before trying to use anything in the ros api. In this example your publisher is fine but you're calling roslibpy.Ros() before initializing the main code as it's own node.
rospy.init_node('main_node')
ego.set_destination(publisher.GoalPublisher.publish_2d_nav_goal(self=publisher.GoalPublisher,pose_x=9425.16015625, pose_y=9823.15527344, pose_z=0.0))
ros = roslibpy.Ros(host='localhost', port=9090)
ros.run()
sim.run()

Python Class Initialization Error. Cannot initialize an Imported class

I am trying to initialize a class ModuleLMPC from commander.py which is the main class. I get following error.
File "D:\CARLA\PythonAPI\examples\fnc\commander.py", line 89, in __init__
self.LMPC = ModuleLMPC(self.dt, self.LapTime, self.maxLaps, self.Map)
TypeError: 'module' object is not callable
I import ModuleLMPC as:
from ModuleLMPC import ModuleLMPC
I am trying to import ModuleLMPC from ModuleLMPC.py file. They have the same name.
The ModuleLMPC first few lines look like:
from SysModel import Simulator, PID
from Classes import ClosedLoopData, LMPCprediction
from PathFollowingLTVMPC import PathFollowingLTV_MPC
from PathFollowingLTIMPC import PathFollowingLTI_MPC
from LMPC import ControllerLMPC
from Utilities import Regression
import numpy as np
import pdb
import pickle
class ModuleLMPC(object):
def __init(self, dt, Time, maxlaps, map):
# ======================================================================================================================
# ============================ Choose which controller to run ==========================================================
# ======================================================================================================================
self.RunPID = 1
self.RunMPC = 1
And I initialize ModuleLMPC in commander.py as:
self.LMPC = ModuleLMPC(self.dt, self.LapTime, self.maxLaps, self.Map)
I even moved everything in the same folder. Not sure what the error means.

how to solve classes parameter "self"

I tried to execute the code to create class as client but the problem display talk about the Self._public_key is not defined
...NameError: name 'self' is not defined
# import libraries
import hashlib
import random
import string
import json
import binascii
import numpy as np
import pandas as pd
import pylab as pl
import logging
import datetime
import collections
# following imports are required by PKI
import Crypto
import Crypto.Random
from Crypto.Hash import SHA
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
class Client:
def __init__(self):
random = Crypto.Random.new().read
self._private_key = RSA.generate(1024, random)
self._public_key = self._private_key.publickey()
self._signer = PKCS1_v1_5.new(self._private_key)
def identity(self):
return
binascii.hexlify(self._public_key.exportKey(format='DER')).decode('ascii')
Dinesh = Client()
print (Dinesh.identity)
You are writing binascii.hexlify(self._public_key.exportKey(format='DER')).decode('ascii') at the next line. Try writing it after the return keyword. Hope your error will go away
you should define a Clinet instance and then get it's _public_key:
binascii.hexlify(Client._public_key.exportKey(format='DER')).decode('ascii')
You need to get the identity property with the help of a function, not as a plain attribute. Modify your identity() function as follows:
def identity(self):
idn = binascii.hexlify(self._public_key.exportKey(format='DER')).decode('ascii') # <------
return idn # <------
And then, you can call it like:
Dinesh = Client()
print(Dinesh.identity()) # <------

How to trigger a function without importing everything?

I programmed a gateway to a opcua-server with python-opcua.
The gateway is subscribing some values in the opcua. That is working good and fast.
Now I want to call a script that writes to the opcua.
In principle, it works too. But because I have to import the whole gateway(and all opcua stuff), it is very slow...
My Question: Is is possible to trigger a function in my class-instance without imorting everything?
To start e.g. function setBool(), I have to import Gateway...
#!/usr/bin/env python3.5 -u
# -*- coding: utf-8 -*-
import time
import sys
import logging
from logging.handlers import RotatingFileHandler
from threading import Thread
from opcua import Client
from opcua import ua
from subscribeOpcua import SubscribeOpcua
from cmdHandling import CmdHandling
from keepConnected import KeepConnected
class Gateway(object):
def __init__(self):
OPCUA_IP = '1.25.222.222'
OPCUA_PORT = '4840'
OPCUA_URL = "opc.tcp://{}:{}".format(OPCUA_IP, str(OPCUA_PORT))
addr = "OPCUA-URL:{}.".format(OPCUA_URL)
# Setting up opcua-handler
self.client = Client(OPCUA_URL)
self.opcuaHandlers = [SubscribeOpcua()]
# Connect to opcua
self.connecter = KeepConnected(self.client,self.opcuaHandlers)
self.connecter.start()
def setBool(self, client):
"""Set e boolean variable on opcua-server.
"""
path = ["0:Objects","2:DeviceSet"...]
root = client.get_root_node()
cmd2opcua = root.get_child(path)
cmd2opcua.set_value(True)
if __name__ == "__main__":
"""Open connecter when gateway is opened directly.
"""
connect = Gateway()
The only way to prevent a code from runing when importing a module is to put it inside a method:
def import_first_part():
global re
global defaultdict
print('import this first part')
# import happen locally
# because when you do `import re` actually
# re = __import__('re')
import re
from collections import defaultdict
def import_second_part():
print('import pandas')
# really unnecessary check here because if we import
# pandas for the second time it will just retrieve the object of module
# the code of module is executed only in the first import in life of application.
if 'pandas' in globals():
return
global pandas
import pandas
def use_regex():
import_first_part()
# do something here
if __name__ == '__main__':
use_regex()
re.search('x', 'xb') # works fine
I checked that 'pandas' is in global scope before reimport it again but really this is not necessary, because when you import a module for the second time it's just retrieved no heavy calculation again.

Script crashes when called from a second script

I have a report generation script (let's call this script A)that generates a PDF report. I want to import this in a new script (script B) and call the functions from within this new script.
The problem:
Script A crashes when called from Script B exactly at the creation of a QPixmap object. Python console restarts.
Script A runs fine when it is run on its own, but if I try to call it from Command Prompt python.exe crashes.
The following is Script B. All it does is it imports Script A, creates an instance of a class defined in A, and uses that to call a method of that object.
import Script A as et
a = "sample"
mdbPath = "C:\\Python27\\test.mdb"
directory = "C:\\Python27"
ui = et.HawkAutomationScript()
ui.Main(mdbPath,directory,a)
Script A contains the definition of a class called HawkAutomationScript. This object contains two functions to note: one Main function and one function to generate the report. These are the imported modules:
from random import*
import sys
import os
import subprocess
import time
from datetime import datetime
from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import QRect
from PyQt4.QtGui import QTextDocument, QPrinter, QApplication, QPainter
from string import Template
import shutil
import time
import pyodbc
This is the definition of the class and the Main function:
doc = QTextDocument()
myCursor = QtGui.QTextCursor(doc)
class HawkAutomationScript(object):
def Main(self,mdb,directory,name):
Ui_FormObject = HawkAutomationScript()
## Filling in the Report ##
Ui_FormObject.fnGenerateReport(directory,name)
def fnGenerateReport(self,directory,name):
now = datetime.now()
dateString = now.strftime("%d-%b-%Y") # For getting Current Date
dirPath = "C:\\"
ResultName = "SelfTest_Results"
testName = name+".pdf"
subDirPath = dirPath + name
if(os.path.isdir(dirPath)):
if(os.path.isdir(subDirPath)):
subDirPath = subDirPath + testName
else:
os.mkdir(subDirPath)
subDirPath = subDirPath + testName
else:
os.mkdir(dirPath)
os.mkdir(subDirPath)
subDirPath = subDirPath + testName
pixmap = QtGui.QPixmap(doc.size().width(), doc.size().height()) ################
printer = QPrinter()
printer.setOutputFileName(subDirPath)
printer.setOutputFormat(QPrinter.PdfFormat)
doc.print_(printer)
# Create a QPainter to draw our content
painter = QPainter(pixmap)
painter.begin( printer )
doc.drawContents(painter)
painter.end()
This is all the relevant code and it is runnable.
If I run script B, A crashes at the QPixmap line marked in the code. But if I copy the lines from B and run A on its own, the PDF report is generated. But if I run A on its own from Command Prompt python.exe crashes.
Any help would be really appreciated. Thank you!!

Categories

Resources