PyQt5 overriding QDockwidget event bug? - events

I have the following problem where I want to customize the QDockwidget event function and calling super() already gives me an error withouth Code in it.
Error:
TypeError: invalid result from DockWindow.event(), an integer is required (got type NoneType)
Here is my actual Code:
from PyQt5.QtWidgets import QApplication, QDockWidget
from PyQt5.QtWidgets import QMainWindow
from PyQt5 import QtCore
import sys
class DockWindow(QDockWidget):
def __init__(self, parent=None):
super(DockWindow, self).__init__(parent, QtCore.Qt.Widget)
def event(self, ev):
# I actually want to do stuff here. But following already produces an error.
super(DockWindow, self).event(ev)
class MainWindow(QMainWindow):
def __init__(self, parent=None):
super().__init__(parent, QtCore.Qt.Window)
self.dock_window = DockWindow(parent=self)
self.addDockWidget(QtCore.Qt.RightDockWidgetArea, self.dock_window)
def main(argv):
app = QApplication(sys.argv)
win = MainWindow()
win.show()
app.exec_()
if __name__ == '__main__':
main(sys.argv)
EDIT:
return super(DockWindow, self).event(ev)
does the trick!

Related

Problems with SelectMenu discord.py

I'm trying to make SelectMenu to give out roles on the server I need to make it infinite, but I don't understand how. And besides, the one I wrote does not give out roles. I already third day sit with this error, and do not understand what is wrong. Bot does not even show what the error, the console is empty. here is the code. What do I have to do to make it work as intended?
#client.command()
async def sm(inter):
view =None
if inter.author.id == 1012357055987851345:
await inter.send('Text',
components = [
Select(
placeholder = 'Выберете роль',
options = [
SelectOption(label="Роль", value="Девушка"),
SelectOption(label="Роль2", value="Rainbow"),
])])
interaction = await client.wait_for("select_option")
selected = interaction.values[0]
if selected == "Роль":
user = inter.author
role = client.get_role(1029824401878810624)
await inter.user.add_roles(role)
await inter.send("Роли выданы")
if selected == "Роль2":
await user.add_roles(role)
await inter.send("Роли выданы")
And if you can, show me the working version as an example.
imports:
from msilib.schema import Component
from optparse import Option
import discord
from discord.ui import Select, View
import json
import os
import random
import asyncio
import aiohttp
from discord.ext import commands
from dislash import slash_commands
from discord_slash import SlashCommand
from discord_slash import SlashContext
import discord_components
from discord_components import DiscordComponents, Select, SelectOption, Button, ButtonStyle
from discord_components import *
maybe you can use discord.py2, it worked for me

Phaser 3. Importing phaser/src/core/Game produce error during runtime

The phaser game not starting error on
import Game1 from "phaser/src/core/Game";
import { Game } from "phaser";
console.log(Game1, Game);
const app = new Game1(gameSettings);
the following output of the console log which are similar class:
but when I trie to make use the one from the phaser js directly, no error found
import { Game } from "phaser";
const app = new Game(gameSettings);
Thanks in advance for answers which part I do wrong.
In all example I found on the web I see this kind of imports for Phaser
import 'phaser';
import Phaser from 'phaser';
import * as Phaser from 'phaser';
and then boot the game with
new Phaser.Game(config)

how to share a session object created in fixture having scope as session in pytest / unittest tests

