В программе QtDesigner создал файл, перекинул из формата .ui
в .py
, зашел в Visual Studio Code, и ничего не работает из за ошибки при from PySide2.QtGui import QFontDatabase
выдает ошибку Trailling coma not allowed without surrounding parenthness
from PySide2 import QtCore, QtGui
import sys
from ui import Ui_Form
from PySide2.QtCore import QCoreApplication, QMetaObject, QObject, QPoint, QSize, QUrl, Qt
from PySide2.QtGui import QBrush, QColor, QConicalGradient, QCursor, QFont
from PySide2.QtGui import QFontDatabase, QIcon, QLinearGradient, QPalette, QPainter, QPixmap,
from PySide2.QtGui import QRadialGradient
from PySide2.QtWidgets import *
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
if MainWindow.objectName():
MainWindow.setObjectName(u"MainWindow")
MainWindow.resize(370, 426)
MainWindow.setStyleSheet(u"QPushButton{n"
"height: 70px;n"
"widght: 70px;n"
"font-size: 14 px;n"
"font-weight: bold;n"
"text-align: center;n"
"borders: none;n"
"}n"
"n"
"QPushButton:hover{n"
" background-color: silver;n"
"}n"
"n"
"QPushButton:pressed{n"
" background-color:gold;n"
"}")
self.centralwidget = QWidget(MainWindow)
self.centralwidget.setObjectName(u"centralwidget")
self.gridLayoutWidget = QWidget(self.centralwidget)
self.gridLayoutWidget.setObjectName(u"gridLayoutWidget")
self.gridLayoutWidget.setGeometry(QRect(20, 80, 331, 301))
self.gridLayout = QGridLayout(self.gridLayoutWidget)
self.gridLayout.setObjectName(u"gridLayout")
self.gridLayout.setContentsMargins(0, 0, 0, 0)
self.pushButton_3 = QPushButton(self.gridLayoutWidget)
self.pushButton_3.setObjectName(u"pushButton_3")
self.gridLayout.addWidget(self.pushButton_3, 2, 2, 1, 1)
self.pushButton_2 = QPushButton(self.gridLayoutWidget)
self.pushButton_2.setObjectName(u"pushButton_2")
self.gridLayout.addWidget(self.pushButton_2, 2, 1, 1, 1)
self.pushButton_6 = QPushButton(self.gridLayoutWidget)
self.pushButton_6.setObjectName(u"pushButton_6")
self.gridLayout.addWidget(self.pushButton_6, 1, 2, 1, 1)
self.pushButton_4 = QPushButton(self.gridLayoutWidget)
self.pushButton_4.setObjectName(u"pushButton_4")
self.gridLayout.addWidget(self.pushButton_4, 1, 0, 1, 1)
self.pushButton_7 = QPushButton(self.gridLayoutWidget)
self.pushButton_7.setObjectName(u"pushButton_7")
self.gridLayout.addWidget(self.pushButton_7, 0, 0, 1, 1)
self.pushButton_8 = QPushButton(self.gridLayoutWidget)
self.pushButton_8.setObjectName(u"pushButton_8")
self.gridLayout.addWidget(self.pushButton_8, 0, 1, 1, 1)
self.pushButton_9 = QPushButton(self.gridLayoutWidget)
self.pushButton_9.setObjectName(u"pushButton_9")
self.gridLayout.addWidget(self.pushButton_9, 0, 2, 1, 1)
self.pushButton_5 = QPushButton(self.gridLayoutWidget)
self.pushButton_5.setObjectName(u"pushButton_5")
self.gridLayout.addWidget(self.pushButton_5, 1, 1, 1, 1)
self.pushButton = QPushButton(self.gridLayoutWidget)
self.pushButton.setObjectName(u"pushButton")
self.gridLayout.addWidget(self.pushButton, 2, 0, 1, 1)
self.pushButton_10 = QPushButton(self.gridLayoutWidget)
self.pushButton_10.setObjectName(u"pushButton_10")
self.gridLayout.addWidget(self.pushButton_10, 3, 1, 1, 1)
self.verticalLayoutWidget = QWidget(self.centralwidget)
self.verticalLayoutWidget.setObjectName(u"verticalLayoutWidget")
self.verticalLayoutWidget.setGeometry(QRect(19, 9, 331, 61))
self.verticalLayout = QVBoxLayout(self.verticalLayoutWidget)
self.verticalLayout.setObjectName(u"verticalLayout")
self.verticalLayout.setContentsMargins(0, 0, 0, 0)
MainWindow.setCentralWidget(self.centralwidget)
self.statusbar = QStatusBar(MainWindow)
self.statusbar.setObjectName(u"statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QMetaObject.connectSlotsByName(MainWindow)
# setupUi
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(QCoreApplication.translate("MainWindow", u"MainWindow", None))
self.pushButton_3.setText(QCoreApplication.translate("MainWindow", u"9", None))
self.pushButton_2.setText(QCoreApplication.translate("MainWindow", u"8", None))
self.pushButton_6.setText(QCoreApplication.translate("MainWindow", u"6", None))
self.pushButton_4.setText(QCoreApplication.translate("MainWindow", u"4", None))
self.pushButton_7.setText(QCoreApplication.translate("MainWindow", u"1", None))
self.pushButton_8.setText(QCoreApplication.translate("MainWindow", u"2", None))
self.pushButton_9.setText(QCoreApplication.translate("MainWindow", u"3", None))
self.pushButton_5.setText(QCoreApplication.translate("MainWindow", u"5", None))
self.pushButton.setText(QCoreApplication.translate("MainWindow", u"7", None))
self.pushButton_10.setText(QCoreApplication.translate("MainWindow", u"0", None))
# retranslateUi
Consider the following four slightly different examples: Python 3.10.0rc1 ... >>> from math import sin and cos File "<stdin>", line 1 from math import sin and cos ^^^ SyntaxError: invalid syntax >>> from math import sin, cos, and tan File "<stdin>", line 1 from math import sin, cos, and tan ^^^ SyntaxError: trailing comma not allowed without surrounding parentheses >>> from math import (sin, cos,) and tan File "<stdin>", line 1 from math import (sin, cos,) and tan ^^^ SyntaxError: invalid syntax >>> from math import sin, cos and tan File "<stdin>", line 1 from math import sin, cos and tan ^^^ SyntaxError: invalid syntax ==== In all four cases, the keyword 'and' is correctly identified as causing the error. In the second case, the message given may suggest that adding parentheses is all that is needed to correct the problem; however, that is "obviously" not the case as shown in the third case. **Perhaps** when a _keyword_ like 'and' is identified as a problem, a generally better message would be something like SyntaxError: the keyword 'and' is not allowed here leaving out all guesses like 'surrounding by parentheses', "meaning == instead of =", 'perhaps forgot a comma', etc., which are sometimes added by Python 3.10+ ? I am fully and painfully aware that attempting to provide helpful and accurate error message is challenging...
This message is not new to Python 3.10 as it is also shown with Python 3.9.5. >>> from math import sin, cos, and tan File "<stdin>", line 1 from math import sin, cos, and tan ^ SyntaxError: trailing comma not allowed without surrounding parentheses
The problem is not the keyword, is that we are parsing correctly until the "and" and we find the comma there. It happens with anything that invalidates more items: >>> from math import sin, cos, $ tan File "<stdin>", line 1 from math import sin, cos, $ tan ^ SyntaxError: trailing comma not allowed without surrounding parentheses
Маленькая, но уж очень полезная статья о том, как использовать замыкающие запятые в JavaScript.
Кто-то называет их просто Trailing Commas, без перевода. Кто-то говорит, что это висящие запятые, конечные запятые или последние запятые. Слышал даже, что её называют гуляющей запятой. Я же сторонник более подходящего варианта в техническом отношении, а именно за замыкающую запятую. Использование англоязычного варианта мне кажется неуместным в этом случае.
Вообще, некоторые замыкающие запятые можно было использовать, своеобразно конечно, ещё с самого зарождения JavaScript. Но эти совершенно новые и ниже вы узнаете буквально всё про них.
Что такое замыкающая запятая и почему она полезна?
Предположим, что у вас есть список домашних дел и вы скорее всего разделяете эти самые дела запятыми:
dishes, vacuum, tidy
Замыкающая запятая это просто запятая, которая идёт после последнего элемента в списке. Она необязательна, но в некоторых случаях использования в JS, мы можем её использовать:
dishes, vacuum, tidy,
И знаете, есть несколько случаев, когда вам всё таки понадобится её использовать. Предположим, что вам надо программно добавлять элементы в массив:
Без замыкающей запятой большинство значений может быть добавлено в массив, как value + ','
. Но тут надо немного доработать логику в коде и убедиться в том, что последний элемент будет добавлен в массив без запятой в конце.
С замыкающей запятой, все элементы могут быть добавлены в массив, как value + ','
.
Массивы
С самого зарождения JavaScript, замыкающие запятые можно было использовать при создании массивов:
// Оба варианта одинаковы:
let arr = [ 1, 2 ];
let arr = [ 1, 2 , ];
arr.length; // 2
Объекты
Замыкающие запятые также вполне можно использовать и в объектах:
// Оба варианта одинаковы:
let obj = {
a: 95,
b: 23
};
let obj = {
a: 95,
b: 23,
};
Указание параметров и вызовы функции
Начиная с ES 2017, замыкающие запятые можно использовать в указании параметров и вызовах функции:
// Оба варианта одинаковы:
function f(a,b) {}
function f(a,b,) {}
// Оба варианта одинаковы:
f(1,2);
f(1,2,);
Однако, если в аргументе для функции будет только замыкающая запятая, то вы получите синтаксическую ошибку:
function f(,) {};
// SyntaxError: missing formal parameter
f(,);
// SyntaxError: expected expression, got ','
Rest параметры
При использовании rest
параметров нельзя применять замыкающие запятые, так как получите в ответ SyntaxError
:
function f(...a,) {};
// SyntaxError: parameter after rest parameter
let [a, ...b,] = [1, 2, 3, 4, 5];
// SyntaxError: rest element may not have a trailing comma
JSON
В JSON нельзя использовать замыкающие запятые. Попытаясь спарсить JSON с такой запятой, вы получите синтаксическую ошибку:
JSON.parse('["a", "b",]');
// SyntaxError JSON.parse: unexpected character
Python Online Compiler
Write, Run & Share Python code online using OneCompiler’s Python online compiler for free. It’s one of the robust, feature-rich online compilers for python language, supporting both the versions which are Python 3 and Python 2.7. Getting started with the OneCompiler’s Python editor is easy and fast. The editor shows sample boilerplate code when you choose language as Python or Python2 and start coding.
Taking inputs (stdin)
OneCompiler’s python online editor supports stdin and users can give inputs to programs using the STDIN textbox under the I/O tab. Following is a sample python program which takes name as input and print your name with hello.
import sys
name = sys.stdin.readline()
print("Hello "+ name)
About Python
Python is a very popular general-purpose programming language which was created by Guido van Rossum, and released in 1991. It is very popular for web development and you can build almost anything like mobile apps, web apps, tools, data analytics, machine learning etc. It is designed to be simple and easy like english language. It’s is highly productive and efficient making it a very popular language.
Tutorial & Syntax help
Loops
1. If-Else:
When ever you want to perform a set of operations based on a condition IF-ELSE is used.
if conditional-expression
#code
elif conditional-expression
#code
else:
#code
Note:
Indentation is very important in Python, make sure the indentation is followed correctly
2. For:
For loop is used to iterate over arrays(list, tuple, set, dictionary) or strings.
Example:
mylist=("Iphone","Pixel","Samsung")
for i in mylist:
print(i)
3. While:
While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.
while condition
#code
Collections
There are four types of collections in Python.
1. List:
List is a collection which is ordered and can be changed. Lists are specified in square brackets.
Example:
mylist=["iPhone","Pixel","Samsung"]
print(mylist)
2. Tuple:
Tuple is a collection which is ordered and can not be changed. Tuples are specified in round brackets.
Example:
myTuple=("iPhone","Pixel","Samsung")
print(myTuple)
Below throws an error if you assign another value to tuple again.
myTuple=("iPhone","Pixel","Samsung")
print(myTuple)
myTuple[1]="onePlus"
print(myTuple)
3. Set:
Set is a collection which is unordered and unindexed. Sets are specified in curly brackets.
Example:
myset{"iPhone","Pixel","Samsung"}
print{myset}
4. Dictionary:
Dictionary is a collection of key value pairs which is unordered, can be changed, and indexed. They are written in curly brackets with key — value pairs.
Example:
mydict = {
"brand" :"iPhone",
"model": "iPhone 11"
}
print(mydict)
Supported Libraries
Following are the libraries supported by OneCompiler’s Python compiler
Name | Description |
---|---|
NumPy | NumPy python library helps users to work on arrays with ease |
SciPy | SciPy is a scientific computation library which depends on NumPy for convenient and fast N-dimensional array manipulation |
SKLearn/Scikit-learn | Scikit-learn or Scikit-learn is the most useful library for machine learning in Python |
Pandas | Pandas is the most efficient Python library for data manipulation and analysis |
Matplotlib | Matplotlib is a cross-platform, data visualization and graphical plotting library for Python programming and it’s numerical mathematics extension NumPy |
DOcplex | DOcplex is IBM Decision Optimization CPLEX Modeling for Python, is a library composed of Mathematical Programming Modeling and Constraint Programming Modeling |
ERROR:
[lau@192 superlists]$ python manage.py test
Creating test database for alias 'default' ...
E
======================================================================
ERROR: lau.tests (unittest.loader._FailedTest)
----------------------------------------------------------------------
ImportError: Failed to import test module: lau.tests
Traceback (most recent call last):
File "/home/lau/anaconda3/lib/python3.5/unittest/loader.py", line 428, in _find_test_path
module = self._get_module_from_name(name)
File "/home/lau/anaconda3/lib/python3.5/unittest/loader.py", line 369, in _get_module_from_name
__import__(name)
File "/home/lau/PycharmProjects/python core/superlists/lau/tests.py", line 3, in <module>
from lists.views import home_page
File "/home/lau/anaconda3/lib/python3.5/site-packages/lists.py", line 7, in <module>
def print_list (the_list, indent = false, level = 0):
NameError: name 'false' is not defined
----------------------------------------------------------------------
Ran 1 test in 0.000s
FAILED (errors=1)
Destroying test database for alias 'default' ...
tests.py:
from django.test import TestCase
from django.core.urlresolvers import resolve
from lists.views import home_page
class HomePageTest(TestCase):
def test_root_url_resolves_to_home_page_view(self):
found = resolve('/')
self.assertEqual(found.func,home_page)
urls.py
from django.conf.urls import url,patterns,include
from django.contrib import admin
urlpatterns = ['',
url(r'^admin/', admin.site.urls),
url(r'^$', 'lau.views.home_page', name='home'),]
views.py
from django.shortcuts import render
def home_page():
Pass
No matter how it is modified, it is error: lau.tests (unittest.loader. _ failedtest)
Google for a long time, only see a similar
Original answer: i have found my mistake.
I am really puzzled. The solution is confusing. I pray to the Great God for an answer. Thank you. Xiaobai thanked me again.
Thank you for your concern and help. After studying all night, the problem has been solved.
There are three main points in my question:
First point: The problem is tests.py inside
tests.py:from django.test import TestCase from django.core.urlresolvers import resolve ***from lists.views import home_page*** class HomePageTest(TestCase): def test_root_url_resolves_to_home_page_view(self): found = resolve('/') self.assertEqual(found.func,home_page) —————————————————————————————————————————————————————— Viewpoints import home _ page this code should be changed to Viewpoints import home page, because the books used are step by step, which leads to this kind of Howlers.
The second point: after solving the above-mentioned problems, an import error: cannotimport name’ patterns’ error occurred.
Solution: Modify in urls.py and import home_pagefrom django.conf.urls import include,url from django.contrib import admin from lau.views import home_page urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^$', home_page),
The third point: This is my own feeling. In django1.10, pattern was abandoned, but I still used pattern. This is very wrong. Besides, I didn’t read things carefully and the official documents didn’t read through. I am really ashamed of this kind of Howlers.
Summarize errors and solutions:
ImportError: cannot import name 'patterns' Solution: Abandon patterns TypeError: view must be a callable or a list/tuple in the case of include(). Solution: Import the home_page module to solve the problem. SyntaxError: trailing comma not allowed without surrounding parentheses Resolution: Check punctuation marks at import ERROR:unittest,loader.FailedTest Solution: Check whether tests.py file is introduced correctly and whether there are spaces in the file.
For reference, please visit:
http://stackoverflow.com/ques …
http://python.6.x6.nabble.com …