cannot import name 'MDToolbar' from 'kivymd.uix.toolbar' - python-3.x

I am trying to run the below code,
from kivymd.uix.screen import MDScreen
from kivymd.app import MDApp
from kivy.uix.image import Image
from kivymd.uix.button import MDFillRoundFlatIconButton, MDFillRoundFlatButton
from kivymd.uix.textfield import MDTextField
from kivymd.uix.label import MDLabel
from kivymd.uix.toolbar import MDToolbar
class ConverterApp(MDApp):
def build(self):
screen = MDScreen()
self.toolbar = MDToolbar(title = 'Binary to Decimal')
self.toolbar.pos_hint = {'top':1}
screen.add_widget(self.toolbar)
return screen
if __name__ == '__main__':
ConverterApp().run()
But seeing a output error, which is
from kivymd.uix.toolbar import MDToolbar
ImportError: cannot import name 'MDToolbar' from 'kivymd.uix.toolbar'
I even searched on google, regarding this module error, but didn't get the required answer.
Can anyone solve this issue?

Related

How to pass variable from views to model in Django

Models.py
from django.db import models
class Voiceapi(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=200)
voice_text = models.CharField(max_length=200,default="voice_data")
Views.py
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
from rest_framework import viewsets
import requests
import gdown
from pydub import AudioSegment
import speech_recognition as sr
from .serializers import *
from .models import *
import time
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
from urllib.request import urlopen
# create a viewset
class VoiceViewSet(viewsets.ModelViewSet):
# define queryset
queryset = Voiceapi.objects.all()
# specify serializer to be used
serializer_class = VoiceSerializer
#
print(Voiceapi.objects.values())
datas = Voiceapi.objects.values()
print(datas)
for i in datas:
try:
print("Audio File-->",i['name'])
audio_url = i['name']
audio_id = i['id']
def VoiceRecognizer(audio,audio_id):
r = sr.Recognizer()
with sr.AudioFile(audio) as source:
audio_text = r.listen(source)
try:
text = r.recognize_google(audio_text)
print(text)
Voiceapi.objects.filter(pk=audio_id).update(voice_text=text)
except:
print('Audio Not Clear')
audio = "/home/venpep/voicetotext/messages/media/test.wav"
VoiceRecognizer(audio,audio_id)
except:
print("Not audio file")
I need to pass the variable "text" from my view.py to models.py to set the default in voice_text.Is there any solution to get the text from the view page. The text variable is a basic string that needs to pass to the models.py
as I understood from your comment, you can override the save method in django model and put your logic, in this way you can edit field value before save it and send it in response
class Voiceapi(models.Model):
...
def save(self, *args, **kwargs):
...

Author's code works but mine doesn't [Kivy]

I'm learning from a book about making apps with Kivy and there's this block of code:
from kivy.app import App
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
class TestApp(App):
press_count = 1
def button_press(self, button_pressed):
print('Button Pressed', TestApp.press_count, 'TImes')
TestApp.press_count += 1
def build(self):
my_btn = Button(text='Click Me')
my_btn.bind(on_press=TestApp.button_press)
textinput = TextInput(text='Data Inside TextInput')
box_layout = BoxLayout(orientation='vertical')
box_layout.add_widget(widget=my_btn)
box_layout.add_widget(widget=textinput)
return box_layout
if __name__ == '__main__':
TestApp().run()
when I run this I get understandably TypeError: button_press() missing 1 required positional argument: 'button_pressed' my question is why the author of the book isn't getting this error and the code runs ?
my_btn.bind(on_press=TestApp.button_press)
This is wrong, it should be my_btn.bind(on_press=self.button_press).

How to read a Kivy.properties.NumericProperty value in my code at a specific point

So basically I have a kivy project in which,I have a layout that I use in many classes,as such..I have made in custom and put it in a separate file so I can just reference it from different parts of my code.
Snippet:
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder
Builder.load_string('''
<CustLayout>:
#code here
''')
class CustLayout(BoxLayout):
t_length = NumericProperty(0)
my_len = 0
print(my_len)
def __init__(self, **kwargs):
super(Silvertable,self).__init__(**kwargs)
self.bind(t_length=self.on_t_length)
#This statement is executed after all other prints
print(self.t_length)
def on_t_length(self,instance,length):
#I'd like to get kv file value before the next line
self.my_len = length
print(my_len)
My kiv file:
#:import Silvertable silvertables.Silvertable
#chunk of code
BoxLayout:
Silvertable:
t_length: 5
Here,I DO get the value but unfortunately too late.That is,I get the value after the program has finished.my_len Doesn't change it's still 0
Bind Kivy Properties
The value of my_len is 0 (zero) because the print() functions were executed first before the run() method.
The value of my_len did change from 0 to 5 as per binding on property of t_length.
Please refer to the example and trace for details.
Example
main.py
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import NumericProperty
from kivy.lang import Builder
Builder.load_string('''
<CustLayout>:
t_length: 5
''')
class CustLayout(BoxLayout):
t_length = NumericProperty(0)
my_len = 0
print("\tCustLayout.class level-start: my_len=", my_len)
def __init__(self, **kwargs):
super(CustLayout,self).__init__(**kwargs)
print("\nCustLayout.__init__:")
self.bind(t_length=self.on_t_length)
#This statement is executed after all other prints
print("\tself.t_length=", self.t_length)
print("\tself.my_len=", self.my_len)
def on_t_length(self, instance, length):
print("\nCustLayout.on_t_length:")
#I'd like to get kv file value before the next line
self.my_len = length
print("\tself.my_len=", self.my_len)
print("\tCustLayout.class level-end: my_len=", my_len)
class TestBindProperty(App):
def build(self):
print("\nTestBindProperty.build:")
return CustLayout()
def on_stop(self):
print("\tTestBindProperty.on_stop: my_len=", self.root.my_len)
if __name__ == "__main__":
TestBindProperty().run()
Output