we are creating tests by implementing unittest and pytest in python. we want to use fixtures for doing setup and tear down at session and test level.
How to use object created in setup session fixture to be used in setup of function fixture. Example I want to create a driver object like driver = webdriver.Chrome() of intializing the browser and using the driver object in test methods and function scope fixture.
conftest.py
import pytest
#pytest.fixture(scope="session")
def setupsession():
print("Starting Session")
yield
print("Ending Session")
#pytest.fixture(scope="module")
def setupmodule(request):
print("starting module")
yield
print("Ending Module")
#pytest.fixture(scope="class")
def setupclass(request):
print("starting module")
yield
print("Ending Module")
Basetest.py
import unittest
class BaseTest(unittest.TestCase):
def setUp(self):
print("inside Base setup")
def tearDown(self):
print("inside base teardown")
test.py
import pytest
from wav2.fixtures.base_test import BaseTest
#pytest.mark.usefixtures("setupsession", "setupmodule")
class TestSample(BaseTest):
def test1(self):
print("calling inside test test1")
self.assertTrue(False)
def test2(self):
print("calling inside test tes`enter code here`t2")
A fixture can use other fixture too. That means you can use a session fixture inside a module fixture, you can use a module fixture inside a class fixture and so on. You can also use same scope fixture in other fixture. Only 2 limit is that you can not import a fixture backwards (like using a function level fixture in the class level fixture) and there can not be a circular dependency.
Please find the same example given in question with an additional fixture with scope=function and using a fixture inside another fixture.
conftest.py
import pytest
import unittest
#pytest.fixture(scope="session")
def setupsession(request):
print("Starting Session")
yield "session_obj"
print("Ending Session")
#pytest.fixture(scope="module")
def setupmodule(request, setupsession):
print("starting module")
yield setupsession, "module_obj"
print("Ending Module")
#pytest.fixture(scope="class")
def setupclass(request, setupmodule):
print("starting class")
yield (*setupmodule, "class_obj")
print("Ending class")
#pytest.fixture(scope="function")
def setupmethod(request, setupclass):
print("starting method")
yield (*setupclass, "class_obj")
print("Ending method")
Note: As we have created setupmethod fixture, it is not necessary to create BaseTest with setUp and tearDown method. But, it's your choice depending on the structure of hte test cases.
test_file.py
#pytest.mark.usefixtures("setupmethod")
class TestSample(BaseTest):
def test1(self):
print("calling inside test test1")
self.assertTrue(False)
def test2(self):
print("calling inside test tes`enter code here`t2")
Reference: http://devork.be/talks/advanced-fixtures/advfix.html

Plone - How can I make a validator validate a field from a behavior for a specific content type?

