Форум сайта python.su
import pygame def inter(x1, y1, x2, y2, db1, db2): if x1 > x2-db1 and x1 < x2+db2 and y1 > y2-db1 and y1 < y2+db2: return 1 else: return 0 pygame.init() window = pygame.display.set_mode((560, 560)) screen = pygame.Surface((560, 560)) player = pygame.Surface((60, 60)) zet = pygame.Surface((60, 60)) arrow = pygame.Surface((20, 60)) count = 0 player.set_colorkey((255, 255, 255)) arrow.set_colorkey((255, 255, 255)) zet.set_colorkey((255, 255, 255)) img_b = pygame.image.load('BG2.gif') img_s = pygame.image.load('s.png') img_p = pygame.image.load('p.png') img_z = pygame.image.load('z.png') myfont = pygame.font.SysFont('myspase', 22) a_x = 1000 a_y = 1000 strike = False z_x = 0 z_y = 0 x_p = 0 y_p = 450 right = True done = False while done == False: for e in pygame.event.get(): if e.type == pygame.QUIT: done = True if e.type == pygame.KEYDOWN and e.key == pygame.K_s: y_p += 9 if e.type == pygame.KEYDOWN and e.key == pygame.K_w: y_p -= 9 if e.type == pygame.KEYDOWN and e.key == pygame.K_d: x_p += 9 if e.type == pygame.KEYDOWN and e.key == pygame.K_a: x_p -= 9 if e.type == pygame.KEYDOWN and e.key == pygame.K_SPACE: if strike == False: strike = True a_x = x_p + 20 a_y = y_p - 60 if strike: a_y -= 1 if a_y < 0: strike = False a_y = 1000 a_x = 1000 if inter(a_x, a_y, z_x, z_y, 20, 40): count += 1 strike = False a_y = 1000 a_x = 1000 if right: z_x += 0.2 if z_x > 350: z_x -= 0.2 right = False else: z_x -= 0.2 if z_x < 0: z_x += 0.2 right = True string = myfont.render('поподаний: '+str(count), 0, (255,0,0)) screen.blit(img_b, (0, 0)) arrow.blit(img_s, (0, 0)) player.blit(img_p, (0, 0)) zet.blit(img_z, (0, 0)) screen.blit(string, (0,50)) screen.blit(arrow, (a_x, a_y)) screen.blit(zet, (z_x, z_y)) screen.blit(player, (x_p, y_p)) window.blit(screen, (0, 0)) pygame.display.update() pygame.quit()
import asyncio import websockets import serial class My: def __init__(self): self.ser = serial.Serial('COM8', 115200, timeout=None) async def myhello(self, websocket, path): name = await websocket.recv() await self.send(b'asd') await self.read() print(f"< {name}") greeting = f"Hello {name}!" await websocket.send(greeting) print(f"> {greeting}") async def send(self, data): self.ser.write(data) async def read(self): text = self.ser.readline() print(text) myex = My() start_server = websockets.serve(myex.myhello, "localhost", 8266) asyncio.get_event_loop().run_until_complete(start_server) asyncio.get_event_loop().run_forever()
package net.viralpatel.android.speechtotextdemo; // имя пакета import java.util.ArrayList; import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.Intent; import android.os.Bundle; import android.speech.RecognizerIntent; import android.view.Menu;// не нужно import android.view.View; import android.widget.ImageButton;// не нужно import android.widget.TextView;// не нужно import android.widget.Toast; public class MainActivity extends Activity { protected static final int RESULT_SPEECH = 1; private ImageButton btnSpeak; private TextView txtText; // не нужно создают gui @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); txtText = (TextView) findViewById(R.id.txtText); btnSpeak = (ImageButton) findViewById(R.id.btnSpeak); // а вот здесь вешают событие на клик кнопки btnSpeak.setOnClickListener(new View.OnClickListener() { // само событие @Override public void onClick(View v) { // намериние вызова голосового ввода (объект) Intent intent = new Intent( RecognizerIntent.ACTION_RECOGNIZE_SPEECH); // выбирают язык intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US"); /* непонятный вызов startActivityForResult (откуда?) * а главное куда результат сгружает * ммм ага отправлят обратно callback * ... бладж это 2012*/ try { startActivityForResult(intent, RESULT_SPEECH); txtText.setText(""); // сообщение об исключении } catch (ActivityNotFoundException a) { Toast t = Toast.makeText(getApplicationContext(), "Opps! Your device doesn't support Speech to Text", Toast.LENGTH_SHORT); t.show(); } } }); } @Override //не нужно public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } @Override // ага этим парсим результат (переопределение) protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case RESULT_SPEECH: { if (resultCode == RESULT_OK && null != data) { ArrayList<String> text = data .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS); txtText.setText(text.get(0)); } break; } } }
MainActivity.java package info.androidhive.speechtotext; import java.util.ArrayList;/ import java.util.Locale; import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.Intent;/ import android.os.Bundle; import android.speech.RecognizerIntent; import android.view.Menu; import android.view.View; import android.widget.ImageButton; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity { private TextView txtSpeechInput; private ImageButton btnSpeak; private final int REQ_CODE_SPEECH_INPUT = 100; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); txtSpeechInput = (TextView) findViewById(R.id.txtSpeechInput); btnSpeak = (ImageButton) findViewById(R.id.btnSpeak); // hide the action bar getActionBar().hide(); btnSpeak.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { promptSpeechInput(); } }); } /** * Showing google speech input dialog * */ private void promptSpeechInput() { Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); /* python_act = autoclass('org.kivy.android.PythonActivity') mActivity = python_act.mActivity REQ_CODE_SPEECH_INPUT = 100 Intent = autoclass('android.content.Intent') RecognizerIntent = autoclass('android.speech.RecognizerIntent') Locale = autoclass('java.util.Locale') * intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH) intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH) intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM) intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault()) intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "test") * startActivityForResult(intent, REQ_CODE_SPEECH_INPUT) * */ intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault()); / не нужно это собщение для польхователя intent.putExtra(RecognizerIntent.EXTRA_PROMPT, getString(R.string.speech_prompt)); try { startActivityForResult(intent, REQ_CODE_SPEECH_INPUT); } catch (ActivityNotFoundException a) { Toast.makeText(getApplicationContext(), getString(R.string.speech_not_supported), Toast.LENGTH_SHORT).show(); } } /** * Receiving speech input * */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case REQ_CODE_SPEECH_INPUT: { if (resultCode == RESULT_OK && null != data) { ArrayList<String> result = data .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS); txtSpeechInput.setText(result.get(0)); } break; } } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
from kivy.app import App from kivy.lang import Builder from kivy.uix.screenmanager import Screen from kivy.clock import Clock from kivy.core.window import Window from kivy.config import Config from kivy.utils import platform from jnius import autoclass Builder.load_file("TEdt.kv") Window.softinput_mode = '' class TextEdit(Screen): ''' тут не связанный с проблемой код ''' def test2(self, instance): ''' пытаюсь запустить stt ''' try: #REQ_CODE_SPEECH_INPUT = 100 python_act = autoclass('org.kivy.android.PythonActivity') mActivity = python_act.mActivity #* REQ_CODE_SPEECH_INPUT = 100 Intent = autoclass('android.content.Intent') RecognizerIntent = autoclass( 'android.speech.RecognizerIntent') Locale = autoclass('java.util.Locale') #* intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH) intent.putExtra( RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM) # надо как то с локалями разобраться intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "en-EN") intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "test") result = mActivity.startActivityForResult(intent,REQ_CODE_SPEECH_INPUT).getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS) self.ids.txt.text = \ f"{str(mActivity.__dict__)} {str(dir(mActivity))} {result}" #*# что здесь за 3 параметра #Activity = autoclass('android.app.Activity') #mActivity.onActivityResult(mActivity.requestCode, #mActivity.resultCode, #mActivity.data) except Exception as err: self.ids.txt.text = f"test2 {err}"
import random print("Приветствую в игре: \ 'Камень, ножницы, бумага'") print(" Игра будет против ИИ.") print(" Игра состоит их трёх раундов!") print(" Победитель будет тем у кого будет больше очков!") print(" Используй большие буквы чтобы выбрать:") print(" [r] - камень") print(" [s] - ножницы") print(" [p] - бумага") user_score = 0 user_choice = 0 bot_score = 0 bot_choice = 0 print("---------- НАЧАЛО ИГРЫ ------") for i in range(3): print(" ------ РАУНД № " + str(i+1) + " --------") bot_choice = random.choice(["R", "S", "P"]) user_choice = input(" Твой выбор:") print ("Ты:" + user_choice + " x Бот:" + bot_choice + " - ", end = " ") if user_choice == bot_choice: print("Ничья") elif user_choice == "R": if bot_choice == "S": user_score = user_score + 1 print("Игрок победил в раунде!") else: bot_score = bot_score + 1 print("Бот победил в раунде!") elif user_choice == "S": if bot_choice == "P": user_score = user_score + 1 print("Игрок победил в раунде!") else: bot_score = bot_score + 1 print("Бот победил в раунде!") elif user_choice == "P": if bot_choice == "R": user_score = user_score + 1 print("Игрок победил в раунде!") else: bot_score = bot_score + 1 print("Бот победил в раунде!") else: print("Error") if user_score > bot_score: print("Результаты игры: Игрок победил!") elif user_score < bot_score: print("Результаты игры: Бот победил!") else: print("Результаты игры: Ничья")
jupyter --paths
m=[] n='' while True: n=str(input()) if n=='end': break else: m.append([int(i) for i in n.split()]) m2 = [[sum([m[i-1][j], m[i+1][j], m[i][j-1], m[i][j+1]]) for j in range(len(m[0]))] for i in range(len(m))]
Выполняется(%prep): /bin/sh -e /var/tmp/rpm-tmp.63FGwo + umask 022 + cd /home/centos/rpmbuild/BUILD + cd /home/centos/rpmbuild/BUILD + rm -rf semaphore-0.4.65 + /usr/bin/unzip -qq /home/centos/rpmbuild/SOURCES/semaphore-0.4.65.zip + STATUS=0 + '[' 0 -ne 0 ']' + cd semaphore-0.4.65 + /usr/bin/chmod -Rf a+rX,u+w,g-w,o-w . + exit 0 Выполняется(%build): /bin/sh -e /var/tmp/rpm-tmp.gRqFOO + umask 022 + cd /home/centos/rpmbuild/BUILD + cd semaphore-0.4.65 + /usr/bin/python2 setup.py build Installed /home/centos/rpmbuild/BUILD/semaphore-0.4.65/milksnake-0.1.5-py2.7.egg running build running build_py creating build/lib creating build/lib/semaphore copying semaphore/_compat.py -> build/lib/semaphore copying semaphore/envelope.py -> build/lib/semaphore copying semaphore/exceptions.py -> build/lib/semaphore copying semaphore/utils.py -> build/lib/semaphore copying semaphore/processing.py -> build/lib/semaphore copying semaphore/auth.py -> build/lib/semaphore copying semaphore/consts.py -> build/lib/semaphore copying semaphore/__init__.py -> build/lib/semaphore error: No such file or directory ошибка: Неверный код возврата из /var/tmp/rpm-tmp.gRqFOO (%build) Ошибки сборки пакетов: Неверный код возврата из /var/tmp/rpm-tmp.gRqFOO (%build)
cat /var/tmp/rpm-tmp.gRqFOO #!/bin/sh RPM_SOURCE_DIR="/home/centos/rpmbuild/SOURCES" RPM_BUILD_DIR="/home/centos/rpmbuild/BUILD" RPM_OPT_FLAGS="-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic" RPM_LD_FLAGS="-Wl,-z,relro " RPM_ARCH="x86_64" RPM_OS="linux" export RPM_SOURCE_DIR RPM_BUILD_DIR RPM_OPT_FLAGS RPM_LD_FLAGS RPM_ARCH RPM_OS RPM_DOC_DIR="/usr/share/doc" export RPM_DOC_DIR RPM_PACKAGE_NAME="python-semaphore" RPM_PACKAGE_VERSION="0.4.65" RPM_PACKAGE_RELEASE="1.el7" export RPM_PACKAGE_NAME RPM_PACKAGE_VERSION RPM_PACKAGE_RELEASE LANG=C export LANG unset CDPATH DISPLAY ||: RPM_BUILD_ROOT="/home/centos/rpmbuild/BUILDROOT/python-semaphore-0.4.65-1.el7.x86_64" export RPM_BUILD_ROOT PKG_CONFIG_PATH="${PKG_CONFIG_PATH}:/usr/lib64/pkgconfig:/usr/share/pkgconfig" export PKG_CONFIG_PATH set -x umask 022 cd "/home/centos/rpmbuild/BUILD" cd 'semaphore-0.4.65' /usr/bin/python2 setup.py build
import requests import csv from bs4 import BeautifulSoup as bs headers = {'accept': '*/*', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:72.0) Gecko/20100101 Firefox/72.0'} MAIN_URL = 'https://www.yoox.com' base_url = 'https://www.yoox.com/ru/%D0%B4%D0%BB%D1%8F%20%D0%BC%D1%83%D0%B6%D1%87%D0%B8%D0%BD/%D0%BE%D0%B4%D0%B5%D0%B6%D0%B4%D0%B0/shoponline#/dept=clothingmen&gender=U&season=X&page=1' def yoox_parse(base_url, headers): session = requests.Session() request = session.get(base_url, headers=headers) clothes = [] urls = [] urls.append(base_url) if request.status_code == 200: soup = bs(request.content, 'html.parser') try: pagination = soup.find_all('li', attrs={'class': 'text-light'}) count = int(pagination[-1].text) for i in range(1,count): url = f'https://www.yoox.com/ru/%D0%B4%D0%BB%D1%8F%20%D0%BC%D1%83%D0%B6%D1%87%D0%B8%D0%BD/%D0%BE%D0%B4%D0%B5%D0%B6%D0%B4%D0%B0/shoponline#/dept=clothingmen&gender=U&season=X&page={i}' if url not in urls: urls.append(url) except: pass for url in urls: request = session.get(url, headers=headers) soup = bs(request.content, 'html.parser') divs = soup.find_all('div', attrs={'class': 'col-8-24'}) for div in divs: brand = div.find('div', attrs={'class': 'brand font-bold text-uppercase'}) group = div.find('div', attrs={'class': 'microcategory font-sans'}) old_price = div.find('span', attrs={'class': 'oldprice text-linethrough text-light'}) new_price = div.find('span', attrs={'class': 'newprice font-bold'}) price = div.find('span', attrs={'class': 'fullprice font-bold'}) sizes = div.find_all('span', attrs={'class': 'aSize'}) href = div.find('a', attrs={'class': 'itemlink'}) art = div.find('div', attrs={'class': ''}) if brand and group and new_price: # new_price выводит только товары со скидкой clothes.append({ 'art': art, 'href': MAIN_URL + href.get('href'), 'sizes': [size.get_text() for size in sizes], 'brand': brand.get_text(), 'group': group.get_text(strip=True), 'old_price': old_price.get_text().replace(' ', '').replace('руб', '') if old_price else None, 'new_price': new_price.get_text().replace(' ', '').replace('руб', '') if new_price else None, 'price': price.get_text().replace(' ', '').replace('руб', '') if price else None, }) print(len(clothes)) else: print('ERROR or Done') return clothes def files_writer(clothes): with open('parsed_yoox_man_clothes.csv', 'w', newline='') as file: a_pen = csv.writer(file) a_pen.writerow(('Артикул', 'Ссылка', 'Размер', 'Марка', 'Категория', 'Старая цена', 'Новая цена', 'Цена')) for clothe in clothes: a_pen.writerow((clothe['art'], clothe['href'], clothe['sizes'], clothe['brand'], clothe['group'], clothe['old_price'], clothe['new_price'], clothe['price'])) clothes = yoox_parse(base_url, headers) files_writer(clothes)
from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget from PyQt5.QtWebEngineWidgets import QWebEngineView
html = open('index.html', 'r').read() self.browser = QWebEngineView()
self.browser.page().runJavaScript("subscribe()", self.ready)
messaging.requestPermission() .then(function () { .... }
ball = pygame.draw.circle(screen, RED, (53, 53), 30)
while not game_over: for event in pygame.event.get(): if event.type == pygame.MOUSEBUTTONUP: ball.move_ip(50, 50) pygame.display.update()