Can't import sikuli modules from Sikuli IDE 1.0.0 - sikuli

I'm using Sikuli IDE 1.0.0 on Mac, trying to get a simple test case working where I call a script in one module from another.
The modules are all in the same directory.
testModule.sikuli just has this:
from sikuli import *
def testFunc():
exit(1)
testImport.sikuli just has this:
import testModule
reload(testModule)
testModule.testFunc()
running testImport just yields:
[error] ImportError ( No module named testModule )
on the import testModule line.
I've tried various additions to testImport including:
myScriptPath="[my project path]"
if not myScriptPath in sys.path: sys.path.append(myScriptPath)
None of these seem to work.

I think the import just brings the new functions into the same module.
Try calling testFunc() instead of testModule.testFunc().

I've encountered the same issue. I have solved this problem using classes.
Try this code:
testModule.sikuli:
from sikuli import *
class test:
def testFunc(self):
exit(1)
testImport.sikuli:
import testModule
foo = testModule.test()
foo.testFunc()
This should work assuming your files are in the same folder (for example ./test/testImport.sikuli and ./test/testModule.sikuli)

Related

Avoid using web-only libraries outside Flutter web plugin packages

I'm building a Flutter app that I am trying to make work on the web. Part of it contains some web specific code:
import 'dart:html' as html;
import 'package:flutter/foundation.dart';
class DownloadViewModel extends ChangeNotifier {
static const String url = 'https://example.com/api/v1/app/myapp_1.0.0.apk';
void onAndroidDownloadPressed() {
html.window.open(url, 'AndroidApp');
}
}
However the dart:html import gives the following error:
Avoid using web-only libraries outside Flutter web plugin packages
The longer version of the warning looks like this:
Avoid using web libraries, dart:html, dart:js and dart:js_util in
Flutter packages that are not web plugins. These libraries are not
supported outside a web context; functionality that depends on them
will fail at runtime in Flutter mobile, and their use is generally
discouraged in Flutter web.
Web library access is allowed in:
plugin packages that declare web as a supported context
otherwise, imports of dart:html, dart:js and dart:js_util are disallowed.
And it's not just a warning. This actually prevents building an Android or iOS app (even though this method isn't accessible from non-Web Flutter apps).
The only solution I've figured out is to comment out the import when I am building for Android and iOS and then uncomment it when I am building for the web. Is there a better solution?
Use the universal_html package. It supports the browser, Dart VM, and Flutter and is a stand-in replacement for dart:html and other web related libraries.
dependencies:
universal_html: ^1.2.1
Then instead of using import 'dart:html' as html; you can use the following import:
import 'package:universal_html/html.dart' as html;
For those who came to this page for other related web import problems (like dart:js), this plugin also supports the following imports:
import 'package:universal_html/driver.dart';
import 'package:universal_html/html.dart';
import 'package:universal_html/indexed_db.dart';
import 'package:universal_html/js.dart';
import 'package:universal_html/js_util.dart';
import 'package:universal_html/prefer_sdk/html.dart';
import 'package:universal_html/prefer_sdk/indexed_db.dart';
import 'package:universal_html/prefer_sdk/js.dart';
import 'package:universal_html/prefer_sdk/js_util.dart';
import 'package:universal_html/prefer_sdk/svg.dart';
import 'package:universal_html/prefer_sdk/web_gl.dart';
import 'package:universal_html/prefer_universal/html.dart';
import 'package:universal_html/prefer_universal/indexed_db.dart';
import 'package:universal_html/prefer_universal/js.dart';
import 'package:universal_html/prefer_universal/js_util.dart';
import 'package:universal_html/prefer_universal/svg.dart';
import 'package:universal_html/prefer_universal/web_gl.dart';
import 'package:universal_html/svg.dart';
import 'package:universal_html/web_gl.dart';
Since the merge of Flutter-web into the main Flutter repository, it's no longer possible to directly add imports for web libraries (e.g. dart:html, or dart:js) in a Flutter project on the main channel when targeting Web, Android and iOS.
Use the universal html package which provides extensive support for multiple platforms and web libraries.
From the root level of your project, command
flutter pub add universal_html
import 'package:universal_html/html.dart' as html
This package isn't required to run some web files (e.g. dart:js). In my case, I just had to remove the import 'dart:js' import statement.