I am using Plone 4.3 and I have a form.SchemaForm plone.directives have an interface that has a start field from IEventBasic and a validator:
from datetime import timedelta
from plone.directives import form
from plone.app.contenttypes.interfaces import IEvent
from z3c.form import validator
from zope.component import provideAdapter
from zope.interface import Invalid
class IMyObject(form.SchemaForm)
my_field_a = schema.TextLine(title='a_field')
...
class MyObject(Item):
implements(IMyObject, IEvent)
class EndMyObjectValidator(validator.SimpleFieldValidator):
def validate(self,value):
#code for checking if end field is within a certain range from start field
if self.end > self.start + timedelta(days=6):
raise Invalid('The end date is not within range of the start date's week')
validator.WidgetValueDiscriminators(EndMyObjectValidator, field=IEventBasic['end'])
provideAdapter(EndMyObjectValidator)
In my type file (my.object.myobject.xml under profiles/default/types), I place the behavior in the behaviors section.
<behaviors>
<element value="plone.app.event.dx.behaviors.IEventBasic"/>
</behaviors>
The problem is it validates the end field in any Event object or any object that implements the IEventBasic interface/schema.
I thought maybe since the Plone documentation says that the parameters 'view' and 'context' of WidgetValueDiscriminators accept an interface, then I could do either:
validator.WidgetValidatorDiscriminators(EndMyObjectValidator, view=IMyObject, field=IEventBasic['end'])
or
validator.WidgetValidatorDiscriminators(EndMyObjectValidator, context=IMyObject,field=IEventBasic['end']
Unfortunately, none of those trigger at all. I guess I'm misunderstanding what the context and view parameters actually do.
How can I make it so the validators are specifically for dealing with MyObject?
Source: http://docs.plone.org/develop/addons/schema-driven-forms/customising-form-behaviour/validation.html
For now I am doing:
...
from gpcl.container.my_container import MyContainer
...
class EndMyObjectValidator(validator.SimpleFieldValidator):
def validate(self,value):
if self.widgets.form.portal_type <> 'my.object.myobject':
return
...
validator.WidgetValueDiscriminators(EndMyObjectValidator, field=IEventBasic['end'])
provideAdapter(EndMyObjectValidator)
Update 2:
I removed my comment before because it was for an unrelated problem.
I changed the way I was checking for the type.
Ok, register your own Add Form and Subclassing the Default Dexterity Add Form. More Information about Validating in action handlers and Custom Add Forms
in my task.py (Contenttype and so on...):
# -*- coding: utf-8 -*-
from zope.interface import implementer
from zope.interface import Invalid
from z3c.form import button
from z3c.form import validator
from z3c.form import util
from z3c.form.interfaces import ActionExecutionError
from z3c.form.interfaces import WidgetActionExecutionError
from plone.dexterity.content import Item
from plone.dexterity.browser import add
from viisionar.training.interfaces import ITask
from Products.statusmessages.interfaces import IStatusMessage
from my.addon import _
#implementer(ITask)
class Task(Item):
pass
class AddForm(add.DefaultAddForm):
portal_type = 'Task'
def __init__(self, context, request, ti=None):
super(AddForm, self).__init__(context, request, ti=None)
#button.buttonAndHandler(_('Save'), name='save')
def handleAdd(self, action):
print "Handle Add"
data, errors = self.extractData()
if errors:
self.status = self.formErrorsMessage
return
# Your Custom validation
# Debug Do what yo want
print data
if error:
"""
# Global Portal Message
raise ActionExecutionError(Invalid(_(u"Please provide a valid end date")))
# or
# Error Message in Widget
raise WidgetActionExecutionError('IEventBasic.end', Invalid(u"Please put the the right end date"))
"""
# /Your Custom validation
obj = self.createAndAdd(data)
if obj is not None:
# mark only as finished if we get the new object
self._finishedAdd = True
IStatusMessage(self.request).addStatusMessage(
self.success_message, "info"
)
class AddView(add.DefaultAddView):
form = AddForm
in my configure.zcml i register the custom Add form
<adapter
for="
Products.CMFCore.interfaces.IFolderish
zope.publisher.interfaces.browser.IDefaultBrowserLayer
plone.dexterity.interfaces.IDexterityFTI"
provides="zope.publisher.interfaces.browser.IBrowserPage"
factory="my.addon.task.AddView"
name="Task" />
<class class="my.addon.task.AddView">
<require
permission="cmf.AddPortalContent"
interface="zope.publisher.interfaces.browser.IBrowserPage"/>
</class>
in my task.xml Definition:
<property name="factory">Task</property>
<property name="schema">my.addon.interfaces.ITask</property>
<property name="klass">my.addon.task.Task</property>
<property name="behaviors">
<element value="plone.app.content.interfaces.INameFromTitle" />
<element value="plone.app.event.dx.behaviors.IEventBasic"/>
</property>

WebSocketHandler doesn't call initialize

What I'm trying to do, is have an object (it's a gstreamer process that runs in a seperate thread) to be able to call the write_message() function of a WebSocketHandler
Here is a piece of code that I currently have
app = tornado.web.Application([
(r'/', RadioSocketHandler),
])
class RadioSocketHandler(tornado.websocket.WebSocketHandler):
def initialize(self):
self.player = MusicPlayer(self)
thread.start_new(self.player.start(), ())
class MusicPlayer(object):
websocket_handler = None
def __init__(self, sockethandler):
self.websocket_handler = sockethandler
self.websocket_handler.write_message("success")
However, it does not work. 'initialize' is never called. What am I doing wrong?
__init__()
doesn't work either.
Or is there another way to call a function from the RadioSocketHandler outside of it's own class?
I'm quite new to Python fyi
Alright I got it working with the following:
app = tornado.web.Application([
(r'/', RadioSocketHandler, {'player': player}),
])
class RadioSocketHandler(tornado.websocket.WebSocketHandler):
def __init__(self, *args, **kwargs):
self.musicplayer = kwargs.pop('player')
self.musicplayer.set_sockethandler(self)
super(RadioSocketHandler, self).__init__(*args, **kwargs)
class MusicPlayer(object):
websocket_handler = None
def set_sockethandler(self, handler):
self.websocket_handler = handler
I had to give the arguments to the init function on a different way. And I forgot super()

Resources