RuntimeError: Please destroy the QApplication singleton before creating a new QApplication instance

When i run python-pyside2 project server first, then it works well.
And the site also work well, but if i press F5 btn to refresh in browser.
Site shows error page Runtime at/
import sys
from urllib.request import urlopen
from bs4 import BeautifulSoup
from PySide2.QtGui import *
from PySide2.QtCore import *
from PySide2.QtWebKitWidgets import *
from PySide2.QtWidgets import QApplication
class dynamic_render(QWebPage):
def __init__(self, url):
self.frame = None
self.app = QApplication(sys.argv)
QWebPage.__init__(self)
self.loadFinished.connect(self._loadFinished)
self.mainFrame().load(QUrl(url))
QTimer.singleShot(0, self.sendKbdEvent)
QTimer.singleShot(100, app.quit)
self.app.exec_()
def _loadFinished(self, result):
self.frame = self.mainFrame()
self.app.quit()
self.app = None
Below, scaping code using pyside2:
I don't know how can i fix it?
Best regards.
Thanks.
Check if already an instance of QApplication is present or not as the error occurs when an instance is already running and you are trying to create a new one.
Write this in your main function:
if not QtWidgets.QApplication.instance():
app = QtWidgets.QApplication(sys.argv)
else:
app = QtWidgets.QApplication.instance()
For my pyside2 unit test the following worked fairly well
import PySide2
import unittest
class Test_qapplication(unittest.TestCase):
def setUp(self):
super(Test_qapplication, self).setUp()
if isinstance(PySide2.QtGui.qApp, type(None)):
self.app = PySide2.QtWidgets.QApplication([])
else:
self.app = PySide2.QtGui.qApp
def tearDown(self):
del self.app
return super(Test_qapplication, self).tearDown()
it was loosely based on stack overflow : unit-and-functional-testing-a-pyside-based-application

Cassandra ExecutionResult on importlib._bootstrap failed

I am trying to execute multi-process to pull the data from Cassandra. But, I'm facing the issue.I want to pull it for single key or multiple keys using the multi-process provided my Cassandra
My cassandra_db class
from cassandra.cluster import Cluster
import cassandra
import pandas as pd
import numpy as np
from datetime import datetime
import sys
import os
from threading import Event
import itertools
from multiprocessing import Pool
from cassandra.concurrent import execute_concurrent_with_args
from cassandra.query import tuple_factory
ip_address = '127.0.0.1'
class cassandra_db(object):
concurrency = 2 # chosen to match the default in execute_concurrent_with_args
def __init__(self,process_count=None):
self.pool = Pool(processes=process_count, initializer=self._setup)
#classmethod
def _setup(cls):
cls.session = Cluster([ip_address]).connect(keyspace='test')
cls.session.row_factory = pandas_factory
cls.prepared = cls.session.prepare('SELECT * FROM tr_test WHERE key=?')
def close_pool(self):
self.pool.close()
self.pool.join()
def get_results(self, params):
try:
xrange
except NameError:
xrange = range
params = list(params)
print("-----> ",params)
print("-----+>",self.concurrency)
self.pool.map(_multiprocess_get, (params[n:n + self.concurrency] for n in xrange(0, len(params), self.concurrency)))
#classmethod
def _results_from_concurrent(cls, params):
return execute_concurrent_with_args(cls.session, cls.prepared, params)
def _multiprocess_get(params):
return cassandra_db._results_from_concurrent(params)
My calling class
import os
import pandas as pd
import sys
relative_path='/home/anji'
sys.path.append(os.path.join(relative_path ,'commons','Database Operations'))
from cassandra.cluster import Cluster
from cassandra.auth import PlainTextAuthProvider
from cassandra_db import cassandra_db
from cassandra.policies import ConstantReconnectionPolicy
processes =2
con_db = cassandra_db(processes)
keys=[(1,),(2,)]
df = con_db.get_results(keys)
print("Result",df.head())
Error:
multiprocessing.pool.MaybeEncodingError: Error sending result: '[[ExecutionResult(success=True, result_or_exc=<cassandra.cluster.ResultSet object at 0x7fa93658bbe0>), ExecutionResult(success=True, result_or_exc=<cassandra.cluster.ResultSet object at 0x7fa936a2e0f0>)]]'. Reason: 'PicklingError("Can't pickle <class 'importlib._bootstrap.ExecutionResult'>: attribute lookup ExecutionResult on importlib._bootstrap failed",)'
My trying to execute for 2 keys but facing the issue. Can any help me to solve this issue

Resources