Django MySQL Error (1146, "Table 'db_name.django_content_type' doesn't exist")

I am getting the error
django.db.utils.ProgrammingError: (1146, "Table 'db_name.django_content_type' doesn't exist")
when trying to do the initial migration for a django project with a new database that I'm deploying on the production server for the first time.
I suspected the problem might be because one of the the apps had a directory full of old migrations from a SQLite3 development environment; I cleared those out but it didn't help. I also searched and found references to people having the problem with multiple databases, but I only have one.
Django version is 1.11.6 on python 3.5.4, mysqlclient 1.3.12
Some considerations:
Are you calling ContentType.objects manager anywhere in your code that may be called before the db has been built?
I am currently facing this issue and need a way to check the db table has been built before I can look up any ContentTypes
I ended up creating a method to check the tables to see if it had been created, not sure if it will also help you:
def get_content_type(cls):
from django.contrib.contenttypes.models import ContentType
from django.db import connection
if 'django_content_type' in connection.introspection.table_names():
return ContentType.objects.get_for_model(cls)
else:
return None
As for migrations, my understanding is that they should always belong in your version control repo, however you can squash, or edit as required, or even rebuild them, this linked helps me with some migrations problems:
Reset Migrations
Answering my own question:
UMDA's comment was right. I have some initialization code for the django-import-export module that looks at content_types, and evidently I have never deployed the app from scratch in a new environment since I wrote it.
Lessons learned / solution:
will wrap the offending code in an exception block, since I should
only have this exception once when deploying in a new environment
test clean deployments in a new environment more regularly.
(edit to add) consider whether your migrationsdirectories belong in .gitignore. For my purposes they do.
(Relatively new to stackoverflow etiquette - how do I credit UMDA's comment for putting me on the right track?)
I had the same issue when trying to create a generic ModelView (where the model name would be passed as a variable in urls.py). I was handling this in a kind of silly way:
Bad idea: a function that returns a generic class-based view
views.py
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.contenttypes.models import ContentType
from django.views.generic.edit import DeleteView
def get_generic_delete_view(model_name):
model_type = ContentType.objects.get(app_label='myapp', model=model_name)
class _GenericDelete(LoginRequiredMixin, DeleteView):
model = model_type.model_class()
template_name = "confirm_delete.html"
return _GenericDelete.as_view()
urls.py
from django.urls import path, include
from my_app import views
urlpatterns = [
path("mymodels/<name>/delete/", views.get_generic_delete_view("MyModel"),
]
Anyway. Let's not dwell in the past.
This was fixable by properly switching to a class-based view, instead of whatever infernal hybrid is outlined above, since (according to this SO post) a class-based view isn't instantiated until request-time.
Better idea: actual generic class-based view
views.py
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.contenttypes.models import ContentType
from django.views.generic.edit import DeleteView
class GenericDelete(LoginRequiredMixin, DeleteView):
template_name = "confirm_delete.html"
def __init__(self, **kwargs):
model = kwargs.pop("model")
model_type = ContentType.objects.get(app_label='myapp', model=model)
self.model = model_type.model_class()
super().__init__()
urls.py
from django.urls import path, include
from my_app import views
urlpatterns = [
path("mymodels/<name>/delete/", views.GenericDelete.as_view(model="MyModel"),
]
May you make new and better mistakes.
Chipping in because maybe this option will appeal better in some scenarios.
Most of the project's imports usually cascade down from your urls.py. What I usually do, is wrap the urls.py imports in a try/except statement and only create the routes if all imports were successful.
What this accomplishes is to create your project's / app's routes only if the modules were imported. If there is an error because the tables do not yet exist, it will be ignored, and the migrations will be done. In the next run, hopefully, you will have no errors in your imports and everything will run smoothly. But if you do, it's easy to spot because you won't have any URLs. Also, I usually add an error log to guide me through the issue in those cases.
A simplified version would look like this:
# Workaround to avoid programming errors on greenfield migrations
register_routes = True
try:
from myapp.views import CoolViewSet
# More imports...
except Exception as e:
register_routes = False
logger.error("Avoiding creation of routes. Error on import: {}".format(e))
if register_routes:
# Add yout url paterns here
Now, maybe you can combine Omar's answer for a more sensible, less catch-all solution.

Python error: argument -c/--conf is required

I'm new in python, my native language is C. I'm doing a code in python for a surveillance system triggered by motion using OpenCV. I based my code in the one made by Adrian Rosebrock in his blog pyimagesearch.com. Originally the code was developed for a Raspiberry Pi with a Pi Camera module attached to it, now I'm trying to adapt to my notebook's webcam. He made a easier tutorial about a simple code for motion detection and it worked very nicely in my PC. But I'm having a hardtime with this other code. Probably it's a silly mistake, but as begginer I couldn't found a specific answer to this issue.
This image have the part of the code that is causing the error (line 15) and the structure of the project on the left side of the screen. Image of python project for surveillance.
Similar part, originall code:
# import the necessary packages
from pyimagesearch.tempimage import TempImage
from dropbox.client import DropboxOAuth2FlowNoRedirect
from dropbox.client import DropboxClient
from picamera.array import PiRGBArray
from picamera import PiCamera
import argparse
import warnings
import datetime
import imutils
import json
import time
import cv2
# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-c", "--conf", required=True,
help="path to the JSON configuration file")
args = vars(ap.parse_args())
# filter warnings, load the configuration and initialize the Dropbox
# client
warnings.filterwarnings("ignore")
conf = json.load(open(args["conf"]))
client = None
Until now I only change these things:
Exclude the imports relatives to pi camera.
Change camera = PiCamera() by camera = cv2.VideoCapture(0). This way I use notebook's webcam.
Exclude:
camera.resolution = tuple(conf["resolution"])
camera.framerate = conf["fps"]
rawCapture = PiRGBArray(camera, size=tuple(conf["resolution"]))
Substitute the line for f in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True): by while True:.
Exclude two lines in program that was rawCapture.truncate(0).
Probably there is more things to repair, if you now please tell me, but first I'd like to understand how solve that mensage error. I use PyCharm in Windows 7 with Python 2.7 and OpenCV 3.1. Sorry for not post the entire code, but once that this is my first question in the site and I have 0 reputation, apparently I can just post 2 links. The entire originall code is in the pyimagesearch.com. Thank you for your time!
I think you probably not running it properly. Error message is clear. You are adding argument that means you need to provide them while running which you are not doing.
Check this how he ran this in tutorial link you provided
http://www.pyimagesearch.com/2015/06/01/home-surveillance-and-motion-detection-with-the-raspberry-pi-python-and-opencv#crayon-56d3c5551ac59089479643
Notice on the Figure 6 screen capture in #Rhoit's link.
python pi_surveillance.py --conf conf.json
The program was initialized with the name and these --conf conf.json words.
In your code:
ap = argparse.ArgumentParser()
ap.add_argument("-c", "--conf", required=True,
help="path to the JSON configuration file")
ap is a piece of code that reads these inputs from the commandline, and parses the information. This definition specifies that a --conf argument is required, as demonstrated in Figure 6.
The error indicates that you omitted this information:
argument -c/--conf is required

Scala NoClassDefFoundError related to Swing

I have a GUI class named Gui.scala and Eclipse does not show any errors directly in the scala file. My Scala version is 2.11 and I have manually added scala-swing-2.10.4.jar to my build path in Eclipse. If I don't do this, Eclipse complains that it does not find the Swing library.
First lines of my source code look like this:
package filmreviews
import scala.swing._
import event._
import javax.imageio.ImageIO
import javax.swing.ImageIcon
import java.io.File
import java.awt.image.BufferedImage
import java.net.URI
import java.net.URL
import java.awt.Desktop
import java.awt.Cursor
import java.awt.Color
import javax.swing.border
import javax.swing.BorderFactory
import javax.swing.UIManager
object Gui extends SimpleSwingApplication {
def top = new MainFrame {
...more code here...
I get the following error:
Exception in thread "AWT-EventQueue-0" java.lang.NoClassDefFoundError: scala/collection/GenTraversableOnce$class
Also, there is a long list telling where in code the error happened. Only lines referring to my own code are:
at filmreviews.Gui$$anon$3.<init>(Gui.scala:17)
at filmreviews.Gui$.top(Gui.scala:17)
at filmreviews.Gui$.top(Gui.scala:16)
This is why I think it is related to the creation of the MainFrame object. It can also be related to how I have manually added the Swing library to the build path. However, I don't know what causes the error or how to fix it.
If you're using Scala 2.11, you will need a version of scala-swing built for 2.11. 2.10.4 is binary incompatible with 2.11.
You can find the jar for a 2.11-compatible version on maven central.
Or for those using sbt:
libraryDependencies += "org.scala-lang.modules" %% "scala-swing" % "1.0.1"

Geronimo FTP Server on Fedora 19

I am trying to use the FTP server (factory) in Geronimo 3.0.1 on Fedora 19, in eclipse kepler. I have the following import which produces no error:
import org.apache.mina.*;
However, when I declare
FTPServerFactory ftpFactory;
FTPServer ftpServer;
neither of FTPServer and FTPServerFactory is resolvable. The usual eclipse hints in the editor, which are very cool, offer no help in this case. My build path has the mina-core.jar (This is the only MINA jar that I find in /usr/share/java/apache-mina). The build path dialog flags errors, not explicitly for mina, stating the the following are missing:
org.eclipse.JRE_CONTAINER/
org.eclipse.jdt.internal.debug.uio.launcher.StandardVMType/
java-1.7.0-openjdk-1.7.0.25.x86-64
I suspect that my installation is missing other mina jars and am at a loss for the three errors above except that the last one is strange given that the that the build path has
java-1.7.0-openjdk-1.7.0
My environment is all relatively new, so there could be problems in a number of places. Any advice on where to start?
Thanks in advance.
I am not sure what happened when I logged in. Please disregard the empty question.
I have the following, which does not produce errors.
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.ftplet.FtpReply;
import org.apache.ftpserver.ftplet.FtpRequest;
import org.apache.ftpserver.ftplet.FtpSession;
import org.apache.ftpserver.ftplet.Ftplet;
import org.apache.ftpserver.ftplet.FtpletContext;
import org.apache.ftpserver.ftplet.FtpletResult;
import org.apache.ftpserver.listener.ListenerFactory;
import org.apache.ftpserver.ssl.SslConfigurationFactory;
import org.apache.ftpserver.usermanager.*;
import org.apache.ftpserver.usermanager.impl.BaseUser;
My build path includes
ftpserver-core-1.06.jar - /usr/share/java/apache-ftpserver/common/lib
A code fragment follows
//Add the user to the FTP server as well.
PropertiesUserManagerFactory userManagerFactory = new PropertiesUserManagerFactory();
userManagerFactory.setFile(new File("myusers.properties"));
userManagerFactory.setPasswordEncryptor(new SaltedPasswordEncryptor());
org.apache.ftpserver.ftplet.UserManager um = userManagerFactory.createUserManager();
BaseUser user = new BaseUser();
user.setName(newCredentials.getUserID());
user.setPassword(ConfigurationValues.get("ftpGenericPassword"));
new File(ConfigurationValues.get("ftpFilesRoot")+newCredentials.getUserID());
user.setHomeDirectory("ftproot");
um.save(user);
I hope this is of use. Takes a little burrowing to sort it out.