Dataset Viewer (First 5GB)
Auto-converted to Parquet
metadata
dict
text
stringlengths
60
3.49M
{ "source": "00-00-00-11/Raid-Toolbox", "score": 2 }
#### File: Raid-Toolbox/spammer/asciispam.py ```python import discord import random import sys import aiohttp token = sys.argv[1] tokenno = sys.argv[2] textchan = sys.argv[3] allchan = sys.argv[4] SERVER = sys.argv[5] useproxies = sys.argv[6] if useproxies == 'True': proxy_list = open("proxies.txt").read().splitlines() proxy = random.choice(proxy_list) con = aiohttp.ProxyConnector(proxy="http://"+proxy) client = discord.Client(connector=con) else: client = discord.Client() @client.event async def on_ready(): server = client.get_guild(int(SERVER)) if allchan == 'true': while not client.is_closed(): for channel in server.text_channels: myperms = channel.permissions_for(server.get_member(client.user.id)) if not myperms.send_messages: continue asc = '' for x in range(1999): num = random.randrange(13000) asc = asc + chr(num) try: await channel.send(asc) except Exception: pass else: txtchan = client.get_channel(int(textchan)) while not client.is_closed(): asc = '' for x in range(1999): num = random.randrange(13000) asc = asc + chr(num) try: await txtchan.send(asc) except Exception: pass try: client.run(token, bot=False) except Exception as c: print (c) ``` #### File: Raid-Toolbox/spammer/embedspam.py ```python import discord import sys import random import aiohttp token = sys.argv[1] title = sys.argv[2] author = sys.argv[3] iconurl = sys.argv[4] thumburl = sys.argv[5] footer = sys.argv[6] textchan = sys.argv[7] useproxies = sys.argv[8] if useproxies == 'True': proxy_list = open("proxies.txt").read().splitlines() proxy = random.choice(proxy_list) con = aiohttp.ProxyConnector(proxy="http://"+proxy) client = discord.Client(connector=con) else: client = discord.Client() # set embed embed=discord.Embed(title=title) embed.set_author(name=author, icon_url=iconurl) embed.set_thumbnail(url=thumburl) embed.set_footer(text=footer) @client.event async def on_ready(): try: txtchan = client.get_channel(int(textchan)) while True: await txtchan.send(embed=embed) except Exception: pass try: client.run(token, bot=False) except Exception as c: print (c) ``` #### File: Raid-Toolbox/spammer/friender.py ```python import sys import requests import random token = sys.argv[1] userid = sys.argv[2] useproxies = sys.argv[3] if useproxies == 'True': proxy_list = open("proxies.txt").read().splitlines() def proxyfriend(): try: proxy = random.choice(proxy_list) requests.put(apilink, headers=headers, proxies={"http": proxy, "https": proxy}) except Exception: proxyfriend() apilink = 'https://discordapp.com/api/v6/users/@me/relationships/'+ str(userid) headers={ 'Authorization': token, 'Content-Type': 'application/json' } if useproxies == 'True': proxyfriend() else: requests.put(apilink, headers=headers) ``` #### File: Raid-Toolbox/spammer/groupdmspam.py ```python import discord import sys import random import aiohttp import logging token = sys.argv[1] group = sys.argv[2] tokenno = sys.argv[3] msgtxt = sys.argv[4] useproxies = sys.argv[5] logging.basicConfig(filename='RTB.log', filemode='w', format='Token {}'.format(str(tokenno))+' - %(levelname)s - %(message)s',level=logging.CRITICAL) if useproxies == 'True': proxy_list = open("proxies.txt").read().splitlines() proxy = random.choice(proxy_list) con = aiohttp.ProxyConnector(proxy="http://"+proxy) client = discord.Client(connector=con) else: client = discord.Client() @client.event async def on_ready(): groupdm = client.get_channel(int(group)) while not client.is_closed(): try: await groupdm.send(msgtxt) except Exception: pass try: client.run(token, bot=False) except Exception as c: logging.critical('Token {} Unable to login: {}'.format(str(tokenno),str(c))) print (c) ``` #### File: Raid-Toolbox/spammer/rolemention.py ```python import discord import sys import random import aiohttp useproxies = sys.argv[4] if useproxies == 'True': proxy_list = open("proxies.txt").read().splitlines() proxy = random.choice(proxy_list) con = aiohttp.ProxyConnector(proxy="http://"+proxy) client = discord.Client(connector=con) else: client = discord.Client() token = sys.argv[1] SERVER = sys.argv[2] tokenno = sys.argv[3] @client.event async def on_ready(): server = client.get_guild(int(SERVER)) mention = '' try: for role in server.roles: if role.mentionable: mention += role.mention + ' ' else: continue while not client.is_closed(): for channel in server.text_channels: myperms = channel.permissions_for(server.get_member(client.user.id)) if not myperms.send_messages: continue for m in [mention[i:i+1999] for i in range(0, len(mention), 1999)]: try: await channel.send(m) except Exception: pass except Exception as e: print (e) pass try: client.run(token, bot=False) except Exception as c: print (c) ``` #### File: Raid-Toolbox/spammer/trafficlight.py ```python import discord import asyncio import random import sys import aiohttp useproxies = sys.argv[2] if useproxies == 'True': proxy_list = open("proxies.txt").read().splitlines() proxy = random.choice(proxy_list) con = aiohttp.ProxyConnector(proxy="http://"+proxy) client = discord.Client(connector=con) else: client = discord.Client() token = sys.argv[1] @client.event async def on_ready(): while not client.is_closed(): randoms = ['1','2','3'] presence = (random.choice(randoms)) if presence == '1': await client.change_presence(status=discord.Status.online) await asyncio.sleep(3) elif presence == '2': await client.change_presence(status=discord.Status.idle) await asyncio.sleep(3) elif presence == '3': await client.change_presence(status=discord.Status.do_not_disturb) await asyncio.sleep(3) try: client.run(token, bot=False) except Exception as c: print (c) ``` #### File: Raid-Toolbox/spammer/vcspam.py ```python import discord import asyncio import sys import random import aiohttp token = sys.argv[1] tokenno = sys.argv[2] voice_id = sys.argv[3] useproxies = sys.argv[4] # proxies for voice chats smh if useproxies == 'True': proxy_list = open("proxies.txt").read().splitlines() proxy = random.choice(proxy_list) con = aiohttp.ProxyConnector(proxy="http://"+proxy) client = discord.Client(connector=con) else: client = discord.Client() @client.event async def on_ready(): await asyncio.sleep(1) voice_channel = client.get_channel(int(voice_id)) while not client.is_closed(): vc = await voice_channel.connect() vc.play(discord.FFmpegPCMAudio('spammer/file.wav')) vc.source = discord.PCMVolumeTransformer(vc.source) vc.source.volume = 10.0 while vc.is_playing(): await asyncio.sleep(3) await vc.disconnect(force=True) try: client.run(token, bot=False) except Exception as c: print(c) ```
{ "source": "00000111/aiocouchdb", "score": 2 }
#### File: aiocouchdb/tests/utils.py ```python import asyncio import base64 import contextlib import datetime import functools import os import random import unittest import unittest.mock as mock import uuid as _uuid from collections import deque, defaultdict import aiocouchdb.client import aiocouchdb.errors from aiocouchdb.client import urljoin, extract_credentials from yarl import URL TARGET = os.environ.get('AIOCOUCHDB_TARGET', 'mock') def run_in_loop(f): @functools.wraps(f) def wrapper(testcase, *args, **kwargs): coro = asyncio.coroutine(f) future = asyncio.wait_for(coro(testcase, *args, **kwargs), timeout=testcase.timeout) return testcase.loop.run_until_complete(future) return wrapper class MetaAioTestCase(type): def __new__(cls, name, bases, attrs): for key, obj in attrs.items(): if key.startswith('test_'): attrs[key] = run_in_loop(obj) return super().__new__(cls, name, bases, attrs) class TestCase(unittest.TestCase, metaclass=MetaAioTestCase): _test_target = TARGET timeout = 10 url = URL('http://localhost:5984') def setUp(self): self.loop = asyncio.new_event_loop() asyncio.set_event_loop(self.loop) wraps = None if self._test_target != 'mock': wraps = self._request_tracer(aiocouchdb.client.request) self._patch = mock.patch('aiocouchdb.client.request', wraps=wraps) self.request = self._patch.start() self._set_response(self.prepare_response()) self._req_per_task = defaultdict(list) self.loop.run_until_complete(self.setup_env()) def tearDown(self): self.loop.run_until_complete(self.teardown_env()) self._patch.stop() self.loop.close() @asyncio.coroutine def setup_env(self): sup = super() if hasattr(sup, 'setup_env'): yield from sup.setup_env() @asyncio.coroutine def teardown_env(self): sup = super() if hasattr(sup, 'teardown_env'): yield from sup.teardown_env() def future(self, obj): fut = asyncio.Future(loop=self.loop) fut.set_result(obj) return fut def _request_tracer(self, f): @functools.wraps(f) def wrapper(*args, **kwargs): current_task = asyncio.Task.current_task(loop=self.loop) self._req_per_task[current_task].append((args, kwargs)) return f(*args, **kwargs) return wrapper def prepare_response(self, *, cookies=None, data=b'', err=None, headers=None, status=200): def make_side_effect(queue): def side_effect(*args, **kwargs): fut = asyncio.Future(loop=self.loop) if queue: resp.content.at_eof.return_value = False fut.set_result(queue.popleft()) elif err: fut.set_exception(err) else: resp.content.at_eof.return_value = True fut.set_result(b'') return fut return side_effect headers = headers or {} headers.setdefault('CONTENT-TYPE', 'application/json') cookies = cookies or {} if isinstance(data, list): chunks_queue = deque(data) lines_queue = deque((b''.join(data)).splitlines(keepends=True)) else: chunks_queue = deque([data]) lines_queue = deque(data.splitlines(keepends=True)) resp = aiocouchdb.client.HttpResponse('', '') resp._post_init(self.loop) resp.status = status resp.headers = headers resp.cookies = cookies resp.content = unittest.mock.Mock() resp.content._buffer = bytearray() resp.content.at_eof.return_value = False resp.content.read.side_effect = make_side_effect(chunks_queue) resp.content.readany.side_effect = make_side_effect(chunks_queue) resp.content.readline.side_effect = make_side_effect(lines_queue) resp.close = mock.Mock(side_effect=resp.close) return resp @contextlib.contextmanager def response(self, *, cookies=None, data=b'', err=None, headers=None, status=200): resp = self.prepare_response(cookies=cookies, data=data, err=err, headers=headers, status=status) self._set_response(resp) yield resp resp.close() self._set_response(self.prepare_response()) def _set_response(self, resp): if self._test_target == 'mock': self.request.return_value = self.future(resp) def assert_request_called_with(self, method, *path, **kwargs): self.assertTrue(self.request.called and self.request.call_count >= 1) current_task = asyncio.Task.current_task(loop=self.loop) if current_task in self._req_per_task: call_args, call_kwargs = self._req_per_task[current_task][-1] else: call_args, call_kwargs = self.request.call_args self.assertEqual((method, urljoin(self.url, *path)), call_args) kwargs.setdefault('data', None) kwargs.setdefault('headers', {}) kwargs.setdefault('params', {}) for key, value in kwargs.items(): self.assertIn(key, call_kwargs) if value is not Ellipsis: self.assertEqual(value, call_kwargs[key]) class ServerTestCase(TestCase): server_class = None url = os.environ.get('AIOCOUCHDB_URL', 'http://localhost:5984') @asyncio.coroutine def setup_env(self): self.url, creds = extract_credentials(self.url) self.server = self.server_class(self.url, loop=self.loop) if creds is not None: self.cookie = yield from self.server.session.open(*creds) else: self.cookie = None sup = super() if hasattr(sup, 'setup_env'): yield from sup.setup_env() @asyncio.coroutine def teardown_env(self): sup = super() if hasattr(sup, 'teardown_env'): yield from sup.teardown_env() class DatabaseTestCase(ServerTestCase): database_class = None def new_dbname(self): return dbname(self.id().split('.')[-1]) @asyncio.coroutine def setup_env(self): yield from super().setup_env() dbname = self.new_dbname() self.url_db = urljoin(self.url, dbname) self.db = self.database_class( self.url_db, dbname=dbname, loop=self.loop) yield from self.setup_database(self.db) @asyncio.coroutine def setup_database(self, db): with self.response(data=b'{"ok": true}'): yield from db.create() @asyncio.coroutine def teardown_env(self): yield from self.teardown_database(self.db) yield from super().teardown_env() @asyncio.coroutine def teardown_database(self, db): with self.response(data=b'{"ok": true}'): try: yield from db.delete() except aiocouchdb.errors.ResourceNotFound: pass class DocumentTestCase(DatabaseTestCase): document_class = None @asyncio.coroutine def setup_env(self): yield from super().setup_env() docid = uuid() self.url_doc = urljoin(self.db.resource.url, docid) self.doc = self.document_class( self.url_doc, docid=docid, loop=self.loop) yield from self.setup_document(self.doc) @asyncio.coroutine def setup_document(self, doc): with self.response(data=b'{"rev": "1-ABC"}'): resp = yield from doc.update({}) self.rev = resp['rev'] class DesignDocumentTestCase(DatabaseTestCase): designdoc_class = None @asyncio.coroutine def setup_env(self): yield from super().setup_env() docid = '_design/' + uuid() self.url_ddoc = urljoin(self.db.resource.url, *docid.split('/')) self.ddoc = self.designdoc_class( self.url_ddoc, docid=docid, loop=self.loop) yield from self.setup_document(self.ddoc) @asyncio.coroutine def setup_document(self, ddoc): with self.response(data=b'{"rev": "1-ABC"}'): resp = yield from ddoc.doc.update({ 'views': { 'viewname': { 'map': 'function(doc){ emit(doc._id, null) }' } } }) self.rev = resp['rev'] class AttachmentTestCase(DocumentTestCase): attachment_class = None @asyncio.coroutine def setup_env(self): yield from super().setup_env() self.attbin = self.attachment_class( urljoin(self.doc.resource.url, 'binary'), name='binary') self.atttxt = self.attachment_class( urljoin(self.doc.resource.url, 'text'), name='text') self.url_att = self.attbin.resource.url @asyncio.coroutine def setup_document(self, doc): with self.response(data=b'{"rev": "1-ABC"}'): resp = yield from doc.update({ '_attachments': { 'binary': { 'data': base64.b64encode(b'Time to relax!').decode(), 'content_type': 'application/octet-stream' }, 'text': { 'data': base64.b64encode(b'Time to relax!').decode(), 'content_type': 'text/plain' } } }) self.rev = resp['rev'] def modify_server(section, option, value): assert section != 'admins', 'use `with_fixed_admin_party` decorator' @asyncio.coroutine def apply_config_changes(server, cookie): oldval = yield from server.config.update(section, option, value, auth=cookie) return oldval @asyncio.coroutine def revert_config_changes(server, cookie, oldval): if not oldval: try: yield from server.config.delete(section, option, auth=cookie) except aiocouchdb.errors.ResourceNotFound: pass else: if not (yield from server.config.exists(section, option)): return oldval = yield from server.config.update(section, option, oldval, auth=cookie) assert oldval == value, ('{} != {}'.format(oldval, value)) def decorator(f): @functools.wraps(f) def wrapper(testcase, **kwargs): server, cookie = testcase.server, testcase.cookie oldval = yield from apply_config_changes(server, cookie) try: yield from f(testcase, **kwargs) finally: yield from revert_config_changes(server, cookie, oldval) return wrapper return decorator def with_fixed_admin_party(username, password): @asyncio.coroutine def apply_config_changes(server, cookie): oldval = yield from server.config.update('admins', username, password, auth=cookie) cookie = yield from server.session.open(username, password) return oldval, cookie @asyncio.coroutine def revert_config_changes(server, cookie, oldval): if not oldval: try: yield from server.config.delete('admins', username, auth=cookie) except aiocouchdb.errors.ResourceNotFound: pass else: yield from server.config.update('admins', username, oldval, auth=cookie) def decorator(f): @functools.wraps(f) def wrapper(testcase, **kwargs): server, cookie = testcase.server, testcase.cookie oldval, cookie = yield from apply_config_changes(server, cookie) if cookie is not None: kwargs[username] = cookie try: yield from f(testcase, **kwargs) finally: yield from revert_config_changes(server, cookie, oldval) return wrapper return decorator def using_database(dbarg='db'): @asyncio.coroutine def create_database(server, cookie): db = server[dbname()] yield from db.create(auth=cookie) return db @asyncio.coroutine def drop_database(db, cookie): try: yield from db.delete(auth=cookie) except aiocouchdb.errors.ResourceNotFound: pass def decorator(f): @functools.wraps(f) def wrapper(testcase, **kwargs): server, cookie = testcase.server, testcase.cookie with testcase.response(data=b'{"ok": true}'): db = yield from create_database(server, cookie) assert dbarg not in kwargs, \ 'conflict: both {} and {} are referenced as {}'.format( db, kwargs[dbarg], dbarg ) kwargs[dbarg] = db try: yield from f(testcase, **kwargs) finally: with testcase.response(data=b'{"ok": true}'): yield from drop_database(db, cookie) return wrapper return decorator @asyncio.coroutine def populate_database(db, docs_count): def generate_docs(count): for _ in range(count): dt = datetime.datetime.fromtimestamp( random.randint(1234567890, 2345678901) ) dta = [dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second] doc = { '_id': uuid(), 'created_at': dta, 'num': random.randint(0, 10), 'type': random.choice(['a', 'b', 'c']) } yield doc if not (yield from db.exists()): yield from db.create() docs = list(generate_docs(docs_count)) updates = yield from db.bulk_docs(docs) mapping = {doc['_id']: doc for doc in docs} if not updates: return {} for update in updates: mapping[update['id']]['_rev'] = update['rev'] return mapping def uuid(): return _uuid.uuid4().hex def dbname(idx=None, prefix='test/aiocouchdb'): if idx: return '/'.join((prefix, idx, uuid())) else: return '/'.join((prefix, uuid())) def run_for(*targets): def decorator(f): @functools.wraps(f) @unittest.skipIf(TARGET not in targets, 'runs only for targets: %s' % ', '.join(targets)) def wrapper(*args, **kwargs): return f(*args, **kwargs) return wrapper return decorator def skip_for(*targets): def decorator(f): @functools.wraps(f) @unittest.skipIf(TARGET in targets, 'skips for targets: %s' % ', '.join(targets)) def wrapper(*args, **kwargs): return f(*args, **kwargs) return wrapper return decorator ```
{ "source": "0000Blaze/Smart-Attendance", "score": 2 }
#### File: Smart-Attendance/teacherApp/teacher.py ```python from server import client_teacher from numpy import spacing from kivymd.app import MDApp from kivymd.uix.boxlayout import MDBoxLayout from kivymd.uix.button import MDRaisedButton from kivymd.uix.label import MDLabel from kivy.uix.image import Image from kivymd.uix.textfield import MDTextField from kivymd.uix.datatables import MDDataTable from kivy.metrics import dp from kivy.uix.screenmanager import ScreenManager, Screen class LoginWindow(Screen): pass class AttendanceWindow(Screen): pass cardColor = [0.796875, 0.8984375, 0.99609375, 1] textColor = [0, 0, 0, 1] backgroundColor = [0.59765625, 0.8046875, 0.99609375, 1] sm = ScreenManager() sm.add_widget(LoginWindow(name="login")) sm.add_widget(AttendanceWindow(name="attendance")) class MainApp(MDApp): teacherId = "" classId = "" className = "" classList = [] subjectId = "" subjectname = "" subjectList = [] attendanceId = "" attendanceList = {} attendanceToBeDone = [] attendanceListMini = [] data_tables = None stop_btn = None present_btn = None def __init__(self, **kwargs): self.title = "Smart Attendance" super().__init__(**kwargs) def build(self): loginBg = MDBoxLayout() loginBg.md_bg_color = backgroundColor imageLayout = MDBoxLayout(size_hint=(0.15, 0.15), pos_hint={'center_x': .5, 'center_y': .9}) imageObj = Image(source="./assets/icon.png") imageLayout.add_widget(imageObj) smallCard = MDBoxLayout() smallCard.md_bg_color = cardColor smallCard.size_hint = (0.5, 0.65) smallCard.radius = [40, 40, 40, 40] smallCard.orientation = "vertical" smallCard.pos_hint = {'center_x': .5, 'center_y': .5} teacherIDBox = MDBoxLayout() teacherIDBox.pos_hint = {'center_x': .5, 'center_y': .5} teacherIDBox.orientation = 'vertical' teacherIDBox.adaptive_height = True teacherIDBox.size_hint = (0.5, 1.0) self.teacherIDInp = MDTextField(hint_text="Teacher Id:") self.teacherIDInp.color_mode = "custom" self.teacherIDInp.line_color_normal = textColor self.teacherIDInp.line_color_focus = textColor self.teacherIDInp.hint_text_color = textColor self.teacherIDInp.pos_hint = {'center_x': .5, 'center_y': .2} self.classIDInp = MDTextField(hint_text="Class Id:") self.classIDInp.hint_text = "Class Id:" self.classIDInp.color_mode = "custom" self.classIDInp.line_color_normal = textColor self.classIDInp.line_color_focus = textColor self.classIDInp.hint_text_color = textColor self.classIDInp.pos_hint = {'center_x': .5, 'center_y': .2} teacherIDLabel = MDLabel(text="Teacher Id:") teacherIDLabel.size_hint = (1, 0.2) classIDLabel = MDLabel(text="Class Id:") classIDLabel.size_hint = (1, 0.2) teacherIDBox.add_widget(teacherIDLabel) teacherIDBox.add_widget(self.teacherIDInp) teacherIDBox.add_widget(classIDLabel) teacherIDBox.add_widget(self.classIDInp) connectButton = MDRaisedButton(text="Connect") connectButton.pos_hint = {'center_x': .5, 'center_y': .5} connectButton.bind(on_press=self.connectCallback) subjectNameLayout = MDBoxLayout(orientation="vertical") subjectNameLayout.pos_hint = {'center_x': .5, 'center_y': .5} subjectNameLayout.size_hint = (0.65, 0.5) subjectNameLayout.adaptive_height = True self.teacherName = MDLabel(pos_hint={'center_x': .5, 'center_y': .5}) self.teacherName.text = "" self.subjectName = MDLabel(pos_hint={'center_x': .5, 'center_y': .5}) self.subjectName.text = "No Connection" subjectNameLayout.add_widget(self.teacherName) subjectNameLayout.add_widget(self.subjectName) startButton = MDRaisedButton(text="Start") startButton.pos_hint = {'center_x': .5, 'center_y': .5} startButton.bind(on_release=self.startCallback) smallCard.add_widget(teacherIDBox) smallCard.add_widget(connectButton) smallCard.add_widget(subjectNameLayout) smallCard.add_widget(startButton) smallCard.add_widget(MDLabel(size_hint=(1, 0.2))) loginScreen = sm.get_screen("login") loginScreen.add_widget(loginBg) loginScreen.add_widget(imageLayout) loginScreen.add_widget(smallCard) ########################################################################### attendanceBg = MDBoxLayout() attendanceBg.md_bg_color = backgroundColor attendanceBox = MDBoxLayout(orientation="vertical") attendanceBox.pos_hint = {"center_x": .5, "center_y": .9} attendanceBox.size_hint = (0.9, 0.2) # attendanceBox.adaptive_height = True # attendanceBox = MDBoxLayout(spacing="40dp") # attendanceBox.md_bg_color = [1, 0, 0, 1] attendanceInnerBox1 = MDBoxLayout(orientation="horizontal") attendanceInnerBox1.size_hint = (1, 0.5) self.attendanceTextLabel = MDLabel( text="Attendance will time out in 10 minutes") backButton = MDRaisedButton(text="Back") backButton.bind(on_press=self.backCallback) attendanceInnerBox2 = MDBoxLayout(orientation="horizontal") attendanceInnerBox2.size_hint = (1, 0.5) self.attendanceCodeLabel = MDLabel(text="Attendance Code :") refreshButton = MDRaisedButton(text="Refresh") refreshButton.bind(on_press=self.refreshCallback) attendanceInnerBox1.add_widget(self.attendanceTextLabel) attendanceInnerBox1.add_widget(backButton) attendanceInnerBox2.add_widget(self.attendanceCodeLabel) attendanceInnerBox2.add_widget(refreshButton) attendanceBox.add_widget(attendanceInnerBox1) attendanceBox.add_widget(attendanceInnerBox2) # stopAttendanceButton = MDRaisedButton(text="Stop Attendance") # stopAttendanceButton.bind(on_press=self.stopAttendanceCallback) attendanceScreen = sm.get_screen("attendance") attendanceScreen.add_widget(attendanceBg) attendanceScreen.add_widget(attendanceBox) # attendanceScreen.add_widget(stopAttendanceButton) return sm def getSubject(self): try: subjectListFromServer = client_teacher.updateClassAndSubjects( self.teacherId) # # get subject list of each class teached by teacher # for i in subjectListFromServer["subject"]: # self.subjectList.append(i) # print(subjectList) if "error" not in subjectListFromServer: # print(subjectListFromServer["teacher_name"]) self.subjectId = subjectListFromServer["subject"][0][0] self.subjectname = subjectListFromServer["subject"][0][1] self.teacherName.text = str( "Welcome, ") + str(subjectListFromServer["teacher_name"]) # print(self.subjectId) except Exception as e: print("Subject retrival error", e) pass def startAttendanceSheet(self): try: AttendanceListFromServer = client_teacher.startAttendance( self.teacherId, self.classId, self.subjectId) print(self.teacherId, self.classId, self.subjectId) if "error" in AttendanceListFromServer: print(AttendanceListFromServer["error"]) self.attendanceTextLabel.text = AttendanceListFromServer["error"] else: # save attendance code self.attendanceId = AttendanceListFromServer["acode"] for list in AttendanceListFromServer["student_list"]: #print(list[0], list[1]) presence = "Absent" presenceList = [list[1], presence] self.attendanceList[list[0]] = presenceList print(AttendanceListFromServer["timeout"]) self.attendanceTextLabel.text = AttendanceListFromServer["timeout"] except Exception as e: print("error :", e) def updateAttendanceSheet(self): try: AttendanceListFromServer = client_teacher.getAttendance( self.teacherId, self.classId) if "error" in AttendanceListFromServer: print(AttendanceListFromServer["error"]) else: # update presence in list keys = AttendanceListFromServer["student_list"] # print(keys) for key in keys: self.attendanceList[key][1] = "Present" self.widgetRemover() # removes old instance of datatable,stop and present button attendanceScreen = sm.get_screen("attendance") # adds data table , stop and present button self.load_table(attendanceScreen) except Exception as e: print(e) def finalAttendanceSheet(self, *args): try: AttendanceListFromServer = client_teacher.stopAttendance( self.teacherId, self.classId) if "error" in AttendanceListFromServer: print(AttendanceListFromServer["error"]) self.attendanceTextLabel.text = AttendanceListFromServer["error"] else: print(AttendanceListFromServer["success"]) self.attendanceTextLabel.text = AttendanceListFromServer["success"] except Exception as e: print(e) def manualPresent(self, *args): try: for text in self.attendanceToBeDone: print("Done presence", text) client_teacher.markAttendance( self.teacherId, self.classId, text) except: print("some error occured during manual attendance") # empty selected check for presence while len(self.attendanceToBeDone) > 0: self.attendanceToBeDone.pop() # print("After",self.attendanceToBeDone) self.updateAttendanceSheet() def startCallback(self, *args): self.startAttendanceSheet() self.attendanceCodeLabel.text = "Attendance Code: " + \ str(self.attendanceId) sm.current = "attendance" attendanceScreen = sm.get_screen("attendance") self.load_table(attendanceScreen) def connectCallback(self, *args): self.classIDInp.text = self.classIDInp.text.upper() self.teacherId = self.teacherIDInp.text self.classId = self.classIDInp.text self.getSubject() # print("searching subject for", self.teacherID, self.classID) self.subjectName.text = str(self.subjectname) def stopAttendanceCallback(self, *args): self.finalAttendanceSheet() self.attendanceCodeLabel.text = "Attendance Code: " pass def backCallback(self, *args): sm.current = "login" def refreshCallback(self, *args): self.updateAttendanceSheet() self.widgetRemover() aScreen = sm.get_screen("attendance") self.load_table(aScreen) def stopCallback(self, *args): self.finalAttendanceSheet() pass def presentCallback(self, *args): self.manualPresent() attendanceScreen = sm.get_screen("attendance") self.widgetRemover() self.load_table(attendanceScreen) pass def load_table(self, aScreen): # list to make attendance list a list for initial insert in data table AttendListMini = [] for key in self.attendanceList: AttendListMini.append(key) AttendListMini.append(self.attendanceList[key][0]) AttendListMini.append(self.attendanceList[key][1]) self.data_tables = MDDataTable( pos_hint={'center_y': 0.5, 'center_x': 0.5}, size_hint=(0.7, 0.6), rows_num=48, check=True, # use_pagination=True, column_data=[ ("Roll Number", dp(40)), ("Student", dp(30)), ("Presence", dp(30)), ], row_data=[ (AttendListMini[i*3], AttendListMini[(i*3)+1], AttendListMini[(i*3)+2]) for i in range(int(len(AttendListMini)/3)) # (f"{i + 1}", "2.23", "3.65") # for i in range(50) ], ) self.data_tables.bind(on_check_press=self.check_press) self.stop_btn = MDRaisedButton( text="Stop", pos_hint={'center_y': 0.1, 'center_x': 0.6} ) self.stop_btn.bind(on_press=self.stopCallback) self.present_btn = MDRaisedButton( text="Mark Present", pos_hint={'center_y': 0.1, 'center_x': 0.3} ) self.present_btn.bind(on_press=self.presentCallback) aScreen.add_widget(self.data_tables) aScreen.add_widget(self.stop_btn) aScreen.add_widget(self.present_btn) # return layout def check_press(self, instance_table, current_row): print(current_row) self.attendanceToBeDone.append(current_row[0]) def widgetRemover(self): attendanceScreen = sm.get_screen("attendance") attendanceScreen.remove_widget(self.data_tables) attendanceScreen.remove_widget(self.stop_btn) attendanceScreen.remove_widget(self.present_btn) # attendanceScreen.clear_widgets() # attendanceScreen.add_widget(MDLabel(text="hi ravi")) if __name__ == "__main__": MainApp().run() ```
{ "source": "0000duck/MPlib", "score": 3 }
#### File: MPlib/mplib/planner.py ```python from typing import Sequence, Tuple, Union import os import numpy as np from transforms3d.quaternions import quat2mat import toppra import toppra as ta import toppra.constraint as constraint import toppra.algorithm as algo from .pymp import * class Planner: """Motion planner.""" # TODO(jigu): default joint vel and acc limits # TODO(jigu): how does user link names and joint names are exactly used? def __init__( self, urdf: str, user_link_names: Sequence[str], user_joint_names: Sequence[str], move_group: str, joint_vel_limits: Union[Sequence[float], np.ndarray], joint_acc_limits: Union[Sequence[float], np.ndarray], srdf: str = "" ): r"""Motion planner for robots. Args: urdf: Unified Robot Description Format file. user_link_names: names of links, the order user_joint_names: names of the joints to plan move_group: target link to move, usually the end-effector. joint_vel_limits: maximum joint velocities for time parameterization, which should have the same length as joint_acc_limits: maximum joint accelerations for time parameterization, which should have the same length as srdf: Semantic Robot Description Format file. References: http://docs.ros.org/en/kinetic/api/moveit_tutorials/html/doc/urdf_srdf/urdf_srdf_tutorial.html """ self.urdf = urdf if srdf == "" and os.path.exists(urdf.replace(".urdf", ".srdf")): srdf = urdf.replace(".urdf", ".srdf") print("No SRDF file provided. Try to load %s." % srdf) self.srdf = srdf self.user_link_names = user_link_names self.user_joint_names = user_joint_names self.joint_name_2_idx = {} for i, joint in enumerate(self.user_joint_names): self.joint_name_2_idx[joint] = i self.link_name_2_idx = {} for i, link in enumerate(self.user_link_names): self.link_name_2_idx[link] = i self.robot = articulation.ArticulatedModel( urdf, srdf, [0, 0, -9.81], self.user_joint_names, self.user_link_names, verbose=False, convex=True, ) self.pinocchio_model = self.robot.get_pinocchio_model() self.planning_world = planning_world.PlanningWorld( [self.robot], ["robot"], [], [] ) if srdf == "": self.generate_collision_pair() self.robot.update_SRDF(self.srdf) assert(move_group in self.user_link_names) self.move_group = move_group self.robot.set_move_group(self.move_group) self.move_group_joint_indices = ( self.robot.get_move_group_joint_indices() ) self.joint_types = self.pinocchio_model.get_joint_types() self.joint_limits = np.concatenate( self.pinocchio_model.get_joint_limits() ) self.planner = ompl.OMPLPlanner(world=self.planning_world) self.joint_vel_limits = joint_vel_limits self.joint_acc_limits = joint_acc_limits self.move_group_link_id = self.link_name_2_idx[self.move_group] assert len(self.joint_vel_limits) == len( self.move_group_joint_indices ), len(self.move_group_joint_indices) assert len(self.joint_acc_limits) == len(self.move_group_joint_indices) def generate_collision_pair(self, sample_time = 1000000, echo_freq = 100000): print("Since no SRDF file is provided. We will first detect link pairs that will always collide. This may take several minutes.") n_link = len(self.user_link_names) cnt = np.zeros((n_link, n_link), dtype=np.int32) for i in range(sample_time): qpos = self.pinocchio_model.get_random_configuration() self.robot.set_qpos(qpos, True) collisions = self.planning_world.collide_full() for collision in collisions: u = self.link_name_2_idx[collision.link_name1] v = self.link_name_2_idx[collision.link_name2] cnt[u][v] += 1 if i % echo_freq == 0: print("Finish %.1f%%!" % (i * 100 / sample_time)) import xml.etree.ElementTree as ET from xml.dom import minidom root = ET.Element('robot') robot_name = self.urdf.split('/')[-1].split('.')[0] root.set('name', robot_name) self.srdf = self.urdf.replace(".urdf", ".srdf") for i in range(n_link): for j in range(n_link): if cnt[i][j] == sample_time: link1 = self.user_link_names[i] link2 = self.user_link_names[j] print("Ignore collision pair: (%s, %s), reason: always collide" % (link1, link2)) collision = ET.SubElement(root, 'disable_collisions') collision.set('link1', link1) collision.set('link2', link2) collision.set('reason', 'Default') srdffile = open(self.srdf, "w") srdffile.write(minidom.parseString(ET.tostring(root)).toprettyxml(indent=" ")) srdffile.close() print("Saving the SRDF file to %s" % self.srdf) def distance_6D(self, p1, q1, p2, q2): return np.linalg.norm(p1 - p2) + min( np.linalg.norm(q1 - q2), np.linalg.norm(q1 + q2) ) def check_joint_limit(self, q): n = len(q) flag = True for i in range(n): if self.joint_types[i].startswith("JointModelR"): if np.abs(q[i] - self.joint_limits[i][0]) < 1e-3: continue q[i] -= ( 2 * np.pi * np.floor((q[i] - self.joint_limits[i][0]) / (2 * np.pi)) ) if q[i] > self.joint_limits[i][1] + 1e-3: flag = False else: if ( q[i] < self.joint_limits[i][0] - 1e-3 or q[i] > self.joint_limits[i][1] + 1e-3 ): flag = False return flag def IK(self, goal_pose, start_qpos, mask = [], n_init_qpos=20, threshold=1e-3): index = self.link_name_2_idx[self.move_group] min_dis = 1e9 idx = self.move_group_joint_indices qpos0 = np.copy(start_qpos) results = [] self.robot.set_qpos(start_qpos, True) for i in range(n_init_qpos): ik_results = self.pinocchio_model.compute_IK_CLIK( index, goal_pose, start_qpos, mask ) flag = self.check_joint_limit(ik_results[0]) # will clip qpos # check collision self.planning_world.set_qpos_all(ik_results[0][idx]) if (len(self.planning_world.collide_full()) != 0): flag = False if flag: self.pinocchio_model.compute_forward_kinematics(ik_results[0]) new_pose = self.pinocchio_model.get_link_pose(index) tmp_dis = self.distance_6D( goal_pose[:3], goal_pose[3:], new_pose[:3], new_pose[3:] ) if tmp_dis < min_dis: min_dis = tmp_dis if tmp_dis < threshold: result = ik_results[0] unique = True for j in range(len(results)): if np.linalg.norm(results[j][idx] - result[idx]) < 0.1: unique = False if unique: results.append(result) start_qpos = self.pinocchio_model.get_random_configuration() mask_len = len(mask) if mask_len > 0: for j in range(mask_len): if mask[j]: start_qpos[j] = qpos0[j] if len(results) != 0: status = "Success" elif min_dis != 1e9: status = ( "IK Failed! Distance %lf is greater than threshold %lf." % (min_dis, threshold) ) else: status = "IK Failed! Cannot find valid solution." return status, results def TOPP(self, path, step=0.1, verbose=False): N_samples = path.shape[0] dof = path.shape[1] assert dof == len(self.joint_vel_limits) assert dof == len(self.joint_acc_limits) ss = np.linspace(0, 1, N_samples) path = ta.SplineInterpolator(ss, path) pc_vel = constraint.JointVelocityConstraint(self.joint_vel_limits) pc_acc = constraint.JointAccelerationConstraint(self.joint_acc_limits) instance = algo.TOPPRA( [pc_vel, pc_acc], path, parametrizer="ParametrizeConstAccel" ) jnt_traj = instance.compute_trajectory() ts_sample = np.linspace( 0, jnt_traj.duration, int(jnt_traj.duration / step) ) qs_sample = jnt_traj(ts_sample) qds_sample = jnt_traj(ts_sample, 1) qdds_sample = jnt_traj(ts_sample, 2) return ts_sample, qs_sample, qds_sample, qdds_sample, jnt_traj.duration def update_point_cloud(self, pc, resolution=1e-3): self.planning_world.update_point_cloud(pc, resolution) def update_attached_box(self, size, pose, link_id=-1): if link_id == -1: link_id = self.move_group_link_id self.planning_world.update_attached_box(size, link_id, pose) def plan( self, goal_pose, current_qpos, mask = [], time_step=0.1, rrt_range=0.1, planning_time=1, fix_joint_limits=True, use_point_cloud=False, use_attach=False, verbose=False, ): self.planning_world.set_use_point_cloud(use_point_cloud) self.planning_world.set_use_attach(use_attach) n = current_qpos.shape[0] if fix_joint_limits: for i in range(n): if current_qpos[i] < self.joint_limits[i][0]: current_qpos[i] = self.joint_limits[i][0] + 1e-3 if current_qpos[i] > self.joint_limits[i][1]: current_qpos[i] = self.joint_limits[i][1] - 1e-3 self.robot.set_qpos(current_qpos, True) collisions = self.planning_world.collide_full() if len(collisions) != 0: print("Invalid start state!") for collision in collisions: print("%s and %s collide!" % (collision.link_name1, collision.link_name2)) idx = self.move_group_joint_indices ik_status, goal_qpos = self.IK(goal_pose, current_qpos, mask) if ik_status != "Success": return {"status": ik_status} if verbose: print("IK results:") for i in range(len(goal_qpos)): print(goal_qpos[i]) goal_qpos_ = [] for i in range(len(goal_qpos)): goal_qpos_.append(goal_qpos[i][idx]) self.robot.set_qpos(current_qpos, True) status, path = self.planner.plan( current_qpos[idx], goal_qpos_, range=rrt_range, verbose=verbose, time=planning_time, ) if status == "Exact solution": if verbose: ta.setup_logging("INFO") else: ta.setup_logging("WARNING") times, pos, vel, acc, duration = self.TOPP(path, time_step) return { "status": "Success", "time": times, "position": pos, "velocity": vel, "acceleration": acc, "duration": duration, } else: return {"status": "RRT Failed. %s" % status} def plan_screw( self, target_pose, qpos, qpos_step=0.1, time_step=0.1, use_point_cloud=False, use_attach=False, verbose=False, ): self.planning_world.set_use_point_cloud(use_point_cloud) self.planning_world.set_use_attach(use_attach) qpos = np.copy(qpos) self.robot.set_qpos(qpos, True) def pose7D2mat(pose): mat = np.eye(4) mat[0:3, 3] = pose[:3] mat[0:3, 0:3] = quat2mat(pose[3:]) return mat def skew(vec): return np.array( [ [0, -vec[2], vec[1]], [vec[2], 0, -vec[0]], [-vec[1], vec[0], 0], ] ) def pose2exp_coordinate(pose: np.ndarray) -> Tuple[np.ndarray, float]: def rot2so3(rotation: np.ndarray): assert rotation.shape == (3, 3) if np.isclose(rotation.trace(), 3): return np.zeros(3), 1 if np.isclose(rotation.trace(), -1): return np.zeros(3), -1e6 theta = np.arccos((rotation.trace() - 1) / 2) omega = ( 1 / 2 / np.sin(theta) * np.array( [ rotation[2, 1] - rotation[1, 2], rotation[0, 2] - rotation[2, 0], rotation[1, 0] - rotation[0, 1], ] ).T ) return omega, theta omega, theta = rot2so3(pose[:3, :3]) if theta < -1e5: return omega, theta ss = skew(omega) inv_left_jacobian = ( np.eye(3) / theta - 0.5 * ss + (1.0 / theta - 0.5 / np.tan(theta / 2)) * ss @ ss ) v = inv_left_jacobian @ pose[:3, 3] return np.concatenate([v, omega]), theta self.pinocchio_model.compute_forward_kinematics(qpos) ee_index = self.link_name_2_idx[self.move_group] current_p = pose7D2mat(self.pinocchio_model.get_link_pose(ee_index)) target_p = pose7D2mat(target_pose) relative_transform = target_p @ np.linalg.inv(current_p) omega, theta = pose2exp_coordinate(relative_transform) if theta < -1e4: return {"status": "screw plan failed."} omega = omega.reshape((-1, 1)) * theta index = self.move_group_joint_indices path = [np.copy(qpos[index])] while True: self.pinocchio_model.compute_full_jacobian(qpos) J = self.pinocchio_model.get_link_jacobian(ee_index, local=False) delta_q = np.linalg.pinv(J) @ omega delta_q *= qpos_step / (np.linalg.norm(delta_q)) delta_twist = J @ delta_q flag = False if np.linalg.norm(delta_twist) > np.linalg.norm(omega): ratio = np.linalg.norm(omega) / np.linalg.norm(delta_twist) delta_q = delta_q * ratio delta_twist = delta_twist * ratio flag = True qpos += delta_q.reshape(-1) omega -= delta_twist def check_joint_limit(q): n = len(q) for i in range(n): if ( q[i] < self.joint_limits[i][0] - 1e-3 or q[i] > self.joint_limits[i][1] + 1e-3 ): return False return True within_joint_limit = check_joint_limit(qpos) self.planning_world.set_qpos_all(qpos[index]) collide = self.planning_world.collide() if ( np.linalg.norm(delta_twist) < 1e-4 or collide or within_joint_limit == False ): return {"status": "screw plan failed"} path.append(np.copy(qpos[index])) if flag: if verbose: ta.setup_logging("INFO") else: ta.setup_logging("WARNING") times, pos, vel, acc, duration = self.TOPP( np.vstack(path), time_step ) return { "status": "Success", "time": times, "position": pos, "velocity": vel, "acceleration": acc, "duration": duration, } ```
{ "source": "0000matteo0000/pyqtgraph", "score": 3 }
#### File: pyqtgraph/examples/MultiAxisPlotWidgetExample.py ```python import numpy as np import pyqtgraph as pg from pyqtgraph.Qt.QtWidgets import QMainWindow def mkStripedPen(colors, blending=0.0001, span=[0, 15], orientation="horizontal", width=2): stops = [] stops_colors = [] previous = None for i, color in enumerate(colors + [None]): pos = i / len(colors) if previous is not None: stops.append(pos - blending) stops_colors.append(previous) if color is not None: stops.append(pos) stops_colors.append(color) previous = color return pg.ColorMap(stops, stops_colors, mapping=pg.ColorMap.REPEAT).getPen(span=span, orientation=orientation, width=width) app = pg.mkQApp() mw = QMainWindow() mw.resize(800, 400) pg.setConfigOption("background", "w") pg.setConfigOption("foreground", "k") mpw = pg.MultiAxisPlotWidget() mw.setCentralWidget(mpw) mw.show() # LEGEND mpw.addLegend(offset=(0, 0)) # TITLE mpw.setTitle("MultiAxisPlotWidget Example") # AXYS ax1 = mpw.addAxis("sx1", "bottom", text="Samples1", units="sx1") ax1c = "red" ax1.setPen(ax1c) ax2 = mpw.addAxis("sx2", "bottom", text="Samples2", units="sx2") ax2c = "green" ax2.setPen(ax2c) ay1 = mpw.addAxis("sy1", "left", text="Data1", units="sy1") ay1c = "cyan" ay1.setPen(ay1c) ay2 = mpw.addAxis("sy2", "left", text="Data2", units="sy2") ay2c = "magenta" ay2.setPen(ay2c) # CHARTS c0, pi0 = mpw.addChart("Dataset 0") c0.setPen("black") c1, pi1 = mpw.addChart("Dataset 1", xAxisName="sx1", yAxisName="sy1") c1.setPen(mkStripedPen([ax1c, ay1c])) c2, pi2 = mpw.addChart("Dataset 2", xAxisName="sx2", yAxisName="sy1") c2.setPen(mkStripedPen([ax2c, ay1c])) c3, pi3 = mpw.addChart("Dataset 3", xAxisName="sx2", yAxisName="sy2") c3.setPen(mkStripedPen([ax2c, ay2c])) # make and display chart mpw.makeLayout( # optional, selects and orders axes displayed. # remember to include the default axes if used. axes=["bottom", "sx1", "sx2", "sy2", "sy1", "left"], # optional, selects charts displayed charts=["Dataset 0", "Dataset 1", "Dataset 2", "Dataset 3"] ) mpw.enableAxisAutoRange() for i, c in enumerate([c0, c1, c2, c3, ], start=1): c.setData(np.array(np.sin(np.linspace(0, i * 2 * np.pi, num=1000)))) mpw.update() # Start Qt event loop unless running in interactive mode. if __name__ == '__main__': pg.exec() ```
{ "source": "0000sir/opencv-graphic-experiments", "score": 3 }
#### File: opencv-graphic-experiments/x-4/x-4.py ```python import cv2 import numpy as np def separate_frame(frame, width, height): odd_frame = np.zeros((height, width, 3), np.uint8) even_frame = np.zeros((height,width, 3), np.uint8) for x in range(0, height-1): for y in range(0, width-1): point = frame[x, y] r0 = point[2]%2==0 and point[2] or 0 g0 = point[1]%2==0 and point[1] or 0 b0 = point[0]%2==0 and point[0] or 0 r1 = point[2]%2==1 and point[2] or 0 g1 = point[1]%2==1 and point[1] or 0 b1 = point[0]%2==1 and point[0] or 0 even_frame[x,y] = [g0, r0, b0] odd_frame[x,y] = [g1, r1, b1] return (odd_frame, even_frame) img = cv2.imread('../people.jpg') #cv2.imshow('img', img) height, width = img.shape[:2] img0,img1 = separate_frame(img, width, height) cv2.imshow('img-0', img0) cv2.imshow('img-1', img1) cv2.waitKey(0) cv2.destroyAllWindows() ```
{ "source": "00-01/gap_sdk", "score": 2 }
"\n#### File: nntool/execution/execution_progress.py\n```python\nclass ExecutionProgress(object):\n (...TRUNCATED)
{ "source": "0003088/libelektra-qt-gui-test", "score": 2 }
"\n#### File: python/python/python_configparser.py\n```python\nimport kdb\nimport configparser\n\ncl(...TRUNCATED)
{ "source": "000alen/Phaedra", "score": 3 }
"\n#### File: Phaedra/Phaedra/Knowledge.py\n```python\nfrom typing import Dict, List\n\nimport wikip(...TRUNCATED)
{ "source": "000james000/swift", "score": 2 }
"\n#### File: utils/lldb/lldbToolBox.py\n```python\nimport argparse\nimport os\nimport shlex\nimport(...TRUNCATED)

This dataset is a version of this dataset JanSchTech/starcoderdata-python-edu-lang-score which in turn is a version of the starcoderv1 dataset.

We have collapsed the files that belongs to the same repository into one larger file to help models learn the relationship between code within the same repository.

Downloads last month
21