text stringlengths 8 6.05M |
|---|
# coding: utf-8
import numpy as np
class Sigmoid(object):
@staticmethod
def y(z):
return 1 / (1 + np.exp(-z))
@staticmethod
def dy_dz(y):
return y * (1. - y)
|
from django.conf import settings
from django.contrib.auth.models import AbstractUser
#importing AbstractUser from django, it's a model. It has defined what it means to be an abstract user. It's a model that comes baked in, and we're going to inherit from that model.
from django.db import models
class User(AbstractUser):
pass
class Profile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True,)
avatar = models.ImageField(upload_to='profiles/')
display_name = models.CharField(max_length=255)
def __str__(self):
return self.display_name
#when image is uploaded through a profile, it gets nested within the profile directory within media
#class User(AbstractUser):
# pass
#if you don't have any fields that you're going to add, you need to at least put pass or it will error out
# on_delete=models.CASCADE This means that when the user gets deleted the profile does as well.
#avatar = models.ImageField(upload_to='profiles/') going to have an image directory, and within this we'll have a profiles directory.
#models.CharField(max_length=255) if it's going to be a longer entry- use a textfield (ex blog post)
|
import csv
import cv2
import numpy as np
import sklearn
default_batch_size = 30
### Generator and Image Processing
def generator(data, batch_size=default_batch_size):
path = './data/IMG/'
while 1: # Loop forever so the generator never terminates
for i in range(0, len(data), batch_size):
batch = data[i:i+batch_size]
images = []
measurements = []
for row in batch:
center_image = cv2.imread(path + row[0].split('/')[-1])
center_image = cv2.cvtColor(center_image, cv2.COLOR_BGR2RGB)
images.append(center_image)
left_image = cv2.imread(path + row[1].split('/')[-1])
left_image = cv2.cvtColor(left_image, cv2.COLOR_BGR2RGB)
images.append(left_image)
right_image = cv2.imread(path + row[2].split('/')[-1])
right_image = cv2.cvtColor(right_image, cv2.COLOR_BGR2RGB)
images.append(right_image)
correction = 0.05
steering_angle = float(row[3])
measurements.append(steering_angle)
measurements.append(steering_angle + correction)
measurements.append(steering_angle - correction)
augmented_images, augmented_measurements = augment(images, measurements)
X = np.array(augmented_images)
y = np.array(augmented_measurements)
yield sklearn.utils.shuffle(X, y)
# Flip images for augmented data
def augment(images, measurements):
augmented_images, augmented_measurements = [], []
for image, measurement in zip(images, measurements):
augmented_images.append(image)
augmented_measurements.append(measurement)
augmented_images.append(cv2.flip(image, 1))
augmented_measurements.append(measurement * -1.0)
return augmented_images, augmented_measurements
### Model Architecture
from keras.models import Sequential
from keras.layers import Flatten, Dense, Dropout, Lambda, Cropping2D, Convolution2D
model = Sequential()
# Normalization
model.add(Lambda(lambda x: (x / 255.0) - 0.5, input_shape=(160, 320, 3)))
# Cropping
model.add(Cropping2D(cropping=((70, 25), (0, 0))))
# Convolutional Layers
model.add(Convolution2D(24, 5, 5, subsample=(2, 2), activation='relu'))
model.add(Convolution2D(36, 5, 5, subsample=(2, 2), activation='relu'))
model.add(Convolution2D(48, 5, 5, subsample=(2, 2), activation='relu'))
model.add(Convolution2D(64, 3, 3, activation='relu'))
model.add(Convolution2D(64, 3, 3, activation='relu'))
# Fully Connected Layers
model.add(Flatten())
model.add(Dense(100))
model.add(Dropout(0.3))
model.add(Dense(50))
model.add(Dropout(0.3))
model.add(Dense(10))
model.add(Dense(1))
model.compile(loss='mse', optimizer='adam')
### Model Training
from keras.models import Model
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
data = []
with open('./data/driving_log.csv') as csvfile:
reader = csv.reader(csvfile)
for line in reader:
data.append(line)
data = data[1:] # remove csv title line
train_samples, validation_samples = train_test_split(data, test_size=0.2)
train_generator = generator(train_samples)
validation_generator = generator(validation_samples)
model.fit_generator(train_generator,
samples_per_epoch = len(train_samples),
validation_data = validation_generator,
nb_val_samples = len(validation_samples),
nb_epoch=5,
verbose=1)
model.save('model.h5') |
import gym
from gym import wrappers
import qlearning
import numpy
import matplotlib.pyplot as plt
NUM_EPISODES = 2000
N_BINS = [8, 8, 8, 8]
MAX_STEPS = 200
FAIL_PENALTY = -100
EPSILON = 0.5
EPSILON_DECAY = 0.99
LEARNING_RATE = 0.05
DISCOUNT_FACTOR = 0.9
RECORD = False
MIN_VALUES = [-0.5, -2.0, -0.5, -3.0]
MAX_VALUES = [0.5, 2.0, 0.5, 3.0]
BINS = [numpy.linspace(MIN_VALUES[i], MAX_VALUES[i], N_BINS[i])
for i in xrange(4)]
def discretize(obs):
return tuple([int(numpy.digitize(obs[i], BINS[i])) for i in xrange(4)])
def train(agent, env, history, num_episodes=NUM_EPISODES):
for i in xrange(NUM_EPISODES):
if i % 100:
print "Episode {}".format(i + 1)
obs = env.reset()
cur_state = discretize(obs)
for t in xrange(MAX_STEPS):
action = agent.get_action(cur_state)
observation, reward, done, info = env.step(action)
next_state = discretize(observation)
if done:
reward = FAIL_PENALTY
agent.learn(cur_state, action, next_state, reward, done)
print("Episode finished after {} timesteps".format(t + 1))
history.append(t + 1)
break
agent.learn(cur_state, action, next_state, reward, done)
cur_state = next_state
if t == MAX_STEPS - 1:
history.append(t + 1)
print("Episode finished after {} timesteps".format(t + 1))
return agent, history
env = gym.make('CartPole-v0')
if RECORD:
env = wrappers.Monitor(env, '/tmp/cartpole-experiment-1', force=True)
def get_actions(state):
return [0, 1]
agent = qlearning.QLearningAgent(get_actions,
epsilon=EPSILON,
alpha=LEARNING_RATE,
gamma=DISCOUNT_FACTOR,
epsilon_decay=EPSILON_DECAY)
history = []
agent, history = train(agent, env, history)
if RECORD:
env.monitor.close()
avg_reward = [numpy.mean(history[i*100:(i+1)*100]) for i in xrange(int(len(history)/100))]
f_reward = plt.figure(1)
plt.plot(numpy.linspace(0, len(history), len(avg_reward)), avg_reward)
plt.ylabel('Rewards')
f_reward.show()
print 'press enter to continue'
raw_input()
plt.close()
# Display:
print 'press ctrl-c to stop'
while True:
obs = env.reset()
cur_state = discretize(obs)
done = False
t = 0
while not done:
env.render()
t = t+1
action = agent.get_action(cur_state)
observation, reward, done, info = env.step(action)
next_state = discretize(observation)
if done:
reward = FAIL_PENALTY
agent.learn(cur_state, action, next_state, reward, done)
print("Episode finished after {} timesteps".format(t+1))
history.append(t+1)
break
agent.learn(cur_state, action, next_state, reward, done)
cur_state = next_state
|
# time complexity O(n)
# space complexity O(1)
def is_palindrome(input):
if input < 0:
return False
divisor = 1
while(input/divisor >= 10):
divisor *= 10
# print("divisor: ", divisor)
while(input > 0):
leading = input // divisor
trailing = input % 10
# print("leading:", leading)
# print("trailing:", trailing)
if leading!=trailing:
return False
input = (input % divisor) // 10
# print("input:", input)
divisor = divisor / 100
return True
print("-121 -> ",is_palindrome(-121))
print("0 -> ",is_palindrome(0))
print("1221 -> ",is_palindrome(1221))
print("9010109 -> ",is_palindrome(9010109))
print("9010209 -> ",is_palindrome(9010209))
|
from django.contrib.auth.models import Group, User # type: ignore
from rest_framework import authentication # type: ignore
from rest_framework import exceptions
from carts.oidc import (
extract_kid,
fetch_pub_key,
fetch_user_info,
invalidate_cache,
verify_token,
)
from carts.carts_api.models import (
AppUser,
State,
RoleFromUsername,
RolesFromJobCode,
StatesFromUsername,
User,
)
from carts.carts_api.model_utils import role_from_raw_ldap_job_codes
from rest_framework.permissions import AllowAny
from datetime import datetime
class JwtAuthentication(authentication.BaseAuthentication):
def authenticate(self, request):
raw_token = self._extract_token(request)
print("+++++++++raw token: " + raw_token)
try:
return self._do_authenticate(raw_token)
except Exception as e:
msg = [
"authentication failed on first attempt, ",
"invalidating cache and trying again...",
]
print(e, "".join(msg), flush=True)
invalidate_cache()
return self._do_authenticate(raw_token)
def _extract_token(self, request):
try:
token_string = request.META.get("HTTP_AUTHORIZATION")
return token_string.split("Bearer ")[1]
except:
raise exceptions.AuthenticationFailed(
"Authentication failed: Bearer token missing!"
)
def _do_authenticate(self, token):
try:
print(f"\n\n%%%%>got token: {token}")
kid = extract_kid(token)
print(f"\n\n%%%%>kid extracted: {kid}")
key = fetch_pub_key(kid)
print(f"\n\n%%%%>key extracted: {key}")
verify_token(token, key)
print(f"\n\n%%%%>token verified: {kid}")
user_info = fetch_user_info(token)
# Check if user is_active in database, if not exit
if _is_user_active(user_info) == False:
print("username: ", user_info.preferred_username)
return
user = _get_or_create_user(user_info)
return (user, None)
except Exception:
raise exceptions.AuthenticationFailed("Authentication failed.")
def _is_user_active(user_info):
""" Returns boolean of is_active column in auth_user table """
if User.objects.filter(username=user_info["preferred_username"]).exists():
response = User.objects.filter(
username=user_info["preferred_username"]
).values_list("is_active", flat=True)[0]
else:
response = True
return response
def _get_or_create_user(user_info):
print(f"$$$$\n\nin create user\n\n\n")
user, _ = User.objects.get_or_create(
username=user_info["preferred_username"],
)
user.first_name = user_info["given_name"]
user.last_name = user_info["family_name"]
user.email = user_info["email"]
user.last_login = datetime.now()
print(f"$$$$\n\nobtained user", user.email, "\n\n\n")
role_map = [*RolesFromJobCode.objects.all()]
print(f"$$$$\n\nhere's a role map", role_map, "\n\n\n")
print(f"\n\n getting user with username: ", user.username)
username_map = [*RoleFromUsername.objects.filter(username=user.username)]
print(f"\n\n $$$$$username_map is: ", username_map)
role = role_from_raw_ldap_job_codes(
role_map, username_map, user_info["job_codes"]
)
print(f"\n\n!!!$$$$$role is: ", role)
states = []
if role in ("state_user"):
# This is where we load their state from the table that
# associates EUA IDs to states, but here we default to MA,
# which we'll need to change once we have proper test users.
try:
state_relationship = StatesFromUsername.objects.get(
username=user.username
)
if state_relationship:
state_codes = state_relationship.state_codes
states = State.objects.filter(code__in=state_codes)
except StatesFromUsername.DoesNotExist:
pass
app_user, _ = AppUser.objects.get_or_create(user=user)
app_user.states.set(states)
app_user.role = role
print(f"$$$$\n\nabout to save app_user\n\n\n")
app_user.save()
if role == "state_user" and states:
group = Group.objects.get(name__endswith=f"{states[0].code} sections")
user.groups.set([group])
if role == "admin_user":
group = Group.objects.get(name="Admin users")
user.groups.set([group])
if role == "co_user":
group = Group.objects.get(name="CO users")
user.groups.set([group])
if role == "bus_user":
group = Group.objects.get(name="Business owner users")
user.groups.set([group])
user.save()
return user
|
'''
TODO
'''
from datetime import datetime
import requests
import pandas as pd
# officeID values
DEV = True
OFFICE_SENATE = 6
SENATE_TYPE_ID = 'C'
STATES = ['CA', 'KY', 'OR'] if DEV else [
'AL', 'AK', 'AZ', 'AR', 'CA', 'CO', 'CT', 'DE', 'FL', 'GA', 'HI', 'ID',
'IL', 'IN', 'IA', 'KS', 'KY', 'LA', 'ME', 'MD', 'MA', 'MI', 'MN', 'MS',
'MO', 'MT', 'NE', 'NV', 'NH', 'NJ', 'NM', 'NY', 'NC', 'ND', 'OH', 'OK',
'OR', 'PA', 'RI', 'SC', 'SD', 'TN', 'TX', 'UT', 'VT', 'VA', 'WA', 'WV',
'WI', 'WY']
API_DATE_FORMAT = '%m/%d/%Y'
TODAY = datetime.utcnow().date()
OUTPUT = 'data'
class APIHandler:
def __init__(self, api_key):
self._api_key = api_key
self.url = 'http://api.votesmart.org'
self.params = {'key': self._api_key, 'o': 'JSON'}
self.Officials = Officials(self.url, self.params)
self.CandidateBio = CandidateBio(self.url, self.params)
def get_current_senators(self):
print('Getting current senator data...')
out = []
for state in STATES:
res = self.Officials.get_by_office_state(OFFICE_SENATE, state)
res = {k.replace('candidateList_', ''): v for k,v in res.items()}
df = pd.DataFrame(res)
out.append(df)
self.senators = pd.concat(out, sort=False)
self.senator_ids = self.senators.candidateId
print('Current senator data obtained.')
def get_senator_bios(self):
print('Getting senator bios...')
msg = ('Must obtain Senator IDs using APIHandler.get_current_senators()'
' first')
assert self.senator_ids is not None, msg
bios = []
for senator in self.senator_ids:
print(f' for senator with ID: {senator}...', end='\r')
bio = self.CandidateBio.get_bio(senator)
detailed_bio = self.CandidateBio.get_detailed_bio(senator)
bio.update(detailed_bio)
bio_df = self._json_to_df(bio, index='bio_candidate_candidateId')
bios.append(bio_df)
bios = pd.concat(bios, sort=False)
self.senator_bios = bios
print('\nSenator bios obtained.')
def save_data(self):
dfs = [self.senators, self.senator_bios]
filenames = ['senators', 'senator_bios']
for df, filename in zip(dfs, filenames):
outpath = f'{OUTPUT}/{filename}_{TODAY}.csv'
print(f'Saving data to {outpath}...')
df.to_csv(outpath, index=False)
def _json_to_df(self, json_obj, index=None):
json_obj = self._format_json(json_obj)
df = pd.DataFrame(json_obj, index=[json_obj[index]])
return df
def _format_json(self, json_obj):
for k, v in json_obj.items():
if isinstance(v, list):
json_obj[k] = str(v)
elif '/' in v and not v.startswith('http'):
try:
json_obj[k] = datetime.strptime(v, API_DATE_FORMAT).date()
except BaseException as e:
print(f'Could not convert {v} to date:\n{e}')
return json_obj
class Officials:
def __init__(self, url, params):
self.params = params
self.url = f'{url}/Officials'
def get_by_office_state(self, office, state):
params = self.params.copy()
params.update({'officeId': office, 'stateId': state})
url = f'{self.url}.getByOfficeState'
res = call(url, params)
flat = flatten(res, out={})
return flat
class CandidateBio:
def __init__(self, url, params):
self.params = params
self.url = f'{url}/CandidateBio'
self.ignore = ['generalInfo', 'pronunciation', 'shortTitle']
def get_bio(self, candidate_id):
params = self.params
params.update({'candidateId': candidate_id})
url = f'{self.url}.getBio'
res = call(url, params)
return flatten(res, out={}, ignore=self.ignore)
def get_detailed_bio(self, candidate_id):
params = self.params
params.update({'candidateId': candidate_id})
url = f'{self.url}.getDetailedBio'
res = call(url, params)
return flatten(res, out={}, ignore=self.ignore)
def call(url, params):
try:
res = requests.get(url, params)
return res.json()
except BaseException as e:
print(f'Error obtaining data from {url} with params: '
f'{self.params}\n{e}')
return {}
def flatten(json_obj, out, prefix='', ignore=None):
ignore = ['generalInfo', 'pronunciation', 'shortTitle']
if type(json_obj) is str:
if prefix in out:
out[prefix].append(json_obj)
else:
out[prefix] = [json_obj]
else:
for k, v in json_obj.items():
if k in ignore:
continue
k_adj = f'{prefix}_{k}' if prefix else k
if type(v) in [str, int, float, bool] or v is None:
out[k_adj] = v
elif type(v) is dict:
flatten(v, out, k_adj)
elif type(v) is list:
if type(v[0]) is str:
out[k_adj] = v
else:
for d in v:
for lk, lv in d.items():
lk_adj = f'{prefix}_{lk}'
if lk_adj in out:
out[lk_adj].append(lv)
else:
out[lk_adj] = [lv]
return out
|
# -*- coding: utf-8 -*-
# Copyright (C) 2010 Francesco Piccinno
#
# Author: Francesco Piccinno <stack.box@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
import os
import sys
import os.path
try:
from tarfile import TarFile
from lzma import LZMAFile
except ImportError:
print "You need to install python-pyliblzma to handle .xz pkg files"
from tempfile import mkstemp
from collections import defaultdict
class Pkg(object):
def __init__(self, path):
if path.endswith('.gz'):
self.fd = TarFile.gzopen(path)
elif path.endswith('.xz'):
self.fd = TarFile.open(fileobj=LZMAFile(path))
else:
raise Exception('Unsupported file type %s' % path)
self.pkg_info = defaultdict(list)
self.members = []
# Extract most used information
if self.parse_pkginfo():
self.parse_contents()
self.name = self.pkg_info.get('pkgname')
self.desc = self.pkg_info.get('pkgdesc')[0]
self.depends = self.pkg_info.get('depend') or []
self.groups = self.pkg_info.get('group') or []
if isinstance(self.name, (list, tuple)) and len(self.name) == 1:
self.name = self.name[0]
def is_executable(self, member):
xbit = 7 << 6
if member.path.endswith('.desktop'):
raise StopIteration()
if member.mode & xbit == xbit and \
member.isfile():
name = member.path
# Ignore too nested executable
if name.count('/') > 3:
return False
blacklist = True
for white in ('bin/', 'sbin/',
'usr/share', 'usr/bin',
'usr/sbin'):
if name.startswith(white):
blacklist = False
break
if blacklist:
return False
name = os.path.basename(name)
# Ignore also UPPER file names
if name.isupper():
return False
if '.' not in name:
return True
for ext in ('.sh', ):
if name.endswith(ext):
return True
return False
def parse_contents(self):
try:
members = filter(self.is_executable,
self.fd.members)
self.members = [member.path for member in members]
self.members.sort()
except StopIteration:
self.members = []
#self.pkg_info.clear()
def parse_pkginfo(self):
try:
member = self.fd.getmember('.PKGINFO')
buff = self.fd.extractfile(member)
return self.parse_buffer(buff)
except Exception, exc:
return False
def parse_buffer(self, buff):
for line in buff.readlines():
line = line.strip()
if line[0] == '#':
continue
key, value = line.split('=', 1)
self.pkg_info[key.strip()].append(value.strip())
return 'group' in self.pkg_info
if __name__ == '__main__':
p = Pkg(sys.argv[1])
print p.members
print p.pkg_info
|
# Generated from Naja.g4 by ANTLR 4.9
from antlr4 import *
if __name__ is not None and "." in __name__:
from .NajaParser import NajaParser
else:
from NajaParser import NajaParser
# This class defines a complete listener for a parse tree produced by NajaParser.
class NajaListener(ParseTreeListener):
# Enter a parse tree produced by NajaParser#prog.
def enterProg(self, ctx:NajaParser.ProgContext):
pass
# Exit a parse tree produced by NajaParser#prog.
def exitProg(self, ctx:NajaParser.ProgContext):
pass
# Enter a parse tree produced by NajaParser#declaravar.
def enterDeclaravar(self, ctx:NajaParser.DeclaravarContext):
pass
# Exit a parse tree produced by NajaParser#declaravar.
def exitDeclaravar(self, ctx:NajaParser.DeclaravarContext):
pass
# Enter a parse tree produced by NajaParser#tipo.
def enterTipo(self, ctx:NajaParser.TipoContext):
pass
# Exit a parse tree produced by NajaParser#tipo.
def exitTipo(self, ctx:NajaParser.TipoContext):
pass
# Enter a parse tree produced by NajaParser#bloco.
def enterBloco(self, ctx:NajaParser.BlocoContext):
pass
# Exit a parse tree produced by NajaParser#bloco.
def exitBloco(self, ctx:NajaParser.BlocoContext):
pass
# Enter a parse tree produced by NajaParser#cmd.
def enterCmd(self, ctx:NajaParser.CmdContext):
pass
# Exit a parse tree produced by NajaParser#cmd.
def exitCmd(self, ctx:NajaParser.CmdContext):
pass
# Enter a parse tree produced by NajaParser#cmdleitura.
def enterCmdleitura(self, ctx:NajaParser.CmdleituraContext):
pass
# Exit a parse tree produced by NajaParser#cmdleitura.
def exitCmdleitura(self, ctx:NajaParser.CmdleituraContext):
pass
# Enter a parse tree produced by NajaParser#cmdescrita.
def enterCmdescrita(self, ctx:NajaParser.CmdescritaContext):
pass
# Exit a parse tree produced by NajaParser#cmdescrita.
def exitCmdescrita(self, ctx:NajaParser.CmdescritaContext):
pass
# Enter a parse tree produced by NajaParser#escrita.
def enterEscrita(self, ctx:NajaParser.EscritaContext):
pass
# Exit a parse tree produced by NajaParser#escrita.
def exitEscrita(self, ctx:NajaParser.EscritaContext):
pass
# Enter a parse tree produced by NajaParser#cmdattrib.
def enterCmdattrib(self, ctx:NajaParser.CmdattribContext):
pass
# Exit a parse tree produced by NajaParser#cmdattrib.
def exitCmdattrib(self, ctx:NajaParser.CmdattribContext):
pass
# Enter a parse tree produced by NajaParser#cmdselecao.
def enterCmdselecao(self, ctx:NajaParser.CmdselecaoContext):
pass
# Exit a parse tree produced by NajaParser#cmdselecao.
def exitCmdselecao(self, ctx:NajaParser.CmdselecaoContext):
pass
# Enter a parse tree produced by NajaParser#cmdelse.
def enterCmdelse(self, ctx:NajaParser.CmdelseContext):
pass
# Exit a parse tree produced by NajaParser#cmdelse.
def exitCmdelse(self, ctx:NajaParser.CmdelseContext):
pass
# Enter a parse tree produced by NajaParser#cmdenquanto.
def enterCmdenquanto(self, ctx:NajaParser.CmdenquantoContext):
pass
# Exit a parse tree produced by NajaParser#cmdenquanto.
def exitCmdenquanto(self, ctx:NajaParser.CmdenquantoContext):
pass
# Enter a parse tree produced by NajaParser#cmdexecute.
def enterCmdexecute(self, ctx:NajaParser.CmdexecuteContext):
pass
# Exit a parse tree produced by NajaParser#cmdexecute.
def exitCmdexecute(self, ctx:NajaParser.CmdexecuteContext):
pass
# Enter a parse tree produced by NajaParser#cmdcondicao.
def enterCmdcondicao(self, ctx:NajaParser.CmdcondicaoContext):
pass
# Exit a parse tree produced by NajaParser#cmdcondicao.
def exitCmdcondicao(self, ctx:NajaParser.CmdcondicaoContext):
pass
# Enter a parse tree produced by NajaParser#expr.
def enterExpr(self, ctx:NajaParser.ExprContext):
pass
# Exit a parse tree produced by NajaParser#expr.
def exitExpr(self, ctx:NajaParser.ExprContext):
pass
# Enter a parse tree produced by NajaParser#termo.
def enterTermo(self, ctx:NajaParser.TermoContext):
pass
# Exit a parse tree produced by NajaParser#termo.
def exitTermo(self, ctx:NajaParser.TermoContext):
pass
del NajaParser |
import copy
def merge_main(master_schedule, new_schedule):
"""
Merge a new schedule with the main schedule found in the database.
:param master_schedule: [{"": [[],[],...]},...]
:param new_schedule: [{"": [[],[],...]},...]
:return: master_schedule
"""
nm = copy.deepcopy(master_schedule)
for i in range(len(nm)):
for key, value in nm[i].items():
for j in range(len(value)):
if new_schedule[i][key][j][1]:
value[j][1] = True
return nm
|
import torch.nn as nn
from src.set_encoders import (
ContextBasedLinear,
ContextBasedMultiChannelLinear,
ContextFreeEncoder)
from src.set_decoders import LinearSumSet, SimpleSubset
from src.util_layers import FlattenElements
import torch.nn.functional as F
class ElementFlatten(nn.Module):
def forward(self, x):
batch_size, dim1, dim2, dim3 = x.size()
return x.view(batch_size, dim1*dim2*dim3)
def get_MNIST_extractor():
# from the keras MNIST example:
# https://github.com/keras-team/keras/blob/12a060f63462f2e5f838b70cadb2079b4302f449/examples/mnist_cnn.py#L47-L57
return nn.Sequential(nn.Conv2d(1, 32, (3, 3)),
nn.ReLU(),
nn.Conv2d(32, 32, (3, 3)),
nn.ReLU(),
nn.MaxPool2d((2,2)),
ElementFlatten(),
nn.Linear(4608, 128),
nn.ReLU())
class Set2RealNet(nn.Module):
"""
Used when the input is to be interpreted as a Set of MNIST digits
and the output is a real number calculated from the set
"""
def __init__(self, encode_set=False):
super().__init__()
# per element encoder is a conv neural network
cfe = get_MNIST_extractor()
self.cfe = ContextFreeEncoder(cfe, '2d')
self.flatten = FlattenElements()
# if encode_set:
# self.cbl1 = ContextBasedLinear(nonlinearity=nn.ReLU)
# self.cbl2 = ContextBasedLinear(nonlinearity=nn.ReLU)
# self.encode_set = True
# else:
self.encode_set = False
self.lss = LinearSumSet()
# self.lineartoh1 = nn.Linear(128, 128)
# self.relu = nn.ReLU()
# self.lineartoh2 = nn.Linear(128, 32)
# self.relu = nn.ReLU()
# self.linearout = nn.Linear(32, 1)
self.l1 = nn.Linear(128, 128)
self.l2 = nn.Linear(128, 100)
self.l3 = nn.Linear(100, 1)
self.relu = nn.ReLU()
def forward(self, x):
x = self.cfe(x) # encode individual images
x = self.flatten(x) # flatten individual images
x = self.lss(x) # collapse the set
# final rho function is a simple 2 layer NN
x = self.l1(x)
x = self.relu(x)
x = self.l2(x)
x = self.relu(x)
x = self.l3(x)
return x
class Seq2RealNet(nn.Module):
"""
Used when the input is to be interpreted as a _sequence_ of MNIST digits
and the output is a real number calculated from the sequence
"""
def __init__(self):
super().__init__()
# per element encoder is a conv neural network
cfe = get_MNIST_extractor()
self.cfe = ContextFreeEncoder(cfe, '2d')
self.flatten = FlattenElements()
# self.lstm = nn.LSTM(128, 64, 1)
# self.relu = nn.ReLU()
# self.linearout = nn.Linear(64, 1)
# attempt to make it more equal to the set based method
self.lstm = nn.LSTM(128, 32, 2)
self.relu = nn.ReLU()
self.linearout = nn.Linear(32, 1)
def forward(self, x):
x = self.cfe(x)
x = self.flatten(x)
x = x.permute(1, 0, 2)
hT, _ = self.lstm(x)
x = hT[-1]
x = self.relu(x)
x = self.linearout(x)
return x
class Set2SubsetNet(nn.Module):
"""
Used when the input is to be interpreted as a set of MNIST digits
and the output is a subset of those elements as indicated by probabilities
"""
def __init__(self, logprobs=True):
super().__init__()
# per element encoder is a conv neural network
cfe = get_MNIST_extractor()
self.cfe = ContextFreeEncoder(cfe, '2d')
self.cbe = ContextBasedMultiChannelLinear(128, 128, nonlinearity=nn.ReLU)
self.cbe2 = ContextBasedMultiChannelLinear(128, 64, nonlinearity=nn.ReLU)
self.cbe3 = ContextBasedMultiChannelLinear(64, 1, nonlinearity=None)
self.logprobs = logprobs
def forward(self, x):
x = self.cfe(x)
x = self.cbe(x)
x = self.cbe2(x)
x = self.cbe3(x)
if not self.logprobs:
x = F.sigmoid(x)
return x
class Set2SubsetNetNull(nn.Module):
def __init__(self, logprobs=True):
super().__init__()
mnist_extractor = get_MNIST_extractor()
classifier = nn.Sequential(mnist_extractor,
nn.Linear(128, 128),
nn.ReLU(),
nn.Linear(128, 64),
nn.ReLU(),
nn.Linear(64, 1))
self.cfe = ContextFreeEncoder(classifier, '2d')
self.logprobs = logprobs
def forward(self, x):
x = self.cfe(x)
if not self.logprobs:
x = F.sigmoid(x)
return x
# def Seq2SubsetNet(nn.Module):
# """
# Used when the input is to be interpreted as a sequence of MNIST digits
# and the output is a subset of those elements as indicated by probabilities
# """
# def __init__(self, logprobs=True):
# super().__init__()
# # per element encoder is a conv neural network
# cfe = get_MNIST_extractor()
# self.cfe = ContextFreeEncoder(cfe, '2d')
# self.flatten = FlattenElements()
# self.lstm = nn.LSTM(...)
|
class Solution:
def evalRPN(self, tokens):
if not tokens:
return 0
stack = []
for item in tokens:
if item in '+-/*':
n1, n2 = stack.pop(), stack.pop()
if item == '+':
stack.append(n1 + n2)
elif item == '-':
stack.append(n2 - n1)
elif item == "*":
stack.append(n1 * n2)
else:
stack.append(n2 / n1)
else:
stack.append(int(item))
return stack.pop()
|
import requests
url = 'http://www.baidu.com/'
strhtml = requests.get(url)#git方式获取网页数据,存至strhtml变量
print(strhtml.text)#文本形式输出网页 |
#!/usr/bin/env python
from trillium.extensions import celery
from trillium import create_app, DefaultConfig
if __name__ == '__main__':
app = create_app(DefaultConfig)
with app.app_context():
celery.start()
|
from numpy.random import RandomState
from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams
from random import Random
seed = 42
py_rng = Random(seed)
np_rng = RandomState(seed)
t_rng = RandomStreams(seed)
def set_seed(n):
global seed, py_rng, np_rng, t_rng
seed = n
py_rng = Random(seed)
np_rng = RandomState(seed)
t_rng = RandomStreams(seed)
|
import pytest
from onegov.newsletter import NewsletterCollection, RecipientCollection
from onegov.newsletter.errors import AlreadyExistsError
def test_newsletter_collection(session):
newsletters = NewsletterCollection(session)
n = newsletters.add("My Newsletter", "<h1>My Newsletter</h1>")
assert n.name == "my-newsletter"
assert n.title == "My Newsletter"
assert n.html == "<h1>My Newsletter</h1>"
n = newsletters.by_name('my-newsletter')
assert n.name == "my-newsletter"
assert n.title == "My Newsletter"
assert n.html == "<h1>My Newsletter</h1>"
newsletters.delete(n)
assert newsletters.by_name('my-newsletter') is None
def test_recipient_collection(session):
recipients = RecipientCollection(session)
r = recipients.add("info@example.org")
assert r.address == "info@example.org"
assert r.group is None
r = recipients.by_id(r.id)
assert r.address == "info@example.org"
assert r.group is None
r = recipients.by_address(r.address, 'abc')
assert r is None
r = recipients.by_address('info@example.org')
assert r.address == "info@example.org"
assert r.group is None
recipients.delete(r)
assert recipients.by_address('info@example.org') is None
def test_newsletter_already_exists(session):
newsletters = NewsletterCollection(session)
newsletters.add("My Newsletter", "<h1>My Newsletter</h1>")
with pytest.raises(AlreadyExistsError) as e:
newsletters.add("My Newsletter", "<h1>My Newsletter</h1>")
assert e.value.args == ('my-newsletter', )
|
from pyVim import connect
from pyVmomi import vim
from pyVmomi import vmodl
import atexit
# import tools.cli as cli
import ssl
def getHosts(content):
host_view = content.viewManager.CreateContainerView(content.rootFolder, [vim.HostSystem], True)
obj = [host for host in host_view.view]
host_view.Destroy()
return obj
def main():
service_instance = connect.SmartConnectNoSSL(host='127.0.0.1', user='user', pwd='pass', port=8989)
atexit.register(connect.Disconnect, service_instance)
content = service_instance.RetrieveContent()
hosts = getHosts(content)
for host in hosts:
print(host.name)
if __name__ == "__main__":
main()
|
from math import log10
def nsn(N):
K = sum( list( map( int, list( str(N)))))
return N/K
def snuke(N):
k = int( log10(N))+1
s = N
now = nsn(N)
for d in range(k+1):
x = (10**(d+1))*(N//(10**(d+1)) + 1) - 1
y = nsn(x)
if y < now:
s = x
now = y
return s
K = int( input())
ans = 1
print(1)
for i in range(K-1):
ans = snuke( ans + 1)
print(ans)
|
from django.contrib import admin
from .models import Article,Comment,HashTag
# Register your models here.
@admin.register(Article,Comment,HashTag)
class FeedAdmin(admin.ModelAdmin):
pass
|
#!/usr/bin/env python3
# encoding: utf-8
"""
exercise3.py
Created by Jakub Konka on 2011-10-28.
Copyright (c) 2011 University of Strathclyde. All rights reserved.
"""
import random as rnd
import math
## Revision
def WC_Words(filename):
try:
f = open(filename,'r')
contents = f.read().split('\n')
f.close()
contents = [elem for elem in contents if elem != ""]
lines = len(contents)
words = sum([len(elem.split()) for elem in contents])
chars = sum([len(elem) for elem in contents])
print("Analysing file {0}. Lines: {1} Words: {2} Characters: {3}".format(filename, lines, words, chars))
except IOError:
print('Cannot open file {0} for reading!'.format(filename))
# strings = []
# with open(filename) as f:
# for line in f:
# strings = strings + [line.rstrip()]
# lines = len(strings)
# words = 0
# for string in strings:
# words = words + len(string.split())
# characters = 0
# for string in strings:
# characters = characters + len(string)
# print("Lines:", lines, "Words:", words, "Characters:", characters)
def RandBox():
size = rnd.randint(2,10)
print("Box of size {0}.".format(size))
edge = "+" + size*"-" + "+"
print(edge)
for i in range(size-2):
print("|" + size*" " + "|")
print(edge)
def RandRect():
width = rnd.randint(2,10)
height = rnd.randint(2,10)
edge = "+" + width*"-" + "+"
print(edge)
for i in range(height):
print("|" + width*" " + "|")
print(edge)
## Reading text files
def Words():
try:
strings = []
with open("words.txt", 'r') as f:
for line in f:
strings.append(line.rstrip())
print("First word:",strings[0]," Last word:",strings[-1])
except IOError:
print("Cannot open file words.txt for reading!")
def RandomWord():
try:
strings = []
with open("words.txt", 'r') as f:
for line in f:
strings.append(line.rstrip())
n = rnd.randint(0,len(strings)-1)
print("{0}th word: {1}".format(n+1,strings[n]))
except IOError:
print("Cannot open file words.txt for reading!")
def Censor(filename):
try:
words = []
vowels = set(['a','e','i','o','u','y'])
with open(filename, 'r') as f:
for line in f:
words.append(line.rstrip())
n = rnd.randint(0,len(words)-1)
word = []
for letter in words[n]:
if letter in vowels:
word.append("*")
else:
word.append(letter)
print("{0}th censored word: {1}".format(n+1,''.join(word)))
except IOError:
print("Cannot open file {0} for reading!".format(filename))
def FirstLetter():
try:
strings = []
with open("words.txt", 'r') as f:
for line in f:
strings.append(line.rstrip())
first_let = input("Type the first letter of a word: ")
words = [w for w in strings if w[0] == first_let]
print("Words starting with \"{0}\":".format(first_let))
for w in words:
print(w)
except IOError:
print("Cannot open file words.txt for reading!")
## Games
def HighLow():
num = rnd.randint(0,100)
user_num = int(input("Guess: "))
while user_num != num:
if user_num > num:
print("Too high.")
else:
print("Too low.")
user_num = int(input("Guess: "))
print("You got it!")
def GuessWord():
try:
words = []
vowels = set(['a','e','i','o','u','y'])
with open("words.txt", 'r') as f:
for line in f:
words.append(line.rstrip())
n = rnd.randint(0,len(words)-1)
word = []
for letter in words[n]:
if letter in vowels:
word.append("*")
else:
word.append(letter)
print("Censored:", ''.join(word))
user_word = input("Guess the word: ")
while user_word != words[n]:
print("Nope, try again.")
user_word = input("Guess the word: ")
print("You got it!")
except IOError:
print("Cannot open file words.txt for reading!")
## Code phrase
def CodePhrase():
files = ["nouns.txt", "verbs.txt", "adjectives.txt", "nouns.txt"]
try:
code_frag = []
strings = []
for ff in files:
with open(ff, 'r') as f:
for line in f:
strings.append(line.rstrip())
n = rnd.randint(0,len(strings)-1)
code_frag.append(strings[n])
print("The {0} {1}s the {2} {3}.".format(code_frag[0],code_frag[1],code_frag[2],code_frag[3]))
except IOError:
print("Cannot open file for reading!")
## Hangman
def Hangman():
try:
words = []
guessed = []
with open("words.txt", 'r') as f:
for line in f:
words.append(line.rstrip())
n = rnd.randint(0,len(words)-1)
word = words[n]
letters = [e for e in word]
censored = ''.join(['*' for i in range(len(word))])
tries = 0
max_tries = 15
while tries < max_tries and censored != word:
print(censored)
print(guessed)
user_letter = input("Guess a letter or a word: ")
guessed.append(user_letter)
if len(user_letter) == 1:
if user_letter not in letters:
print("{0} is not in the word.".format(user_letter))
else:
while user_letter in letters:
index = letters.index(user_letter)
censored_list = list(censored)
censored_list[index] = user_letter
censored = ''.join(censored_list)
letters[index] = '*'
else:
if user_letter == word:
censored = word
else:
print("{0} is not the word.".format(user_letter))
tries += 1
print(censored)
print(guessed)
if tries == max_tries:
print("You lose!")
else:
print("You won!")
except IOError:
print("Cannot open file words.txt for reading!")
## Pi
def Pi(n):
inside = 0
for i in range(n):
x,y = rnd.uniform(-1,1),rnd.uniform(-1,1)
if x**2 + y**2 < 1:
inside += 1
print("The approximate value of pi is: {0}".format(4 * inside/n))
if __name__ == '__main__':
# files = ["adjectives.txt", "nouns.txt", "verbs.txt", "words.txt"]
# for f in files:
# WC_Words(f)
# Censor(f)
# RandBox()
# RandRect()
# Words()
# RandomWord()
# FirstLetter()
# HighLow()
# GuessWord()
# CodePhrase()
Hangman()
# Pi(1000)
|
from django.shortcuts import render
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from .models import HeartBeat
import json
import logging
logger = logging.getLogger(__name__)
# Create your views here.
@csrf_exempt
def beat(request, identifier):
data = None
if request.method == 'POST':
try:
data = json.loads(request.body)
except json.JSONDecodeError as e:
logger.exception('Could not load json body')
HeartBeat.objects.create(identifier=identifier, meta=json.dumps(data))
return JsonResponse({'status': 'ok'})
def graph(request, identifier):
sequence = HeartBeat.objects.filter(identifier=identifier).order_by('created_at')
map_beat = lambda b: {'created_at': b.created_at, 'meta': json.loads(b.meta)}
resp_data = {
'status': 'ok',
'count': sequence.count(),
'data': [map_beat(b) for b in sequence]
}
return JsonResponse(resp_data)
|
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 3 15:04:56 2019
@author: LEGION-JCWP
"""
import tellurium as te
import roadrunner
""" This model assumes that K_AB > A_total and that """
r = te.loada("""
J0: A + B -> AB ; K_AB * A * B - 1/K_AB * AB
J1: B + C -> BC ; K_BC * B * C - 1/K_BC * BC
J4: AB + C -> ABC ; K_AB_C * AB * C - 1/K_AB_C * ABC
J5: BC + A -> ABC ; K_BC_A * BC * A - 1/K_BC_A * ABC
# *******************************
# Parameters
A = 1;
B = 1;
C = 1;
K_AB = 1;
K_BC = 0.1;
K_AB_C = 1;
K_BC_A = 0.1;
""")
simulation = r.simulate(start=0, end=100, steps=100)
r.plot(simulation)
print(simulation[100,6])
print(simulation)
concentrations = [0, 0.01, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10]
for i in concentrations:
r.resetToOrigin()
r.B = i
m = r.simulate(0, 5, 100, ['time', 'ABC'])
print(m)
te.plotArray (m, show=False, labels = ['Concentration=' + str(i)], resetColorCycle = False) |
# pylint: disable=no-member, unused-wildcard-import, no-name-in-module
import pygame
from pygame import mouse
import pieces as pieces_lib
import math
import time
import sys
from random import shuffle, randint, choice
import network
import json
from oooooooooooooooooooooooooooooooooooooooooooootils import *
import _thread
import asyncio
import ntpath
from webbrowser import open_new
# these two lines saved my life
import nest_asyncio
nest_asyncio.apply()
if __name__ == "__main__":
import main
color_key = {
'green': (13, 252, 65),
'blue': (13, 29, 252),
'teal': (15, 246, 250),
'red': (250, 15, 15),
'orange': (255, 128, 43),
'purple': (168, 24, 245),
'yellow': (255, 223, 13),
'gray': (107, 115, 120)
}
class Game:
def __init__(self):
#############################
#############################
self.dev = True #############
#############################
#############################
if self.dev:
print("IN DEVELOPMENT MODE: DISABLES DISCORD RPC")
self.presence_connected = None
if not self.dev:
# creates a new asyncio loop
self.discord_rpc_loop = asyncio.new_event_loop()
# initializes the discord RPC with this new loop
self.RPC = pypresence.Presence(
client_id="778689610263560212",
loop=self.discord_rpc_loop
)
# use a thread to start this loop and run forever
_thread.start_new_thread(self.start_background_loop, ())
# then run the task on this loop
asyncio.run_coroutine_threadsafe(self.start_connect_presence(), self.discord_rpc_loop)
pygame.init()
self.font = pygame.font.Font(get_path('assets/fonts/arial.ttf'), 32)
self.time_opened = time.time()
self.width = 750
self.height = 800
self.name = ""
self.running = True
self.multiplayer = False
self.clock = pygame.time.Clock()
self.screen = pygame.display.set_mode((self.width, self.height), flags = pygame.RESIZABLE)
self.icon = pygame.image.load(get_path('assets/images/tetrium.png'))
pygame.display.set_icon(self.icon)
self.caption = "Tetrium"
pygame.display.set_caption(self.caption)
# 30px x 30px is one block
self.resting = []
self.last_time = 0
self.continuous = True
self.round = 1
self.level = 1
self.score = 0
self.lines = 0
self.time_started = 0
self.game_over_rematched_bool = False
self.fullscreen = False
# list of numbers, with numbers being attack amounts
self.meter = []
self.meter_stage = 1
self.opp_meter_stage = None
self.opp_resting = []
self.opp_meter = []
self.opp_piece_blocks = []
self.opp_name = None
self.rows_cleared = []
self.chat = []
self.small_font = pygame.font.Font(get_path('assets/fonts/arial.ttf'), 15)
self.medium_font = pygame.font.Font(get_path('assets/fonts/arial.ttf'), 20)
self.big_font = pygame.font.Font(get_path('assets/fonts/arial.ttf'), 30)
self.very_big_medium_font = pygame.font.Font(get_path('assets/fonts/arial.ttf'), 70)
self.very_big_font = pygame.font.Font(get_path('assets/fonts/arial.ttf'), 75)
self.enormous_font = pygame.font.Font(get_path('assets/fonts/arial.ttf'), 120)
self.default_controls = {
"Move Right": "d",
"Move Left": "a",
"Soft Drop": "s",
"Hard Drop": "down",
"Hold Piece": "up",
"Rotate Clockwise": "right",
"Rotate Counter-Clockwise": "left",
"Toggle Movement": "g",
"Toggle Music": "m",
"Toggle Fullscreen": "f11",
"Pause": "p"
}
with open(get_path('settings.json')) as f:
settings = json.load(f)
self.initial_nickname = settings['name']
self.music = settings['audio']['main'] * settings['audio']['music']
self.sfx = settings['audio']['main'] * settings['audio']['sfx']
self.sounds = {
"correct rotate": pygame.mixer.Sound(get_path('assets/sfx/move_effect_success.wav')),
"hold": pygame.mixer.Sound(get_path('assets/sfx/hold_effect.wav')),
"row cleared": pygame.mixer.Sound(get_path('assets/sfx/row_cleared.wav')),
"meter send": pygame.mixer.Sound(get_path('assets/sfx/meter_send.wav')),
"meter recieve": pygame.mixer.Sound(get_path('assets/sfx/meter_recieve.wav')),
"countdown": pygame.mixer.Sound(get_path('assets/sfx/countdown.wav')),
"countdown go": pygame.mixer.Sound(get_path('assets/sfx/countdown_go.wav')),
"garbage recieve": pygame.mixer.Sound(get_path('assets/sfx/garbage_recieve.wav'))
}
self.sfx_channel = pygame.mixer.Channel(1)
self.sfx_channel.set_volume(self.sfx)
# list of all files in music folder
self.tracks = [get_path(f'assets/music/{filename}') for filename in os.listdir(get_path('assets/music'))]
self.current_track = settings['track']
self.random_track = False
if self.current_track == 'random':
self.current_track = randint(0, len(self.tracks)-1)
self.random_track = True
_thread.start_new_thread(self.cycle_music, ())
pygame.mixer.music.load(self.tracks[self.current_track])
pygame.mixer.music.set_volume(self.music)
if self.random_track:
pygame.mixer.music.play(0)
else:
pygame.mixer.music.play(-1)
self.left_controls = {
"Move Left": settings["controls"]["Move Left"],
"Move Right": settings["controls"]["Move Right"],
"Soft Drop": settings["controls"]["Soft Drop"],
"Toggle Movement": settings["controls"]["Toggle Movement"],
"Toggle Music": settings["controls"]["Toggle Music"]
}
self.right_controls = {
"Rotate Clockwise": settings["controls"]["Rotate Clockwise"],
"Rotate Counter-Clockwise": settings["controls"]["Rotate Counter-Clockwise"],
"Hold Piece": settings["controls"]["Hold Piece"],
"Hard Drop": settings["controls"]["Hard Drop"],
"Toggle Fullscreen": settings["controls"]["Toggle Fullscreen"],
"Pause": settings["controls"]["Pause"],
}
self.fullscreen_key = settings["controls"]["Toggle Fullscreen"]
#first tuple is rgb of background color, second is foreground
self.themes = [
['Default', (0, 0, 0), (101, 142, 156)],
['Random', (0, 0, 0), (255, 255, 255)],
['Blue Mystique', (0, 20, 39), (101, 142, 156)],
['Sky High', (39, 38, 53), (177, 229, 242)],
['Jungle Adventure', (1, 38, 34), (184, 242, 230)],
['Sahara Desert', (30, 47, 35), (179, 156, 77)],
['Cotton Candy', (61, 64, 91), (202, 156, 225)],
['Velvety Mango', (60, 21, 24), (255, 140, 66)],
['Road to Heaven', (17, 20, 25), (92, 200, 255)],
['Night Sky', (0, 0, 0), (0, 20, 39)],
['Camouflage', (13, 27, 30), (101, 104, 57)],
['Coral Reef', (38, 70, 83), (42, 157, 143)],
['Tropical Sands', (38, 70, 83), (233, 196, 106)],
]
try:
self.theme_index = settings['theme']
except:
self.theme_index = 0
with open(get_path('settings.json')) as f:
full_dict = json.load(f)
full_dict['theme'] = self.theme_index
with open(get_path('settings.json'), 'w') as f:
json.dump(full_dict, f, indent=2)
theme = self.themes[self.theme_index]
self.background_color = theme[1]
self.foreground_color = theme[2]
self.set_grid_color(self.foreground_color)
self.set_text_color(self.foreground_color)
self.theme_text = theme[0]
self.random_theme = True if self.theme_text == 'Random' else False
self.resize_screen_setup()
def cycle_music(self):
try:
while self.random_track:
if not pygame.mixer.music.get_busy():
self.current_track += 1
if self.current_track >= len(self.tracks): self.current_track = 0
pygame.mixer.music.load(self.tracks[self.current_track])
pygame.mixer.music.play(0)
pygame.mixer.music.set_volume(self.music)
except:
pass
def play_sound(self, sound):
if not self.sfx_channel.get_busy():
self.sfx_channel.play(self.sounds[sound])
else:
self.sounds[sound].set_volume(self.sfx_channel.get_volume())
self.sounds[sound].play()
self.sounds[sound].set_volume(1)
def set_grid_color(self, color):
self.grid_color = tuple(darken(i, 10) for i in color)
@staticmethod
def complimentary_color(color: tuple):
def contrast(val):
return int(abs((val + 255/2) - 255))
return tuple(contrast(i) for i in color)
def set_text_color(self, color):
contrast = self.complimentary_color(color)
self.text_color = color
self.preview_color = contrast
def render(self, pieces=None, held=None):
self.screen.fill(self.background_color)
pygame.draw.rect(self.screen, self.foreground_color, self.playing_field_rect)
self.draw_grid(self.playing_field_rect, 30, self.grid_color)
for block in self.resting:
block.render()
# for piece order
for i in range(1, 4):
pygame.draw.circle(self.screen, self.foreground_color, (self.playing_field_rect.x + self.playing_field_rect.width + 100/2, (self.playing_field_rect.y - 100) + 130*i), 40)
text = self.font.render('Next', True, self.text_color)
textRect = text.get_rect()
textRect.center = (self.playing_field_rect.x + self.playing_field_rect.width + 100/2, self.playing_field_rect.y - 40)
self.screen.blit(text, textRect)
# putting pieces in the circles
if pieces:
position = 1
for piece in pieces:
for color, x, y, width, height in pieces_lib.preview_piece(self.playing_field_rect.x + self.playing_field_rect.width + 100/2, (self.playing_field_rect.y - 100) + position*130, piece):
pygame.draw.rect(self.screen, color_key[color], (x, y, width, height))
position += 1
# for hold area
pygame.draw.circle(self.screen, self.foreground_color, (self.playing_field_rect.x - 100/2, self.playing_field_rect.y + 30), 40)
text = self.font.render('Hold', True, self.text_color)
textRect = text.get_rect()
textRect.center = (self.playing_field_rect.x - 100/2, self.playing_field_rect.y - 40)
self.screen.blit(text, textRect)
if held:
for color, x, y, width, height in pieces_lib.preview_piece(self.playing_field_rect.x - 50, self.playing_field_rect.y + 30, held):
pygame.draw.rect(self.screen, color_key[color], (x, y, width, height))
text = self.font.render(f"Continuous Movement: {'On' if self.continuous else 'Off'}", True, self.text_color)
textRect = text.get_rect()
textRect.center = (self.playing_field_rect.x + self.playing_field_rect.width/2, self.playing_field_rect.y + self.playing_field_rect.height + 80)
self.screen.blit(text, textRect)
font = pygame.font.Font(get_path('assets/fonts/arial.ttf'), 25)
text = font.render(f"Level: {self.level}", True, self.text_color)
textRect = text.get_rect()
textRect.center = (self.playing_field_rect.x + self.playing_field_rect.width + 20, self.playing_field_rect.y + self.playing_field_rect.height + 25)
self.screen.blit(text, textRect)
self.score = int(self.score)
text = self.font.render(f"Score: {self.score}", True, self.text_color)
textRect = text.get_rect()
textRect.center = (self.playing_field_rect.x + self.playing_field_rect.width/2, self.playing_field_rect.y + self.playing_field_rect.height + 25)
self.screen.blit(text, textRect)
text = font.render(f"Lines: {self.lines}", True, self.text_color)
textRect = text.get_rect()
textRect.center = (self.playing_field_junk_meter_rect.x + textRect.width/3, self.playing_field_rect.y + self.playing_field_rect.height + 25)
self.screen.blit(text, textRect)
font = pygame.font.Font(get_path('assets/fonts/arial.ttf'), 20)
time_elapsed = math.floor(time.time() - self.time_started)
minutes = time_elapsed // 60
remaining_seconds = time_elapsed % 60
time_elapsed = f"{minutes}m {remaining_seconds}s"
text = font.render(f"Time Elapsed: {time_elapsed}", True, self.text_color)
textRect = text.get_rect()
textRect.center = (self.playing_field_rect.x + self.playing_field_rect.width/2, self.playing_field_rect.y - 75)
self.screen.blit(text, textRect)
text = font.render(self.name, True, self.text_color)
textRect = text.get_rect()
textRect.center = (self.playing_field_rect.x + self.playing_field_rect.width/2, self.playing_field_rect.y - 20)
self.screen.blit(text, textRect)
text = font.render(self.opp_name, True, self.text_color)
textRect = text.get_rect()
textRect.center = (self.second_screen_rect.x + self.second_screen_rect.width/2, self.second_screen_rect.y - 20)
self.screen.blit(text, textRect)
if self.multiplayer:
# junk line meter
pygame.draw.rect(self.screen, self.preview_color, self.playing_field_junk_meter_rect_outline)
pygame.draw.rect(self.screen, self.foreground_color, self.playing_field_junk_meter_rect)
meter_block = 0
for index, amount in enumerate(self.meter):
if not index and self.meter_stage != 4:
if self.meter_stage == 1:
color = color_key["yellow"]
elif self.meter_stage == 2:
color = color_key["orange"]
else:
color = color_key["red"]
else:
color = color_key["gray"]
darkened = tuple(darken(i) for i in color)
for block in range(amount):
if meter_block >= 10:
break
block_rect = pygame.Rect(
self.playing_field_junk_meter_rect.x,
(self.playing_field_junk_meter_rect.y +
self.playing_field_junk_meter_rect.height - 30) -
(30 * meter_block), 30, 30
)
pygame.draw.rect(
self.screen,
color,
block_rect
)
self.draw_block_borders(block_rect, darkened)
meter_block += 1
self.render_second_screen()
def render_second_screen(self):
pygame.draw.rect(self.screen, self.foreground_color, self.second_screen_rect)
self.draw_grid(self.second_screen_rect, 15, self.grid_color)
if self.time_started + 1 > time.time():
return
for x, y, color in self.opp_resting: # noqa pylint: disable=not-an-iterable
Block(x, y, color, colorByName = False).render_second()
if self.opp_piece_blocks:
for x, y, color in self.opp_piece_blocks: # noqa pylint: disable=not-an-iterable
Block(x, y, color, colorByName = False).render_second()
# junk line meter
pygame.draw.rect(self.screen, self.preview_color, self.opp_screen_junk_meter_rect_outline)
pygame.draw.rect(self.screen, self.foreground_color, self.opp_screen_junk_meter_rect)
meter_block = 0
for index, amount in enumerate(self.opp_meter):
if not index:
if self.opp_meter_stage == 1:
color = color_key["yellow"]
elif self.opp_meter_stage == 2:
color = color_key["orange"]
else:
color = color_key["red"]
else:
color = color_key["gray"]
darkened = tuple(darken(i) for i in color)
for _ in range(amount):
if meter_block >= 10:
break
block_rect = pygame.Rect(
self.opp_screen_junk_meter_rect.x,
(self.opp_screen_junk_meter_rect.y +
self.opp_screen_junk_meter_rect.height - 15) -
(15 * meter_block), 15, 15
)
pygame.draw.rect(
self.screen,
color,
block_rect
)
game.draw_block_borders(block_rect, darkened, block_size_difference = 2)
meter_block += 1
def draw_grid(self, rect, block_size, color):
#I subtract 3 in both ones because if not it overlaps a tiny bit and triggeres OCD
for x_pos in range(rect.x, rect.x + rect.width, block_size):
pygame.draw.line(self.screen, color, (x_pos, rect.y), (x_pos, rect.y + rect.height - 3), 1)
for y_pos in range(rect.y, rect.y + rect.height, block_size):
pygame.draw.line(self.screen, color, (rect.x, y_pos), (rect.x + rect.width - 3, y_pos), 1)
def outdated_version_screen(self, new_version, download_link):
text_color = game.foreground_color
rect_color = tuple(darken(color) for color in game.foreground_color)
copy_button_dimensions = (300, 45)
copy_button_pos = (self.width/2 - copy_button_dimensions[0]/2, self.height/2 - copy_button_dimensions[1]/2)
copy_button_rect = pygame.Rect(*copy_button_pos, *copy_button_dimensions)
quit_button_dimensions = (140, 40)
quit_button_pos = (self.width/2 - quit_button_dimensions[0]/2, 700)
quit_button_rect = pygame.Rect(*quit_button_pos, *quit_button_dimensions)
def draw_text():
text1 = self.font.render("You are running an outdated", True, rect_color)
text2 = self.font.render("version of the game", True, rect_color)
text3 = self.font.render(f"Your Version: {network.version}", True, rect_color)
text4 = self.font.render(f"New Version: {new_version}", True, rect_color)
self.screen.blit(text1, (self.width/2-200, 100))
self.screen.blit(text2, (self.width/2-130, 150))
self.screen.blit(text3, (self.width/2-140, 250))
self.screen.blit(text4, (self.width/2-140, 290))
def draw_buttons(mouse):
pygame.draw.rect(self.screen, tuple(darken(i, 15) for i in rect_color) if copy_button_rect.collidepoint(mouse) else rect_color, copy_button_rect)
copy_button_text = self.font.render("UPDATE NOW", True, text_color)
self.screen.blit(copy_button_text, (copy_button_pos[0] + 40, copy_button_pos[1] + 3))
pygame.draw.rect(self.screen, tuple(darken(i, 15) for i in rect_color) if quit_button_rect.collidepoint(mouse) else rect_color, quit_button_rect)
quit_button_text = self.font.render("Go Back", True, text_color)
self.screen.blit(quit_button_text, (quit_button_pos[0] + 10, quit_button_pos[1] + 3))
breakOut = False
def check_click(pos):
nonlocal breakOut
if copy_button_rect.collidepoint(pos):
open_new(download_link)
elif quit_button_rect.collidepoint(pos):
breakOut = True
while True:
game.screen.fill(game.background_color)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.VIDEORESIZE or self.check_fullscreen(event):
try:
game.width, game.height = event.w, event.h
except:
pass
game.resize_all_screens()
copy_button_pos = (self.width/2 - copy_button_dimensions[0]/2, self.height/2 - copy_button_dimensions[1]/2)
copy_button_rect = pygame.Rect(*copy_button_pos, *copy_button_dimensions)
quit_button_pos = (self.width/2 - quit_button_dimensions[0]/2, 700)
quit_button_rect = pygame.Rect(*quit_button_pos, *quit_button_dimensions)
elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
check_click(event.pos)
draw_text()
draw_buttons(pygame.mouse.get_pos())
if breakOut:
break
pygame.display.update()
self.clock.tick(60)
def disconnected_screen(self, text1, text2):
def draw_text():
dc_text_1 = self.font.render(text1, True, game.foreground_color)
dc_text_2 = self.font.render(text2, True, game.foreground_color)
self.screen.blit(dc_text_1, (self.width/2 - dc_text_1.get_rect().width/2, 200))
self.screen.blit(dc_text_2, (self.width/2 - dc_text_2.get_rect().width/2, 300))
def draw_button():
pygame.draw.rect(self.screen, tuple(darken(color, 15) for color in game.foreground_color) if button_rect.collidepoint(mouse) else game.foreground_color, button_rect)
button_text = self.font.render("FIND NEW MATCH", True, button_text_color)
self.screen.blit(button_text, (button_pos[0] + 10, button_pos[1] + 3))
def check_click(pos):
nonlocal disconnected
if button_rect.collidepoint(pos):
disconnected = False
game.running = False
button_text_color = (0,0,0)
button_dimensions = (300, 40)
button_pos = (self.width/2 - button_dimensions[0]/2, self.height/2 - button_dimensions[1]/2)
button_rect = pygame.Rect(*button_pos, *button_dimensions)
disconnected = True
while disconnected:
mouse = pygame.mouse.get_pos()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.VIDEORESIZE or self.check_fullscreen(event):
try:
game.width, game.height = event.w, event.h
except:
pass
game.resize_all_screens()
button_pos = (self.width/2 - button_dimensions[0]/2, self.height/2 - button_dimensions[1]/2)
button_rect = pygame.Rect(*button_pos, *button_dimensions)
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
check_click(event.pos)
self.screen.fill(game.background_color)
draw_text()
draw_button()
pygame.display.update()
game.clock.tick(60)
def countdown(self, countdown):
pygame.mixer.music.pause()
last_second = int(countdown - time.time())
while countdown > time.time():
for event in pygame.event.get():
if event.type == pygame.QUIT:
return False
elif event.type == pygame.VIDEORESIZE or game.check_fullscreen(event):
try:
game.width, game.height = event.w, event.h
except:
pass
game.resize_all_screens()
seconds = int(countdown - time.time())
if seconds != last_second:
if seconds:
self.play_sound('countdown')
else:
self.play_sound('countdown go')
last_second = seconds
if not seconds:
seconds = "GO"
self.screen.fill(game.background_color)
above_text = self.medium_font.render("Game starts in...", True, game.foreground_color)
self.screen.blit(above_text, (game.width/2-above_text.get_rect().width/2, 150))
countdown_text = self.enormous_font.render(str(seconds), True, game.foreground_color)
self.screen.blit(countdown_text, (game.width/2-countdown_text.get_rect().width/2, game.height/2))
pygame.display.update()
self.clock.tick(60)
pygame.mixer.music.unpause()
game.time_started = time.time()
return True
def game_over_rematched(self):
return not self.game_over_rematched_bool
def chat_screen(self, send_chat):
message_text = ''
message_text_width = 0
input_active = False
held_key = ""
held_unicode = ""
held_time = 0
input_box_width = 300
input_box_height = 50
input_box_x = (self.width - input_box_width)/2
input_box_y = self.height - 100
input_box = pygame.Rect(input_box_x, input_box_y, input_box_width, input_box_height)
input_box_bkg = pygame.Rect((self.width - input_box_width)/2 , input_box_y, input_box_width, input_box_height)
def draw_messages(start):
last_y = 0
#it starts drawing from the start up
for idx, msg in enumerate(reversed(self.chat)):
text_render = game.small_font.render(msg, True, self.foreground_color)
game.screen.blit(text_render, (self.width/2 - 100, start - 50 * (idx + 1)))
#returning top most y to know where to stop scrolling
if idx == len(self.chat) - 1:
last_y = start - 50 * (idx + 1)
#draw a rectangle to cover the messages behind the message box if the user scrolls down
pygame.draw.rect(self.screen, self.background_color, (0, input_box_y - 15, self.width, self.height - input_box_y + 15))
return last_y
def send_text(text):
send_chat(f"chat {text}")
self.chat.append(f"You: {text}")
return ''
def draw_chat_box(message, active):
if active:
input_bkg_color = (0, 0, 255)
else:
input_bkg_color = (0, 0, 0)
pygame.draw.rect(game.screen, input_bkg_color, input_box, 10)
pygame.draw.rect(game.screen, (255,255,255), input_box_bkg)
message_render = game.medium_font.render(message, True, game.background_color) if message else game.small_font.render("send a message", True, game.foreground_color)
message_render_rect = message_render.get_rect()
game.screen.blit(message_render, (input_box.x + 5, input_box.y + message_render_rect.height/2))
return message_render_rect.width
def get_input(text: str, text_width: int):
if text_width < input_box.width - 15:
return text
return ''
def scroll(bottom: int, top: int, dr: int) -> int:
"""
-1 = up -> text comes down
1 = down -> text comes up
"""
print(bottom, top)
#making sure its not off screen
if (dr == -1 and top < 30) or (dr == 1 and bottom > input_box_y):
return bottom + 30 * dr * -1
return bottom
message_bottom = input_box_y
message_top = 0
running = True
while running:
# NOTE in order to send a chat message
# used the send() and chat.append() functions where text is the message to send
# the list, chat, is a list of messages that start with "me" or "opp"
# if it starts with "me", then it is by this client, if its "opp" the message is by the opponent
#Makes sure that if game starts while were in this screen it goes back to game
running = self.game_over_rematched()
game.update_presence(
details = "In chat screen",
state = "Chatting",
start = game.time_opened,
large_image = "tetrium"
)
mouse = pygame.mouse.get_pos()
self.screen.fill(self.background_color)
#Game over loop
for event in pygame.event.get():
if event.type == pygame.QUIT:
if self.connected:
game.n.disconnect()
pygame.quit()
sys.exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
if input_box.collidepoint(event.pos):
input_active = True
else:
input_active = False
if start_screen.back_button.collidepoint(mouse):
running = False
elif event.button == 4:
message_bottom = scroll(message_bottom, message_top, -1)
elif event.button == 5:
message_bottom = scroll(message_bottom, message_top, 1)
elif event.type == pygame.KEYDOWN:
#sending message
if message_text and event.key == pygame.K_RETURN:
message_text = send_text(message_text)
if input_active:
if event.key == pygame.K_BACKSPACE:
message_text = message_text[:-1]
else:
message_text += get_input(event.unicode, message_text_width)
if held_key != pygame.key:
held_time = time.time() + 0.5
held_key = event.key
if event.key == pygame.K_BACKSPACE:
held_unicode = "backspace"
else:
held_unicode = event.unicode
elif event.type == pygame.KEYUP:
held_time = time.time() + 0.5
if event.key == held_key:
held_key = ""
held_unicode = ""
elif event.type == pygame.VIDEORESIZE or self.check_fullscreen(event):
try:
game.width, game.height = event.w, event.h
except: pass
self.resize_all_screens()
input_box_x = (self.width - input_box_width)/2
input_box_y = self.height - 100
input_box = pygame.Rect(input_box_x, input_box_y, input_box_width, input_box_height)
input_box_bkg = pygame.Rect((self.width - input_box_width)/2 , input_box_y, input_box_width, input_box_height)
if held_key and time.time() >= held_time:
held_time = time.time() + 0.05
if held_unicode == "backspace":
message_text = message_text[:-1]
else:
message_text += get_input(held_unicode, message_text_width)
start_screen.draw_back_button(mouse)
message_top = draw_messages(message_bottom)
message_text_width = draw_chat_box(message_text, input_active)
pygame.display.update()
async def connect_presence(self):
try:
print("Connecting to Discord RPC...")
self.RPC.connect()
print("Discord RPC connected")
self.presence_connected = True
except Exception as e:
print(e)
self.presence_connected = False
async def start_connect_presence(self):
self.discord_rpc_loop.create_task(self.connect_presence())
def start_background_loop(self):
asyncio.set_event_loop(self.discord_rpc_loop)
self.discord_rpc_loop.run_forever()
async def async_update_presence(self, details, state, start, large_image):
try:
self.RPC.update(
state=state,
details=details,
start=start,
large_image=large_image,
large_text=large_image
)
except Exception as e:
print(e)
def update_presence(self, state, details, start, large_image):
if not self.dev and self.presence_connected:
self.discord_rpc_loop.create_task(self.async_update_presence(details, state, start, large_image))
def check_random_theme(self):
if self.random_theme:
random_theme_pick = randint(0, len(self.themes) -1)
theme = self.themes[randint(0, len(self.themes) -1)]
while theme[0] == 'Random':
random_theme_pick = randint(0, len(self.themes) -1)
theme = self.themes[random_theme_pick]
self.background_color = theme[1]
self.foreground_color = theme[2]
self.set_text_color(self.foreground_color)
self.set_grid_color(self.foreground_color)
settings_screen.set_buttons_color(self.foreground_color)
@staticmethod
def draw_block_borders(block_rect, color, block_size_difference = 5):
block_size = block_rect.width
#draw trapezoid on bottom
pygame.draw.polygon(game.screen, color,
[
#bottom left of trapezoid
(block_rect.x, block_rect.y + block_rect.height),
#top left of trapezoid
(block_rect.x + block_size_difference, block_rect.y + block_size - block_size_difference),
#top right of trapezoid
(block_rect.x + block_size - block_size_difference, block_rect.y + block_size - block_size_difference),
#bottom right of trapezoid
(block_rect.x + block_rect.width, block_rect.y + block_rect.height)
]
)
#draw trapezoid on right
pygame.draw.polygon(game.screen, tuple(lighten(i, 15) for i in color),
[
#bottom left of trapezoid
(block_rect.x + block_rect.width, block_rect.y + block_rect.height),
#top left of trapezoid
(block_rect.x + block_size - block_size_difference, block_rect.y + block_size - block_size_difference),
#top right of trapezoid
(block_rect.x + block_size - block_size_difference, block_rect.y + block_size_difference),
#bottom right of trapezoid
(block_rect.x + block_rect.width, block_rect.y)
]
)
def resize_screen_setup(self):
#BEFORE:
# self.playing_field_rect = pygame.Rect(100, 100, 300, 600)
# self.second_screen_rect = pygame.Rect(570, 250, 150, 300)
# self.playing_field_junk_meter_rect = pygame.Rect(35, 397, 30, 300)
# self.playing_field_junk_meter_rect_outline = pygame.Rect(32, 394, 36, 306)
# self.opp_screen_junk_meter = pygame.Rect(540, 399, 15, 150)
# self.opp_screen_junk_meter_outline = pygame.Rect(539, 398, 17, 152)
#NOTE y and for this rect has to have 100 margin on both sides
#NOTE x and for this rect has to have 100 margin left, 350 margin right
playing_field_rect_height = 600
playing_field_rect_y = self.height/2 - playing_field_rect_height/2
playing_field_rect_x = (self.width - 350 - (200 if self.multiplayer else 0))/2
self.playing_field_rect = pygame.Rect(playing_field_rect_x, playing_field_rect_y, 300, playing_field_rect_height)
self.second_block_y_offset = self.playing_field_rect.y + 150
self.block_x_offset = playing_field_rect_x - 100
playing_field_junk_meter_width = 30
playing_field_junk_meter_height = self.playing_field_rect.width
self.playing_field_junk_meter_rect = pygame.Rect(
self.playing_field_rect.x - 100/2 - playing_field_junk_meter_width/2,
self.playing_field_rect.y + self.playing_field_rect.height - playing_field_junk_meter_height,
playing_field_junk_meter_width,
playing_field_junk_meter_height
)
offset = 6
self.playing_field_junk_meter_rect_outline = pygame.Rect(
self.playing_field_junk_meter_rect.x - offset/2,
self.playing_field_junk_meter_rect.y - offset/2,
self.playing_field_junk_meter_rect.width + offset,
self.playing_field_junk_meter_rect.height + offset,
)
second_screen_rect_height = 150
self.second_screen_rect = pygame.Rect(
self.playing_field_rect.x + self.playing_field_rect.width + 170,
self.playing_field_rect.y + self.playing_field_rect.height/2 - second_screen_rect_height,
second_screen_rect_height,
300,
)
opp_screen_junk_meter_height = self.second_screen_rect.width
self.opp_screen_junk_meter_rect = pygame.Rect(
self.second_screen_rect.x - 30,
self.second_screen_rect.y + self.second_screen_rect.height - opp_screen_junk_meter_height,
15,
opp_screen_junk_meter_height
)
offset = 3
self.opp_screen_junk_meter_rect_outline = pygame.Rect(
self.opp_screen_junk_meter_rect.x - offset/2,
self.opp_screen_junk_meter_rect.y - offset/2,
self.opp_screen_junk_meter_rect.width + offset,
self.opp_screen_junk_meter_rect.height + offset,
)
def check_fullscreen(self, event, ingame = False):
mouse_number_key = {
1: 'left click',
2: 'middle click',
3: 'right click'
}
if event.type in (pygame.MOUSEBUTTONDOWN, pygame.KEYDOWN):
if event.type == pygame.KEYDOWN:
key_name = pygame.key.name(event.key)
else:
if 1 <= event.button <= 3:
key_name = mouse_number_key[event.button]
else:
key_name = None
if key_name == self.fullscreen_key:
self.toggle_fullscreen()
if ingame:
pygame.mouse.set_visible(False)
return True
return False
def toggle_fullscreen(self):
self.fullscreen = not self.fullscreen
if self.fullscreen:
self.width, self.height = pygame.display.get_desktop_sizes()[0]
pygame.display.quit()
self.screen = pygame.display.set_mode((self.width, self.height), flags = pygame.FULLSCREEN)
pygame.display.init()
else:
self.width, self.height = 750, 800
pygame.display.quit()
self.screen = pygame.display.set_mode((750, 800), flags = pygame.RESIZABLE)
pygame.display.init()
pygame.display.set_icon(self.icon)
pygame.display.set_caption(self.caption)
self.resize_all_screens()
def resize_all_screens(self):
self.resize_screen_setup()
start_screen.resize_screen()
settings_screen.resize_screen()
pygame.display.flip()
def pause(self, control, render_board):
running = True
pause_text = self.very_big_font.render('PAUSED', True, self.background_color)
transparent_bg = pygame.Surface((self.width, self.height), pygame.SRCALPHA)
alpha_surface = pygame.Surface(transparent_bg.get_size(), pygame.SRCALPHA)
alpha_surface.set_alpha(128)
time_started_difference = time.time() - game.time_started
while running:
game.time_started = time.time() - time_started_difference
alpha_surface.fill((128, 128, 128, 10))
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.VIDEORESIZE or self.check_fullscreen(event):
try:
self.width, self.height = event.w, event.h
except:
pass
self.resize_all_screens()
elif event.type == pygame.KEYDOWN:
if event.key == control:
running = False
render_board()
alpha_surface.blit(pause_text, pause_text.get_rect(center = (self.width/2 - 25, self.height/2)))
self.screen.blit(alpha_surface, (0, 0), special_flags = pygame.BLEND_RGBA_MULT)
pygame.display.update()
def vfx(self, fx_type, piece, intensity = 5):
if fx_type == VFX.hard_drop:
def hard_drop_shake(intensity, _):
for _ in range(intensity):
self.playing_field_rect.y += 1
time.sleep(5/2500)
time.sleep(5/62.5)
for _ in range(intensity * 2):
self.playing_field_rect.y -= 1
time.sleep(5/2500)
time.sleep(5/62.5)
for _ in range(intensity):
self.playing_field_rect.y += 1
time.sleep(5/2500)
_thread.start_new_thread(hard_drop_shake, (intensity, 0))
game = Game()
class VFX:
hard_drop = 0
class StartScreen(Game):
def __init__(self):
self.ready = False
self.rgb_stage = 0
self.version_text = game.small_font.render(f"v {network.version}", True, (255, 255, 255))
self.input_box_width = 300
self.input_box_height = 50
self.mute_button_radius = 35
self.multiplayer_button_text_color = (255, 255, 255)
self.credits_button_height = 30
self.input_text_width = 0
self.back_button = pygame.Rect(10, 10, 75, 65)
self.piece_types = ['I', 'O', 'T', 'L', 'J', 'Z', 'S']
self.resize_screen()
self.r, self.g, self.b = 255, 0, 0
self.last_falls = [time.time() for _ in self.pieces]
self.input_box_placeholder = game.medium_font.render("Enter a name...", True, (96, 93, 93))
self.input_active = False
self.input_text = game.initial_nickname
self.settings_button_text = game.medium_font.render('SETTINGS', True, (0, 0, 0))
self.credits_button_text = game.small_font.render('CREDITS', True, (0, 0, 0))
self.connected = False
self.started = False
self.back_icon = pygame.image.load(get_path('assets/images/arrow-back.png'))
self.disconnect_button_text = game.font.render('Disconnect', True, (self.r, self.g, self.b))
def resize_screen(self):
self.max_x = int((game.width/30)-4)
self.max_y = int((game.height/30))
step_y = 5
step_x = 1
#It might seem confusing whats happeneing here but dw about it, just making sure blocks are spaced out
self.x_pos = list(range(-3, self.max_x, step_x)) + [randint(0, self.max_x) for _ in range(3)]
self.y_pos = list(range(-3, self.max_y, step_y)) + [randint(0, self.max_y) for _ in range(3)]
shuffle(self.x_pos)
shuffle(self.y_pos)
self.pieces = [
Piece(x_pos, y_pos, choice(self.piece_types)) for x_pos, y_pos in zip(self.x_pos, self.y_pos)
]
rect = self.version_text.get_rect()
self.version_text_rect = self.version_text.get_rect(center=(game.width-(rect.width/2)-10, rect.height+10))
self.r, self.g, self.b = 255, 0, 0
self.last_falls = [time.time() for _ in self.pieces]
self.multiplayer_button_text_color = (255, 255, 255)
self.multiplayer_button_text = game.font.render('MULTIPLAYER', True, self.multiplayer_button_text_color)
self.multiplayer_button_rect = pygame.Rect(game.width/2-self.multiplayer_button_text.get_width()/2, game.height/2, 230, 40)
self.disconnect_button_rect = pygame.Rect(game.width/2-90, game.height/2+200, 175, 40)
self.s = pygame.Surface((game.width, game.height), pygame.SRCALPHA) # noqa pylint: disable=too-many-function-args
self.input_box_y = game.height/2 - 85
self.input_box_x = (game.width - self.input_box_width)/2
self.input_box = pygame.Rect(self.input_box_x, self.input_box_y, self.input_box_width, self.input_box_height)
self.input_box_bkg = pygame.Rect((game.width - self.input_box_width)/2 , game.height/2 - 85, self.input_box_width, self.input_box_height)
self.settings_button_pos = (0 , game.height - 30)
self.settings_button = pygame.Rect(0, game.height - self.credits_button_height, 125, self.credits_button_height)
self.credits_button_pos = (game.width - 70, game.height - self.credits_button_height)
self.credits_button = pygame.Rect(self.credits_button_pos[0], self.credits_button_pos[1], 70, self.credits_button_height)
self.back_icon = pygame.image.load(get_path('assets/images/arrow-back.png'))
self.back_button = pygame.Rect(10, 10, 75, 65)
self.disconnect_button_rect = pygame.Rect(game.width/2-90, game.height/2+70, 175, 40)
self.disconnect_button_text = game.font.render('Disconnect', True, (self.r, self.g, self.b))
self.singleplayer_button_text_color = (255, 255, 255)
self.singleplayer_button_text = game.font.render('SINGLEPLAYER', True, self.singleplayer_button_text_color)
self.singleplayer_button_rect = pygame.Rect(game.width/2-self.singleplayer_button_text.get_width()/2, game.height/2+60, 250, 40)
def check_started(self):
return not self.started
def draw_back_button(self, pos = (-10, -10)):
white = (255, 255, 255)
color = tuple(darken(i) for i in white) if start_screen.back_button.collidepoint(pos) else white
pygame.draw.rect(game.screen, color, start_screen.back_button)
game.screen.blit(start_screen.back_icon, (-3, -7))
def draw_buttons(self):
#if mouse hovering make it lighter
if self.multiplayer_button_rect.collidepoint(self.mouse):
colooooooooor = (255,255,255)
self.multiplayer_button_text_color = (self.r, self.g, self.b)
else:
colooooooooor = (0, 0, 0)
self.multiplayer_button_text_color = (255, 255, 255)
pygame.draw.rect(game.screen, colooooooooor, self.multiplayer_button_rect)
if self.singleplayer_button_rect.collidepoint(self.mouse):
colooooooooor = (255,255,255)
self.singleplayer_button_text_color = (self.r, self.g, self.b)
else:
colooooooooor = (0, 0, 0)
self.singleplayer_button_text_color = (255, 255, 255)
self.singleplayer_button_text = game.font.render('SINGLEPLAYER', True, self.singleplayer_button_text_color)
pygame.draw.rect(game.screen, colooooooooor, self.singleplayer_button_rect)
def credits_screen(self):
credits_list = ['Made by', 'okay#2996', 'and', 'AliMan21#6527']
text_y = 0
text_offset = 80
text_scroll_dist_multiplier = 4000
def draw_text(tup):
index, text = tup
rendered_text = game.font.render(text, True, (255,255,255))
game.screen.blit(rendered_text, (rendered_text.get_rect(center = (game.width/2, game.height/2))[0], text_y + (index * text_offset)))
running = True
while running:
mouse = pygame.mouse.get_pos()
#Makes sure that if game starts while were in this screen it goes back to game
running = start_screen.check_started()
#Game over loop
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.VIDEORESIZE or game.check_fullscreen(event):
try:
game.width, game.height = event.w, event.h
except:
pass
game.resize_all_screens()
elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
if self.back_button.collidepoint(event.pos):
running = False
break
text_scroll_dist = game.width / text_scroll_dist_multiplier
game.screen.fill((0, 0, 0))
self.draw_tetris_pieces(self.pieces)
self.draw_back_button(mouse)
text_y = text_y + text_scroll_dist if text_y <= (game.height + 100) else -1 * (len(credits_list) * text_offset)
list(map(draw_text, enumerate(credits_list)))
pygame.display.update()
def draw_text(self, mouse):
if not self.connected:
self.multiplayer_button_text = game.font.render('MULTIPLAYER', True, self.multiplayer_button_text_color)
game.screen.blit(self.singleplayer_button_text, (self.singleplayer_button_rect.x + 7, self.singleplayer_button_rect.y + 3))
else:
self.multiplayer_button_text = game.font.render('Waiting for opponent...', True, (self.r, self.g, self.b))
if self.disconnect_button_rect.collidepoint(mouse):
color = tuple(darken(i) for i in (255, 255, 255))
else:
color = (255, 255, 255)
pygame.draw.rect(game.screen, color, self.disconnect_button_rect)
game.screen.blit(self.disconnect_button_text, (self.disconnect_button_rect.x + 7, self.disconnect_button_rect.y + 1))
self.multiplayer_button_rect.x = game.width/2-self.multiplayer_button_text.get_width()/2
title_text = game.very_big_font.render('TETRIUM', True, (self.r, self.g, self.b))
game.screen.blit(self.multiplayer_button_text, (self.multiplayer_button_rect.x + 7, self.multiplayer_button_rect.y + 3))
game.screen.blit(title_text, (game.width/2 - 165, game.height/2 - 200))
game.screen.blit(self.version_text, self.version_text_rect)
def draw_input_text(self):
if not self.input_text:
game.screen.blit(self.input_box_placeholder, (self.input_box_x + 25, self.input_box_y + 12))
input_text_render = game.big_font.render(self.input_text, True, (0, 0, 0))
self.input_text_width = input_text_render.get_rect().width
game.screen.blit(input_text_render, (self.input_box_x + 5, self.input_box_y + 6))
def draw_input_box(self):
if self.input_active:
input_bkg_color = (0, 0, 255)
else:
input_bkg_color = (0, 0, 0)
pygame.draw.rect(game.screen, input_bkg_color, self.input_box, 10)
pygame.draw.rect(game.screen, (255,255,255), self.input_box_bkg)
self.draw_input_text()
def get_input(self, key):
if self.input_text_width < self.input_box_width - 15:
self.input_text += key
def start(self):
self.input_active = False
# saving nickname
with open(get_path('settings.json')) as f:
settings = json.load(f)
settings['name'] = self.input_text
with open(get_path('settings.json'), 'w') as f:
json.dump(settings, f, indent=2)
game.n = network.Network()
if game.n.p == "no connection":
self.no_connection_screen()
return
self.input_text = self.input_text.strip()
if not self.input_text:
self.input_text = "Player"
if isinstance(game.n.p, str):
outdated_info = game.n.p.split()
# new version number # download link
game.outdated_version_screen(outdated_info[2], outdated_info[3])
return
game.update_presence(
details="In Start Menu",
state="Waiting for match",
start=game.time_opened,
large_image="tetrium"
)
self.multiplayer_button_rect.x -= 100
self.connected = True
game.name = self.input_text
game.n.send("name " + self.input_text)
_thread.start_new_thread(self.wait_for_game, ())
def cycle_colors(self, rgb):
r, g, b = rgb
if self.rgb_stage == 0:
if g < 255 and r > 0:
g += 1
r -= 1
else:
self.rgb_stage = 1
elif self.rgb_stage == 1:
if b < 255 and g > 0:
b += 1
g -= 1
else:
self.rgb_stage = 2
elif self.rgb_stage == 2:
if r < 255 and b > 0:
r += 1
b -= 1
else:
self.rgb_stage = 0
return (r, g, b)
def draw_tetris_pieces(self, pieces, rotate = True):
for i, piece in enumerate(pieces):
#means piece is off the screen
if piece.y >= 28:
#Moves it back up
piece.move(0, -30)
piece.render(False)
try:
if time.time() > self.last_falls[i]:
piece.move(0, 1)
self.last_falls[i] = time.time() + 0.75
#this is just an algorithm for occasionally turning the pieces
if rotate and randint(0, 7) == 3:
piece.rotate(randint(0, 1), False)
except:
break
def draw_credits_button(self, pos):
color = tuple(map(lighten, (self.r,self.g, self.b))) if self.credits_button.collidepoint(pos) else (self.r, self.g, self.b)
pygame.draw.rect(game.screen, color, self.credits_button)
game.screen.blit(self.credits_button_text, (self.credits_button_pos[0] + 3, self.credits_button_pos[1] + 5))
def draw_settings_button(self, pos):
color = tuple(map(lighten, (self.r,self.g, self.b))) if self.settings_button.collidepoint(pos) else (self.r, self.g, self.b)
pygame.draw.rect(game.screen, color, self.settings_button)
game.screen.blit(self.settings_button_text, (self.settings_button_pos[0] + 10, self.settings_button_pos[1] + 3))
def wait_for_game(self):
self.status = 'get'
while True:
if self.status == 'get':
data = game.n.send('get')
elif self.status == 'disconnect':
game.n.disconnect()
break
try:
if data.ready: #type: ignore
time.sleep(1)
data = game.n.send('get')
game.opp_name = data.opp_name(game.n.p)
self.ready = True
self.started = True
break
except Exception as e:
if not isinstance(e, AttributeError):
raise e
break
@staticmethod
def no_connection_screen():
display_time = time.time() + 3
game.screen.fill(game.background_color)
text = game.very_big_font.render("No connection", True, game.foreground_color)
game.screen.blit(text, (game.width/2-text.get_rect().width/2, 300))
pygame.display.update()
while display_time > time.time():
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.VIDEORESIZE or game.check_fullscreen(event):
try:
game.width, game.height = event.w, event.h
except:
pass
game.resize_all_screens()
game.clock.tick(60)
def main(self):
running = True
initial_presence = False
held_time = 0
held_key = ""
held_unicode = ""
last_cycle = 0
while running:
#NOTE make sure this is at the top
self.s.fill((0,0,0, 2))
#Makes sure that if game starts while were in this screen it goes back to game
running = start_screen.check_started()
# print(initial_presence, game.presence_connected)
if not initial_presence and game.presence_connected:
game.update_presence(
details = "In Start Menu",
state = "Idling",
start = game.time_opened,
large_image = "tetrium"
)
initial_presence = True
self.mouse = pygame.mouse.get_pos()
#Game over loop
for event in pygame.event.get():
if event.type == pygame.QUIT:
if self.connected:
game.n.disconnect()
pygame.quit()
sys.exit()
elif event.type == pygame.VIDEORESIZE or game.check_fullscreen(event):
try:
game.width, game.height = event.w, event.h
except:
pass
game.resize_all_screens()
elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
if self.multiplayer_button_rect.collidepoint(event.pos) and not self.connected:
self.start()
game.screen.fill((0, 0, 0))
game.update_presence(
details = "In Start Menu",
state = "Idling",
start = game.time_opened,
large_image = "tetrium"
)
elif self.singleplayer_button_rect.collidepoint(event.pos) and not self.connected:
game.multiplayer = False
running = False
self.started = True
game.name = self.input_text
# saving nickname
with open(get_path('settings.json')) as f:
settings = json.load(f)
settings['name'] = self.input_text
with open(get_path('settings.json'), 'w') as f:
json.dump(settings, f, indent=2)
elif self.disconnect_button_rect.collidepoint(event.pos) and self.connected:
self.status = 'disconnect'
game.screen.fill((0, 0, 0))
self.connected = False
initial_presence = False
elif self.credits_button.collidepoint(event.pos):
self.credits_screen()
self.s.fill((0, 0, 0))
elif self.settings_button.collidepoint(event.pos):
settings_screen.main()
self.s.fill((0, 0, 0))
elif self.input_box.collidepoint(event.pos) and not self.connected:
self.input_active = True
else:
self.input_active = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_RETURN:
self.start()
game.screen.fill((0, 0, 0))
if self.input_active:
if event.key == pygame.K_BACKSPACE:
self.input_text = self.input_text[:-1]
else:
self.get_input(event.unicode)
if held_key != pygame.key:
held_time = time.time() + 0.5
held_key = event.key
if event.key == pygame.K_BACKSPACE:
held_unicode = "backspace"
else:
held_unicode = event.unicode
elif event.type == pygame.KEYUP:
held_time = time.time() + 0.5
if event.key == held_key:
held_key = ""
held_unicode = ""
if held_key and time.time() >= held_time:
held_time = time.time() + 0.05
if held_unicode == "backspace":
self.input_text = self.input_text[:-1]
else:
self.get_input(held_unicode)
if time.time() >= last_cycle:
last_cycle = time.time() + 1/60
game.screen.blit(self.s, (0, 0))
self.r, self.g, self.b = self.cycle_colors((self.r, self.g, self.b))
self.draw_tetris_pieces(self.pieces)
self.draw_credits_button(self.mouse)
self.draw_settings_button(self.mouse)
if not self.connected:
self.draw_buttons()
self.draw_text(self.mouse)
self.draw_input_box()
# checking if game started
if self.connected and self.ready:
game.multiplayer = True
self.connected = False
self.multiplayer_button_rect = pygame.Rect(game.width/2-60, game.height/2, 200, 40)
self.started = True
running = False
break
pygame.display.update()
game.time_started = time.time()
game.running = True
game.resize_screen_setup()
class SettingsScreen(StartScreen):
def __init__(self):
self.buttons_color = game.foreground_color
self.background_color = game.background_color
self.resize_screen()
def set_buttons_color(self, color):
self.buttons_color = color
for i in range(len(self.buttons)):
self.buttons[i][2] = color
def resize_screen(self):
self.buttons = [
[
pygame.Rect(game.width/2 - 200/2, game.height/2 - 200, 200, 50),
game.big_font.render('CONTROLS', True, (0, 0, 0)),
self.buttons_color,
self.pick_controls_screen
],
[
pygame.Rect(game.width/2 - 200/2, game.height/2 - 100, 200, 50),
game.big_font.render('THEMES', True, (0, 0, 0)),
self.buttons_color,
self.pick_themes_screen
],
[
pygame.Rect(game.width/2 - 200/2, game.height/2, 200, 50),
game.big_font.render('GAMEPLAY', True, (0, 0, 0)),
self.buttons_color,
self.gameplay_screen
],
[
pygame.Rect(game.width/2 - 200/2, game.height/2 + 100, 200, 50),
game.big_font.render('AUDIO', True, (0, 0, 0)),
self.buttons_color,
self.audio_screen
]
]
def audio_screen(self):
with open(get_path('settings.json')) as f:
settings = json.load(f)
audio_settings = settings['audio']
slider_width = game.width/1.5
slider_radius = game.height/80
sliders = [
{
"json name": "main",
"name": "Main Volume",
"pos": (0, 0),
"default": 1.0
},
{
"json name": "music",
"name": "Music",
"pos": (0, 0),
"default": 0.5
},
{
"json name": "sfx",
"name": "Sound Effects",
"pos": (0, 0),
"default": 1.0
},
]
def set_slider_pos():
for i in range(len(sliders)):
y_pos = (game.height/8 + game.height/16) * (i + 0.5)
sliders[i]['pos'] = (game.width/2, y_pos)
set_slider_pos()
def screen_size_change():
set_slider_pos()
reset_button_rect.x = game.width/2-40
reset_button_rect.y = game.height - 35
for x in range(len(sliders)):
sliders[x]["value"] = audio_settings[sliders[x]["json name"]]
def draw_sliders():
for slider in sliders:
name, pos, value = slider["name"], slider["pos"], slider["value"]
text_element = game.big_font.render(name, True, game.foreground_color)
game.screen.blit(text_element, (pos[0] - text_element.get_rect().width/2, pos[1]))
pygame.draw.rect(game.screen, game.foreground_color, (pos[0] - slider_width/2, pos[1] + 70, slider_width, 4))
pygame.draw.circle(game.screen, game.foreground_color, center= ((pos[0]-slider_width/2) + int(value * slider_width), pos[1]+72), radius=slider_radius)
measurement = f'{int(value*100)}%'
value_element = game.medium_font.render(measurement, True, game.foreground_color)
game.screen.blit(value_element, (pos[0] - value_element.get_rect().width/2, pos[1]+90))
reset_button_rect = pygame.Rect(game.width/2-40, game.height - 35, 80, 25)
def path_leaf(path):
head, tail = ntpath.split(path)
return tail or ntpath.basename(head)
track_names = [path_leaf(path).replace('.wav', '') for path in game.tracks]
def draw_reset_button():
if reset_button_rect.collidepoint(mouse):
reset_button_color = tuple(darken(color, 15) for color in game.foreground_color)
else:
reset_button_color = game.foreground_color
pygame.draw.rect(game.screen, reset_button_color, reset_button_rect)
reset_button_text = game.medium_font.render("RESET", True, game.background_color)
game.screen.blit(reset_button_text, (game.width/2-reset_button_text.get_rect().width/2, reset_button_rect.y))
left_arrow = pygame.image.load(get_path('assets/images/left_arrow.png'))
left_arrow = pygame.transform.scale(left_arrow, (30, 30))
dimensions = left_arrow.get_height()
left_arrow_pos = (game.width/4 - left_arrow.get_width()/2, game.height - dimensions/2 - 140)
right_arrow = pygame.image.load(get_path('assets/images/right_arrow.png'))
right_arrow = pygame.transform.scale(right_arrow, (30, 30))
right_arrow_pos = (((game.width/4)*3) - right_arrow.get_width()/2, game.height - dimensions/2 - 140)
left_arrow_rect = left_arrow.get_rect(center = (left_arrow_pos[0] + dimensions/2, left_arrow_pos[1] + dimensions/2))
right_arrow_rect = right_arrow.get_rect(center = (right_arrow_pos[0] + dimensions/2, right_arrow_pos[1] + dimensions/2))
hover_scale_factor = 1.1
def is_dark(rgb):
r, g, b = rgb
cutoff = 30
if r < cutoff and g < cutoff and b < cutoff:
return True
return False
def draw_arrows(mouse):
dark = is_dark(game.background_color)
#hover effect
if left_arrow_rect.collidepoint(mouse):
if dark:
new_left_arrow = left_arrow
new_left_arrow_rect = new_left_arrow.get_rect(center = (left_arrow_pos[0] + dimensions/2, left_arrow_pos[1] + dimensions/2))
new_left_arrow_rect_color = tuple(darken(i) for i in game.foreground_color)
else:
new_left_arrow = pygame.transform.scale(left_arrow, (int(dimensions * hover_scale_factor), int(dimensions * hover_scale_factor)))
new_left_arrow_rect = new_left_arrow.get_rect(center = (left_arrow_pos[0] + dimensions/2, left_arrow_pos[1] + dimensions/2))
new_left_arrow_rect_color = game.foreground_color
else:
new_left_arrow = left_arrow
new_left_arrow_rect = left_arrow_rect
new_left_arrow_rect_color = game.foreground_color
if right_arrow_rect.collidepoint(mouse):
if dark:
new_right_arrow = right_arrow
new_right_arrow_rect = new_right_arrow.get_rect(center = (right_arrow_pos[0] + dimensions/2, right_arrow_pos[1] + dimensions/2))
new_right_arrow_rect_color = tuple(darken(i) for i in game.foreground_color)
else:
new_right_arrow = pygame.transform.scale(right_arrow, (int(dimensions * hover_scale_factor), int(dimensions * hover_scale_factor)))
new_right_arrow_rect = new_right_arrow.get_rect(center = (right_arrow_pos[0] + dimensions/2, right_arrow_pos[1] + dimensions/2))
new_right_arrow_rect_color = game.foreground_color
else:
new_right_arrow = right_arrow
new_right_arrow_rect = right_arrow_rect
new_right_arrow_rect_color = game.foreground_color
if dark:
pygame.draw.rect(game.screen, new_left_arrow_rect_color, new_left_arrow_rect)
pygame.draw.rect(game.screen, new_right_arrow_rect_color, new_right_arrow_rect)
game.screen.blit(new_left_arrow, left_arrow_pos)
game.screen.blit(new_right_arrow, right_arrow_pos)
if not game.random_track:
music_name = track_names[game.current_track]
else:
music_name = "Auto Cycle"
def draw_music_switcher():
soundtrack_text = game.medium_font.render("Soundtrack", True, game.foreground_color)
game.screen.blit(soundtrack_text, (game.width/2-soundtrack_text.get_rect().width/2, game.height-210))
music_name_text = game.big_font.render(music_name, True, game.foreground_color)
game.screen.blit(music_name_text, (game.width/2-music_name_text.get_rect().width/2, game.height-160))
draw_arrows(mouse)
if not game.random_track:
track_number = game.current_track + 1
else:
track_number = 0
def next_music(direction):
nonlocal music_name, track_number
options = track_names.copy()
options.insert(0, "Auto Cycle")
# right
if direction == 1:
track_number += 1
if track_number >= len(options):
track_number = 0
# left
elif direction == 0:
track_number -= 1
if track_number < 0:
track_number = len(options) - 1
music_name = options[track_number]
pygame.mixer.music.stop()
if track_number == 0:
game.current_track = randint(0, len(game.tracks)-1)
if not game.random_track:
pygame.mixer.music.stop()
game.random_track = True
_thread.start_new_thread(game.cycle_music, ())
settings['track'] = 'random'
else:
game.random_track = False
game.current_track = track_number - 1
pygame.mixer.music.load(game.tracks[game.current_track])
pygame.mixer.music.play(-1)
pygame.mixer.music.set_volume(game.music)
settings['track'] = game.current_track
running = True
dragging = None
while running:
running = start_screen.check_started()
for slider in sliders:
audio_settings[slider["json name"]] = slider["value"]
mouse = pygame.mouse.get_pos()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.VIDEORESIZE or game.check_fullscreen(event):
try:
game.width, game.height = event.w, event.h
except:
pass
game.resize_all_screens()
screen_size_change()
left_arrow_pos = (game.width/4 - left_arrow.get_width()/2, game.height - dimensions/2 - 140)
right_arrow_pos = (((game.width/4)*3) - right_arrow.get_width()/2, game.height - dimensions/2 - 140)
left_arrow_rect = left_arrow.get_rect(center = (left_arrow_pos[0] + dimensions/2, left_arrow_pos[1] + dimensions/2))
right_arrow_rect = right_arrow.get_rect(center = (right_arrow_pos[0] + dimensions/2, right_arrow_pos[1] + dimensions/2))
slider_width = game.width/1.5
slider_radius = game.height/80
elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
# back button
if start_screen.back_button.collidepoint(event.pos):
running = False
with open(get_path('settings.json'), 'w') as f:
json.dump(settings, f, indent=2)
elif reset_button_rect.collidepoint(mouse):
for slider in sliders:
slider['value'] = slider['default']
track_number = 0
next_music(-1)
elif left_arrow_rect.collidepoint(event.pos):
next_music(0)
elif right_arrow_rect.collidepoint(event.pos):
next_music(1)
elif not dragging:
for slider in sliders:
x, y = slider["pos"]
value = slider["value"]
if x - slider_width/2 + int(value * slider_width) - slider_radius < mouse[0] < x - slider_width/2 + int(value * slider_width) + slider_radius and y + 72 - slider_radius < mouse[1] < y + 72 + slider_radius:
dragging = slider["name"]
break
elif event.type == pygame.MOUSEBUTTONUP and event.button == 1:
if dragging: dragging = None
if dragging:
for slider in sliders:
if slider["name"] == dragging:
value = mouse[0] - (slider["pos"][0] - slider_width / 2)
if value < 0: value = 0
elif value > slider_width: value = slider_width
value /= slider_width
slider["value"] = value
game.screen.fill(game.background_color)
draw_sliders()
draw_reset_button()
draw_music_switcher()
self.draw_back_button(mouse)
game.music = audio_settings['main'] * audio_settings['music']
game.sfx = audio_settings['main'] * audio_settings['sfx']
pygame.mixer.music.set_volume(game.music)
game.sfx_channel.set_volume(game.sfx)
pygame.display.update()
if not running:
with open(get_path('settings.json'), 'w') as f:
json.dump(settings, f, indent=2)
def gameplay_screen(self):
with open(get_path('settings.json')) as f:
settings = json.load(f)
gameplay_settings = settings["gameplay"]
controls = settings["controls"]
slider_width = game.width/1.5
slider_radius = game.height/80
sliders = [
{
"json name": "das",
"name": "Delayed Auto Shift",
"pos": (0, 0),
"default": 0.8
},
{
"json name": "arr",
"name": "Auto Repeat Rate",
"pos": (0, 0),
"default": 0.85
},
{
"json name": "sds",
"name": "Soft Drop Speed",
"pos": (0, 0),
"default": 0.17
}
]
def set_slider_pos():
for i in range(len(sliders)):
y_pos = (game.height/8 + game.height/16) * (i + 0.5)
sliders[i]['pos'] = (game.width/2, y_pos)
set_slider_pos()
def screen_size_change():
set_slider_pos()
reset_button_rect.x = game.width/2-40
reset_button_rect.y = game.height - 35
for x in range(len(sliders)):
sliders[x]["value"] = gameplay_settings[sliders[x]["json name"]]
def draw_sliders():
for slider in sliders:
name, pos, value = slider["name"], slider["pos"], slider["value"]
text_element = game.big_font.render(name, True, game.foreground_color)
game.screen.blit(text_element, (pos[0] - text_element.get_rect().width/2, pos[1]))
pygame.draw.rect(game.screen, game.foreground_color, (pos[0] - slider_width/2, pos[1] + 70, slider_width, 4))
pygame.draw.circle(game.screen, game.foreground_color, center= ((pos[0]-slider_width/2) + int(value * slider_width), pos[1]+72), radius=slider_radius)
if name == "Delayed Auto Shift":
measurement = int(value * 500)
measurement = f"{measurement}ms"
elif name == "Auto Repeat Rate":
measurement = 205 - (int(value * 195) + 5)
measurement = f"{measurement}ms"
else:
#name == "Soft Drop Speed"
measurement = int(value*78) + 2
measurement = f"x{measurement}"
value_element = game.medium_font.render(measurement, True, game.foreground_color)
game.screen.blit(value_element, (pos[0] - value_element.get_rect().width/2, pos[1]+90))
piece = Piece((game.width/2)/30 - 3.3, 20, "O")
def draw_preview():
text_element = game.big_font.render("Preview", True, game.foreground_color)
game.screen.blit(text_element, (game.width/2 - text_element.get_rect().width/2, game.height/2+140))
text_element2 = game.medium_font.render("Move left and right to try it out", True, game.foreground_color)
game.screen.blit(text_element2, (game.width/2 - text_element2.get_rect().width/2, game.height/2+190))
piece.render(preview=False)
def can_move(moving):
if moving == 1 and piece.x < game.width//30 - 5: return True
elif moving == -1 and piece.x > -1.3: return True
return False
reset_button_rect = pygame.Rect(game.width/2-40, game.height - 35, 80, 25)
def draw_reset_button():
if reset_button_rect.collidepoint(mouse):
reset_button_color = tuple(darken(color, 15) for color in game.foreground_color)
else:
reset_button_color = game.foreground_color
pygame.draw.rect(game.screen, reset_button_color, reset_button_rect)
reset_button_text = game.medium_font.render("RESET", True, game.background_color)
game.screen.blit(reset_button_text, (game.width/2-reset_button_text.get_rect().width/2, reset_button_rect.y))
running = True
dragging = None
moving = 0
last_move = 0
das_start = 0
while running:
running = start_screen.check_started()
for slider in sliders:
gameplay_settings[slider["json name"]] = slider["value"]
if moving:
if can_move(moving) and time.time() > das_start:
if time.time() > last_move:
piece.move(moving, 0)
last_move = time.time() + (0.205 - ((gameplay_settings['arr'] * 0.195) + 0.005))
mouse = pygame.mouse.get_pos()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.VIDEORESIZE or game.check_fullscreen(event):
try:
game.width, game.height = event.w, event.h
except:
pass
game.resize_all_screens()
screen_size_change()
piece = Piece((game.width/2)/30 - 3.3, 20, "O")
slider_width = game.width/1.5
slider_radius = game.height/80
elif event.type == pygame.KEYDOWN:
key_name = pygame.key.name(event.key)
if key_name == controls['Move Left']:
if can_move(-1):
moving = -1
das_start = max(time.time() + (gameplay_settings['das'] * 0.5), time.time() + 0.205 - ((gameplay_settings['arr'] * 0.195) + 0.005))
piece.move(-1, 0)
elif key_name == controls['Move Right']:
if can_move(1):
moving = 1
das_start = max(time.time() + (gameplay_settings['das'] * 0.5), time.time() + 0.205 - ((gameplay_settings['arr'] * 0.195) + 0.005))
piece.move(1, 0)
elif event.type == pygame.KEYUP:
key_name = pygame.key.name(event.key)
if key_name == controls['Move Left']:
if moving == -1:
moving = 0
elif key_name == controls['Move Right']:
if moving == 1:
moving = 0
elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
# back button
if start_screen.back_button.collidepoint(event.pos):
running = False
with open(get_path('settings.json'), 'w') as f:
json.dump(settings, f, indent = 2)
elif reset_button_rect.collidepoint(mouse):
for slider in sliders:
slider['value'] = slider['default']
with open(get_path('settings.json'), 'w') as f:
json.dump(settings, f, indent = 2)
elif not dragging:
for slider in sliders:
x, y = slider["pos"]
value = slider["value"]
if x - slider_width/2 + int(value * slider_width) - slider_radius < mouse[0] < x - slider_width/2 + int(value * slider_width) + slider_radius and y + 72 - slider_radius < mouse[1] < y + 72 + slider_radius:
dragging = slider["name"]
break
elif event.type == pygame.MOUSEBUTTONUP and event.button == 1:
if dragging: dragging = None
if dragging:
for slider in sliders:
if slider["name"] == dragging:
value = mouse[0] - (slider["pos"][0] - slider_width / 2)
if value < 0: value = 0
elif value > slider_width: value = slider_width
value /= slider_width
slider["value"] = value
game.screen.fill(game.background_color)
draw_sliders()
draw_preview()
draw_reset_button()
self.draw_back_button(mouse)
pygame.display.update()
#Write to json if loop stopped, meaning they pressed back or game started
with open(get_path('settings.json'), 'w') as f:
json.dump(settings, f, indent = 2)
def pick_themes_screen(self):
#issue: we need to call setup function for this outside of this function but we cant cause its not a class
def render_game_preview(bkg_color, fgd_color):
pygame.draw.rect(game.screen, bkg_color, pygame.Rect(0, 0, game.width, game.height))
pygame.draw.rect(game.screen, fgd_color, new_playing_field_rect)
self.draw_tetris_pieces(self.pieces)
#It was a lot of work to change the start and end position of the blocks, so i just cover them with a rect so look like theyre not going off screen
pygame.draw.rect(game.screen, bkg_color, pygame.Rect(0, 0, game.width, (game.height - new_playing_field_rect.height)/2))
pygame.draw.rect(game.screen, bkg_color, pygame.Rect(0, new_playing_field_rect.y + new_playing_field_rect.height, game.width, (game.height - new_playing_field_rect.height)))
def is_dark(rgb):
r, g, b = rgb
cutoff = 30
if r < cutoff and g < cutoff and b < cutoff:
return True
def draw_arrows(mouse):
dark = False
if is_dark(game.background_color):
dark = True
#hover effect
if left_arrow_rect.collidepoint(mouse):
if dark:
new_left_arrow = left_arrow
new_left_arrow_rect = new_left_arrow.get_rect(center = (left_arrow_pos[0] + dimensions/2, left_arrow_pos[1] + dimensions/2))
new_left_arrow_rect_color = tuple(darken(i, 15) for i in game.foreground_color)
else:
new_left_arrow = pygame.transform.scale(left_arrow, (int(dimensions * hover_scale_factor), int(dimensions * hover_scale_factor)))
new_left_arrow_rect = new_left_arrow.get_rect(center = (left_arrow_pos[0] + dimensions/2, left_arrow_pos[1] + dimensions/2))
new_left_arrow_rect_color = game.foreground_color
else:
new_left_arrow = left_arrow
new_left_arrow_rect = left_arrow_rect
new_left_arrow_rect_color = game.foreground_color
if right_arrow_rect.collidepoint(mouse):
if dark:
new_right_arrow = right_arrow
new_right_arrow_rect = new_right_arrow.get_rect(center = (right_arrow_pos[0] + dimensions/2, right_arrow_pos[1] + dimensions/2))
new_right_arrow_rect_color = tuple(darken(i, 15) for i in game.foreground_color)
else:
new_right_arrow = pygame.transform.scale(right_arrow, (int(dimensions * hover_scale_factor), int(dimensions * hover_scale_factor)))
new_right_arrow_rect = new_right_arrow.get_rect(center = (right_arrow_pos[0] + dimensions/2, right_arrow_pos[1] + dimensions/2))
new_right_arrow_rect_color = game.foreground_color
else:
new_right_arrow = right_arrow
new_right_arrow_rect = right_arrow_rect
new_right_arrow_rect_color = game.foreground_color
if dark:
pygame.draw.rect(game.screen, new_left_arrow_rect_color, new_left_arrow_rect)
pygame.draw.rect(game.screen, new_right_arrow_rect_color, new_right_arrow_rect)
game.screen.blit(new_left_arrow, left_arrow_pos)
game.screen.blit(new_right_arrow, right_arrow_pos)
def change_theme():
theme = game.themes[game.theme_index]
game.theme_text = theme[0]
background_color = theme[1]
foreground_color = theme[2]
game.foreground_color = foreground_color
game.background_color = background_color
game.set_grid_color(foreground_color)
game.set_text_color(foreground_color)
self.set_buttons_color(foreground_color)
self.background_color = background_color
#we need a seperate var because if we rely on theme text, then once we change the theme (since its random), it will no longer think its random
if game.theme_text == 'Random':
game.random_theme = True
else:
game.random_theme = False
def next_theme(direction):
#direction 0 = left, 1 = right
themes_len = len(game.themes)
if direction and game.theme_index >= themes_len - 1:
val = 0
game.theme_index = 0
elif direction:
val = 1
elif game.theme_index <= 0:
val = 0
game.theme_index = themes_len - 1
else:
val = -1
game.theme_index += val
change_theme()
rgb_stage = 0
r, g, b = 255, 0, 0
def cycle_colors():
nonlocal r, g, b, rgb_stage
if rgb_stage == 0:
if g < 255 and r > 0:
g += 1
r -= 1
else:
rgb_stage = 1
elif rgb_stage == 1:
if b < 255 and g > 0:
b += 1
g -= 1
else:
rgb_stage = 2
elif rgb_stage == 2:
if r < 255 and b > 0:
r += 1
b -= 1
else:
rgb_stage = 0
def draw_title():
title = game.very_big_medium_font.render(game.theme_text, True, game.foreground_color)
title_rect = title.get_rect()
game.screen.blit(title, (game.width/2 - title_rect.width/2, 10))
def store_theme():
with open(get_path('settings.json')) as f:
full_dict = json.load(f)
full_dict['theme'] = game.theme_index
with open(get_path('settings.json'), 'w') as f:
json.dump(full_dict, f, indent = 2)
def random_theme():
if game.random_theme:
if not randint(0, 2):
cycle_colors()
text = game.enormous_font.render('?', True, (game.background_color))
text_rect = text.get_rect(center = (new_playing_field_rect.x + new_playing_field_rect.width/2, new_playing_field_rect.y + new_playing_field_rect.height/2))
game.screen.blit(text, text_rect)
offset = 10
left_arrow = pygame.image.load(get_path('assets/images/left_arrow.png'))
dimensions = left_arrow.get_height()
left_arrow_pos = (offset, game.height/2 - dimensions/2)
right_arrow_pos = (game.width - dimensions - offset, game.height/2 - dimensions/2)
right_arrow = pygame.image.load(get_path('assets/images/right_arrow.png'))
left_arrow_rect = left_arrow.get_rect(center = (left_arrow_pos[0] + dimensions/2, left_arrow_pos[1] + dimensions/2))
right_arrow_rect = right_arrow.get_rect(center = (right_arrow_pos[0] + dimensions/2, right_arrow_pos[1] + dimensions/2))
hover_scale_factor = 1.1
new_playing_field_rect = pygame.Rect(game.width/2 - game.playing_field_rect.width/2, game.playing_field_rect.y, game.playing_field_rect.width, game.playing_field_rect.height)
min_x = int(new_playing_field_rect.x/30)
max_x = min_x + int(new_playing_field_rect.width/30) - 5
max_y = int(new_playing_field_rect.height/30)
step_y = int(max_y/5) or 1
step_x = 1
#It might seem confusing whats happeneing here but dw about it, just making sure blocks are spaced out
x_pos = list(range(min_x, max_x, step_x))
y_pos = list(range(0, max_y, step_y))
shuffle(x_pos)
self.pieces = [
Piece(x_pos, y_pos, choice(start_screen.piece_types)) for x_pos, y_pos in zip(x_pos, y_pos)
]
self.last_falls = [time.time() for _ in self.pieces]
running = True
while running:
#bkg color
mouse = pygame.mouse.get_pos()
#Makes sure that if game starts while were in this screen it goes back to game
running = start_screen.check_started()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.VIDEORESIZE or game.check_fullscreen(event):
try:
game.width, game.height = event.w, event.h
except:
pass
game.resize_all_screens()
left_arrow_pos = (offset, game.height/2 - dimensions/2)
right_arrow_pos = (game.width - dimensions - offset, game.height/2 - dimensions/2)
left_arrow_rect = left_arrow.get_rect(center = (left_arrow_pos[0] + dimensions/2, left_arrow_pos[1] + dimensions/2))
right_arrow_rect = right_arrow.get_rect(center = (right_arrow_pos[0] + dimensions/2, right_arrow_pos[1] + dimensions/2))
new_playing_field_rect = pygame.Rect(game.width/2 - game.playing_field_rect.width/2, game.playing_field_rect.y, game.playing_field_rect.width, game.playing_field_rect.height)
min_x = int(new_playing_field_rect.x/30)
max_x = min_x + int(new_playing_field_rect.width/30) - 5
max_y = int(new_playing_field_rect.height/30)
step_y = int(max_y/5) or 1
step_x = 1
x_pos = list(range(min_x, max_x, step_x))
y_pos = list(range(0, max_y, step_y))
shuffle(x_pos)
self.pieces = [
Piece(x_pos, y_pos, choice(start_screen.piece_types)) for x_pos, y_pos in zip(x_pos, y_pos)
]
self.last_falls = [time.time() for _ in self.pieces]
elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
if start_screen.back_button.collidepoint(event.pos):
store_theme()
running = False
elif left_arrow_rect.collidepoint(event.pos):
next_theme(0)
elif right_arrow_rect.collidepoint(event.pos):
next_theme(1)
render_game_preview(game.background_color, (r, g, b) if game.random_theme else game.foreground_color)
random_theme()
draw_title()
self.draw_back_button(mouse)
draw_arrows(mouse)
pygame.display.update()
game.check_random_theme()
def pick_controls_screen(self):
def draw_controls(controls, pos, color, keys_bkg_color = (0, 0, 0), value_bkg_color = self.background_color, underline = False, clicked_index = -1):
replace_keys = {
'left click': 'lmb',
'middle click': 'mmb',
'right click': 'rmb',
'up': '↑',
'down': '↓',
'right': '→',
'left': '←',
'left shift': 'lshft',
'right shift': 'rshft',
'caps lock': 'caps',
'return': 'entr',
'left ctrl': 'lctrl',
'right ctrl': 'rctrl',
'left meta': 'wn',
'right meta': 'wn',
'left alt': 'lalt',
'right alt': 'ralt',
'compose': 'cmp',
'space': 'spc',
'escape': 'esc',
'print screen': 'prnt',
'scroll lock': 'scrl',
'break': 'brk',
'insert': 'insrt',
'page up': 'pup',
'page down': 'pdwn',
'backspace': 'bksp',
}
text_rects = []
#pos 0 = left side, 1 = right side
for index, values in enumerate(controls):
description, key = values
modified_key = replace_keys[key].upper() if key in replace_keys.keys() else key.upper()
text_1 = game.big_font.render(modified_key, True, (0, 0, 0))
text_2 = game.medium_font.render(f" = {description}", True, color)
text_2_rect = text_2.get_rect()
text_2_rect.center = ((200 if pos == 0 else game.width - 150), (index * 50) + 450)
text_1_rect = text_1.get_rect()
text_1_rect.center = (text_2_rect.x - text_1_rect.width/2, text_2_rect.y + 10)
#Dw about mechanics of this, just know that This just toggles True/False every half a second
if underline and index == clicked_index and int(str(round(time.time(), 1))[-1:]) < 5:
pygame.draw.rect(game.screen, (255, 255, 255), pygame.Rect(text_1_rect.x, text_1_rect.y + 2, text_1_rect.width, text_1_rect.height + 2))
pygame.draw.rect(game.screen, value_bkg_color, text_1_rect)
pygame.draw.rect(game.screen, keys_bkg_color, text_2_rect)
game.screen.blit(text_1, (text_1_rect.x, text_1_rect.y))
game.screen.blit(text_2, (text_2_rect.x, text_2_rect.y))
text_rects.append(text_1_rect)
return text_rects
def get_keys_bkg_color(color: tuple):
darkened = tuple(darken(i, 30) for i in color)
r, g, b = darkened
if r <= 10 and g <= 10 and b <= 10:
return tuple(lighten(i, 30) for i in color)
return darkened
def key_exists_err():
text = game.big_font.render('KEY ALREADY IN USE', True, (255, 0, 0))
text_rect = text.get_rect(center = (game.width/2, game.height/2 - 100))
start_time = time.time()
while time.time() - start_time <= 0.5:
for event in pygame.event.get():
if event.type == pygame.VIDEORESIZE or game.check_fullscreen(event):
try:
game.width, game.height = event.w, event.h
except:
pass
game.resize_all_screens()
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
game.screen.blit(text, (text_rect.x, text_rect.y))
pygame.display.update()
def draw_reset_button(mouse):
inital_color = self.buttons_color
color = tuple(darken(i, 15) for i in inital_color) if reset_button.collidepoint(mouse) else inital_color
pygame.draw.rect(game.screen, color, reset_button)
game.screen.blit(reset_text, (game.width/2 - 50 + 20, game.height - 45 + 12))
def reset_controls():
with open(get_path('settings.json')) as f:
full_dict = json.load(f)
full_dict['controls'] = game.default_controls
with open(get_path('settings.json'), 'w') as f:
json.dump(full_dict, f, indent=2)
game.left_controls = {
"Move Left": game.default_controls["Move Left"],
"Move Right": game.default_controls["Move Right"],
"Soft Drop": game.default_controls["Soft Drop"],
"Toggle Movement": game.default_controls["Toggle Movement"],
"Toggle Music": game.default_controls["Toggle Music"]
}
game.right_controls = {
"Rotate Clockwise": game.default_controls["Rotate Clockwise"],
"Rotate Counter-Clockwise": game.default_controls["Rotate Counter-Clockwise"],
"Hold Piece": game.default_controls["Hold Piece"],
"Hard Drop": game.default_controls["Hard Drop"],
"Toggle Fullscreen": game.default_controls["Toggle Fullscreen"],
"Pause": game.default_controls["Pause"]
}
game.fullscreen_key = full_dict["controls"]["Toggle Fullscreen"]
def draw_title():
game.screen.blit(title_text_1, (game.width/2 - 140, 100))
game.screen.blit(title_text_2, (game.width/2 - 200, 160))
def draw_prompt():
if clicked:
color = self.buttons_color if int(str(round(time.time(), 1))[-1:]) < 5 else game.background_color
prompt_text = game.big_font.render('PRESS A KEY', True, color)
game.screen.blit(prompt_text, (game.width/2 - 100, 300))
mouse_number_key = {
1: 'left click',
2: 'middle click',
3: 'right click'
}
def get_key_input(key, mouse_clicked = False):
if not mouse_clicked:
key = pygame.key.name(key)
else:
key = mouse_number_key[key]
keys = list(list(game.left_controls.values()) + list(game.right_controls.values()))
if clicked_index_1 >= 0:
if key not in keys:
game.left_controls[list(game.left_controls.keys())[clicked_index_1]] = key
else:
key_exists_err()
elif clicked_index_2 >= 0:
if key not in keys:
game.right_controls[list(game.right_controls.keys())[clicked_index_2]] = key
else:
key_exists_err()
with open(get_path('settings.json')) as f:
full_dict = json.load(f)
full_controls = dict(game.left_controls, **game.right_controls)
full_dict['controls'] = full_controls
with open(get_path('settings.json'), 'w') as f:
json.dump(full_dict, f, indent=2)
game.fullscreen_key = full_dict["controls"]["Toggle Fullscreen"]
title_text_1 = game.big_font.render('CLICK ON A BOX TO', True, (255, 255, 255))
title_text_2 = game.big_font.render('CHANGE YOUR CONTROLS', True, (255, 255, 255))
reset_text = game.medium_font.render('RESET', True, (0, 0, 0))
text_boxes_1 = []
text_boxes_2 = []
clicked = False
clicked_index_1 = -1
clicked_index_2 = -1
reset_button = pygame.Rect(game.width/2 - 50, game.height - 35, 100, 27)
running = True
while running:
#bkg color
game.screen.fill(game.background_color)
mouse = pygame.mouse.get_pos()
#Makes sure that if game starts while were in this screen it goes back to game
running = start_screen.check_started()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.VIDEORESIZE or game.check_fullscreen(event):
try:
game.width, game.height = event.w, event.h
except:
pass
game.resize_all_screens()
elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
if clicked:
if 1 <= event.button <= 3:
get_key_input(event.button, mouse_clicked=True)
clicked = False
elif event.button == 1:
if start_screen.back_button.collidepoint(event.pos):
running = False
elif reset_button.collidepoint(event.pos):
reset_controls()
else:
for index, text_box in enumerate(text_boxes_1):
if text_box.collidepoint(event.pos):
clicked = True
clicked_index_2 = -1
clicked_index_1 = index
for index, text_box in enumerate(text_boxes_2):
if text_box.collidepoint(event.pos):
clicked = True
clicked_index_1 = -1
clicked_index_2 = index
elif event.type == pygame.KEYDOWN:
if clicked:
get_key_input(event.key)
clicked = False
reset_button = pygame.Rect(game.width/2 - 50, game.height - 35, 100, 27)
self.draw_back_button(mouse)
draw_reset_button(mouse)
draw_title()
draw_prompt()
keys_bkg_color = get_keys_bkg_color(game.background_color)
text_boxes_1 = draw_controls(game.left_controls.items(), 0, (255, 255, 255), keys_bkg_color = keys_bkg_color, value_bkg_color = self.buttons_color, underline = clicked, clicked_index = clicked_index_1)
text_boxes_2 = draw_controls(game.right_controls.items(), 1, (255, 255, 255), keys_bkg_color = keys_bkg_color, value_bkg_color = self.buttons_color, underline = clicked, clicked_index = clicked_index_2)
pygame.display.update()
def draw_buttons(self):
for button, text, color, _ in self.buttons:
pygame.draw.rect(game.screen, color, button)
text_rect = text.get_rect(center = (button.x + button.width/2, button.y +button.height/2))
game.screen.blit(text, text_rect)
def buttons_hover(self, mouse):
for index, button in enumerate(self.buttons):
if button[0].collidepoint(mouse):
#2 is the color index
self.buttons[index][2] = tuple(darken(i, 20) for i in self.buttons_color)
else:
self.buttons[index][2] = self.buttons_color
def main(self):
running = True
while running:
#bkg color
game.screen.fill(game.background_color)
mouse = pygame.mouse.get_pos()
#Makes sure that if game starts while were in this screen it goes back to game
running = start_screen.check_started()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.VIDEORESIZE or game.check_fullscreen(event):
try:
game.width, game.height = event.w, event.h
except:
pass
game.resize_all_screens()
elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
for button, _, _, func in self.buttons:
if button.collidepoint(event.pos):
func()
if start_screen.back_button.collidepoint(event.pos):
running = False
self.buttons_hover(mouse)
self.draw_back_button(mouse)
self.draw_buttons()
pygame.display.update()
game.clock.tick(60)
class Block(Game):
def __init__(self, x, y, color, colorByName = True):
self.x, self.y = x, y
if colorByName:
self.color = color_key[color]
else:
self.color = color
self.size = 30
self.flash_start = 0
self.direction = 0
self.fade_start = 0
def render(self, offset = True):
x_offset_val = game.playing_field_rect.x if offset else 100
y_offset_val = game.playing_field_rect.y
# normal
if time.time() > self.flash_start + 0.2 and not self.fade_start:
darker = tuple(darken(i) for i in self.color)
block_rect = pygame.Rect((self.x-1) * self.size + x_offset_val, (self.y-1)* self.size + y_offset_val, self.size, self.size)
pygame.draw.rect(game.screen, self.color, block_rect)
game.draw_block_borders(block_rect, darker)
# flashing
elif time.time() <= self.flash_start + 0.2:
flash_time = self.flash_start + 0.2 - time.time()
flash_color = []
# whether it flashes dark or light
direction = self.direction
# orange, blue, purple flashes light
if flash_time >= 0.1:
direction *= -1
for color in self.color:
color = color + (flash_time * 270 * direction)
if color > 255: color = 255
elif color < 0: color = 0
flash_color.append(color)
flash_color = tuple(flash_color)
darker = tuple(darken(i) for i in flash_color)
block_rect = pygame.Rect((self.x-1) * self.size + game.playing_field_rect.x, (self.y-1)* self.size + y_offset_val, 30, 30)
game.draw_block_borders(block_rect, darker)
pygame.draw.rect(game.screen, flash_color, block_rect)
pygame.draw.rect(game.screen, flash_color, ((self.x-1) * self.size + game.playing_field_rect.x + 5, (self.y-1)* self.size + y_offset_val + 5, 20, 20))
# fading
else:
fade_time = self.fade_start + 0.5 - time.time()
if fade_time > 0:
color_difference = [255 - color for color in self.color]
fade_color = []
for x in range(3):
fade_color.append((color_difference[x] / 0.5 * (0.5 - fade_time)) + self.color[x])
fade_color = tuple(fade_color)
else:
fade_color = (255, 255, 255)
darker = tuple(darken(i) for i in fade_color)
block_rect = pygame.Rect((self.x-1) * self.size + game.playing_field_rect.x, (self.y-1)* self.size + y_offset_val, 30, 30)
game.draw_block_borders(block_rect, darker)
pygame.draw.rect(game.screen, fade_color, ((self.x-1) * self.size + game.playing_field_rect.x + 5, (self.y-1)* self.size + y_offset_val + 5, 20, 20))
# for putting blocks on second screen
def render_second(self):
darker = tuple(darken(i) for i in self.color)
block_rect = pygame.Rect((self.x-1) * self.size/2 + 570 + game.block_x_offset, (self.y-1)* self.size/2 + game.second_block_y_offset, 15, 15)
pygame.draw.rect(game.screen, self.color, block_rect)
game.draw_block_borders(block_rect, darker, block_size_difference = 2)
def render_preview(self):
pygame.draw.rect(game.screen, game.preview_color, ((self.x-1) * self.size + game.playing_field_rect.x, (self.y-1)* self.size + game.playing_field_rect.y, 30, 30))
pygame.draw.rect(game.screen, game.foreground_color, ((self.x-1) * self.size + game.playing_field_rect.x + 3, (self.y-1)* self.size + game.playing_field_rect.y + 3, 24, 24))
class Piece(Game):
def __init__(self, x, y, piece):
self.x, self.y = x, y
self.piece_type = piece
self.blocks = list(map(lambda args: Block(*args), pieces_lib.get_piece(x, y, piece)))
self.rotation = "0"
if piece == "T":
self.corners = {"point left": [x-1, y-1], "point right": [x+1, y-1], "flat left": [x-1, y+1], "flat right": [x+1, y+1]}
elif piece == "I":
self.x += 0.5
self.y += 0.5
def move(self, x, y):
self.x += x
self.y += y
for block in self.blocks:
block.x += x
block.y += y
if self.piece_type == "T":
for coords in self.corners.values():
coords[0] += x
coords[1] += y
def flash(self):
if self.piece_type in ("L", "J", "T"):
direction = -1
else:
direction = 1
for block in self.blocks:
block.direction = direction
block.flash_start = time.time()
def _set_rotation_value(self, direct):
if direct == 0:
if self.rotation == "0":
self.rotation = "R"
elif self.rotation == "R":
self.rotation = "2"
elif self.rotation == '2':
self.rotation = 'L'
elif self.rotation == 'L':
self.rotation = '0'
else:
if self.rotation == "0":
self.rotation = "L"
elif self.rotation == "L":
self.rotation = "2"
elif self.rotation == '2':
self.rotation = 'R'
elif self.rotation == 'R':
self.rotation = '0'
def _path_check(self, direct, x, y, play_sound = True):
# invert y direction
y *= -1
self.move(x, y)
if not self.check_overlap():
if play_sound:
game.play_sound('correct rotate')
return True
# reset
self.move(-1*x, -1*y)
return False
#0 means clockwise, 1 means counterclockwise
def rotate(self, direct: int, play_sound = True):
if self.piece_type == "O": return game.play_sound('correct rotate') if play_sound else None
org_block_coords = []
x, y = self.x, self.y # noqa pylint: disable=unused-variable
if direct == 0:
#clockwise
for block in self.blocks:
#Math formula
temp_x, temp_y = block.x, block.y
org_block_coords.append((temp_x, temp_y))
block.x = (-1*(temp_y-self.y) + self.x)
block.y = ((temp_x - self.x) + self.y)
if self.piece_type == "T":
org_corner_coords = []
for coords in self.corners.values():
temp_x, temp_y = coords
org_corner_coords.append([temp_x, temp_y])
coords[0] = (-1*(temp_y-self.y) + self.x)
coords[1] = ((temp_x - self.x) + self.y)
else:
#counter-clockwise
for block in self.blocks:
#Math formula
temp_x, temp_y = block.x, block.y
org_block_coords.append((temp_x, temp_y))
block.x = (temp_y - self.y + self.x)
block.y = (-1*(temp_x - self.x) + self.y)
if self.piece_type == "T":
org_corner_coords = []
for coords in self.corners.values():
temp_x, temp_y = coords
org_corner_coords.append([temp_x, temp_y])
coords[0] = (temp_y - self.y + self.x)
coords[1] = (-1*(temp_x - self.x) + self.y)
old_rotation = self.rotation
self._set_rotation_value(direct)
if self.check_overlap():
# all following SRS Tetris guideline
if self.piece_type == "I":
# clockwise
if direct == 0:
# 0 -> R
if old_rotation == "0":
if self._path_check(direct, -2, 0, play_sound): return
if self._path_check(direct, 1, 0, play_sound): return
if self._path_check(direct, -2, -1, play_sound): return
if self._path_check(direct, 1, 2, play_sound): return
# R -> 2
elif old_rotation == 'R':
if self._path_check(direct, -1, 0, play_sound): return
if self._path_check(direct, 2, 0, play_sound): return
if self._path_check(direct, -1, 2, play_sound): return
if self._path_check(direct, 2, -1, play_sound): return
# 2 -> L
elif old_rotation == '2':
if self._path_check(direct, 2, 0, play_sound): return
if self._path_check(direct, -1, 0, play_sound): return
if self._path_check(direct, 2, 1, play_sound): return
if self._path_check(direct, -1, -2, play_sound): return
# L -> 0
elif old_rotation == "L":
if self._path_check(direct, 1, 0, play_sound): return
if self._path_check(direct, -2, 0, play_sound): return
if self._path_check(direct, 1, -2, play_sound): return
if self._path_check(direct, -2, 1, play_sound): return
# counterclockwise
else:
# R -> 0
if old_rotation == "R":
if self._path_check(direct, 2, 0, play_sound): return
if self._path_check(direct, -1, 0, play_sound): return
if self._path_check(direct, 2, 1, play_sound): return
if self._path_check(direct, -1, -2, play_sound): return
# 2 -> R
elif old_rotation == "2":
if self._path_check(direct, 1, 0, play_sound): return
if self._path_check(direct, -2, 0, play_sound): return
if self._path_check(direct, 1, -2, play_sound): return
if self._path_check(direct, -2, 1, play_sound): return
# L -> 2
elif old_rotation == "L":
if self._path_check(direct, -2, 0, play_sound): return
if self._path_check(direct, 1, 0, play_sound): return
if self._path_check(direct, -2, -1, play_sound): return
if self._path_check(direct, 1, 2, play_sound): return
# 0 -> L
elif old_rotation == "0":
if self._path_check(direct, -1, 0, play_sound): return
if self._path_check(direct, 2, 0, play_sound): return
if self._path_check(direct, -1, 2, play_sound): return
if self._path_check(direct, 2, -1, play_sound): return
else:
# clockwise
if direct == 0:
# 0 -> R
if old_rotation == "0":
if self._path_check(direct, -1, 0, play_sound): return
if self._path_check(direct, -1, 1, play_sound): return
if self._path_check(direct, 0, -2, play_sound): return
if self._path_check(direct, -1, -2, play_sound): return
# R -> 2
elif old_rotation == 'R':
if self._path_check(direct, 1, 0, play_sound): return
if self._path_check(direct, 1, -1, play_sound): return
if self._path_check(direct, 0, 2, play_sound): return
if self._path_check(direct, 1, 2, play_sound): return
# 2 -> L
elif old_rotation == '2':
if self._path_check(direct, 1, 0, play_sound): return
if self._path_check(direct, 1, 1, play_sound): return
if self._path_check(direct, 0, -2, play_sound): return
if self._path_check(direct, 1, -2, play_sound): return
# L -> 0
elif old_rotation == "L":
if self._path_check(direct, -1, 0, play_sound): return
if self._path_check(direct, -1, -1, play_sound): return
if self._path_check(direct, 0, 2, play_sound): return
if self._path_check(direct, -1, 2, play_sound): return
# counterclockwise
else:
# R -> 0
if old_rotation == "R":
if self._path_check(direct, 1, 0, play_sound): return
if self._path_check(direct, 1, -1, play_sound): return
if self._path_check(direct, 0, 2, play_sound): return
if self._path_check(direct, 1, 2, play_sound): return
# 2 -> R
elif old_rotation == "2":
if self._path_check(direct, -1, 0, play_sound): return
if self._path_check(direct, -1, 1, play_sound): return
if self._path_check(direct, 0, -2, play_sound): return
if self._path_check(direct, -1, -2, play_sound): return
# L -> 2
elif old_rotation == "L":
if self._path_check(direct, -1, 0, play_sound): return
if self._path_check(direct, -1, -1, play_sound): return
if self._path_check(direct, 0, 2, play_sound): return
if self._path_check(direct, -1, 2, play_sound): return
# 0 -> L
elif old_rotation == "0":
if self._path_check(direct, 1, 0, play_sound): return
if self._path_check(direct, 1, 1, play_sound): return
if self._path_check(direct, 0, -2, play_sound): return
if self._path_check(direct, 1, -2, play_sound): return
# if all tests fail
self.rotation = old_rotation
# reset
for index, block in enumerate(self.blocks):
block.x, block.y = org_block_coords[index]
if self.piece_type == "T":
for index, coords in enumerate(self.corners.values()):
coords = org_corner_coords[index] #type: ignore
elif play_sound:
game.play_sound('correct rotate')
"""
First move piece in bounds if it is out of bounds.
If there is any overlapping conflict, then do the following:
Check if the piece is ok if it moves two blocks up, if not,
Check if it can move right by two blocks if clockwise, or left if counterclockwise,
if not,
check the other direction.
If all of these fail, then the rotation will not occur.
"""
def check_overlap(self):
for block in self.blocks:
if block.y > 20 or block.x < 1 or block.x > 10:
return True
for resting in game.resting:
if block.x == resting.x and block.y == resting.y:
return True
return False
def overlapping_blocks(self):
for block in self.blocks:
for resting in game.resting:
if (block.x == resting.x and block.y == resting.y):
return True
return False
def check_floor(self):
for block in self.blocks:
# if hits floor
if block.y > 20:
return True
# if hits another block
for resting_block in game.resting:
if resting_block.x == block.x and resting_block.y == block.y:
return True
return False
def check_right(self):
for block in self.blocks:
# if hits wall
if block.x > 9:
return True
# if hits another block
for resting_block in game.resting:
if resting_block.x == block.x+1 and resting_block.y == block.y:
return True
return False
def check_left(self):
for block in self.blocks:
# if hits wall
if block.x < 2:
return True
# if hits another block
for resting_block in game.resting:
if resting_block.x == block.x-1 and resting_block.y == block.y:
return True
return False
def render(self, preview = True):
# to render preview
if preview:
downCount = 0
while not self.check_floor():
self.move(0, 1)
downCount += 1
self.move(0, -1)
for block in self.blocks:
block.render_preview()
for _ in range(downCount):
self.move(0, -1)
self.move(0, 1)
# for actual piece
for block in self.blocks:
block.render(preview)
start_screen = StartScreen()
settings_screen = SettingsScreen() |
from examples.rps.rpsbot import RPSRobot
from examples.rps.robotteam import RobotTeam
import hackathon
beat = {"R": "P", "P": "S", "S": "R"}
rbeat = {"P": "R", "S": "P", "R": "S"}
class RPSGame(hackathon.Game):
def __init__(self, robots: list, *args, **kwargs):
super().__init__(robots, *args, **kwargs)
self.env.globals["RobotTeam"] = RobotTeam
self.playera = RPSRobot(self, robots[0], RobotTeam.FIRST)
self.playerb = RPSRobot(self, robots[1], RobotTeam.SECOND)
self.playera.init_code()
self.playerb.init_code()
self.actions = []
self.score = {RobotTeam.FIRST: 0, RobotTeam.SECOND: 0}
def run(self, *args, rounds=1000, **kwargs):
while len(self.actions) < rounds:
self.playera.run()
self.playerb.run()
actiona = self.playera.globals.get("output", "R")
actionb = self.playerb.globals.get("output", "R")
self.actions.append({RobotTeam.FIRST: actiona, RobotTeam.SECOND: actionb})
if actiona == beat[actionb]: # A won
self.score[RobotTeam.FIRST] += 1
if beat[actiona] == actionb: # B won
self.score[RobotTeam.SECOND] += 1
return self.score
|
#!/usr/bin/python
#Control dynamixel with key input (position control).
#NOTE: Run before this script: rosrun ay_util fix_usb_latency.sh
#NOTE: Run before this script: ../fix_usb_latency.sh
'''
Keyboard interface:
'q': Quit.
'd','a','w','s': Right turn, left turn, up, down.
'C','B': Move to Center (of rotation), Base (height).
'''
from dxl_util import *
from _config import *
import time
from kbhit2 import TKBHit
import threading
import sys
#Setup the device
dxl= [TDynamixel1(DXL_TYPE[i]) for i,_ in enumerate(DXL_ID)]
for i,_ in enumerate(DXL_ID):
dxl[i].Id= DXL_ID[i]
dxl[i].Baudrate= BAUDRATE
dxl[i].OpMode= OP_MODE
dxl[i].CurrentLimit= CURRENT_LIMIT
dxl[i].Setup()
dxl[i].EnableTorque()
#Move to the current position
p_start= [dxl[i].Position() for i,_ in enumerate(DXL_ID)]
for i,_ in enumerate(DXL_ID):
dxl[i].MoveTo(p_start[i])
time.sleep(0.5) #wait .5 sec
print 'Current position=',[dxl[i].Position() for i,_ in enumerate(DXL_ID)]
def ReadKeyboard(is_running, key_cmd, key_locker):
kbhit= TKBHit()
dt_hold= 0.1
t_prev= 0
while is_running[0]:
c= kbhit.KBHit()
if c is not None or time.time()-t_prev>dt_hold:
with key_locker:
key_cmd[0]= c
t_prev= time.time()
time.sleep(0.0025)
key_cmd= [None]
key_locker= threading.RLock()
is_running= [True]
t1= threading.Thread(name='t1', target=lambda a1=is_running,a2=key_cmd,a3=key_locker: ReadKeyboard(a1,a2,a3))
t1.start()
trg= [dxl[i].Position() for i,_ in enumerate(DXL_ID)] #Current position
while True:
with key_locker:
c= key_cmd[0]; key_cmd[0]= None
mov= [0.0]
d= [20000, 80000]
if c is not None:
if c=='q': break
elif c in ('z','x','c','v'): mov[0]= {'z':-d[1],'x':-d[0],'c':d[0],'v':d[1]}[c]
#elif c in ('C',):
#trg= [P0_CENTER, dxl[1].Position()]
#dxl[0].MoveTo(P0_CENTER, blocking=False)
#elif c in ('B',):
#trg= [dxl[0].Position(), P1_BOTTOM]
#dxl[1].MoveTo(P1_BOTTOM, blocking=False)
elif c=='r':
for i,_ in enumerate(DXL_ID):
dxl[i].Reboot();
time.sleep(0.1);
dxl[i].EnableTorque()
dxl[i].MoveTo(int(trg[i]), blocking=False)
if mov[0]!=0.0:
trg[0]= dxl[0].Position()+mov[0]
print c,mov,trg
dxl[0].MoveTo(int(trg[0]), blocking=False)
#time.sleep(0.002)
else:
#time.sleep(0.0025)
pass
#time.sleep(0.002)
print 'Pos: {0} \t Vel: {1} \t Curr: {2} \t PWM: {3}'.format(
[dxl[i].Position() for i,_ in enumerate(DXL_ID)],
[dxl[i].Velocity() for i,_ in enumerate(DXL_ID)],
[dxl[i].Current() for i,_ in enumerate(DXL_ID)],
[dxl[i].PWM() for i,_ in enumerate(DXL_ID)])
#print 'Positions:',[dxl[i].Position() for i,_ in enumerate(DXL_ID)]
is_running[0]= False
t1.join()
for i,_ in enumerate(DXL_ID):
dxl[i].PrintStatus()
dxl[i].PrintHardwareErrSt()
#dxl[i].DisableTorque()
dxl[i].Quit()
|
'''
Normalized robustness discussion
'''
import warnings
warnings.simplefilter("ignore", UserWarning)
# Import base python modules
import numpy as np
from matplotlib import pyplot as plt
from scipy.optimize import minimize
import scipy.optimize
import os
import sys
import pdb
# Add my local path to the relevant modules list
path = os.getcwd()
rootpath = path.split('Daniel Newman')
rootpath = rootpath[0] + 'Daniel Newman/Python Modules'
sys.path.append(rootpath)
# Import my python scripts
import InputShaping as shaping
import Boom_Crane as BC
import Generate_Plots as genplt
# Use lab plot style
plt.style.use('Crawlab')
# define constants
DEG_TO_RAD = np.pi / 180
G = 9.81 # m / s**2
# t vector characteristics
tmax = 5
t_step = .0001
t = np.arange(0, tmax, t_step)
Startt = 0.
Startt_step = np.round(Startt/t_step).astype(int)
# Geometry of the system
mass = 10 # Mass of the payload in kg
r = 0.81 # length of the boom in meters
# Given normalized initial condition values
normalized_amp = 0.7
phase = np.arange(160,200,1)
phase = np.multiply(phase,DEG_TO_RAD)
# Initial angular conditions
gamma_init = 40. # Luff angle
gamma_dot_init = 0.
phi_init = 0. #-0.0859 / DEG_TO_RAD # Radial swing angle
phi_dot_init = 0. #-0.0147 / DEG_TO_RAD
l_init = .50
l_dot_init = 0.
U0 = np.array([phi_init,phi_dot_init,gamma_init, gamma_dot_init, 0,0])
U0 *= DEG_TO_RAD
U0[-2] = l_init
U0[-1] = l_dot_init
# Actuator constraints
Amax = 174. * 10 # deg / s^2
Vmax = 17.4*2 # deg / s
# C = array of actuator constraints
C = np.array([Amax, Vmax])
C *= DEG_TO_RAD
# Desired final angles
gamma_fin = tmax * Vmax * 2.5
theta_fin = 0.
# Determine the distance to travel
Distance = gamma_fin - gamma_init
Distance *= DEG_TO_RAD
# Approximate natural frequency
#omega = np.sqrt((G - r * C[1]**2 * np.sin(U0[2]))/ l_init)
omega = np.sqrt(G/l_init)
print('Natural Frequency: {}'.format(omega))
# Pack the relevant values based on the initial condition
p = [C, l_init, r, Startt, U0[2],U0[2], t_step,t,U0,Distance]
# Find the amplitude of an unshaped response to a step input given the initial conditions
unshaped_response = BC.response(p,'Unshaped Accel')
t_peak = np.pi / (omega)
t_peak_step = np.round(t_peak/t_step).astype(int)
# Determine the unshaped amplitude
#unshaped_amp = omega * np.sqrt(unshaped_response[t_peak_step,0]**2 + (unshaped_response[t_peak_step,1]/omega)**2)
unshaped_amp = omega * np.sqrt((unshaped_response[t_peak_step,1]/omega)**2)
#t_min = t_peak + np.pi / omega
#t_min_step = np.round(t_min/t_step).astype(int)
#test_amp =
# Determine the null response amplitude from the given normalized condition
null_amp = normalized_amp * unshaped_amp
'''
unshaped_amp = np.zeros_like(phase)
# Iterate through the range of errors for the phase
for i in np.arange(0,len(phase)):
time = phase[i] / omega
# determine the initial conditions
phi_init = null_amp * np.sin(time*omega) / omega
phi_dot_init = null_amp * np.cos(time*omega)
X0 = np.array([0,0,gamma_init, gamma_dot_init, 0,0])
X0 *= DEG_TO_RAD
X0[0] = phi_init
X0[1] = phi_dot_init
X0[-2] = l_init
X0[-1] = l_dot_init
#print(X0)
#print(omega * np.sqrt(phi_init**2 + (phi_dot_init/omega)**2))
p = [C, l_init, r, Startt, X0[2],X0[2], t_step,t,X0,Distance]
# Find the amplitude of an unshaped response to a step input given the initial conditions
unshaped_amp[i] = BC.response(p,'Unshaped Accel',return_response=False)
'''
#print(np.argmin(unshaped_amp))
# Determine the folder for the plots
folder = 'Figures/{}/Boom_{}_Cable_{}/luff_{}/amp_{}'.format(sys.argv[0],r,l_init,gamma_init,normalized_amp)
zeta = 0.0
# Initial guess for shaper 1
X = np.array([0.9,168*DEG_TO_RAD,0.0])
null_amp = lambda X: X[0] * unshaped_amp
def amplitude(X):
if not isinstance(X,scipy.optimize.OptimizeResult):
print(X.dtype)
#if not isinstance(X,scipy.optimize.minimize)
print(np.arctan2((np.sqrt(1 - zeta**2) * X[0] * unshaped_amp * np.sin(X[1]) / omega),
X[0] * unshaped_amp * np.cos(X[1])/(omega)
+ zeta * X[0] * unshaped_amp * np.sin(X[1]) / omega) )
null_amp = X[0] * unshaped_amp
time = X[1] / omega
# determine the initial conditions
phi_init = null_amp * np.sin(time*omega) / omega
phi_dot_init = null_amp * np.cos(time*omega)
X0 = np.array([0,0,gamma_init, gamma_dot_init, 0,0])
X0 *= DEG_TO_RAD
X0[0] = phi_init
X0[1] = phi_dot_init
X0[-2] = l_init
X0[-1] = l_dot_init
p = [C, l_init, r, Startt,gamma_init*DEG_TO_RAD,gamma_init*DEG_TO_RAD, t_step,t,X0,Distance]
Amp = BC.response(p,'Unshaped Accel',return_response=False,ic_phase_error=X[2])
print(Amp)
else:
Amp = X
return Amp
def P(X):
X0 = np.array([X[0] * unshaped_amp * np.sin(X[1]) / omega,X[0] * unshaped_amp * np.cos(X[1]),gamma_init*DEG_TO_RAD, gamma_dot_init*DEG_TO_RAD, l_init,0])
#p = [C, l_init, r, Startt,gamma_init*DEG_TO_RAD,gamma_init*DEG_TO_RAD, t_step,t,X0,Distance]
return X0
#P = lambda X: [C, l_init, r, Startt,gamma_init*DEG_TO_RAD,gamma_init*DEG_TO_RAD, t_step,t,np.array([X[0] * unshaped_amp * np.sin(X[1]) / omega,X[0] * unshaped_amp * np.cos(X[1]),gamma_init*DEG_TO_RAD, gamma_dot_init*DEG_TO_RAD, l_init,0]),Distance]
unshaped_response = amplitude(X)
# Constraints, bounds and function for solving the minimization problem
cons = ({'type': 'eq', 'fun': lambda X: normalized_amp - X[0] * unshaped_amp},
{'type': 'eq', 'fun': lambda X: np.arctan2((np.sqrt(1 - zeta**2) * X[0] * unshaped_amp * np.sin(X[1]) / omega),
X[0] * unshaped_amp * np.cos(X[1])/(omega)
+ zeta * X[0] * unshaped_amp * np.sin(X[1]) / omega)
- X[1]})
bounds = np.array([tuple((0,1.5)),tuple((0,2*np.pi)),tuple((-0.2,.2))])
#fun = amplitude(X)
#fun = lambda X: BC.response([C, l_init, r, Startt,gamma_init*DEG_TO_RAD,gamma_init*DEG_TO_RAD, t_step,t,P(X),Distance],'Unshaped Accel',return_response=False)
#pdb.set_trace()
# Solve for the first shaper times
#phase = minimize(amplitude,X,method='SLSQP',bounds=bounds)#,options={'maxiter':20000,'eps':.5,'ftol':1e-06})
'''
# Plot the data
genplt.compare_responses(
phase,
unshaped_amp,'Shifted Phase',
xlabel='Phase (rad)',ylabel='Phase minimum shift (rad)',
folder=folder,name_append='Response Check',grid=False
)
'''
#time = phase[20] / omega
'''
# determine the initial conditions
phi_init = null_amp * np.sin(time*omega) / omega
phi_dot_init = null_amp * np.cos(time*omega)
X0 = np.array([0,0,gamma_init, gamma_dot_init, 0,0])
X0 *= DEG_TO_RAD
X0[0] = phi_init
X0[1] = phi_dot_init
X0[-2] = l_init
X0[-1] = l_dot_init
p = [C, l_init, r, Startt, X0[2],X0[2], t_step,t,X0,Distance]
genplt.compare_responses(
t,
unshaped_response[:,0],'response',
xlabel='Phase (rad)',ylabel='Phase minimum shift (rad)',
folder=folder,name_append='Response',grid=False
)
genplt.compare_responses(
t,
unshaped_response[:,3],'Velocity',
xlabel='Phase (rad)',ylabel='Phase minimum shift (rad)',
folder=folder,name_append='Velocity',grid=False
)
'''
########################################################################################################
########################################################################################################
X = np.array([0.])
def amplitude(X,gamma_init):
#print(gamma_init)
omega = np.sqrt(G/l_init)
phase = np.pi + X[0]
#print(X)
#if not isinstance(X,scipy.optimize.minimize)
#print(np.arctan2((np.sqrt(1 - zeta**2) * unshaped_amp * np.sin(phase) / omega),
# unshaped_amp * np.cos(phase)/(omega)
# + zeta * unshaped_amp * np.sin(phase) / omega) )
null_amp = unshaped_amp
time = phase / omega
# determine the initial conditions
phi_init = null_amp * np.sin(time*omega) / omega
phi_dot_init = null_amp * np.cos(time*omega)
X0 = np.array([0,0,gamma_init, gamma_dot_init, 0,0])
X0 *= DEG_TO_RAD
X0[0] = phi_init
X0[1] = phi_dot_init
X0[-2] = l_init
X0[-1] = l_dot_init
p = [C, l_init, r, Startt,gamma_init*DEG_TO_RAD,gamma_init*DEG_TO_RAD, t_step,t,X0,Distance]
Amp = BC.response(p,'Unshaped Accel',return_response=False)
#print(Amp)
return Amp
#unshaped_response = amplitude(X)
# Constraints, bounds and function for solving the minimization problem
bounds = np.array([tuple((-1.2,1.2))])
# Solve for the first shaper times
initial_angle = np.arange(1,90,1)
phase_error = np.arange(-0.2,0.2,0.01)
phase_min = np.zeros([len(initial_angle)])
for i in np.arange(0,len(initial_angle)):
#phase = minimize(amplitude,X,args=(initial_angle[i]),bounds=bounds,options={'maxiter':20000,'ftol':1e-08})
last_amp = 1.0
this_amp = 0.0
index=5
for j in np.arange(0,len(phase_error)):
this_amp = amplitude(np.array([phase_error[j]]),initial_angle[i])
if this_amp < last_amp:
last_amp = this_amp
phase_min[i] = phase_error[j]
#print(phase_min[i])
else:
break
#print('Value Written: {}'.format(phase_min[i]))
genplt.compare_responses(initial_angle,phase_min,'Minimum Phase Lower Vel and Accel')
print(phase) |
import warnings, datetime
from surveymonkey.exceptions import SurveyMonkeyWarning
class Call(object):
""" Base class for all API calls """
_api = None
date_params = (
'start_date', 'end_date', 'start_modified_date', 'end_modified_date'
)
@property
def call_name(self):
return self.__class__.__name__.lower()
def __init__(self, api):
self._api = api
def _update_params(self, params, extra_kwargs):
control_kwargs = {}
for key in ('access_token', 'timeout'):
if key in extra_kwargs:
control_kwargs[key] = extra_kwargs.pop(key)
params.update(extra_kwargs)
return control_kwargs
def make_call(self, func, params, extra_kwargs):
if hasattr(func, '__name__'):
uri = '/%s/%s' % (self.call_name, func.__name__[2:])
else:
uri = '/%s' % self.call_name
control_kwargs = self._update_params(params, extra_kwargs)
if not self._api.silent:
unrecognized_params = set(params) - set(func.allowed_params)
if unrecognized_params:
err_msg = (
"At least one of the parameters to the api call: '%s' is "
"unrecognized. Allowed parameters are: '%s'. Unrecognized "
"parameters are: '%s'." % (uri, ', '.join(func.allowed_params),
', '.join(unrecognized_params)))
warnings.warn(err_msg, SurveyMonkeyWarning)
for name in self.date_params:
value = params.get(name)
if value is not None and isinstance(datetime.date):
params[name] = value.strftime("%Y-%m-%d %H:%M:%S")
return self._api.call(uri, params=params, **control_kwargs)
|
#############################################################################
# REVERSE CLASSIFICATION ACCURACY IMPLEMENTATION - 2018 #
# Rob Robinson (r.robinson16@imperial.ac.uk) #
# - Includes RCA.py and RCAfunctions.py #
# #
# Original RCA paper by V. Valindria https://arxiv.org/abs/1702.03407 #
# This implementation written by R. Robinson https://goo.gl/NBmr9G #
#############################################################################
import os
import sys
import subprocess
import shutil
import numpy as np
from scipy import io as scio
import nibabel as nib
from RCAfunctions import registration, getMetrics
import SimpleITK as sitk
import time
import argparse
import scipy.io
G = '\033[32m'
W = '\033[0m'
R = '\033[31m'
############################################################################################################################
######################################### PARSE ARGUMENTS ##################################################################
prog_help = "Script must be given (--refs, --subject, --config, --output\n"\
"--refs = directory where reference images are listed (pre-prepared)\n"\
"--subject = directory containing the image, segmentation and landmarks to be tested\n"\
"--subjects = .txt file containing one subject-folder path per line\n"\
"--config = .cfg filename e.g. 'config.cfg'\n"\
"--GT = the filename of the GT segmentation (optional)\n"\
"--seg = the filename of the test segmentation (optional)\n"\
"--output = root folder to output the files (option - default to pwd)\n"
parser = argparse.ArgumentParser(description='Perform RCA on [subject] using a set of [reference images]')
parser.add_argument('--refs', type=str, default='/vol/biomedic/users/rdr16/RCA2017/registeredCropped')
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('--subject', type=str)
group.add_argument('--subjects', type=str)
parser.add_argument('--config', type=str, default='5kBIOBANK')
parser.add_argument('--output', type=str)
parser.add_argument('--GT', type=str, default=False)
parser.add_argument('--seg', type=str, default=False)
parser.add_argument('--prep', type=str, default=False)
args = parser.parse_args()
##### OUTPUT FOLDERS #####
# This is the *root* of the output
if not args.output:
output_root = os.getcwd()
else:
output_root = args.output
##### SUBJECT FOLDERS #####
# If a list of subjects is given, read them in and assign corresponding outputs (becomes, output_FOLDER/RCA. Default pwd/RCA)
# If a single subject is given, put it in a list (to be read by for loop) and assign the output_FOLDER as given
if args.subjects:
subjectList = []
outputList = []
with open(args.subjects, 'r') as subjects:
subjectList = subjects.read().splitlines()
for line in subjectList:
outputList.append(os.path.join(output_root, os.path.basename(line)))
else:
subjectList = [args.subject] # list so that single subject can enter for-loop
if not os.path.exists(os.path.abspath(output_root)):
os.makedirs(os.path.abspath(output_root))
output_FOLDER = os.path.abspath(output_root)
print G+'[*] output_folder: \t{}'.format(output_FOLDER)+W
outputList = [output_FOLDER]
##### BEGIN FOR LOOP OVER ALL SUBJECTS (OR SINGLE SUBJECT) #####
for subject, output_FOLDER in zip(subjectList, outputList):
t0 = time.time()
##### CHECK: DOES THE SUBJECT EXIST? #####
if not os.path.isdir(os.path.abspath(subject)):
msg = R+"[*] Subject folder doesn't exist: {}\n\n".format(subject)+W
sys.stdout.write(msg + prog_help)
continue
else:
subject_FOLDER = os.path.abspath(subject)
subject_NAME = os.path.basename(subject_FOLDER)
print G+'[*] subject_name: \t{}'.format(subject_NAME)+W
print G+'[*] subject_folder: \t{}'.format(subject_FOLDER)+W
##### CHECK: HAS RCA ALREADY BEEN PERFORMED? #####
# If there's already a data-file or an exception folder - skip this subject
# Otherwise, check if any new files are being created (i.e. RCA in process)
datafile = os.path.join(output_FOLDER, 'data', '{}.mat'.format(subject_NAME))
if os.path.exists(datafile) or os.path.exists(os.path.join(output_FOLDER, 'exception')):
continue
elif os.path.exists(os.path.join(output_FOLDER, 'RCA', 'test')):
if not os.path.exists(datafile) and os.listdir(os.path.join(output_FOLDER, 'RCA', 'test')):
f1 = os.path.getmtime(os.path.join(output_FOLDER, 'RCA', 'test', os.listdir(os.path.join(output_FOLDER, 'RCA', 'test'))[-1]))
time.sleep(10)
f2 = os.path.getmtime(os.path.join(output_FOLDER, 'RCA', 'test', os.listdir(os.path.join(output_FOLDER, 'RCA', 'test'))[-1]))
if f1==f2:
shutil.rmtree(output_FOLDER)
sys.stdout.write('Removing incomplete directory: {}\n'.format(output_FOLDER))
else:
continue
os.makedirs(os.path.join(output_FOLDER, 'data'))
##### CHECK: ARE WE DEALING WITH A GROUND-TRUTH SITUATION? #####
if args.GT:
if not os.path.isfile(os.path.abspath(os.path.join(subject, args.GT))):
msg = R+"[*] Subject GT file doesn't exist: {}\n\n".format(os.path.abspath(os.path.join(subject, args.GT)))+W
sys.exit(msg + prog_help)
else:
subject_GT_FILE = os.path.abspath(os.path.join(subject, args.GT))
print G+'[*] subject_GT: \t{}'.format(os.path.abspath(os.path.join(subject, args.GT)))+W
##### CHECK: DO THE REFERENCE IMAGES EXIST? #####
if not os.path.isdir(os.path.abspath(args.refs)):
msg = R+"[*] Reference image folder doesn't exist: %s\n\n"+W % args.refs
sys.exit(msg + prog_help)
else:
ref_img_FOLDER = os.path.abspath(args.refs)
print G+'[*] ref_folder: \t{}'.format(ref_img_FOLDER)+W
##### ASSIGN: VARIABLES BASED ON THE CONFIG FILE #####
# This line reads in "image_FILE and seg_FILE" variables based on args.config
cfgfile = args.config if args.config[-4:] == '.cfg' else args.config + '.cfg'
if not os.path.exists(os.path.abspath(cfgfile)):
msg = R+"[*] Config file doesn't exist: {}\n\n".format(cfgfile)+W
sys.exit(msg + prog_help)
else:
filenames_CONFIG = os.path.abspath(cfgfile)
print G+'[*] config_file: \t{}'.format(filenames_CONFIG)+W
image_FILE = []
seg_FILE = []
class_list = []
execfile(filenames_CONFIG)
##### CHECK: DOES THE TEST-SEGMENTATION EXIST? #####
if args.seg:
if not os.path.isfile(os.path.abspath(os.path.join(subject, args.seg))):
msg = R+"[*] Subject seg file doesn't exist: {}\n\n".format(os.path.abspath(os.path.join(subject, args.seg)))+W
sys.exit(msg + prog_help)
else:
seg_FILE = os.path.abspath(os.path.join(subject, args.seg))
print G+'[*] subject_seg: \t{}'.format(os.path.abspath(os.path.join(subject, args.seg)))+W
##### ASSIGN: ALL FILES SHOULD NOW BE ACCESSIBLE #####
# Copy the primary image and segmentation to the RCA folder
subject_image_FILE = os.path.abspath(os.path.join(subject_FOLDER, image_FILE ))
subject_seg_FILE = os.path.abspath(os.path.join(subject_FOLDER, seg_FILE ))
os.makedirs(os.path.join(output_FOLDER, 'main_image', 'cropped'))
for f in [subject_image_FILE, subject_seg_FILE]:
shutil.copy(f, os.path.join(output_FOLDER, 'main_image', 'cropped'))
#########################################################################################################################
###################### BEGIN RCA ANALYSIS ###############################################################################
print "\nRCA analysis on:\n" \
"Image:\t\t {}\n" \
"Segmentation:\t {}".format(subject_image_FILE, subject_seg_FILE)
if args.GT:
print "GT Seg.:\t {}\n".format(subject_GT_FILE)
else:
sys.stdout.write('\n')
##### Sometimes the segmentation is not the same depth as the image - getMetrics throws IndexError exception
# Best to catch the error and move on to a different subject rather than quit the loop
try:
Data = registration(subject_folder = subject_FOLDER, output_folder=output_FOLDER, imgFilename=image_FILE, segFilename=seg_FILE, refdir=args.refs, classes=class_list, doBoth=1)
except Exception as e:
print(e)
except (KeyboardInterrupt, SystemExit):
raise
except:
os.makedirs(os.path.join(output_FOLDER, 'exception'))
continue
# To recalculate GT metrics after RCA ###
# print datafile
# Data_ = scipy.io.loadmat(datafile)
# print G+'[*] Loaded data:\t{}\n'.format(datafile)+W
# Data=[]
# for key in Data_.keys():
# if key.startswith('Ref'):
# Data.append([key.split('Ref')[-1]] + list(Data_[key]))
# if len(Data)<100:
# print R+'################ {} ##############'.format(subject_image_FILE)+W
# continue
##### DISPLAY: OUTPUT SOME VISUALS AND STATISTICS FOR RCA #####
DSCs = np.array([data[1] for data in Data])
MSDs = np.array([data[2] for data in Data])
RMSs = np.array([data[3] for data in Data])
HDs = np.array([data[4] for data in Data])
factor = 1 #to change the length of the distribution graph
if len(DSCs[:,-1])>=50:
factor = 2
sys.stdout.write('RCA DSC Distribution:\n')
sys.stdout.write('0.0 - 0.1:\t {:3d} {}\n'.format(len(DSCs[np.where( DSCs[:,-1]<0.1)]),'>'*(len(DSCs[np.where( DSCs[:,-1]<0.1)])/factor)))
sys.stdout.write('0.1 - 0.2:\t {:3d} {}\n'.format(len(DSCs[np.where( (DSCs[:,-1]>=0.1) & (DSCs[:,-1]<0.2) )]), '>'*(len(DSCs[np.where( (DSCs[:,-1]>=0.1) & (DSCs[:,-1]<0.2) )])/factor)))
sys.stdout.write('0.2 - 0.3:\t {:3d} {}\n'.format(len(DSCs[np.where( (DSCs[:,-1]>=0.2) & (DSCs[:,-1]<0.3) )]), '>'*(len(DSCs[np.where( (DSCs[:,-1]>=0.2) & (DSCs[:,-1]<0.3) )])/factor)))
sys.stdout.write('0.3 - 0.4:\t {:3d} {}\n'.format(len(DSCs[np.where( (DSCs[:,-1]>=0.3) & (DSCs[:,-1]<0.4) )]), '>'*(len(DSCs[np.where( (DSCs[:,-1]>=0.3) & (DSCs[:,-1]<0.4) )])/factor)))
sys.stdout.write('0.4 - 0.5:\t {:3d} {}\n'.format(len(DSCs[np.where( (DSCs[:,-1]>=0.4) & (DSCs[:,-1]<0.5) )]), '>'*(len(DSCs[np.where( (DSCs[:,-1]>=0.4) & (DSCs[:,-1]<0.5) )])/factor)))
sys.stdout.write('0.5 - 0.6:\t {:3d} {}\n'.format(len(DSCs[np.where( (DSCs[:,-1]>=0.5) & (DSCs[:,-1]<0.6) )]), '>'*(len(DSCs[np.where( (DSCs[:,-1]>=0.5) & (DSCs[:,-1]<0.6) )])/factor)))
sys.stdout.write('0.6 - 0.7:\t {:3d} {}\n'.format(len(DSCs[np.where( (DSCs[:,-1]>=0.6) & (DSCs[:,-1]<0.7) )]), '>'*(len(DSCs[np.where( (DSCs[:,-1]>=0.6) & (DSCs[:,-1]<0.7) )])/factor)))
sys.stdout.write('0.7 - 0.8:\t {:3d} {}\n'.format(len(DSCs[np.where( (DSCs[:,-1]>=0.7) & (DSCs[:,-1]<0.8) )]), '>'*(len(DSCs[np.where( (DSCs[:,-1]>=0.7) & (DSCs[:,-1]<0.8) )])/factor)))
sys.stdout.write('0.8 - 0.9:\t {:3d} {}\n'.format(len(DSCs[np.where( (DSCs[:,-1]>=0.8) & (DSCs[:,-1]<0.9) )]), '>'*(len(DSCs[np.where( (DSCs[:,-1]>=0.8) & (DSCs[:,-1]<0.9) )])/factor)))
sys.stdout.write('0.9 - 1.0:\t {:3d} {}\n\n'.format(len(DSCs[np.where( (DSCs[:,-1]>=0.9) & (DSCs[:,-1]<=1.0))]), '>'*(len(DSCs[np.where( (DSCs[:,-1]>=0.9) & (DSCs[:,-1]<1.0) )])/factor)))
sys.stdout.flush()
sys.stdout.write('Predicted DSC:\t{}\tAtlas: {}\n'.format(np.max(DSCs[:,-1]), np.argmax(DSCs[:,-1])))
sys.stdout.write('Minimum MSD:\t{}\tAtlas: {}\n'.format(np.min(MSDs[:,-1]), np.argmin(MSDs[:,-1])))
sys.stdout.write('Minimum RMS:\t{}\tAtlas: {}\n'.format(np.min(RMSs[:,-1]), np.argmin(RMSs[:,-1])))
sys.stdout.write('Minimum HD:\t{}\tAtlas: {}\n\n'.format(np.min(HDs[:,-1]), np.argmin(HDs[:,-1])))
##### OUTPUT: PREPARE THE DATA FOR OUTPUT AND CALCULATE THE GT REAL METRICS IF POSSIBLE #####
Datadict = {}
Datadict['ImageID'] = subject_NAME
Datadict['Classes'] = class_list
if args.GT:
realMetrics = getMetrics(sitk.GetArrayFromImage(sitk.ReadImage(subject_GT_FILE)), sitk.GetArrayFromImage(sitk.ReadImage(subject_seg_FILE)), ref_classes=[0,1,2,4])
sys.stdout.write('Real DSC: \t{}\n\n'.format(realMetrics[0][-1]))
sys.stdout.flush()
for ref in Data:
Datadict['Ref{}'.format(ref[0])] = ref[1:]
RefData = np.array([Datadict[ref] for ref in Datadict.keys() if 'Ref' in ref])
maxs = [np.max(RefData, axis=0), np.argmax(RefData, axis=0)+1]
mins = [np.min(RefData, axis=0), np.argmin(RefData, axis=0)+1]
Datadict['MaxMetrics'] = np.concatenate([np.reshape(np.array(maxs)[:,0,:], [2,1,5]), np.array(mins)[:,1:,:]], axis=1).transpose(1,2,0)
if args.GT:
Datadict['GTMetrics'] = realMetrics
scipy.io.savemat(datafile, Datadict)
##### TIME: CALCULATE AND DISPLAY TIME FOR ANALYSIS #####
t1 = time.time()
elapsed = t1 - t0
hours = elapsed//3600
mins = (elapsed-(3600*hours))//60
secs = (elapsed-(3600*hours)-(mins*60))
sys.stdout.write('Elapsed Time: {:02d}h {:02d}m {:02d}s\n\n'.format(int(hours), int(mins), int(secs)))
sys.stdout.flush()
#time.sleep(5)
sys.exit(0) |
def InOrder(ls):
stack=[]
res=[]
i=0
while i < len(ls) or len(stack) > 0:
if i < len(ls):
stack.append(ls[i])
i = 2 * i + 1 #找左孩子
else:
p=stack.pop()
res.append(p)
ind=ls.index(p)
i = 2 * ind + 2 #找右孩子
for i in res:
print(i , end=',')
if __name__ == '__main__':
ls=[1,2,3,4,5,6,7,8,9,10]
InOrder(ls)
|
#!/usr/bin/python
'''
Day 5 - Morning (pt. 1)
The message includes a list of the offsets for each jump.
Jumps are relative: -1 moves to the previous instruction, and 2 skips the next one.
Start at the first instruction in the list.
The goal is to follow the jumps until one leads outside the list.
In addition, these instructions are a little strange; after each jump,
the offset of that instruction increases by 1.
So, if you come across an offset of 3, you would move three instructions forward,
but change it to a 4 for the next time it is encountered.
For example, consider the following list of jump offsets:
0
3
0
1
-3
Positive jumps ("forward") move downward; negative jumps move upward. For legibility in this example, these offset values will be written all on one line, with the current instruction marked in parentheses. The following steps would be taken before an exit is found:
(0) 3 0 1 -3 - before we have taken any steps.
(1) 3 0 1 -3 - jump with offset 0 (that is, don't jump at all). Fortunately, the instruction is then incremented to 1.
2 (3) 0 1 -3 - step forward because of the instruction we just modified. The first instruction is incremented again, now to 2.
2 4 0 1 (-3) - jump all the way to the end; leave a 4 behind.
2 (4) 0 1 -2 - go back to where we just were; increment -3 to -2.
2 5 0 1 -2 - jump 4 steps forward, escaping the maze.
In this example, the exit is reached in 5 steps.
'''
def findExit(file):
with open(file) as f:
content = f.readlines()
content = [x.strip('\n') for x in content]
steps = 0
curIndex = 0
while (curIndex < len(content)):
indexVal = content[curIndex]
content[curIndex] = str(int(content[curIndex]) + 1)
curIndex += int(indexVal)
steps += 1
return steps
print("\nAnswer: " + str(findExit("input/day5.txt")))
'''
Day 5 - Morning (pt. 1)
Now, the jumps are even stranger:
after each jump, if the offset was three or more,
instead decrease it by 1. Otherwise, increase it by 1 as before.
Using this rule with the above example, the process now takes 10 steps,
and the offset values after finding the exit are left as 2 3 2 3 -1.
How many steps does it now take to reach the exit?
'''
def findStrangeExit(file):
with open(file) as f:
content = f.readlines()
content = [x.strip('\n') for x in content]
steps = 0
curIndex = 0
while (curIndex < len(content)):
indexVal = content[curIndex]
if int(indexVal) >= 3:
content[curIndex] = str(int(content[curIndex]) - 1)
else:
content[curIndex] = str(int(content[curIndex]) + 1)
curIndex += int(indexVal)
steps += 1
return steps
print("\nAnswer: " + str(findStrangeExit("input/day5.txt")))
|
# -*- coding: utf-8 -*-
# @Author: gvishal
# @Date: 2019-03-31 00:26:01
# @Last Modified by: vishalgupta07
# @Last Modified time: 2019-04-05 19:04:01
from django.urls import path
from .views import PostListView, PostDetailView, PostCreateView, PostUpdateView, PostDeleteView, UserPostListView, EventListView
from . import views
urlpatterns = [
path('', PostListView.as_view(), name='blog-home'),
path('events/', EventListView.as_view(), name='blog-events'),
path('user/<str:username>', UserPostListView.as_view(), name='user-posts'),
path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'),
path('post/<int:pk>/update/', PostUpdateView.as_view(), name='post-update'),
path('post/<int:pk>/delete/', PostDeleteView.as_view(), name='post-delete'),
path('post/new/', PostCreateView.as_view(), name='post-create'),
]
# <app>/<model>_<viewtype>.html/ |
import itertools
from collections import defaultdict
from locus import Locus
def chrom_sort(chroms):
# get characters after 'chr'
alphanum = [c.split('chr')[1] for c in chroms]
# split up chroms with and without '_', convert numbers to ints for easier sorting
mapped = []
unmapped = []
for an in alphanum:
if '_' in an:
tup = (an.split('_')[0], '_'.join(an.split('_')[1:]))
try:
unmapped.append((int(tup[0]), tup[1]))
except ValueError:
unmapped.append((tup[0], tup[1]))
else:
try:
mapped.append(int(an))
except ValueError:
mapped.append(an)
# sort, and move M's to front
sorted_chroms = []
mapped.sort()
unmapped.sort()
# mapped
if 'M' in mapped:
sorted_chroms.append('chrM')
sorted_chroms.extend(['chr' + str(an) for an in mapped if an != 'M'])
# unmapped
sorted_chroms.extend(['chr' + tup[0] + '_' + tup[1] for tup in unmapped if tup[0] == 'M'])
sorted_chroms.extend(['chr' + str(tup[0]) + '_' + tup[1] for tup in unmapped if tup[0] != 'M'])
return sorted_chroms
def read_ped(filename):
rels = {}
with open(filename, 'r') as f:
for line in f:
fam, child, father, mother = line.split('\t')[:4]
if father != '0':
#if we've already added the proband child, add the sibling
if fam in rels.keys():
rels[fam + '-s'] = (child, father, mother)
else:
rels[fam] = (child, father, mother)
return rels
def read_vcf(filename, rels, fam_type):
fam = filename.split('family')[1].split('.')[0]
header = []
alleles_by_chr = defaultdict(list)
with open(filename, 'r') as f_in:
# header
line = f_in.readline()
header.append(line)
while line[:2] == '##':
line = f_in.readline()
header.append(line)
# get indexes of child/dad/mom/sibling columns
cols = line.strip().split('\t')
child_i = cols.index(rels[fam][0])
dad_i = cols.index(rels[fam][1])
mom_i = cols.index(rels[fam][2])
sib_i = cols.index(rels[fam + '-s'][0]) if fam_type == 'quartet' else None
line = f_in.readline()
while line != '':
# grab genotypes and vcf info
cols = line.strip().split('\t')
nucleotides = [cols[3]] + cols[4].split(',')
child_GT = cols[child_i].split(':')[0]
dad_GT = cols[dad_i].split(':')[0]
mom_GT = cols[mom_i].split(':')[0]
child_col_str = ':' + ':'.join(cols[child_i].split(':')[1:])
dad_col_str = ':' + ':'.join(cols[dad_i].split(':')[1:])
mom_col_str = ':' + ':'.join(cols[mom_i].split(':')[1:])
sibling_GT = cols[sib_i].split(':')[0] if fam_type == 'quartet' else None
sibling_col_str = ':' + ':'.join(cols[sib_i].split(':')[1:]) if fam_type == 'quartet' else None
# convert to GT value lists
dad_vals = dad_GT.replace('/',',').replace('|',',').split(',') if (dad_GT != './.' and dad_GT != '0') else ['0', '0']
mom_vals = mom_GT.replace('/',',').replace('|',',').split(',') if (mom_GT != './.' and mom_GT != '0') else ['0', '0']
if 'chr21' not in cols[0]:
child_vals = child_GT.replace('/',',').replace('|',',').split(',') if (child_GT != './.' and child_GT != '0') else ['0', '0']
else:
child_vals = child_GT.replace('/',',').replace('|',',').split(',') if ('./.' not in child_GT and child_GT != '0') else ['0', '0', '0']
sibling_vals = None
if fam_type == 'quartet':
sibling_vals = sibling_GT.replace('/',',').replace('|',',').split(',') if (sibling_GT != './.' and sibling_GT != '0') else ['0', '0']
# convert to nucleotides
dad_alleles = [nucleotides[int(dad_v)] for dad_v in dad_vals]
mom_alleles = [nucleotides[int(mom_v)] for mom_v in mom_vals]
child_alleles = [nucleotides[int(child_v)] for child_v in child_vals]
sibling_alleles = [nucleotides[int(sib_v)] for sib_v in sibling_vals] if fam_type == 'quartet' else None
# add to alleles list
alleles_by_chr[cols[0]].append(Locus(cols[0], int(cols[1]), '\t'.join(cols[:9]), child_alleles, child_col_str,
dad_alleles, dad_col_str, mom_alleles, mom_col_str, sibling_alleles,
sibling_col_str))
line = f_in.readline()
return alleles_by_chr, header
def output_phased_vcf(filename, loci_by_chr, header, rels, fam_type, phased_regions_by_chr):
file_prefix = filename.split('.vcf')[0]
fam = filename.split('family')[1].split('.')[0]
# write phased vcf file
with open(file_prefix + '.phased.vcf', 'w') as f:
# write VCF header up to column header line
for line in header[:-1]:
f.write(line)
# the order of the individuals needs to be set by us for the output (it can't just be the same order that we
# read it in) because there might be extra individuals in the original VCF that weren't phased)
# write columns names up to the indv IDs
f.write('\t'.join(header[-1].split('\t')[:9]))
# write indv IDs in order: child, dad, mom, sibling (if quartet is used)
f.write('\t%s\t%s\t%s' % (rels[fam][0], rels[fam][1], rels[fam][2]))
if fam_type == 'quartet':
f.write('\t%s' % rels[fam + '-s'][0])
f.write('\n')
# write phased positions
for curr_chr in chrom_sort(loci_by_chr.keys()):
for locus in loci_by_chr[curr_chr]:
# write vcf line preceding phased GT info
f.write(locus.vcf_data)
# write phased GT columns in order of child, dad, mom, sibling (if quartet is used)
f.write('\t%s:%s' % (locus.child_phased_GT, locus.child_col_str))
f.write('\t%s:%s' % (locus.dad_phased_GT, locus.dad_col_str))
f.write('\t%s:%s' % (locus.mom_phased_GT, locus.mom_col_str))
if fam_type == 'quartet':
f.write('\t%s:%s' % (locus.sibling_phased_GT, locus.sibling_col_str))
f.write('\n')
# write bed file with contiguous phased regions
with open(file_prefix + '.phased-regions.bed', 'w') as f:
for curr_chr in chrom_sort(phased_regions_by_chr.keys()):
for chrom, start, end in phased_regions_by_chr[curr_chr]:
f.write('%s\t%i\t%i\n' % (chrom, start, end))
|
import pandas
import matplotlib.pyplot as plt
import random as rd
import math
import numpy as np
def variable(width, height, density, cluster_density):
"""variables"""
node_member, cluster_member, station_member, \
node_energy, shot_dis_data = [], [], [], [], []
len_nodes = math.ceil(density * (width * height))
len_cluster = math.ceil(cluster_density * len_nodes)
return node_member, cluster_member, station_member, shot_dis_data, len_nodes, len_cluster, node_energy
def base_station(num_base, station_member):
"""input base station point"""
for item in range(num_base):
station_member.append(list(map(int, "51,-1".split(','))))
print(pd.__version__)
writer = pd.ExcelWriter('test.xlsx', engine='xlsxwriter')
workbook = writer.book
ws = workbook.add_worksheet('mytab')
ws.write(1,1,'This is a test')
writer.close()
# append data to csv. file
with open('station_member.csv', 'w', newline='') as csvnew:
write = csv.writer(csvnew)
for line in station_member:
write.writerow(line)
return station_member
def current_data(option):
"""use current data not change anything"""
# gain data from .csv files
shot_dis_data, node_member, cluster_member, station_member = [], [], [], []
with open("station_member.csv", 'r') as csvnew:
read = csv.reader(csvnew)
for line in read:
station_member.append(list(map(int, line)))
with open("node_member.csv", 'r') as csvnew:
read = csv.reader(csvnew)
for line in read:
node_member.append(list(map(int, line)))
with open("cluster_member.csv", 'r') as csvnew:
read = csv.reader(csvnew)
for line in read:
cluster_member.append(list(map(int, line)))
with open("shot_dis_data.csv", 'r') as csvnew:
read = csv.reader(csvnew)
for line in read:
shot_dis_data.append(line)
# plot
count_lap = "CURRENT_DATA"
plot(shot_dis_data, node_member, cluster_member, station_member, count_lap, option)
def start():
"""Choose Functions"""
print("Choose 0 new input")
print("Choose 1 current data")
print("Choose 2 random only cluster")
option = int(input("----> "))
if option == 0: # new input
new_input(int(50), int(50), float(0.025), float(0.079), int(1), option)
elif option == 1: # current data:
current_data(option)
elif option == 2:
lap = int(input("how many lap do you need? : "))
random_cluster_ingroup(option, lap)
start()
|
from django.contrib import admin
from .models import *
# Register your models here.
class PersonaAdmin(admin.ModelAdmin):
list_display = ['nombre','apellido','direccion','telefono']
class AutorAdmin(admin.ModelAdmin):
list_display = ['persona']
class UsuarioAdmin(admin.ModelAdmin):
list_display = ['persona']
class LibroAdmin(admin.ModelAdmin):
list_display = ['titulo','descripcion','isbn','editorial','paginas','autor']
class EjemplarAdmin(admin.ModelAdmin):
list_display = ['localizacion']
admin.site.register (Persona, PersonaAdmin)
admin.site.register (Autor, AutorAdmin)
admin.site.register (Usuario, UsuarioAdmin)
admin.site.register (Libro, LibroAdmin)
admin.site.register (Ejemplar, EjemplarAdmin)
|
#!/usr/bin/env python
#
# This is a dictionary test by python
#
people = {
'Alice' : { 'phone' : '2101',
'address' : 'No.1 st,PH,US'
},
'Betch' : { 'phone' : '2155',
'address' : 'No.172,Wall St,US'
},
'Cecil' : { 'phone' : '3106',
'address' : 'No.291,LA,US'
}
}
labels = { 'phone' : 'phone number',
'addr' : 'address'
}
name = raw_input('Name: ')
request = raw_input('Please chose[p] for phone,[a] for adress: ')
if request == 'p' : key = 'phone'
if request == 'a' : key = 'address'
if name in people : print "%s's %s is %s." % (name, labels[key], people[name][key])
|
def make_selector_on_deviceA():
from selector_wizard.make_initial_selector import process_clear_json_dataset
process_clear_json_dataset(name="jst_first_10_selector_A", threshold=0.9,
json_data=None, path_to_this_json=None, model=None)
def make_dataset_for_device_B_by_shift(): #.sig и .conext
from selector_wizard.selector_to_np import selector_to_np_dataset
selector_to_np_dataset(u=128, patch_len=256, name="u128A_256_healthy7", num_leads=1, selector=None)
def show_some_np_data():
from np_datasets_wizard.show_np_dataset import show_np_dataset_1st_lead
show_np_dataset_1st_lead()
def tsne_cutted_patches():
from sample_device.tsne_ecg import visualise
visualise()
#make_selector_on_deviceA()
#make_dataset_for_device_B_by_shift()
#show_some_np_data()
tsne_cutted_patches()
|
from django.urls import path, include
from likes.views import LikeList, unLike
urlpatterns = [
path('', LikeList.as_view()),
path('remove', unLike),
] |
from mrjob.job import MRJob
class
|
import cadquery as cq
length = 3887.
width = 50.
thickness = 5.
box = cq.Workplane("XY").box(length, width, width)
print(box)
box2 = box.translate(thickness, thickness, 0)
show_object(box)
|
import numpy as np
from lmfit import Model
def rational_R_ge(q2,a,b,R):
return a*(1.-R*R*q2/6.+b*q2)/(1+b*q2)
class xy_bootstrap(object):
def read_in(self,filename,seed=7):
data=np.loadtxt(filename,skiprows=1)
self._q2=data[:,0]
self._ge=data[:,1]
self._dge=data[:,2]
np.random.seed(seed)
def single_fit(self):
print("single R fit")
ge=self._ge; q2=self._q2; dge=self._dge
#print("ge q2 dge shape" + str(ge.shape)+ " , " + str(q2.shape) + " , " + str(dge.shape))
modelr=Model(rational_R_ge)
result=modelr.fit(ge,q2=q2,a=1,b=-0.01,R=1.0,weights=1/dge)
print(result.fit_report())
print("a= " + str(result.best_values['a']))
print("b= " + str(result.best_values['b']))
print("R= " + str(result.best_values['R']))
def bs_replace(self, loop, slen):
ge=self._ge; q2=self._q2; dge=self._dge
print("Bootstrap with replacement: nbin tot= " + str(len(q2)) + " , sample nbin= " + str(slen) + " , loop= " + str(loop))
assert(slen <= len(q2))
a_boot=[]
b_boot=[]
radius_boot=[]
r_err_boot=[]
for l in range(loop):
if(np.mod(l,100) == 0):
print("Running: " + str(l) + " | " + str(loop))
idx=np.random.randint(0,len(q2),size=slen)
idx=np.sort(idx)
subq2=q2[idx]; subge=ge[idx]; subdge=dge[idx]
if(np.mod(l,100) == 0):
print(" sizes q2, ge, dge: " + str(subq2.size) + " , " + str(subge.size) + " , " + str(subdge.size))
modelr=Model(rational_R_ge)
result=modelr.fit(subge,q2=subq2,a=1,b=-0.01,R=1.0,weights=1/subdge)
a_boot.append(result.best_values['a'])
b_boot.append(result.best_values['b'])
radius_boot.append(result.best_values['R'])
r_err_boot.append(result.params['R'].stderr)
print('a: ',np.mean(a_boot),' +/- ',(np.std(a_boot)), ' | size= ', len(a_boot))
print('b: ',np.mean(b_boot),' +/- ',(np.std(b_boot)), ' | size= ', len(b_boot))
print('R: ',np.mean(radius_boot),' +/- ',(np.std(radius_boot)), ' | size= ', len(radius_boot))
print('r err: ',np.mean(r_err_boot),' +/- ',(np.std(r_err_boot)), ' | size= ', len(r_err_boot))
return [np.mean(radius_boot), (np.std(radius_boot)), len(radius_boot)]
def bs_noreplace(self, loop, slen):
ge=self._ge; q2=self._q2; dge=self._dge
print("Bootstrap without replacement: nbin tot= " + str(len(q2)) + " , sample nbin= " + str(slen) + " , loop= " + str(loop))
assert(slen <= len(q2))
a_boot=[]
b_boot=[]
radius_boot=[]
r_err_boot=[]
D={}
for l in range(loop):
if(np.mod(l,100) == 0):
print("Running: " + str(l) + " | " + str(loop))
perm=np.arange(len(q2))
np.random.shuffle(perm)
idx=perm[0:slen]
idx=np.sort(idx)
ts=str(idx)
if (ts in D): continue
D[ts]=1
subq2=q2[idx]; subge=ge[idx]; subdge=dge[idx]
if(np.mod(l,100) == 0):
print(" sizes q2, ge, dge: " + str(subq2.size) + " , " + str(subge.size) + " , " + str(subdge.size))
modelr=Model(rational_R_ge)
result=modelr.fit(subge,q2=subq2,a=1,b=-0.01,R=1.0,weights=1/subdge)
a_boot.append(result.best_values['a'])
b_boot.append(result.best_values['b'])
radius_boot.append(result.best_values['R'])
r_err_boot.append(result.params['R'].stderr)
print('a: ',np.mean(a_boot),' +/- ',(np.std(a_boot)), ' | size= ', len(a_boot))
print('b: ',np.mean(b_boot),' +/- ',(np.std(b_boot)), ' | size= ', len(b_boot))
print('R: ',np.mean(radius_boot),' +/- ',(np.std(radius_boot)), ' | size= ', len(radius_boot))
print('r err: ',np.mean(r_err_boot),' +/- ',(np.std(r_err_boot)), ' | size= ', len(r_err_boot))
return [np.mean(radius_boot), (np.std(radius_boot)), len(radius_boot)]
# Test
xyb=xy_bootstrap()
#filename="xy_gen_Q2_GE_41_dipole.txt"
filename="xy_gen_Q2_GE_41_dipole_fluc1.txt"
#filename="xy_gen_Q2_GE_41_dipole_fluc2.txt"
xyb.read_in(filename)
xyb.single_fit()
#[Rmean,Rrms,Rsize]=xyb.bs_replace(1000, 25)
[Rmean,Rrms,Rsize]=xyb.bs_noreplace(100, 40)
print("Rmean,Rrms,Rsize= " + str([Rmean,Rrms,Rsize]))
|
# Generated by Django 2.1 on 2018-10-23 06:41
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('home', '0003_dailyinput_dummy'),
]
operations = [
migrations.RenameField(
model_name='concept',
old_name='id_user',
new_name='user',
),
]
|
import pandas as pd
import pandas as pd
import requests as req
import datetime as dt
import json
import os
def api_call(url_base,i):
json_req = req.get(url_base.format(i))
dfs = []
if json_req.status_code == 200:
jsonstr = json.loads(json_req.content)
for dict_ in jsonstr["features"]:
dfs.append(pd.DataFrame(dict_["attributes"], index=[0]))
return pd.concat(dfs)
def collect_mpi_data():
# main function for running the api over the 200+ species and seasons
url_base = "https://maps.mpi.govt.nz/wss/service/ags-relay/arcgis1/guest/arcgis/rest/services/MARINE/MARINE_Species_SPN/MapServer/{}/query?where=1%3D1&outFields=*&outSR=4326&f=json"
dfs = []
for i in range(1,1000):
try:
dfs.append(api_call(url_base,i))
except:
print("Failed at request number {}. Exiting process".format(i))
break
d_ = "{}/myfishfinder/data/raw/mpiopendata".format(os.path.dirname(os.getcwd()))
if not os.path.exists(d_):
os.makedirs(d_)
pd.concat(dfs).to_csv("{}/{}-{}-{}.csv".format(d_,dt.datetime.now().year,dt.datetime.now().month,dt.datetime.now().day))
|
# Generated by Django 2.2.1 on 2019-07-12 08:28
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('people', '0005_auto_20190711_2032'),
]
operations = [
migrations.CreateModel(
name='organizations',
fields=[
('number', models.BigAutoField(primary_key=True, serialize=False)),
('organization_name', models.CharField(max_length=30)),
('creater', models.CharField(max_length=30)),
('manager', models.CharField(max_length=30)),
('member', models.CharField(max_length=30)),
],
),
migrations.CreateModel(
name='User_info',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('motto', models.CharField(max_length=100)),
('sex', models.IntegerField(choices=[(1, '男'), (2, '女')], default=1)),
('birth_year', models.IntegerField(default=2019)),
('birth_month', models.SmallIntegerField(default=12)),
('birth_date', models.DateField()),
('profile', models.ImageField(upload_to='')),
('name', models.ForeignKey(on_delete='on_delete=models.CASCADE()', to='people.Person')),
],
),
]
|
from .models import Tag, User
from django import forms
class TagForm(forms.Form):
CHOICES = (
('Java', 'Java'),
('Javascript', 'Javascript'),
('Python', 'Python'),
('PHP', 'PHP'),
('HTML', 'HTML'),
('CSS', 'CSS'),
('Cyptocurrency', 'Cyptocurrency'),
)
picked = forms.MultipleChoiceField(choices=CHOICES, widget=forms.CheckboxSelectMultiple(), label="Select tags:")
# class Meta:
# model = Tag
# exclude = ["users"]
|
#edit
print ('this is not an exit')
|
import datetime
from operator import itemgetter
from django.conf import settings
from django.db.models import Q, Subquery, Sum
from django.views.generic.base import TemplateView
from braces.views import LoginRequiredMixin
from rest_framework import renderers
from rest_framework.decorators import action
from rest_framework.response import Response
from drf_renderer_xlsx.mixins import XLSXFileMixin
from drf_renderer_xlsx.renderers import XLSXRenderer
from apps.core import permissions
from apps.core.rest import BaseMy24ViewSet, BaseListView
from apps.order.models import OrderLine
from . import models
from . import serializers
class PurchaseIndex(LoginRequiredMixin, TemplateView):
template_name = 'purchase/index.html'
class PurchaseDeviceIndex(LoginRequiredMixin, TemplateView):
template_name = 'purchase/device.html'
class ProductQueryMixin(object):
def get_totals(self, year):
filter_q = Q(product_relation__in=Subquery(self.queryset.values('id')),
order__order_type='sales', order__start_date__year=year)
return OrderLine.objects.filter(filter_q).aggregate(Sum('price_selling'), Sum('amount'), Sum('price_purchase'))
def get_total_sales(self, year, query):
totals = self.get_totals(year)
product_row = {}
filter_q = Q(product_relation__in=Subquery(self.queryset.values('id')),
order__order_type='sales', order__start_date__year=year)
if query:
filter_q = filter_q & Q(product_relation__name__icontains=query)
for orderline in OrderLine.objects.filter(filter_q).select_related('order').select_related('product_relation'):
if orderline.product_relation.id in product_row:
product_row[orderline.product_relation.id]['amount'] += orderline.amount
product_row[orderline.product_relation.id]['price_purchase_amount'] += orderline.price_purchase.amount
product_row[orderline.product_relation.id]['price_selling_amount'] += orderline.price_selling.amount
else:
product_row[orderline.product_relation.id] = {
'product_image': orderline.product_relation.image.url if orderline.product_relation.image else '',
'product_name': orderline.product_relation.name,
'amount': orderline.amount,
'price_purchase_amount': orderline.price_purchase.amount,
'price_purchase_currency': '%s' % orderline.price_purchase.currency,
'price_selling_amount': orderline.price_selling.amount,
'price_selling_currency': '%s' % orderline.price_selling.currency,
}
response = []
# for row in result:
for key in product_row.keys():
profit = round(product_row[key]['price_selling_amount'] - product_row[key]['price_purchase_amount'], 2)
product_row[key]['profit'] = profit
price_selling_amount = product_row[key]['price_selling_amount']
amount = product_row[key]['amount']
product_row[key]['amount_perc'] = round((amount / totals['amount__sum']) * 100, 2)
product_row[key]['amount_selling_perc'] = round(
(price_selling_amount / totals['price_selling__sum']) * 100, 2
)
response.append(product_row[key])
return sorted(response, key=itemgetter('price_selling_amount'), reverse=True)
def get_total_sales_per_customer(self, year, query):
totals = self.get_totals(year)
customers = {}
filter_q = Q(product_relation__in=Subquery(self.queryset.values('id')),
order__order_type='sales', order__start_date__year=year)
if query:
filter_q = filter_q & Q(order__order_name__icontains=query)
for orderline in OrderLine.objects.filter(filter_q).select_related('order').select_related('product_relation'):
if orderline.order.customer_id in customers:
customers[orderline.order.customer_id]['amount'] += orderline.amount
customers[orderline.order.customer_id]['price_purchase_amount'] += orderline.price_purchase.amount
customers[orderline.order.customer_id]['price_selling_amount'] += orderline.price_selling.amount
else:
customers[orderline.order.customer_id] = {
'order_name': orderline.order.order_name,
'amount': orderline.amount,
'price_purchase_amount': orderline.price_purchase.amount,
'price_purchase_currency': '%s' % orderline.price_purchase.currency,
'price_selling_amount': orderline.price_selling.amount,
'price_selling_currency': '%s' % orderline.price_selling.currency,
}
response = []
for key in customers.keys():
profit = round(customers[key]['price_selling_amount'] - customers[key]['price_purchase_amount'], 2)
customers[key]['profit'] = profit
customers[key]['amount_perc'] = round((customers[key]['amount'] / totals['amount__sum']) * 100, 2)
customers[key]['amount_selling_perc'] = round(
(customers[key]['price_selling_amount'] / totals['price_selling__sum']) * 100, 2
)
response.append(customers[key])
return sorted(response, key=itemgetter('price_selling_amount'), reverse=True)
class ExportXlsView(ProductQueryMixin, XLSXFileMixin, BaseListView):
pagination_class = None
renderer_classes = (XLSXRenderer,)
filename = 'total_sales_per_customer.xlsx'
serializer_class = serializers.ProductTotalSerializer
queryset = models.Product.objects.all()
def get_queryset(self, *arg, **kwargs):
now = datetime.datetime.now()
year = self.request.GET.get('year', now.year)
query = self.request.query_params.get('q')
return self.get_total_sales_per_customer(year, query)
class ProductViewset(ProductQueryMixin, BaseMy24ViewSet):
serializer_class = serializers.ProductSerializer
serializer_detail_class = serializers.ProductSerializer
permission_classes = (
permissions.IsPlanningUser |
permissions.IsEngineer |
permissions.IsCustomerUser |
permissions.IsSalesUser,)
renderer_classes = (renderers.JSONRenderer, renderers.BrowsableAPIRenderer)
paginate_by = 20
filterset_fields = ('product_type',)
search_fields = ('identifier', 'name', 'search_name', 'unit', 'supplier', 'product_type')
queryset = models.Product.objects.all()
model = models.Product
@action(detail=False, methods=['GET'])
def autocomplete(self, request, *args, **kwargs):
query = self.request.query_params.get('q')
data = []
qs = self.queryset
qs = qs.filter(
Q(identifier__icontains=query) |
Q(name__icontains=query) |
Q(name_short__icontains=query) |
Q(search_name__icontains=query) |
Q(unit__icontains=query) |
Q(supplier__icontains=query) |
Q(product_type__icontains=query)
)
for product in qs:
image = '%s%s' % (settings.MEDIA_URL, product.image.name) if product.image else ''
data.append({
'id': product.id,
'identifier': product.identifier,
'name': product.name,
'value': '%s (%s)' % (product, product.unit),
'price_purchase': '%s' % product.price_purchase,
'price_selling': '%s' % product.price_selling,
'price_selling_alt': '%s' % product.price_selling_alt,
'image': image
})
return Response(data)
def get_totals(self, year):
filter_q = Q(product_relation__in=Subquery(self.queryset.values('id')),
order__order_type='sales', order__start_date__year=year)
return OrderLine.objects.filter(filter_q).aggregate(Sum('price_selling'), Sum('amount'), Sum('price_purchase'))
@action(detail=False, methods=['GET'])
def total_sales(self, request, *args, **kwargs):
"""
total sales per product
"""
now = datetime.datetime.now()
year = self.request.GET.get('year', now.year)
query = self.request.query_params.get('q')
response = self.get_total_sales(year, query)
return Response({
'result': response,
'num_pages': 1
})
@action(detail=False, methods=['GET'])
def total_sales_per_customer(self, request, *args, **kwargs):
"""
group product sales per customer and totalize
"""
now = datetime.datetime.now()
year = self.request.GET.get('year', now.year)
query = self.request.query_params.get('q')
response_data = self.get_total_sales_per_customer(year, query)
return Response({
'result': response_data,
'num_pages': 1
})
@action(detail=False, methods=['GET'])
def total_sales_per_product_customer(self, request, *args, **kwargs):
"""
group product sales per customer and totalize
"""
now = datetime.datetime.now()
year = self.request.GET.get('year', now.year)
totals = self.get_totals(year)
query = self.request.query_params.get('q')
customer_products = {}
filter_q = Q(product_relation__in=Subquery(self.queryset.values('id')),
order__order_type='sales', order__start_date__year=year)
if query:
filter_q = filter_q & (Q(order__order_name__icontains=query) | Q(product_relation__name__icontains=query))
for orderline in OrderLine.objects.filter(filter_q).select_related('order').select_related('product_relation'):
key = '%s-%s' % (orderline.order.customer_id, orderline.product_relation.id)
if key in customer_products:
customer_products[key]['amount'] += orderline.amount
customer_products[key]['price_purchase_amount'] += orderline.price_purchase.amount
customer_products[key]['price_selling_amount'] += orderline.price_selling.amount
else:
customer_products[key] = {
'product_image': orderline.product_relation.image.url if orderline.product_relation.image else '',
'product_name': orderline.product_relation.name,
'order_name': orderline.order.order_name,
'amount': orderline.amount,
'price_purchase_amount': orderline.price_purchase.amount,
'price_purchase_currency': '%s' % orderline.price_purchase.currency,
'price_selling_amount': orderline.price_selling.amount,
'price_selling_currency': '%s' % orderline.price_selling.currency,
}
response = []
for key in customer_products.keys():
customer_products[key]['amount_perc'] = round(
(customer_products[key]['amount'] / totals['amount__sum']) * 100, 2
)
customer_products[key]['amount_selling_perc'] = round(
(customer_products[key]['price_selling_amount'] / totals['price_selling__sum']) * 100, 2
)
response.append(customer_products[key])
response = sorted(response, key=itemgetter('price_selling_amount'), reverse=True)
return Response({
'result': response,
'num_pages': 1
})
class SupplierViewset(BaseMy24ViewSet):
serializer_class = serializers.SupplierSerializer
serializer_detail_class = serializers.SupplierSerializer
permission_classes = (permissions.IsPlanningUser,)
search_fields = ('name', 'city', 'identifier', 'email')
queryset = models.Supplier.objects.all()
model = models.Supplier
@action(detail=False, methods=['GET'])
def autocomplete(self, request, *args, **kwargs):
query = self.request.query_params.get('q')
data = []
qs = self.queryset
qs = qs.filter(
Q(name__icontains=query) |
Q(address__icontains=query) |
Q(city__icontains=query) |
Q(email__icontains=query)
)
for supplier in qs:
value = '(%s) %s, %s (%s)' % (supplier.identifier, supplier.name, supplier.city, supplier.country_code)
data.append({
'id': supplier.id,
'name': supplier.name,
'postal': supplier.postal,
'city': supplier.city,
'country_code': supplier.country_code,
'tel': supplier.tel,
'mobile': supplier.mobile,
'email': supplier.email,
'identifier': supplier.identifier,
'contact': supplier.contact,
'remarks': supplier.remarks,
'value': value
})
return Response(data)
class StockLocationViewset(BaseMy24ViewSet):
serializer_class = serializers.StockLocationSerializer
serializer_detail_class = serializers.StockLocationSerializer
permission_classes = (permissions.IsPlanningUser,)
search_fields = ('identifier', 'name')
queryset = models.StockLocation.objects.all()
model = models.StockLocation
class StockMutationViewset(BaseMy24ViewSet):
serializer_class = serializers.StockMutationSerializer
serializer_detail_class = serializers.StockMutationSerializer
permission_classes = (permissions.IsPlanningUser | permissions.IsSalesUser,)
queryset = models.StockMutation.objects.select_related('product').all()
model = models.StockMutation
class StockLocationInventoryViewset(BaseMy24ViewSet):
serializer_class = serializers.StockLocationInventorySerializer
serializer_detail_class = serializers.StockLocationInventorySerializer
permission_classes = (permissions.IsPlanningUser | permissions.IsSalesUser,)
search_fields = ('product__name', 'location__name')
filterset_fields = ('product', 'location')
page_size = 200
queryset = models.StockLocationInventory. \
objects. \
select_related('product', 'location'). \
order_by('product__name'). \
all()
model = models.StockLocationInventory
def get_serializer_class(self):
if self.action == 'list':
return serializers.StockLocationInventorySerializer
if self.action == 'list_full':
return serializers.StockLocationInventoryFullSerializer
return serializers.StockLocationInventorySerializer
@action(detail=False, methods=['GET'])
def list_full(self, request, *args, **kwargs):
return super().list(request, args, kwargs)
@action(detail=False, methods=['GET'])
def list_product_types(self, request, *args, **kwargs):
location_id = self.request.query_params.get('location_id')
qs = self.get_queryset().filter(location_id=location_id).values('product__product_type').distinct()
data = []
for product_type in qs:
data.append({
'location_id': int(location_id),
'product_type': product_type['product__product_type'],
})
return Response(data)
|
import os
def locate_resource_file(fname):
return os.environ['HOME'] + '/rif_data/' + fname
|
import scrapy
import unicodedata
import re
import regex
import sqlite3
from scrapy.crawler import CrawlerProcess
class ao3spider(scrapy.Spider):
name = "hpspider"
allowed_domains = ['archiveofourown.org']
custom_settings = {
'DOWNLOAD_DELAY': 5,
'ROBOTSTXT_OBEY': False,
'AUTOTHROTTLE_ENABLED': True,
'COOKIES_ENABLED': False
}
def start_requests(self):
url = "https://archiveofourown.org/works?utf8=%E2%9C%93&work_search%5Bsort_column%5D=revised_at&work_search%5Bother_tag_names%5D=&work_search%5Bexcluded_tag_names%5D=&work_search%5Bcrossover%5D=F&work_search%5Bcomplete%5D=&work_search%5Bwords_from%5D=&work_search%5Bwords_to%5D=&work_search%5Bdate_from%5D=&work_search%5Bdate_to%5D=&work_search%5Bquery%5D=&work_search%5Blanguage_id%5D=en&commit=Sort+and+Filter&tag_id=Harry+Potter+-+J*d*+K*d*+Rowling"
yield scrapy.Request(url=url, callback=self.parse)
def parse(self,response):
current_page = response.xpath('//ol[@class="pagination actions"]//li/span[@class="current"]/text()').extract()
self.logger.debug("current page: %s", current_page)
next_page = response.xpath('//a[@rel="next"]/@href').get()
if next_page:
self.logger.debug('next search page: %s', next_page)
if '5000' in current_page: # hier begrenze ich die gescrapten fanfictions auf eine bestimmte Anzahl
return
yield response.follow(next_page, self.parse)
story_urls = response.xpath('//li/div/h4/a[1]/@href').getall()
for story_url in story_urls:
self.logger.debug('fanfic link: %s', story_url)
yield response.follow(url=story_url + '?view_full_work=true', callback=self.parse_fanfic)
def parse_fanfic(self, response):
confirmation = response.xpath('//a[text()="Proceed"]')
if confirmation: # Warnung ignorieren
self.logger.debug('Adult content, confirmation needed!')
href = confirmation.attrib['href']
yield response.follow(href, self.parse_fanfic)
return
ao3id = re.search(r'(?:/works/)([0-9]+)', response.url).group(1)
title = response.xpath('//h2[@class="title heading"]/text()').get()
if title is not None:
title = title.strip()
data = response.xpath('//*[@id="chapters"]//p/text()').getall()
data = " ".join(data)
data = unicodedata.normalize("NFKD", data)
data = data.replace(r'\n',' ')
data = data.replace(r'\t','')
data = data.replace(r'\s','')
data = data.replace(r'(See the end of the chapter for .)','')
data = data.strip()
content = data
author = response.xpath('//h3/a[@rel="author"]/text()').getall()
author = ", ".join(author)
metagroup = response.xpath('//dl[@class="work meta group"]')
tags = metagroup.css('dd.freeform.tags li ::text').getall()
tags = ", ".join(tags)
rating = response.xpath('//dd[@class="rating tags"]/ul/li/a/text()').get()
category = response.xpath('//dd[@class="category tags"]/ul/li/a/text()').get()
relationships = response.xpath('//dd[@class="relationship tags"]/ul//li/a/text()').getall()
relationships = ", ".join(relationships)
warnings = response.xpath('/dd[@class="warning tags"]/ul//li/a/text()').getall()
warnings = ", ".join(warnings)
characters = response.xpath('//dd[@class="character tags"]/ul//li/a/text()').getall()
characters = ", ".join(characters)
words = response.xpath('//dd[@class="words"]/text()').get()
chapters = response.xpath('//dd[@class="chapters"]/text()').get()
result = [ao3id, title, author, rating, warnings, relationships, characters, tags, content, words, chapters]
cursor = db.cursor()
cursor.execute("""
INSERT INTO HP
(AO3ID, Title, Author, Rating, Warnings, Relationships, Characters, Tags, Content, Words, Chapters)
VALUES(?, ?, ?, ?, ?, ?, ? , ? , ?, ?, ?)""", result)
db.commit()
db = sqlite3.connect("fanfictions.db")
db.row_factory = sqlite3.Row
cursor = db.cursor()
cursor.execute("""
CREATE TABLE HP(
ID INTEGER PRIMARY KEY,
AO3ID INT,
Title TEXT,
Author TEXT,
Rating TEXT,
Warnings TEXT,
Relationships TEXT,
Characters TEXT,
Tags TEXT,
Content TEXT,
Words INT,
Chapters TEXT
);
""")
db.commit()
process = CrawlerProcess()
process.crawl(ao3spider)
process.start() |
import pygame
import random
from pygame import *
pygame.init()
white = (255, 255, 255)
yellow = (255, 255, 102)
black = (0, 0, 0)
red = (213, 50, 80)
green = (0, 255, 0)
blue = (50, 153, 213)
purple = (184, 61, 186)
dis_width = 600
dis_height = 400
dis = pygame.display.set_mode((dis_width, dis_height))
pygame.display.set_caption('Snake Ga... Wait, what am I doing... what is this?')
clock = pygame.time.Clock()
snake_block = 10
# size of snake
snake_speed = 15
# speed of snake
highscore = 0
#Highscore
font_style = pygame.font.SysFont("bahnschrift", 25)
# game lost text size
score_font = pygame.font.SysFont("Agency FB", 35)
# score text size
def Your_score(score):
value = score_font.render("Your Score: " + str(score), True, yellow)
dis.blit(value, [0, 0])
# score tracker
def our_snake(snake_block, snake_list):
for x in snake_list:
pygame.draw.rect(dis, black, [x[0], x[1], snake_block, snake_block])
def message(msg, color):
mesg = font_style.render(msg, True, color)
dis.blit(mesg, [dis_width / 6, dis_height / 3])
def message2(score):
value = score_font.render("Your Highscore was: " + str(score), True, white)
dis.blit(value, [dis_width / 5, dis_height / 2])
def gameLoop():
game_over = False
game_close = False
x1 = dis_width / 2
y1 = dis_height / 2
x1_change = 0
y1_change = 0
# change of place on screen
snake_List = []
Length_of_snake = 1
# number of snake blocks
global snake_speed
snake_speed = 10
#snake speed
foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
#food block
food2x = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
food2y = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
food3x = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
food3y = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
bgx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
bgy = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
bg2x = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
bg2y = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
bg3x = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
bg3y = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
bg4x = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
bg4y = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
bg5x = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
bg5y = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
bg6x = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
bg6y = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
bg7x = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
bg7y = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
bg8x = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
bg8y = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
bg9x = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
bg9y = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
bg10x = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
bg10y = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
# Decrise score
cgx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
cgy = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
# game over
srx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
sry = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
Music = True
Sound_effect_Red = mixer.Sound("Red.wav")
Sound_effect_Green = mixer.Sound("Green.wav")
Sound_effect_White = mixer.Sound("White.wav")
Sound_effect_Purple = mixer.Sound("Purple.wav")
Sound_effect_lost = mixer.Sound("Lost.wav")
# music & sounds
while not game_over:
if Music== True:
background_music = mixer.Sound("Background.wav")
background_music.play()
background_music.set_volume(0.3)
Music = False
# Background music
while game_close == True:
dis.fill(blue)
global highscore
if Length_of_snake - 1 > highscore:
highscore = Length_of_snake - 1
#highscore
message("You Lost! Press C-Play Again or Q-Quit", red)
message2(highscore)
Your_score(Length_of_snake - 1)
pygame.display.update()
# Displays & Messages
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
game_over = True
game_close = False
if event.key == pygame.K_c:
gameLoop()
# End screen input
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x1_change = -snake_block
y1_change = 0
elif event.key == pygame.K_RIGHT:
x1_change = snake_block
y1_change = 0
elif event.key == pygame.K_UP:
y1_change = -snake_block
x1_change = 0
elif event.key == pygame.K_DOWN:
y1_change = snake_block
x1_change = 0
elif event.key == pygame.K_ESCAPE:
game_over = True
# Game input
if x1 >= dis_width or x1 < 0 or y1 >= dis_height or y1 < 0:
game_close = True
x1 += x1_change
y1 += y1_change
dis.fill(blue)
pygame.draw.rect(dis, green, [foodx, foody, snake_block, snake_block])
pygame.draw.rect(dis, green, [food2x, food2y, snake_block, snake_block])
pygame.draw.rect(dis, green, [food3x, food3y, snake_block, snake_block])
# draws the add number food
pygame.draw.rect(dis, red, [bgx, bgy, snake_block, snake_block])
pygame.draw.rect(dis, red, [bg2x, bg2y, snake_block, snake_block])
pygame.draw.rect(dis, red, [bg3x, bg3y, snake_block, snake_block])
pygame.draw.rect(dis, red, [bg4x, bg4y, snake_block, snake_block])
pygame.draw.rect(dis, red, [bg5x, bg5y, snake_block, snake_block])
pygame.draw.rect(dis, red, [bg6x, bg6y, snake_block, snake_block])
pygame.draw.rect(dis, red, [bg7x, bg7y, snake_block, snake_block])
pygame.draw.rect(dis, red, [bg8x, bg8y, snake_block, snake_block])
pygame.draw.rect(dis, red, [bg9x, bg9y, snake_block, snake_block])
pygame.draw.rect(dis, red, [bg10x, bg10y, snake_block, snake_block])
# draws reduce score food
pygame.draw.rect(dis, purple, [cgx, cgy, snake_block, snake_block])
# draws game over food
pygame.draw.rect(dis, white, [srx, sry, snake_block, snake_block])
snake_Head = []
snake_Head.append(x1)
snake_Head.append(y1)
snake_List.append(snake_Head)
# The players character on the screen
if len(snake_List) > Length_of_snake:
del snake_List[0]
for x in snake_List[:-1]:
if x == snake_Head:
game_close = True
# if snake crash in snake lose game
our_snake(snake_block, snake_List)
# game character
Your_score(Length_of_snake - 1)
# score
pygame.display.update()
if x1 == foodx and y1 == foody:
foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
Length_of_snake += 1
Sound_effect_Green.play()
snake_speed += 1
if x1 == food2x and y1 == food2y:
food2x = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
food2y = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
Length_of_snake += 1
Sound_effect_Green.play()
snake_speed += 1
if x1 == food3x and y1 == food3y:
food3x = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
food3y = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
Length_of_snake += 1
Sound_effect_Green.play()
snake_speed += 1
# food blocks and faster speed
if x1 == bgx and y1 == bgy:
bgx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
bgy = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
Length_of_snake -= 1
snake_speed -= 1
Sound_effect_Red.play()
if x1 == bg2x and y1 == bg2y:
bg2x = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
bg2y = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
Length_of_snake -= 1
snake_speed -= 1
Sound_effect_Red.play()
if x1 == bg3x and y1 == bg3y:
bg3x = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
bg3y = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
Length_of_snake -= 1
snake_speed -= 1
Sound_effect_Red.play()
if x1 == bg4x and y1 == bg4y:
bg4x = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
bg4y = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
Length_of_snake -= 1
snake_speed -= 1
Sound_effect_Red.play()
if x1 == bg5x and y1 == bg5y:
bg5x = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
bg5y = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
Length_of_snake -= 1
snake_speed -= 1
Sound_effect_Red.play()
if x1 == bg6x and y1 == bg6y:
bg6x = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
bg6y = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
Length_of_snake -= 1
snake_speed -= 1
Sound_effect_Red.play()
if x1 == bg7x and y1 == bg7y:
bg7x = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
bg7y = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
Length_of_snake -= 1
snake_speed -= 1
Sound_effect_Red.play()
if x1 == bg8x and y1 == bg8y:
bg8x = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
bg8y = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
Length_of_snake -= 1
snake_speed -= 1
Sound_effect_Red.play()
if x1 == bg9x and y1 == bg9y:
bg9x = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
bg9y = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
Length_of_snake -= 1
snake_speed -= 1
Sound_effect_Red.play()
if x1 == bg10x and y1 == bg10y:
bg9x = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
bg9y = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
Length_of_snake -= 1
snake_speed -= 1
Sound_effect_Red.play()
# score reduce blocks
if x1 == cgx and y1 == cgy:
game_close = True
if x1 == srx and y1 == sry:
srx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
sry = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
Sound_effect_White.play()
if snake_speed > 10:
snake_speed = snake_speed / 2
# Reduce speed blocks
if -5 >= (Length_of_snake - 1):
game_close = True
if game_close == True:
background_music.stop()
if x1 == cgx and y1 == cgy:
Sound_effect_Purple.play()
else:
Sound_effect_lost.play()
clock.tick(snake_speed)
pygame.quit()
quit()
gameLoop()
|
import time
from Util_new import Tag, Option, SubType, setTmp, getTmp, setFound, isFound, isComboActive, setCombo, split, getPlayerID, gameId, setCurState, GameState, setWaiting, setMulligan
from Board import *
from Cards_new import *
from Bachelor.Ba.Util_new import getCurState, Player, EffectTime, Cardtype
from types import IntType
from Play import *
def setMyHero(Id, CardId):
global MY_HERO
MY_HERO = createCard(Id, CardId)
addMinionToMyCards(MY_HERO, 0)
def setMyHeroPower(Id, CardId):
global MY_HERO_POWER
MY_HERO_POWER = createCard(Id, CardId)
addHandcardToMyCards(MY_HERO_POWER, 0)
def setEnemyHero(Id, CardId):
global E_HERO
E_HERO = createCard(Id, CardId)
addMinionToEnemyCards(E_HERO, 0)
def setEnemyHeroPower(Id, CardId):
global E_HERO_POWER
E_HERO_POWER = createCard(Id, CardId)
addHandcardToEnemyCards(E_HERO_POWER, 0)
def setHeroPower(playerId, Id, CardId):
if isMe(getPlayerID()):
setMyHeroPower(Id, CardId)
else:
setEnemyHeroPower(Id, CardId)
def setHero(playerId, Id, CardId):
if isMe(getPlayerID()):
setMyHero(Id, CardId)
else:
setEnemyHero(Id, CardId)
def setPlayerName(line):
players = getPlayers()
Entity = split(line, 'Entity=', ' tag=')
if Entity == getMe():
players[int(split(line, 'value=', '\n'))] = getMe()
else:
players[int(split(line, 'value=', '\n'))] = Entity
def setMyMana(count):
global MY_MANA
MY_MANA = count
def setEnemyMana(count):
global E_MANA
E_MANA = count
def getEnemyPlayerName():
if isMe(1):
return getPlayers()[2]
else:
return getPlayers()[1]
def addMulliganCards(cardInfo, pos):
addHandcardToMyCards(createCard(cardInfo[1], cardInfo[0]), pos)
def changingMulliganCard(cardInfo, line):
Id = gameId(line)
removeMyCardByIngameId(Id)
addHandcardToMyCards(createCard(cardInfo[1], cardInfo[0]), int(split(line, 'zonePos=', ' ')))
MY_MULLIGAN_DONE = False
def isMyMulliganStateDone():
global MY_MULLIGAN_DONE
return MY_MULLIGAN_DONE
def setMyMulliganStateDone(State):
global MY_MULLIGAN_DONE
MY_MULLIGAN_DONE = State
ENEMY_MULLIGAN_DONE = False
def isEnemyMulliganStateDone():
global ENEMY_MULLIGAN_DONE
return ENEMY_MULLIGAN_DONE
def setEnemyMulliganStateDone(State):
global ENEMY_MULLIGAN_DONE
ENEMY_MULLIGAN_DONE = State
def changingToTurns(line):
time.sleep(0.5)
if split(line, 'Entity=', ' tag') == getMe():
setMyMulliganStateDone(True)
else:
setEnemyMulliganStateDone(True)
if isMyMulliganStateDone() and isEnemyMulliganStateDone():
if getMyHandcardCount() == 3:
setCurState(GameState.MY_TURN)
print 'now reading My Turn'
else:
setCurState(GameState.ENEMY_TURN)
print 'now reading Enemy Turn'
def MulliganStates(line, state):
if not len(getPlayers()) == 2 and split(line, 'Entity=', ' tag') == getMe():
if state == 'INPUT':
setMulligan(True)
print 'setMul'
elif state == 'DEALING':
setWaiting(True)
def MulliganCardsChanging():
time.sleep(17)
MulliganChoosing()
setMulligan(False)
time.sleep(2)
MulliganConfirm()
def EnemyCardPlayed(playingLines):
card = None
for line in playingLines:
if 'SubType=PLAY' in line and 'name' in line.split('SubType=PLAY')[0]:
print 'Played Hero Power'
break
elif 'SHOW_ENTITY' in line:
card = createCard(split(line, 'CardID=', '\n'))
card._ingameID = gameId(line)
if card is not None and 'ZONE_POSITION' in line:
if card._cardtype == Cardtype.MINION:
print 'Played', card._name
addMinionToEnemyCards(card, int(split(line, 'value=', '\n')))
card = None
break
elif card._cardtype == Cardtype.SPELL:
print 'Played', card._name
card = None
break
elif card._cardtype == Cardtype.WEAPON:
print 'Played', card._name
card = None
break
elif card._cardtype == Cardtype.SECRET:
print 'Played', card._name
card = None
break
elif card is not None and '- ACTION_END' in line:
if card._cardtype == Cardtype.MINION:
addMinionToEnemyCards(card, 1)
print 'Played', card._name
else:
print 'Player', card._name
def readingFULL_ENTITY(lines):
card = None
isMyCard = False
for l in lines:
if 'CREATOR' in l:
if card._type == Cardtype.ENCHANTMENT:
return Cardtype.ENCHANTMENT
elif 'FULL_ENTITY' in l and not 'CardID=\n' in l:
idx = split(l, 'ID=', ' ')
cardID = split(l, 'CardID=', '\n')
card = createCard(cardID)
card._ingameID = idx
elif 'tag=ZONE' in l:
zone = split(l, 'value=', '\n')
card._zone = zone
elif 'tag=CONTROLLER' in l:
isMyCard = isMe(int(split(l, 'value=', '\n')))
elif 'tage=ZONE_POSITION' in l:
card.set_pos(int(split(l, 'value=', '\n')))
elif 'SHOW_ENTITY' in l:
ingameID = int(split(l, 'ID=', ' '))
cardID = split(l, 'CardID=', '\n')
card = createCard(cardID)
card._ingameID = ingameID
card._zone = Zone.SETASIDE
if isMyCard and card._zone == Zone.PLAY:
addMinionToMyCards(card, card.get_pos())
elif not isMyCard and card._zone == Zone.PLAY:
addMinionToEnemyCards(card, card.get_pos())
elif isMyCard and card._zone == Zone.HAND:
addHandcardToMyCards(card._id, card.get_pos, card._ingameID)
elif not isMyCard and card._zone == Zone.HAND:
pass
def tagging(card, tag, value):
if tag == 'HEALTH':
card._health = value
elif tag == 'ATK':
card._attack = value
elif tag == 'TAUNT':
card.editAbility(Ability.TAUNT, value)
elif tag == 'DIVINE_SHIELD':
card.editAbility(Ability.DIVINESHIELD, value)
elif tag == 'WINDFURY':
card.editAbility(Ability.WINDFURY, value)
elif tag == 'STEALTH':
card.editAbility(Ability.STEALTH, value)
elif tag == 'CHARGE':
card.editAbility(Ability.CHARGE, value)
def toXml(target, Id, tag, value, time):
caster = getCardByIngameId(Id)
if Ability.BATTLECRY in caster._ability:
continue
else:
if caster._cardtype == Cardtype.SECRET:
time = EffectTime.ON_ACTIVATE
elif caster._cardtype == Cardtype.MINION:
time = EffectTime.ON_BOARD
if tag == Tag.TAUNT or tag == Tag.DIVINESHIELD or tag == Tag.WINDFURY or tag == Tag.STEALTH or tag == Tag.CHARGE:
if value == 0:
XML_write(Id, (Effect.DEBUFF, value, tag, time))
else:
XML_write(Id, (Effect.BUFF, value, tag, time))
elif tag == Tag.HEALTH or tag == Tag.ATTACK:
diff = 0
if tag == Tag.HEALTH:
diff = value - target._health
else:
diff = value - target._attack
if diff > 0:
XML_write(Id, (Effect.BUFF, diff, tag, time))
else:
XML_write(Id, (Effect.DEBUFF, diff,tag ,time))
def Full_Entity(lines, time):
i = 0
start = None
end = None
enchanted = []
while i < len(lines):
if 'FULL_ENTITY' in lines[i]:
start = i
elif 'CREATOR' in lines[i] and start is not None:
Id = split(lines[i], 'value=', '\n')
end = i
typ = readingFULL_ENTITY(lines[start:end])
start = None
end = None
if typ == Cardtype.ENCHANTMENT and 'ATTACHED' in lines[i+1]:
enchanted.append(int(split(lines[i+1], 'value=', '\n')))
if len(enchanted) > 0 and 'id=' in lines[i] and 'cardId=' in lines[i]:
idx = gameId(lines[i])
if id in enchanted:
tag = split(lines[i], 'tag=', ' ')
value = int(split(lines[i], 'value=', '\n'))
card = getCardByIngameId(idx)
toXml(card, Id, tag, value, time)
tagging(card, tag, value)
def readTrigger(lines):
for l in lines:
if 'SubType=TRIGGER' in l:
if getMyCardByIngameId(gameId(l))._zone == Zone.GRAVEYARD:
Full_Entity(lines, EffectTime.ON_DEATH)
def readDeaths(lines):
for l in lines:
if 'GRAVEYARD' in l:
if isMe(controllerID(l)):
card = getMyCardByIngameId(gameId(l))
card._zoone = Zone.GRAVEYARD
reorderMyMinionsOnBoard(card.get_pos())
else:
card = getEnemyCardByIngameId(gameId(l))
card._zone = Zone.GRAVEYARD
reorderEnemyMinionsOnBoard(card.get_pos())
def SubTypeAction(Subtype, lines):
if Subtype == SubType.DEATH:
readDeaths(lines)
elif Subtype == SubType.PLAY:
if getCurState() == GameState.ENEMY_TURN:
EnemyCardPlayed(lines)
elif getCurState() == GameState.MY_TURN:
Full_Entity(lines, EffectTime.ON_PLAY)
if not isComboActive():
setCombo(True)
elif Subtype == SubType.TRIGGER:
readTrigger(lines)
def interpretingSubType(idx, cont, Subtype):
i = idx
#jump = 0
while i < (len(cont) - 1):
i += 1
if '- ACTION_END' in cont[i]:
setFound(True)
SubTypeAction(Subtype, cont[idx:(i+1)])
break
if Subtype == SubType.PLAY:
if isFound():
setFound(False)
else:
setTmp(cont[idx:])
setWaiting(True)
print 'Action end Not found'
return i - idx
def interpretingSubType2(cont, Subtype):
i = 0
while i < len(cont):
if '- ACTION_END' in cont[i]:
setFound(True)
setWaiting(False)
SubTypeAction(Subtype, getTmp()+cont[:(i + 1)])
break
i += 1
if isFound():
setFound(False)
return i
else:
setTmp(getTmp() + cont)
return len(cont) - 1
def readingMana(line, player):
if player == Player.ME:
setMyMana(int(split(line, 'value=', '\n')))
else:
setEnemyMana(int(split(line, 'value=', '\n')))
def drawCard(line):
addHandcardToMyCards(createCard(gameId(line), split(line, 'CardID=', '\n')), getMyHandcardCount() + 1)
def attack(lines):
attacker = None
target = None
for l in lines:
if 'SubType=ATTACK' in l:
a, t = l.split('ATTACK')
target = getCardByIngameId(gameId(t))
attacker = getCardByIngameId(gameId(a))
target.takes_Damage(attacker._attack)
attacker.takes_Damage(target._attack)
OPTIONS = []
def addOption(option):
global OPTIONS
OPTIONS.append(option)
def getOption(nr):
global OPTIONS
return OPTIONS[nr]
def getOptions():
global OPTIONS
return OPTIONS
def clearOptions():
global OPTIONS
OPTIONS = []
def showOptions(optionLines):
i = 0
parameter1 = None
parameter2 = None
targets = []
try:
while i < len(optionLines):
if 'option' in optionLines[i]:
output = str(split(optionLines[i], '() - ', ' type')) + ': '
if parameter1 is not None:
if len(targets) != 0:
addOption((parameter1, parameter2, targets))
else:
addOption((parameter1, parameter2))
parameter1 = None
parameter2 = None
targets = []
if 'END_TURN' in optionLines[i]:
output += 'End Turn'
addOption((Option.END, None))
elif 'POWER' in optionLines[i] and 'zone=HAND' in optionLines[i]:
output += 'Play ' +str(split(optionLines[i], 'name=', ' id'))
parameter1 = gameId(optionLines[i])
parameter2 = Option.PLAY
elif 'POWER' in optionLines[i] and 'zone=DECK' in optionLines[i]:
output += 'Play ' + getMyCardByIngameId(gameId(optionLines[i]))._name
elif 'POWER' in optionLines[i] and 'zone=PLAY' in optionLines[i] and 'zonePos=0' in optionLines[i]:
parameter1 = gameId(optionLines[i])
if 'cardId=HERO' in optionLines[i]:
output += 'Hero Attack'
parameter2 = Option.ATTACK
else:
output += 'Play Hero Power'
parameter2 = Option.PLAY
elif 'POWER' in optionLines[i] and 'zone=PLAY' in optionLines[i] and 'zonePos=0' not in optionLines[i]:
output += 'Attack with ' +str(split(optionLines[i], 'name=', ' id'))
parameter1 = gameId(optionLines[i])
parameter2 = Option.ATTACK
if i+4 < len(optionLines):
if 'target' in optionLines[i+4]:
output += '\n \t Possible Targets: '
print output
if 'target' in optionLines[i]:
name = ''
idx = gameId(optionLines[i])
if 'name' in optionLines[i]:
name = str(split(optionLines[i], 'name=', 'id'))
else:
name = getEnemyCardByIngameId(idx)._name
print '\t \t' + name
if type(id) is IntType:
targets.append(idx)
else:
targets.append(gameId(optionLines[i]))
i += 1
if parameter1 is not None:
if len(targets) != 0:
addOption((parameter1, parameter2, targets))
else:
addOption((parameter1, parameter2))
except Exception, e:
print 'showOptions', optionLines[i], e
def findTarget(idx):
try:
cards = getMyCards()
for c in cards:
if cards[c]._zone == Zone.PLAY and cards[c]._ingameID == idx:
return (0, cards[c])
cards = getEnemyCards()
for c in cards:
if cards[c]._zone == Zone.PLAY and cards[c]._ingameID == idx:
return (1, cards[c])
except:
print 'No Target Found'
def choosePlayingCard():
try:
options = getOptions()
toDo = 0
print 'allOptions', options
if len(options) > 1:
toDo = int(random()*len(options) - 1) + 1
else:
EndTurn()
choosenOption = options[toDo]
print 'choosenOption', choosenOption
if choosenOption[0] == Option.End:
EndTurn()
else:
if choosenOption[1] == Option.PLAY:
if len(choosenOption) == 3:
targetIndex = np.random.random_integers(1, len(choosenOption[2])) - 1
target = findTarget(choosenOption[2][targetIndex])
if target[0] == 0:
MinionBoard = getMinionBoard(getMyMinionCount())
else:
MinionBoard = getEnemyMinionBoard(getEnemyMinionCount())
card = getMyCardByIngameId(choosenOption[0])
try:
if card._cardtype == Cardtype.MINION:
playMinionWithTarget(card, 1, getMouseMoveCoords(area(MinionBoard[target[1].get_pos()])))
else:
playHandcard(card, getMouseMoveCoords(area(MinionBoard[target[1].get_pos()])))
except Exception, e:
print 'choosingOption with 3 args' ,e
else:
#randomPos = np.random.random_integers(0,1)
playHandcard(getCardByIngameId(choosenOption[0]), getMouseMoveCoords(area(getMinionBoard(1)[1])))
else:
targetIndex = np.random.random_integers(1, len(choosenOption[2])) - 1
target = findTarget(choosenOption[2][targetIndex])
while target[0] == 0:
targetIndex = np.random.random_integers(1, len(choosenOption[2])) - 1
target = findTarget(choosenOption[2][targetIndex])
drawAttack(getCardByIngameId(choosenOption[0]), target[1])
except Exception, e:
print 'choosePlayingCard:', e |
import threading
import time
from contextlib import contextmanager
class LockManager:
locks = {}
def get(self, key):
thread_id = threading.get_ident()
while self.locks.get(key) not in [None, thread_id, None]:
time.sleep(1)
self.locks[key] = thread_id
def release(self, key):
del self.locks[key]
def is_available(self, key):
thread_id = threading.get_ident()
return self.locks.get(key, thread_id) == thread_id
@contextmanager
def lock(self, key):
thread_id = threading.get_ident()
if self.locks.get(key) == thread_id:
yield
else:
self.get(key)
yield
self.release(key)
|
import operator
from functools import reduce
import os
import math
import pyautogui
from PIL import Image
import fileinput
import time
l={}
p={}
p['30nn']=["ak","aa","qq","kk"]
p['30nns']=[]
p['20nn']=["aa","ak","kk","aq","qq","jj","tt"]
p['20nns']=[]
p['100n']=["aa","kk","qq","jj","tt","99","88","77","66","55","44","33","22","ak","aq","aj","at","9a","8a","7a","6a","5a","4a","kq","jk","kt","jq"]
p['100ns']=["3a","2a","9k","tq","jt"]
p['101n']=["aa","kk","qq","jj","tt","99","88","77","66","55","44","33","22","ak","aq","aj","at","9a","8a","7a","6a","5a","4a","3a","2a","kq","jk","kt","9k","jq"]
p['101ns']=["8k","7k","qt","jt"]
p['102n']=["aa","kk","qq","jj","tt","99","88","77","66","55","44","33","22","ak","aq","aj","at","9a","8a","7a","6a","5a","4a","3a","2a","kq","jk","kt","9k","8k","7k","6k","5k","4k","3k","jq","qt","9q","8q","jt","9j","9t"]
p['102ns']=["2k","7q","6q","5q","8j","7j","8t"]
p['21nn']=["aa","ak","kk","aq","qq","jj","tt"]
p['21nns']=[]
p['111n']=["aa","kk","qq","jj","tt","99","88","77","66","55","44","33","ak","aq","aj","at","9a","8a","7a","kq","jk"]
p['111ns']=["6a","5a","4a","3a","kt","jq"]
p['112n']=["aa","kk","qq","jj","tt","99","88","77","66","55","44","33","ak","aq","aj","at","9a","8a","7a","6a","5a","kq","jk","kt"]
p['112ns']=["4a","3a","2a","9k","jq","qt","jt"]
p['01nn']=["aa","kk","qq","jj","tt","99","88","77","66","55","44","33","22","ak","aq","aj","at","9a","8a","7a","6a","5a","4a","3a","2a","kq","jk","kt","9k","8k","7k","6k","5k","4k","3k","2k","jq","qt","9q","8q","7q","6q","5q","4q","3q","jt","9j","8j","7j","9t","8t","7t","89","79","78"]
p['01nns']=["2q","6j","5j","4j","3j","2j","6t","5t","4t","69","59","68","58","67","57","47","46","56","35","45"]
p['12nn']=["aa","kk","qq","jj","tt","99","88","77","66","55","44","ak","aq","aj","at","9a","kq","jk"]
p['12nns']=["8a","7a"]
p['02nn']=["aa","kk","qq","jj","tt","99","88","77","66","55","44","33","22","ak","aq","aj","at","9a","8a","7a","6a","5a","4a","3a","2a","kq","jk","kt","9k","jq","qt","jt"]
p['02nns']=["8k","7k","6k","5k","4k","3k","9q","8q","9j","8j","7j","9t","8t","7t","89","79","78","68","67","56"]
p['02nb']=["aa","kk","qq","jj","tt","99","88","77","66","55","44","33","22","ak","aq","aj","at","9a","8a","7a","6a","5a","4a","3a","kq","jk","kt","jq","jt"]
p['02nbs']=["2a","9k","8k","7k","qt","9q","8q","9j","8j","8t","9t","89","78"]
locationOfTest="C:/Users/Sree/tester1/"
#create database
filelocation=["","","",""]
filelocation[0]=locationOfTest+"p0.png"
filelocation[1]=locationOfTest+"p1.png"
#filelocation[2]=locationOfTest+"p2.png"
#filelocation[3]=locationOfTest+"p3.png"
filelocationforAllins=[locationOfTest+"allin1.png",locationOfTest+"allin2.png",locationOfTest+"allin3.png"]
filelocationforMyPos=locationOfTest+"mypos.png"
deck=["2","3","4","5","6","7","8","9","t","j","q","k","a"]
####not required
c1=["GREEN","BLUE","RED","GREY"]
ccode=["c","d","h","s"]
GREEN=(32, 137, 28)
BLUE=(21, 89, 153)
RED=(203, 63, 63)
GREY=(82, 82, 82)
DEALT=(180,46,46)
NOTDEALT=(140,125,103)
BUTTON=(233, 184, 108)
NOTBUTTON=(93,34,34)
TURN=(253, 244, 170)
NOTTURN1=(73, 73, 73)
NOTTURN2=(42,43,45)
class Table(object):
def __init__(self):
self.myCards = []
self.allinCount=0 #can be 0,1,2,3
self.myPosition=0 #0=big 1=small 2=none
self.curDecision=2 #0=fold 1=allin 2=new
self.tableno=-1
self.guyAllin='n'
self.button='n'
buttonPixelPosition=()
yellowPixelPosition=()
allinClickPosition = ()
allinPixelPosition =()
foldClickPosition= ()
player1Pos=()
player2Pos=()
player3Pos=()
myPos=()
rightguy1=()
rightguy2=()
def buttonIsMine(self):
print('Checking if dealt')
color1=pyautogui.pixel(self.buttonPixelPosition[0],self.buttonPixelPosition[1])
color2=NOTBUTTON
Diff=[0,0]
Diff[0]=abs(color1[0] - color2[0])+abs(color1[1] - color2[1])+abs(color1[2] - color2[2])
color2=BUTTON
Diff[1]=abs(color1[0] - color2[0])+abs(color1[1] - color2[1])+abs(color1[2] - color2[2])
print(Diff[0])
print(Diff[1])
c=Diff.index(min(Diff))
return c
def analyse(self):
#card1
print('Analysing')
pyautogui.screenshot(filelocation[0],region=self.myCards[0].position)
pixels=pyautogui.pixel(self.myCards[0].pixelposition[0],self.myCards[0].pixelposition[1])
col=findCardColor(pixels)
val=findCardDeck(col,filelocation[0],0)
self.myCards[0].suit=col
self.myCards[0].value=val
print('Card1 done')
#card2
pyautogui.screenshot(filelocation[1],region=self.myCards[1].position)
pixels=pyautogui.pixel(self.myCards[1].pixelposition[0],self.myCards[1].pixelposition[1])
col=findCardColor(pixels)
val=findCardDeck(col,filelocation[1],1)
self.myCards[1].suit=col
self.myCards[1].value=val
print('Card2 done')
#myposition
pyautogui.screenshot(filelocationforMyPos,region=self.myPos)
self.getMyPosition()
print('MyPos done ')
#allins
#pyautogui.screenshot(filelocationforAllins[0],region=self.player1Pos)
#pyautogui.screenshot(filelocationforAllins[1],region=self.player2Pos)
#pyautogui.screenshot(filelocationforAllins[2],region=self.player3Pos)
#compare and decide
self.countAllins()
print('Allin done ')
def hasNothing(self,g):
if(g==0):
print('Checking if hasNothing')
Diff=[0,0]
color1=pyautogui.pixel(self.nothing1PixelPos[0],self.nothing1PixelPos[1])
color2=SOMETHING
Diff[0]=abs(color1[0] - color2[0])+abs(color1[1] - color2[1])+abs(color1[2] - color2[2])
color2=NOTHING
Diff[1]=abs(color1[0] - color2[0])+abs(color1[1] - color2[1])+abs(color1[2] - color2[2])
c=Diff.index(min(Diff))
if(c==1):
print('NOTHING')
return True
else:
print('SOMETHING')
return False
if(g==1):
print('Checking if hasNothing')
Diff=[0,0]
color1=pyautogui.pixel(self.nothing2PixelPos[0],self.nothing2PixelPos[1])
color2=SOMETHING
Diff[0]=abs(color1[0] - color2[0])+abs(color1[1] - color2[1])+abs(color1[2] - color2[2])
color2=NOTHING
Diff[1]=abs(color1[0] - color2[0])+abs(color1[1] - color2[1])+abs(color1[2] - color2[2])
c=Diff.index(min(Diff))
if(c==1):
print('NOTHING')
return True
else:
print('SOMETHING')
return False
if(g==2):
print('Checking if hasNothing')
Diff=[0,0]
color1=pyautogui.pixel(self.nothing3PixelPos[0],self.nothing3PixelPos[1])
color2=SOMETHING
Diff[0]=abs(color1[0] - color2[0])+abs(color1[1] - color2[1])+abs(color1[2] - color2[2])
color2=NOTHING
Diff[1]=abs(color1[0] - color2[0])+abs(color1[1] - color2[1])+abs(color1[2] - color2[2])
c=Diff.index(min(Diff))
if(c==1):
print('NOTHING')
return True
else:
print('SOMETHING')
return False
return True
def hasButton(self,g):
if(g==0):
print('Checking if hasButton')
Diff=[0,0]
color1=pyautogui.pixel(self.button1PixelPos[0],self.button1PixelPos[1])
color2=NOTBUTTON
Diff[0]=abs(color1[0] - color2[0])+abs(color1[1] - color2[1])+abs(color1[2] - color2[2])
color2=BUTTON
Diff[1]=abs(color1[0] - color2[0])+abs(color1[1] - color2[1])+abs(color1[2] - color2[2])
c=Diff.index(min(Diff))
if(c==1):
print('BUTTON')
return True
else:
print('NO BUTTON')
return False
if(g==1):
print('Checking if hasButton')
Diff=[0,0]
color1=pyautogui.pixel(self.button2PixelPos[0],self.button2PixelPos[1])
color2=NOTBUTTON
Diff[0]=abs(color1[0] - color2[0])+abs(color1[1] - color2[1])+abs(color1[2] - color2[2])
color2=BUTTON
Diff[1]=abs(color1[0] - color2[0])+abs(color1[1] - color2[1])+abs(color1[2] - color2[2])
c=Diff.index(min(Diff))
if(c==1):
print('BUTTON')
return True
else:
print('NO BUTTON')
return False
if(g==2):
print('Checking if hasButton')
Diff=[0,0]
color1=pyautogui.pixel(self.button3PixelPos[0],self.button3PixelPos[1])
color2=NOTBUTTON
Diff[0]=abs(color1[0] - color2[0])+abs(color1[1] - color2[1])+abs(color1[2] - color2[2])
color2=BUTTON
Diff[1]=abs(color1[0] - color2[0])+abs(color1[1] - color2[1])+abs(color1[2] - color2[2])
c=Diff.index(min(Diff))
if(c==1):
print('BUTTON')
return True
else:
print('NO BUTTON')
return False
return True
def getMyPosition(self):
im1=Image.open(filelocationforMyPos)
h1 = im1.histogram()
rms=[]
for i in range(0,3):
im2=Image.open(locationOfTest+"database/"+"myPos"+str(i)+".png")
h2 = im2.histogram()
rms.append(math.sqrt(reduce(operator.add,map(lambda a,b: (a-b)**2, h1, h2))/len(h1)) )
c=rms.index(min(rms))
self.myPosition=c
print('MyPos is '+str(c))
def countAllins(self):
n=0
guyAllin='n'
button='n'
if(self.myPosition==0):#BIG BLIND
arr=[0,0,0]
pyautogui.screenshot(filelocationforAllins[0],region=self.player1Pos)
pyautogui.screenshot(filelocationforAllins[1],region=self.player2Pos)
pyautogui.screenshot(filelocationforAllins[2],region=self.player3Pos)
for index in range(0,len(filelocationforAllins)):
im1=Image.open(filelocationforAllins[index])
h1 = im1.histogram()
im2=Image.open(locationOfTest+"database/"+"allin"+".png")
h2 = im2.histogram()
rms=(math.sqrt(reduce(operator.add,map(lambda a,b: (a-b)**2, h1, h2))/len(h1)) )
if(rms<6):
n=n+1
arr[index]=1
if(n==3):
print('Allin is 3')
if(n==2):
print('Allin is 2')
if(n==1):
print('Allin is 1. Checking which guy...')
for index in range(0,len(arr)):
item=arr[index]
if(item==1):
print('Guy at '+str(item)+' is allin')
guyAllin=str(index)
if(guyAllin==2):
cp='A'
else:
if(not(self.hasButton(guyAllin))):
if(guyAllin==0):
cp='C'
if(guyAllin==1):
cp='A'
else:
if(self.hasNothing(guyAllin)):
cp='B'
else:
cp='A'
if(n==0):
print('Allin is 0')
#BIG BLIND DONE. RETURN NO. OF ALLINS AND POSITION OF GUY ALLIN
if(self.myPosition==1):#SMALL BLIND
arr=[0,0,0]
pyautogui.screenshot(filelocationforAllins[1],region=self.player2Pos)
pyautogui.screenshot(filelocationforAllins[2],region=self.player3Pos)
for index in range(0,len(filelocationforAllins)):
if(index==0):#DON'T CHECK LEFT GUY NOW
continue
im1=Image.open(filelocationforAllins[index])
h1 = im1.histogram()
im2=Image.open(locationOfTest+"database/"+"allin"+".png")
h2 = im2.histogram()
rms=(math.sqrt(reduce(operator.add,map(lambda a,b: (a-b)**2, h1, h2))/len(h1)) )
if(rms<6):
n=n+1
arr[index]=1
if(n==3):#SHOULD NOT HAPPEN
print('Allin is 3')
if(n==2):
print(arr)
print('Allin is 2')
if(n==1):
print('Allin is 1. Checking which guy...')
for index in range(0,len(arr)):
item=arr[index]
if(item==1):
print('Guy at '+str(item)+' is allin')
guyAllin=str(index)
if(guyAllin==2):
cp='A'
if(guyAllin==1):
if(self.hasButton(guyAllin)):
cp='A'
else:
cp='B'
if(n==0):
print('Allin is 0')
#SMALL BLIND DONE. RETURN NO. OF ALLINS AND POSITION OF GUY ALLIN
if(self.myPosition==2):#NONE
arr=[0,0,0]
pyautogui.screenshot(filelocationforAllins[2],region=self.player3Pos)
if(self.buttonIsMine()):
for index in range(0,len(filelocationforAllins)):
if(index==0 or index==1):#DON'T CHECK LEFT OR TOP GUY NOW
continue
im1=Image.open(filelocationforAllins[index])
h1 = im1.histogram()
im2=Image.open(locationOfTest+"database/"+"allin"+".png")
h2 = im2.histogram()
rms=(math.sqrt(reduce(operator.add,map(lambda a,b: (a-b)**2, h1, h2))/len(h1)) )
if(rms<6):
n=n+1
arr[index]=1
if(n==3):#SHOULD NOT HAPPEN
print('Allin is 3')
if(n==2):#SHOULD NOT HAPPEN
print('Allin is 2')
if(n==1):
print('Allin is 1')
if(n==0):
print('Allin is 0')
else:
button='b'
n=0
print('Final allins is '+str(n))
self.button=button
self.allinCount=n
self.guyAllin=str(guyAllin)
def isDealt(self):
#check if allin button exists in the region using rms
print('Checking if dealt')
color1=pyautogui.pixel(self.allinPixelPosition[0],self.allinPixelPosition[1])
color2=NOTDEALT
Diff=[0,0]
Diff[0]=abs(color1[0] - color2[0])+abs(color1[1] - color2[1])+abs(color1[2] - color2[2])
color2=DEALT
Diff[1]=abs(color1[0] - color2[0])+abs(color1[1] - color2[1])+abs(color1[2] - color2[2])
print(Diff[0])
print(Diff[1])
c=Diff.index(min(Diff))
if(c==1):
print('Dealt for once !!')
print('Checking if dealt again')
time.sleep(1)
color1=pyautogui.pixel(self.allinPixelPosition[0],self.allinPixelPosition[1])
color2=NOTDEALT
Diff=[0,0]
Diff[0]=abs(color1[0] - color2[0])+abs(color1[1] - color2[1])+abs(color1[2] - color2[2])
color2=DEALT
Diff[1]=abs(color1[0] - color2[0])+abs(color1[1] - color2[1])+abs(color1[2] - color2[2])
print(Diff[0])
print(Diff[1])
c=Diff.index(min(Diff))
if(c==1):
print('Dealt confirmed twice')
#time.sleep(1)
return 1
else:
print('Not Dealt NOT confirmed twice')
return 0
else:
print('Not Dealt !!')
return 0
def isDealt1(self):
#check if allin button exists in the region using rms
print('Checking if dealt')
Diff=[0,0,0]
color1=pyautogui.pixel(self.yellowPixelPosition[0],self.yellowPixelPosition[1])
color2=NOTTURN1
Diff[0]=abs(color1[0] - color2[0])+abs(color1[1] - color2[1])+abs(color1[2] - color2[2])
color2=NOTTURN2
Diff[2]=abs(color1[0] - color2[0])+abs(color1[1] - color2[1])+abs(color1[2] - color2[2])
color2=TURN
Diff[1]=abs(color1[0] - color2[0])+abs(color1[1] - color2[1])+abs(color1[2] - color2[2])
c=Diff.index(min(Diff))
if(c==1):
print('Dealt')
return 1
else:
print('Not Dealt !!')
return 0
def curScenario(self): #complete
a=self.allinCount #0,1,2,3
b=self.myPosition #0=big 1=small 2=none
c=self.guyAllin
d=self.button
myScenario=str(a)+str(b)+str(c)+str(d)
print('Scenario is '+myScenario)
return myScenario
class Card(): #complete
suit = ""
value = ""
position = ()
pixelposition=()
def compare(self,t):
print('Comparing cards')
if(t.suit==self.suit and t.value==self.value):
print('Equal')
return 1
else:
print('Unequal')
return 0
tables=[]
################################################initialization done##############################################
table1=Table()
card1=Card()
table1.tableno=0
table1.buttonPixelPosition=(281,481)
table1.yellowPixelPosition=(484,605)
table1.myPos=(305,477,34,12)
table1.player1Pos=(35,321,45,21)
table1.player2Pos=(311, 178,45,21)
table1.player3Pos=(588, 320,45,21)
card1.position=(287,503,53,40) ###FILL
card1.pixelposition=(330,506) ###FILL
card2=Card()
card2.position=(342,503,53,40) ###FILL
card2.pixelposition=(383,506) ###FILL
table1.myCards.append(card1)
table1.myCards.append(card2)
allinPositionx=603 ###FILL
allinPositiony=566 ###FILL
table1.allinPixelPosition=(579,566) ###FILL
foldPositionx=469 ###FILL
foldPositiony=566 ###FILL
table1.allinClickPosition=(allinPositionx,allinPositiony)
table1.foldClickPosition=(foldPositionx,foldPositiony)
table1.rightguy1=(538,357,38,39)
table1.rightguy2=(604,382,38,10)
table1.nothing1PixelPos=()
table1.nothing2PixelPos=()
table1.nothing3PixelPos=()
table1.button1PixelPos=(137, 326)
table1.button2PixelPos=(395, 273)
table1.button3PixelPos=(572, 405)
tables.append(table1)
table2=Table()
pcard1=Card()
table2.tableno=1
table2.buttonPixelPosition=(959,482)
table2.yellowPixelPosition=(1169,605)
table2.myPos=(982,477,34,12)
table2.player1Pos=(712, 322,45,21)
table2.player2Pos=(988, 178,45,21)
table2.player3Pos=(1265, 321,45,21)
pcard1.position=(965,503,53,40) ###FILL
pcard1.pixelposition=(1007,506) ###FILL
pcard2=Card()
pcard2.position=(1020,503,53,40) ###FILL
pcard2.pixelposition=(1063,506) ###FILL
table2.myCards.append(pcard1)
table2.myCards.append(pcard2)
allinPositionx=1256 ###FILL
allinPositiony=566 ###FILL
table2.allinPixelPosition=(1256,566) ###FILL
foldPositionx=1150 ###FILL
foldPositiony=566 ###FILL
table2.allinClickPosition=(allinPositionx,allinPositiony)
table2.foldClickPosition=(foldPositionx,foldPositiony)
table2.rightguy1=(1215,360,39,34)
table2.rightguy2=(1283,382,38,10)
table2.nothing1PixelPos=()
table2.nothing2PixelPos=()
table2.nothing3PixelPos=()
table2.button1PixelPos=(822, 326)
table2.button2PixelPos=(1080, 273)
table2.button3PixelPos=(1257, 405)
tables.append(table2)
#########################################################################################################################3
def findCardColor(color1): #complete
color2=GREEN
Diff=[0,0,0,0]
Diff[0]=abs(color1[0] - color2[0])+abs(color1[1] - color2[1])+abs(color1[2] - color2[2])
color2=BLUE
Diff[1]=abs(color1[0] - color2[0])+abs(color1[1] - color2[1])+abs(color1[2] - color2[2])
color2=RED
Diff[2]=abs(color1[0] - color2[0])+abs(color1[1] - color2[1])+abs(color1[2] - color2[2])
color2=GREY
Diff[3]=abs(color1[0] - color2[0])+abs(color1[1] - color2[1])+abs(color1[2] - color2[2])
c=Diff.index(min(Diff))
print('Card color is '+str(ccode[c]))
return ccode[c]
def findCardDeck(color,fileaddress,place): #complete
print('Finding card number....')
if(True):
im1=Image.open(fileaddress)
h1 = im1.histogram()
rms=[]
for i in deck:
im2=Image.open(locationOfTest+"database/c"+str(place)+"/"+color+i+".png")
h2 = im2.histogram()
rms.append(math.sqrt(reduce(operator.add,map(lambda a,b: (a-b)**2, h1, h2))/len(h1)) )
c=rms.index(min(rms))
print('Card number is '+deck[c])
return(deck[c])
def makeDecision(curCard1,curCard2,scenario):
#Should return 0,1
x=0
#Choose scenario --return 1-7
suited=0
if(curCard1.suit==curCard2.suit):
suited=1
c1=curCard1.value
c2=curCard2.value
c=c1+c2
c=''.join(sorted(c))
#we have c=kk,qq,tt and suited=1or0
print("Current scenario before decision is "+scenario)
if(c in p[scenario]):
x=1
print('ALL IN')
else:
x=0
print('FOLD')
if(suited):
if(c in p[scenario+'s']):
x=1
print('ALL IN')
return x
#################MAIN CODE################### #complete
t=0 #tableID
i=0
print(tables[0].yellowPixelPosition)
print(tables[0].tableno)
print(tables[0].myPos)
print(tables[0].player1Pos)
print(tables[0].player2Pos)
print(tables[0].player3Pos)
print(tables[0].myCards[0].position)
print(tables[0].myCards[0].pixelposition)
print(tables[0].myCards[1].position)
print(tables[0].myCards[1].pixelposition)
print(tables[0].allinPixelPosition)
print(tables[0].allinClickPosition)
print(tables[0].rightguy1)
print(tables[0].rightguy2)
print(tables[1].yellowPixelPosition)
print(tables[1].tableno)
print(tables[1].myPos)
print(tables[1].player1Pos)
print(tables[1].player2Pos)
print(tables[1].player3Pos)
print(tables[1].myCards[0].position)#
print(tables[1].myCards[0].pixelposition)#
print(tables[1].myCards[1].position)#
print(tables[1].myCards[1].pixelposition)#
print(tables[1].allinPixelPosition)
print(tables[1].allinClickPosition)#
print(tables[1].rightguy1)
print(tables[1].rightguy2)
while(True):
#OBSERVE
print('Table no.'+str(t))
if(tables[t].isDealt1()):
"""
if(i!=0):
print('Not first')
prevCard1=Card()
prevCard2=Card()
prevCard1.suit=tables[t].myCards[0].suit
prevCard1.value=tables[t].myCards[0].value
prevCard2.suit=tables[t].myCards[1].suit
prevCard2.value=tables[t].myCards[1].value
print("t value is *************"+str(t))
"""
tables[t].analyse() #should return success or fail
print('Analysis done')
curCard1=tables[t].myCards[0]
curCard2=tables[t].myCards[1]
if(i!=0):
"""
print("****************************************************************")
print(prevCard1.suit+prevCard1.value)
print(prevCard2.suit+prevCard2.value)
print(curCard1.suit+curCard1.value)
print(curCard2.suit+curCard2.value)
print("****************************************************************")
if(not(prevCard1.compare(curCard1) and prevCard2.compare(curCard2))):
#not visited before
print('not visited before')
tables[t].curDecision=2 #reset variable
"""
#Decide Algorithm
print('about to make a decision')
x=makeDecision(curCard1,curCard2,tables[t].curScenario())
if(x==0):
#Click Fold
if(tables[t].curDecision!=0 or True):
pyautogui.moveTo(tables[t].foldClickPosition[0],tables[t].foldClickPosition[1],0.2)
pyautogui.click()
tables[t].curDecision=0
else:
#Click AllIn
if(tables[t].curDecision!=1 or True):
pyautogui.moveTo(tables[t].allinClickPosition[0],tables[t].allinClickPosition[1],0.2)
pyautogui.click()
tables[t].curDecision=1
i=i+1
t=1-t
#time.sleep(1)
print('switching to table : ' + str(t))
#modifications
#leftguy-allin
#topguy-allin
#rightguy-allin done
#countallins - gives number of allins properly
##############################################
#observing all in at both tables
#TRIGGER: when dealt all in button appears
#wherever first, go
####try analysing other table all in --multiprocessing
#read from table structure the two cards
#find info
#make decision
####compare the info from previous deck in card
#click
####save the card info for the table
#observe all in on both tables starting with second table
#########after decision of scenario is made once , should check how many people left to come to your place. else the number of people calculated to be not allin will be false
"""
#ALLIN COUNTER FOR POSITION=2
if(self.myPosition==2):
pyautogui.screenshot(locationOfTest+'rightGuy1.png',region=self.rightguy1)
im1=Image.open(locationOfTest+'rightGuy1.png')
h1 = im1.histogram()
im2=Image.open(locationOfTest+"database/"+str(self.tableno)+"rightGuy1"+".png")
h2 = im2.histogram()
rms=(math.sqrt(reduce(operator.add,map(lambda a,b: (a-b)**2, h1, h2))/len(h1)) )
if(rms<2):
n=0
else:
pyautogui.screenshot(locationOfTest+'rightGuy2.png',region=self.rightguy2)
im1=Image.open(locationOfTest+'rightGuy2.png')
h1 = im1.histogram()
im2=Image.open(locationOfTest+"database/"+str(self.tableno)+"rightGuy2"+".png")
h2 = im2.histogram()
rms=(math.sqrt(reduce(operator.add,map(lambda a,b: (a-b)**2, h1, h2))/len(h1)) )
if(rms<2):
n=1
else:
n=0
"""
"""
l['00']=['']
l['22']=['']
l['31']=['']
l['32']=['']
l['00s']=[""]
l['22s']=[""]
l['31s']=[""]
l['32s']=[""]
l['30']=["ak","aa","qq","kk"]
l['30s']=[""]
l['20']=["aa","ak","kk","aq","qq","jj"]
l['20s']=[""]
l['10']=["aa","ak","kk","aq","qq","jj","aj","kq","jk","kt","jq","at","9a","tt","99","88","77","66","8a","7a","6a","5a","9k","8k","7k","6k"]
l['10s']=["56","67","78","89","9t","jt"]
l['21']=["ak","aa","qq","kk","jj"]
l['21s']=[""]
l['11']=["aa","ak","kk","aq","qq","jj","aj","kq","jk","kt","qj","at","9a","tt","99","88","77","66","8a","7a","6a","5a","9k","8k","7k","6k"]
l['11s']=["56","67","78","89","9t","jt"]
l['01']=["aa","ak","kk","aq","qq","jj","aj","kq","jk","kt","jq","at","9a","tt","99","88","77","66","55","44","33","22","8a","7a","6a","5a","4a","3a","2a","9k","8k","7k","6k"]
l['01s']=["56","67","78","89","9t","45","34","23"]
l['12']=["aa","ak","kk","aq","qq","jj","aj","kq","jk","kt","jq","at","9a","tt","99","88","77","66"]
l['12s']=["56","67","78","89","9t","jt"]
l['02']=["aa","ak","kk","aq","qq","jj","aj","kq","jk","kt","jq","at","9a","tt","99","88","77","66","55","9k","8k"]
l['02s']=["56","67","78","89","9t","45","jt"]
"""
"""
a1=open(locationOfTest+'testres1.txt','a')
a2=open(locationOfTest+'testres2.txt','a')
a3=open(locationOfTest+'testres3.txt','a')
a4=open(locationOfTest+'testres4.txt','a')
a1.write(k1)
a2.write(k2)
a3.write(k3)
a4.write(k4)
filenames=["C:/Users/Sree/testres1.txt","C:/Users/Sree/testres2.txt","C:/Users/Sree/testres3.txt","C:/Users/Sree/testres4.txt"]
outfilename="C:/Users/Sree/h.txt"
with open(outfilename, 'a') as fout, fileinput.input(filenames) as fin:
for line in fin:
fout.write(line)
"""
"""
pyautogui.screenshot(filelocation[0],region=(288,502,16,17))
pyautogui.screenshot(filelocation[1],region=(342,502,16,17))
pyautogui.screenshot(filelocation[2],region=(967,502,16,17))
pyautogui.screenshot(filelocation[3],region=(1019,502,16,17))
x1=pyautogui.pixel(330,506)
x2=pyautogui.pixel(383,506)
x3=pyautogui.pixel(1007,506)
x4=pyautogui.pixel(1063,506)
k1=findCardColor(x1)
k2=findCardColor(x2)
k3=findCardColor(x3)
k4=findCardColor(x4)
"""
"""
os.system('tesseract.exe '+filelocation[0]+' '+locationOfTest+'testres1 -psm 10 nobatch poker')
os.system('tesseract.exe '+filelocation[1]+' '+locationOfTest+'testres2 -psm 10 nobatch poker')
os.system('tesseract.exe '+filelocation[2]+' '+locationOfTest+'testres3 -psm 10 nobatch poker')
os.system('tesseract.exe '+filelocation[3]+' '+locationOfTest+'testres4 -psm 10 nobatch poker')
"""
"""
os.system('tesseract.exe C:/Users/Sree/p0.png C:/Users/Sree/testres1 -psm 10 nobatch poker')
os.system('tesseract.exe C:/Users/Sree/p1.png C:/Users/Sree/testres2 -psm 10 nobatch poker')
os.system('tesseract.exe C:/Users/Sree/p2.png C:/Users/Sree/testres3 -psm 10 nobatch poker')
os.system('tesseract.exe C:/Users/Sree/p3.png C:/Users/Sree/testres4 -psm 10 nobatch poker')
"""
"""
im1=Image.open("C:/Users/Sree/p1.png")
im2=Image.open("C:/Users/Sree/p2.png")
h1 = im1.histogram()
h2 = im2.histogram()
rms = math.sqrt(reduce(operator.add,map(lambda a,b: (a-b)**2, h1, h2))/len(h1))
"""
|
class Solution(object):
def topKFrequent(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
my_dict = dict()
for i in nums:
if i in my_dict:
my_dict[i] +=1
else:
my_dict[i] = 1
r_list = list()
for i in xrange(0,k):
temp = max(my_dict, key=lambda i: my_dict[i])
r_list.append(temp)
my_dict.pop(temp, None)
return r_list
|
class Solution(object):
def countSubstrings(self, s):
"""
:type s: str
:rtype: int
"""
def helper(i, j):
res1 = 0
while (i >= 0 and j < len(s) and s[i] == s[j]):
res1 += 1
i -= 1
j += 1
return res1
res = 0
for i, ss in enumerate(s):
res += helper(i, i)
res += helper(i, i + 1)
return res |
#stack
expression = "1 2 + 3 4 - *"
class Stack:
def __init__(self):
self.stack = []
def push(self, a):
self.stack.append(a)
def pop(self):
return self.stack.pop()
def is_empty(self):
return not self.stack
if __name__ == '__main__':
stack = Stack()
for e in expression.split(" "):
if e == "*":
stack.push(int(stack.pop()) * int(stack.pop()))
elif e == "+":
stack.push(int(stack.pop()) + int(stack.pop()))
elif e == "-":
stack.push(- int(stack.pop()) + int(stack.pop()))
else:
stack.push(e)
print("result is " + str(stack.pop()))
|
import cv2
import json
import numpy as np
import time
import csv
import os
import sys
from datetime import datetime
import datetime as dt
import matplotlib.pyplot as plt
import configparser
#read config params
config = configparser.ConfigParser()
config.read('../config.ini')
screenHeightPX = int(config['DEFAULT']['screenHeightPX'])
screenWidthPX = int(config['DEFAULT']['screenWidthPX'])
start = -1
end = -1
eventType = None
#read arguments
if len(sys.argv) < 2 or len(sys.argv) > 5:
print("Please provide arguments in the form: <directory> <start time> <end time> <event type>")
print("Start, end time (both given in seconds) and event type are optional")
print("Event types: Scroll, SingleTapConfirmed, DoubleTap, Down, ShowPress, SingleTapUp, LongPress and Fling")
sys.exit(0)
elif len(sys.argv) == 2:
data = sys.argv[1]
elif len(sys.argv) == 4:
data = sys.argv[1]
start = int(sys.argv[2])
end = int(sys.argv[3])
elif len(sys.argv) == 5:
data = sys.argv[1]
start = int(sys.argv[2])
end = int(sys.argv[3])
eventType = sys.argv[4]
if int(start) > int(end):
print ("The start argument should be bigger than the end.")
sys.exit(0)
xCoordinates = np.array([])
yCoordinates = np.array([])
startTs = 0
#loop through touch events
with open(data + '/out/gesture.csv', mode='r') as csvinput:
csv_reader = csv.reader(csvinput, delimiter=',')
#first row is only header info
header = True
for row in csv_reader:
if header == True:
header = False
continue
touchTs = row[0]
currentEventType = row[1]
touchX = int(float(row[5]))
touchY = int(float(row[6]))
try: #milliseconds are missing for a few eyetracking timestamps
touchTs = datetime.strptime(touchTs, "%Y-%m-%d %H:%M:%S.%f")
except:
touchTs = datetime.strptime(touchTs, "%Y-%m-%d %H:%M:%S")
#only consider the chosen event type
if eventType != None and not eventType.lower() in currentEventType.lower():
continue
#filter for chosen timeframe
if startTs == 0:
startTs = touchTs
currentTimePosition = touchTs - startTs
if start != -1 and end != -1:
if currentTimePosition < dt.timedelta(0,int(start)) or currentTimePosition > dt.timedelta(0,int(end)):
continue
if touchX >= 0 and touchX <= screenWidthPX and touchY >= 0 and touchY <= screenHeightPX:
xCoordinates = np.append(xCoordinates, touchX)
yCoordinates = np.append(yCoordinates, touchY)
#prepare and save heatmap plot
heatmap, xedges, yedges = np.histogram2d(xCoordinates, yCoordinates, bins=(120,240))
extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]
plt.clf()
if start >= 0 and end >= 0:
plt.title('Touch Heatmap [' + str(start) + 's,' + str(end) + 's]')
else:
plt.title('Touch Heatmap')
plt.imshow(heatmap.T, extent=extent, origin='lower', interpolation='nearest')
plt.set_cmap('BuPu')
plt.colorbar()
plt.savefig(data + '/out/touchHeatmap.pdf')
|
# q9
for i in range(50, 81, 10):
print(i) |
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
max_ = 0
n = len(s)
if n == 1:
return n
if n == 2:
return int(s[0] != s[1]) + 1
for i in range(n-1):
for j in range(i+1,n):
if s[j] not in s[i:j]:
if j + 1 == n:
if j-i+1 > max_:
max_ = j-i+1
continue
else:
if j-i > max_:
max_ = j-i
break
return max_
if __name__ == '__main__':
s = "abcabcbb"
ret = Solution().lengthOfLongestSubstring(s)
print(ret) |
from wtforms import Form,StringField,ValidationError
from wtforms.validators import Length,Regexp
from apps.front.models import UserModel
class Verify_sendcode(Form): #发送注册验证码验证
mobile = StringField(validators=[Regexp(r'^1(3|4|5|7|8)\d{9}$', message='手机号码输入错误')])
def validate_mobile(self,field):
mobile=field.data
user=UserModel.query.filter_by(mobile=mobile).first()
if user:
raise ValidationError(message='您已经注册过了!')
class Verify_SendLoginCode(Form): #发送登录验证码验证
mobile = StringField(validators=[Regexp(r'^1(3|4|5|7|8)\d{9}$', message='手机号码输入错误')])
def validate_mobile(self, field):
mobile = field.data
user = UserModel.query.filter_by(mobile=mobile).first()
print(user)
if not user:
raise ValidationError(message='您还没有注册哦!') |
# -*- coding: utf-8 -*-
# coding=utf-8
# __author__ = 'zy'
import os
import shutil
import time
import datetime
s = os.sep # 根据unix或win,s为\或/
# root = "d:" + s + "ll" + s #要遍历的目录
# origin = "/Users/zy/Downloads/a/" # 不会被改变
# 所有问题都会被移动到root目录,入参和移动目标的考量
root = "/Users/zy/Downloads/a/"
# 所有被移动文件的后缀名
suffix = ".mp4"
# current (current directory + system support route separator) 当前的操作目录+当前系统支持的路径分割符号
# origin (current directory) 当前的操作目录
# remoteUrl (target time name) 如果移动之后的文件名已经存在,一个带着年月日时分秒的新名字
# localUrl (file current name) 文件的当前地址
def changeMoveFile(origin,dirs,f): # 回调函数的定义
fileNameAsDate = time.strftime("%Y%m%d-%H%M%S", time.localtime())
fname = os.path.splitext(f) # 分割 文件名 和 扩展名 数组
new = fname[0] + suffix # 改文件名字
idx = new.index('.')!=0
# 隐藏文件不理会
if idx:
# 如果 有上级目录则加上 以准确获得当前路径
current = origin + s
remoteUrl = root + fname[0] + "-"+ fileNameAsDate + suffix
localUrl = current + f
# print(current+fname[0])
# print(current +new+fileNameAsDate)
# 当前url+新名字 != 当前url+ 老名字
if new != f or root!= origin:
if os.path.exists(root + new):
if os.path.exists(remoteUrl):
time.sleep(0.1)
changeMoveFile(origin,dirs,f)
else:
print("start rename move:\n" + localUrl + " ---to:---\n" + remoteUrl + "\n")
fileNameAsDate = time.strftime('%Y%m%d-%H%M%S.%f', time.localtime(time.time()))
# shutil.move(localUrl, remoteUrl)
os.rename(localUrl, remoteUrl)
# print(current+new+" exists!, \nuse:\n"+ current + fname[0] + fileNameAsDate + suffix);
else:
print("start move:\n" + localUrl + " ---to---\n" + root + new + "\n")
os.rename(localUrl, root + new)
# 严重逻辑错误,又传入了文件夹 又传入文件 todo
# for root, dirs, files in os.walk(root):
# for f in files:
# if os.path.splitext(f)[0]:
# changeMoveFile(f)
# http://blog.csdn.net/thy38/article/details/4496810
# http://www.cnblogs.com/dreamer-fish/p/3820625.html
# orgin , dirs , files 是 walk这个查询行为的一次查询结果 而不是返回对象
for origin, dirs, files in os.walk(root):
for f in files:
if os.path.splitext(f)[0]:
changeMoveFile(origin,dirs,f)
|
if 0:
print("True")
else:
print("False")
name = input("Please enter your name: ")
if name:
print("Hello, {}".format(name))
else:
print("Are you the man with no name?") |
#!/usr/bin/env python
def checkindex(key):
if not isinstance(key,(int,long)):
raise TypeError
if key < 0:
raise IndexError
class AthimeticSequence:
def __init__(self,start=0, step=1):
self.start=start
self.step=step
self.changed={}
def __getitem__(self,key):
checkindex(key)
try:
return self.changed[key]
except KeyError:
return self.start + key*self.step
def __setitem__(self,key,value):
checkindex(key)
self.changed[key]=value
s=AthimeticSequence(1,2)
print 'key as 4 get value result'
print s[4]
print 'set key as 4 value as 2'
s[4]=2
print s[4]
print 'key as 5 get value result'
print s[5]
|
#!/usr/bin/env python
#=========================================================================
# proc-sim [options] <elf-file>
#=========================================================================
#
# -h --help Display this message
# -v --verbose Verbose mode
# --trace Turn on line tracing
#
# --proc-impl Choose ParcProc implementation (default fl)
# fl : functional-level model
# cl : cycle-level model
#
# The simulator will load the given ELF file. Assumes that the program
# has been compiled such that the start of the program is at 0x1000. The
# simulator will automatically add the following instructions at address
# 0x400 to bootstrap the applications. Also assumes that the program will
# use the following instruction to end the program:
#
# mtc0 r1, proc2mngr
#
# where r1 is one for success and two for failure.
#
# Author : Christopher Batten
# Date : May 25, 2014
#
from __future__ import print_function
import argparse
import sys
import re
import time
from pymtl import *
from pisa import *
from pclib.test import TestSource, TestSink
from pclib.ifcs import MemMsg
from pclib.test.TestMemoryFuture import TestMemory
from proc.parc_fl import ParcProcFL
from proc.parc_fl import GenericXcelFL
from ParcProcCL import ParcProcCL
#-------------------------------------------------------------------------
# Command line processing
#-------------------------------------------------------------------------
class ArgumentParserWithCustomError(argparse.ArgumentParser):
def error( self, msg = "" ):
if ( msg ): print("\n ERROR: %s" % msg)
print("")
file = open( sys.argv[0] )
for ( lineno, line ) in enumerate( file ):
if ( line[0] != '#' ): sys.exit(msg != "")
if ( (lineno == 2) or (lineno >= 4) ): print( line[1:].rstrip("\n") )
def parse_cmdline():
p = ArgumentParserWithCustomError( add_help=False )
# Standard command line arguments
p.add_argument( "-v", "--verbose", action="store_true" )
p.add_argument( "-h", "--help", action="store_true" )
# Additional commane line arguments for the simulator
p.add_argument( "--trace", action="store_true" )
p.add_argument( "--proc-impl", default="fl", choices=["fl","cl"] )
p.add_argument( "elf_file" )
opts = p.parse_args()
if opts.help: p.error()
return opts
#-------------------------------------------------------------------------
# TestHarness
#-------------------------------------------------------------------------
# Maybe this should be refactored somewhere?
class TestHarness (Model):
#-----------------------------------------------------------------------
# constructor
#-----------------------------------------------------------------------
def __init__( s, ProcModel ):
# Instantiate models
s.src = TestSource ( 32, [], 0 )
s.sink = TestSink ( 32, [], 0 )
s.proc = ProcModel ( test_en=False )
s.mem = TestMemory ( MemMsg(32,32), 3 )
s.xcel = GenericXcelFL ()
#-----------------------------------------------------------------------
# elaborate
#-----------------------------------------------------------------------
def elaborate_logic( s ):
# Processor <-> Proc/Mngr
s.connect( s.proc.mngr2proc, s.src.out )
s.connect( s.proc.proc2mngr, s.sink.in_ )
# Processor <-> Memory
s.connect( s.proc.imemreq, s.mem.reqs[0] )
s.connect( s.proc.imemresp, s.mem.resps[0] )
s.connect( s.proc.dmemreq, s.mem.reqs[1] )
s.connect( s.proc.dmemresp, s.mem.resps[1] )
# Processor <-> Accelerator
s.connect( s.proc.xcelreq, s.xcel.xcelreq )
s.connect( s.proc.xcelresp, s.xcel.xcelresp )
# Accelerator <-> Memory
# s.connect( s.xcel.memreq, s.mem.reqs[2] )
# s.connect( s.xcel.memresp, s.mem.resps[2] )
#-----------------------------------------------------------------------
# load
#-----------------------------------------------------------------------
def load( self, mem_image ):
sections = mem_image.get_sections()
for section in sections:
start_addr = section.addr
stop_addr = section.addr + len(section.data)
self.mem.mem[start_addr:stop_addr] = section.data
#-----------------------------------------------------------------------
# done
#-----------------------------------------------------------------------
def done( s ):
return s.proc.status > 0
#-----------------------------------------------------------------------
# line_trace
#-----------------------------------------------------------------------
def line_trace( s ):
return s.src.line_trace() + " > " + \
s.proc.line_trace() + " " + \
s.xcel.line_trace() + " " + \
s.mem.line_trace() + " > " + \
s.sink.line_trace()
#-------------------------------------------------------------------------
# Main
#-------------------------------------------------------------------------
def main():
opts = parse_cmdline()
# Start the wallclock timer
start_time = time.time()
# Load the elf file
mem_image = None
with open(opts.elf_file,'rb') as file_obj:
mem_image = elf.elf_reader( file_obj )
# Add a bootstrap section at address 0x400
bootstrap_asm = """
lui r29, 0x0007
ori r29, r0, 0xfffc
j 0x1000
"""
bootstrap_mem_image = pisa_encoding.assemble( bootstrap_asm )
bootstrap_bytes = bootstrap_mem_image.get_section(".text").data
mem_image.add_section( ".bootstrap", 0x400, bootstrap_bytes )
# Apparently we also need to binary rewrite the jump at 0x1008. This is
# super hacky for now -- this relies on the fact that the binrewrite
# section will be loaded _after_ the primary .text section so that we
# can essentially use the loader to do the binary rewrite.
binrewrite_asm = """
j 0x1020
"""
binrewrite_mem_image = pisa_encoding.assemble( binrewrite_asm )
binrewrite_bytes = binrewrite_mem_image.get_section(".text").data
mem_image.add_section( ".binrewrite", 0x1008, binrewrite_bytes )
# Determine which processor model to use in the simulator
proc_impl_dict = {
'fl' : ParcProcFL,
'cl' : ParcProcCL,
}
# Instantiate and elaborate the model
model = TestHarness( proc_impl_dict[opts.proc_impl] )
model.elaborate()
# Load the program into the model
model.load( mem_image )
# Create a simulator using the simulation tool
sim = SimulationTool( model )
# Run the simulation
sim.reset()
model.proc.go.value = 1
while not model.done():
if opts.trace:
sim.print_line_trace()
sim.cycle()
# Add a couple extra ticks so that the VCD dump is nicer
sim.cycle()
sim.cycle()
sim.cycle()
# Stop the wallclock timer
stop_time = time.time()
sim_time = stop_time - start_time
# Display the result value from the simulator
print()
print( " Simulator return value =", model.proc.status )
# Display statistics
print()
print( " num_total_inst =", model.proc.num_total_inst )
print( " num_total_cycles =", sim.ncycles )
print( " sim_time =", sim_time )
print( " cycles_per_sec =", sim.ncycles / sim_time )
print( " num_inst =", model.proc.num_inst )
print()
main()
|
/home/ajitkumar/anaconda3/lib/python3.7/functools.py |
"""
LeetCode - Medium
"""
"""
Given an m x n matrix. If an element is 0, set its entire row and column to 0. Do it in-place.
Follow up:
A straight forward solution using O(mn) space is probably a bad idea.
A simple improvement uses O(m + n) space, but still not the best solution.
Could you devise a constant space solution?
Example 1:
Input: matrix = [[1,1,1],[1,0,1],[1,1,1]]
Output: [[1,0,1],[0,0,0],[1,0,1]]
Example 2:
Input: matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]
Output: [[0,0,0,0],[0,4,5,0],[0,3,1,0]]
"""
class Solution:
def setZeroes(self, matrix) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
row_set = set()
col_set = set()
for row in range(len(matrix)):
for col in range(len(matrix[row])):
if matrix[row][col] == 0:
row_set.add(row)
col_set.add(col)
for row in range(len(matrix)):
for col in range(len(matrix[row])):
if row in row_set or col in col_set:
matrix[row][col] = 0
print(matrix)
if __name__ == '__main__':
matrix = [[1, 1, 1],
[1, 0, 1],
[1, 1, 1]]
matrix1 = [[0, 1, 2, 0],
[3, 4, 5, 2],
[1, 3, 1, 5]]
print(Solution().setZeroes(matrix1))
|
#!/usr/bin/env python3.6
import json
import sys
import boto3
from aws_console.console import Console
def get_url_via_credentials():
session = boto3.Session()
credentials = session.get_credentials()
frozen_credentials = credentials.get_frozen_credentials()
if frozen_credentials.token == None:
raise Exception("Session token not set (aws_console requires STS credentials).")
credentials_json = json.dumps({
'sessionId': frozen_credentials.access_key,
'sessionKey': frozen_credentials.secret_key,
'sessionToken': frozen_credentials.token
})
return Console().generate_console_url(credentials_json)
def run():
try:
print(get_url_via_credentials())
except Exception as e:
print("Received error:", e)
sys.exit(1)
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9.8 on 2016-09-27 03:30
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('messaging', '0022_auto_20160927_0415'),
]
operations = [
migrations.AddField(
model_name='standardmessaging',
name='cc_recipients_send_email',
field=models.BooleanField(default=True, verbose_name='Send Email'),
),
migrations.AddField(
model_name='standardmessaging',
name='cc_recipients_send_sms',
field=models.BooleanField(default=True, verbose_name='Send SMS'),
),
]
|
'''
Implement atoi to convert a string to an integer.
Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.
Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.
'''
class Solution(object):
def validNumber(self, number):
validList = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-']
valid = False
for n in validList:
if n == number:
valid = True
return valid
def myAtoi(self, str):
"""
:type str: str
:rtype: int
"""
solution = 0
negative = False
count = 0
for i in str:
if self.validNumber(i):
if i == '-':
negative = True
else:
solution = solution * 10 + int(i)
count = count + 1
elif count == 0:
pass
else:
break
if negative == True:
solution = solution * (-1)
return solution
test = Solution()
print test.myAtoi(" +-1112 33")
|
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
df = pd.read_csv('USA_Housing.csv')
print(df.head())
print("="*40)
print(df.info())
print("="*40)
print(df.describe())
print("="*40)
print(df.columns)
print("="*40)
sns.pairplot(df)
plt.show()
sns.distplot(df['Price']) #distrubution of column
plt.show()
print(df.corr())
print("="*40)
sns.heatmap(df.corr(), annot=True)
plt.show()
#training the model using scikit-learn
X = df[['Avg. Area Income', 'Avg. Area House Age', 'Avg. Area Number of Rooms',
'Avg. Area Number of Bedrooms', 'Area Population']]
# in X, we should ignore "Price"(because it is a y) and address (it is string)
y = df['Price']
from sklearn.model_selection import train_test_split
#Creating and Training the Model
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.4, random_state=101)
print(X_train)
print("="*40)
print(y_train)
print("="*40)
#fitting the model
from sklearn.linear_model import LinearRegression
lm = LinearRegression()
lm.fit(X_train, y_train)
#Model Evaluation
print(lm.intercept_)
print("="*40)
print(lm.coef_)
print("="*40)
print(X_train.columns)
print(lm.coef_)
print("="*40)
coeff_df = pd.DataFrame(lm.coef_,X.columns,columns=['Coefficient'])
print(coeff_df)
print("="*40)
# Interpreting the coefficients:
# Holding all other features fixed, a 1 unit increase in Avg. Area Income is associated with an *increase of $21.52 *.
# Holding all other features fixed, a 1 unit increase in Avg. Area House Age is associated with an *increase of $164883.28 *.
# Holding all other features fixed, a 1 unit increase in Avg. Area Number of Rooms is associated with an *increase of $122368.67 *.
# Holding all other features fixed, a 1 unit increase in Avg. Area Number of Bedrooms is associated with an *increase of $2233.80 *.
# Holding all other features fixed, a 1 unit increase in Area Population is associated with an *increase of $15.15 *.
# Analyse from other way
from sklearn.datasets import load_boston
boston = load_boston()
print(boston.keys())
#dict_keys(['data', 'target', 'feature_names', 'DESCR', 'filename'])
print(boston['target']) # ['data'] or ['feature_names'] ['filename'] ['DESCR']
print("="*40)
#Predictions from our Model
predictions = lm.predict(X_test)
print(predictions)
print("="*40)
plt.scatter(y_test, predictions)
plt.show()
sns.distplot((y_test-predictions)) #histogram of residuals
plt.show()
#Regression Evaluation Metrics
## Comparing these metrics:
#Mean Absolute Error (MAE) is the easiest to understand, because it's the average error.
#Mean Squared Error (MSE) is more popular than MAE, because MSE "punishes" larger errors, which tends to be useful in the real world.
#Root Mean Squared Error (RMSE) is even more popular than MSE, because RMSE is interpretable in the "y" units.
#All of these are loss functions, because we want to minimize them.
from sklearn import metrics
print("Mean Absolute Error (MAE) is: {}".format(metrics.mean_absolute_error(y_test,predictions)))
print("="*40)
print("Mean Squared Error (MSE) is: {}".format(metrics.mean_squared_error(y_test,predictions)))
print("="*40)
print("Root Mean Squared Error (RMSE) is: {}".format(np.sqrt(metrics.mean_squared_error(y_test,predictions))))
print("="*40)
|
import json
from channels.generic.websocket import AsyncWebsocketConsumer
class PlayerConsumer(AsyncWebsocketConsumer):
'''Handels all socket communications for each player'''
async def connect(self):
# User that is not authenticated (anonymous) should not be accepted
if 'user' in self.scope and not self.scope['user'].is_anonymous:
self.table_id = self.scope['url_route']['kwargs']['table_id']
# Join the table
await self.channel_layer.group_add(
self.table_id,
self.channel_name
)
self.user = str(self.scope['user'])
await self.accept()
await self.channel_layer.send(
'game_engine',
{
'type': 'player.new',
'player': self.user,
'channel': self.table_id,
'buy_in': 6
}
)
else:
await self.close()
async def receive(self, text_data):
text_data_json = json.loads(text_data)
print(text_data_json)
async def state_update(self, event):
await self.send(text_data=json.dumps(event['state']))
async def disconnect(self, event):
# Leave the table
await self.channel_layer.group_discard(
self.table_id,
self.channel_name
)
|
#!/usr/bin/env python2.7
import db, datetime
def load(conn):
queue_contracts = db.Contract.load_by_state(conn = conn, state = db.Contract.IN_QUEUE)
accepted_contracts = db.Contract.load_by_state(conn = conn, state = db.Contract.IN_PROGRESS)
last_update = reduce(max, [x.last_seen for x in queue_contracts], datetime.datetime.min)
last_update = reduce(max, [x.last_seen for x in accepted_contracts], last_update)
return last_update, queue_contracts, accepted_contracts
def show(last_update, queue_contracts, accepted_contracts):
print 'Last update:', last_update
queue_contracts = list(queue_contracts)
queue_contracts.sort(lambda x,y: cmp((x.created_min,x.contract_id), (y.created_min,y.contract_id)))
print ' ==== IN QUEUE ({n}) ===='.format(n = len(queue_contracts))
for contract in queue_contracts:
print contract
accepted_contracts = list(accepted_contracts)
accepted_contracts.sort(lambda x,y: cmp((x.accepted,x.contract_id), (y.accepted,y.contract_id)))
print ' ==== IN PROGRESS ({n}) ===='.format(n = len(accepted_contracts))
for contract in accepted_contracts:
print contract
if __name__ == '__main__':
from contextlib import closing
with closing(db.new_connection(initdb=False)) as conn:
last_update, queue_contracts, accepted_contracts = load(conn)
show(last_update, queue_contracts, accepted_contracts)
|
num1=[]
for i in range(4):
num1.append(int(input("enter a value ")))
print(num1)
|
from anvil import Anvil
from anvil.entities import KilnRepo
def main():
anvil = Anvil("spectrum")
anvil.create_session_by_prompting()
res = anvil.get_json("/Repo/68219")
repo = KilnRepo.from_json(anvil, res)
subrepos = repo.where_used()
if __name__ == '__main__':
main()
|
#!/usr/bin/python3
# Adapted from http://noahdesu.github.io/2014/06/01/tracing-ceph-with-lttng-ust.html
import sys
import numpy
from babeltrace import *
import time
import math
import getopt
# This is for ceph version 9.0.0-928-g98d1c10 (98d1c1022c098b98bdf7d30349214c00b15cffec)
requests = {
int("0x00100", 16) : {"op" : "CEPH_MDS_OP_LOOKUP"} ,
int("0x00101", 16) : {"op" : "CEPH_MDS_OP_GETATTR"} ,
int("0x00102", 16) : {"op" : "CEPH_MDS_OP_LOOKUPHASH"} ,
int("0x00103", 16) : {"op" : "CEPH_MDS_OP_LOOKUPPARENT"} ,
int("0x00104", 16) : {"op" : "CEPH_MDS_OP_LOOKUPINO"} ,
int("0x00105", 16) : {"op" : "CEPH_MDS_OP_LOOKUPNAME"} ,
int("0x01105", 16) : {"op" : "CEPH_MDS_OP_SETXATTR"} ,
int("0x01106", 16) : {"op" : "CEPH_MDS_OP_RMXATTR"} ,
int("0x01107", 16) : {"op" : "CEPH_MDS_OP_SETLAYOUT"} ,
int("0x01108", 16) : {"op" : "CEPH_MDS_OP_SETATTR"} ,
int("0x01109", 16) : {"op" : "CEPH_MDS_OP_SETFILELOCK"} ,
int("0x00110", 16) : {"op" : "CEPH_MDS_OP_GETFILELOCK"} ,
int("0x0110a", 16) : {"op" : "CEPH_MDS_OP_SETDIRLAYOUT"} ,
int("0x01201", 16) : {"op" : "CEPH_MDS_OP_MKNOD"} ,
int("0x01202", 16) : {"op" : "CEPH_MDS_OP_LINK"} ,
int("0x01203", 16) : {"op" : "CEPH_MDS_OP_UNLINK"} ,
int("0x01204", 16) : {"op" : "CEPH_MDS_OP_RENAME"} ,
int("0x01220", 16) : {"op" : "CEPH_MDS_OP_MKDIR"} ,
int("0x01221", 16) : {"op" : "CEPH_MDS_OP_RMDIR"} ,
int("0x01222", 16) : {"op" : "CEPH_MDS_OP_SYMLINK"} ,
int("0x01301", 16) : {"op" : "CEPH_MDS_OP_CREATE"} ,
int("0x00302", 16) : {"op" : "CEPH_MDS_OP_OPEN"} ,
int("0x00305", 16) : {"op" : "CEPH_MDS_OP_READDIR"} ,
int("0x00400", 16) : {"op" : "CEPH_MDS_OP_LOOKUPSNAP"} ,
int("0x01400", 16) : {"op" : "CEPH_MDS_OP_MKSNAP"} ,
int("0x01401", 16) : {"op" : "CEPH_MDS_OP_RMSNAP"} ,
int("0x00402", 16) : {"op" : "CEPH_MDS_OP_LSSNAP"} ,
int("0x01403", 16) : {"op" : "CEPH_MDS_OP_RENAMESNAP"} ,
int("0x01500", 16) : {"op" : "CEPH_MDS_OP_FRAGMENTDIR"} ,
int("0x01501", 16) : {"op" : "CEPH_MDS_OP_EXPORTDIR"} ,
int("0x01502", 16) : {"op" : "CEPH_MDS_OP_VALIDATE"} ,
int("0x01503", 16) : {"op" : "CEPH_MDS_OP_FLUSH"}
}
# Taken from: https://gordoncluster.wordpress.com/2014/02/13/python-numpy-how-to-generate-moving-averages-efficiently-part-2/
def movingavg(values, window):
weights = numpy.repeat(1.0, window)/window
return numpy.convolve(values, weights, 'valid')
def main(argv):
op = "CEPH_MDS_OP_CREATE"
window = 10
trace = -1
output = -1
try:
opts, args = getopt.getopt(argv, "ht:w:o:d:", ["type=", "window=", "output=", "dir="])
except getopt.GetoptError:
print(sys.argv[0] + " -t <operation> -w <window> -o <outputfile> -d <LTTng trace dir>", file=sys.stderr)
sys.exit(0)
for opt, arg in opts:
if opt == '-h':
print("\nPrint out distribution of the request latencies", file=sys.stderr)
print("\n\tusage: " + sys.argv[0] + " -t <operation> -w <window> -o <outputfile> -d <LTTng trace dir>", file=sys.stderr)
print("\n\nOperations: ", end=" ", file=sys.stderr)
for r in requests:
print(str(r) + " " + requests[r]["op"], end=" ", file=sys.stderr)
print("\n\n", file=sys.stderr)
sys.exit(0)
elif opt in ("-t", "--type"): op = arg
elif opt in ("-w", "--window"): window = arg
elif opt in ("-o", "--output"): output = arg
elif opt in ("-d", "--dir"): trace = arg
if trace == -1 or output == -1:
print("LTTng trace directory (-d) AND output file (-o) must be specified.\n", file=sys.stderr)
sys.exit(0)
# initialize some stuff
traces = TraceCollection()
ret = traces.add_trace(trace, "ctf")
inflight = {}; latencies = {}
start = sys.maxsize; finish = -1
# get the latencies for the specified operation
count = 1
for event in traces.events:
if requests[event["type"]]["op"] == op:
ts, tid = event.timestamp, event["tid"]
# get the thread servicing the client request
if event.name == "mds:req_received":
inflight[tid] = ts
elif event.name == "mds:req_replied" or event.name == "mds:req_early_replied":
# get the first/last timestamp
if ts < start: start = ts
if ts > finish: finish = ts
# add the latency (using the timestamp as key) to the proper bin
t = time.strftime('%H:%M:%S', time.localtime(ts/1e9))
try:
if t not in latencies:
latencies[t] = {}
latencies[t]["all"] = []
latencies[t]["all"].append(ts - inflight[tid])
del inflight[tid]
except KeyError:
continue
count += 1
if count % 10000 == 0:
print("... done with " + str(int(count/1000)) + "k events")
print("... get the average latency for each second time step\n")
# - there's a lot of copying going on here... but the runs usually take about 10 minutes,
# which is only about 600 samples... if we need to do like 6 hours, then this might take
# a while
avgLatencies = []
times = []
for k,v in sorted(latencies.items()):
print("len of " + str(k) + " is " + str(len(v["all"])))
if v and v["all"]:
times.append(k)
avgLatencies.append(numpy.mean(v["all"]))
print("... get the moving averages\n")
try:
mvAvg = movingavg(avgLatencies, window)
except:
print("Not enough values for a moving average", file=sys.stderr)
sys.exit(0)
print("... put the moving average value back into the latencies dictionary\n")
for i in range(len(times)):
latencies[times[i]]["mean"] = avgLatencies[i]
if i < window:
latencies[times[i]]["mvavg"] = 0
else:
latencies[times[i]]["mvavg"] = mvAvg[i - window]
# get the number of requests in that second
f = open(output, 'w')
f.write("# time nrequests latency average\n")
print( "# time nrequests," +
" start=" + time.strftime('%H:%M:%S', time.localtime(start/1e9)) +
" finish=" + time.strftime('%H:%M:%S', time.localtime(finish/1e9)) + "\n")
prevLat = 0; prevMvAvg = 0
for ts in range(math.floor(start/1e9) - 1, math.floor(finish/1e9) + 1):
t = time.strftime('%H:%M:%S', time.localtime(ts))
try:
f.write(str(t) +
" " + str(len(latencies[t]["all"])) +
" " + str(latencies[t]["mean"]/1e6) +
" " + str(latencies[t]["mvavg"]/1e6) + "\n")
prevLat = latencies[t]["mean"]
prevMvAvg = latencies[t]["mvavg"]
except KeyError:
f.write(str(t) + " 0 " +
" " + str(prevLat/1e6) +
" " + str(prevMvAvg/1e6) + "\n")
f.close()
if __name__ == "__main__":
main(sys.argv[1:])
|
import json
import os
import numpy as np
import cv2
import matplotlib.pyplot as plt
import torch
from PIL import Image
import torch
import torch.utils.data
import torchvision
from torchvision.models.detection.faster_rcnn import FastRCNNPredictor
import torchvision
from torchvision.models.detection import FasterRCNN
from torchvision.models.detection.rpn import AnchorGenerator
import torchvision
from torchvision.models.detection.faster_rcnn import FastRCNNPredictor
from torchvision.models.detection.mask_rcnn import MaskRCNNPredictor
import pandas as pd
from engine import train_one_epoch, evaluate
import utils
import transforms as T
#functions
def get_mask(coordenates, height, width):
mask = np.zeros((height, width))
mask[int(coordenates[1]):int(coordenates[1]) + int(coordenates[3]),
int(coordenates[0]):int(coordenates[0]) + int(coordenates[2])] = 1
return mask
def get_instance_segmentation_model(num_classes):
# load an instance segmentation model pre-trained on COCO
model = torchvision.models.detection.maskrcnn_resnet50_fpn(pretrained=True)
# get the number of input features for the classifier
in_features = model.roi_heads.box_predictor.cls_score.in_features
# replace the pre-trained head with a new one
model.roi_heads.box_predictor = FastRCNNPredictor(in_features, num_classes)
# now get the number of input features for the mask classifier
in_features_mask = model.roi_heads.mask_predictor.conv5_mask.in_channels
hidden_layer = 256
# and replace the mask predictor with a new one
model.roi_heads.mask_predictor = MaskRCNNPredictor(in_features_mask,
hidden_layer,
num_classes)
return model
def predict_new_image(original_image, model,device='cpu', threshold=0.7):
im = original_image.copy()
im = im / 255
im = torch.tensor(im.transpose(2, 0, 1), dtype=torch.float32)
model.eval()
with torch.no_grad():
prediction = model([im.to(device)])
boxes = prediction[0]['boxes'].to('cpu').numpy().tolist()
scores = prediction[0]['scores'].to('cpu').numpy().tolist()
for i in range(len(boxes)):
coordenadas = boxes[i]
confianza = scores[i]
if confianza > threshold:
cv2.rectangle(original_image, (int(coordenadas[0]),
int(coordenadas[1])),
(int(coordenadas[2]),
int(coordenadas[3])), (0, 255, 0), 6)
plt.imshow(cv2.cvtColor(original_image, cv2.COLOR_BGR2RGB))
plt.show() |
# Generated by Django 3.0.2 on 2020-06-20 08:58
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('obsapp', '0037_auto_20200620_1311'),
]
operations = [
migrations.AlterField(
model_name='chats',
name='messagetime',
field=models.DateField(default=datetime.datetime(2020, 6, 20, 14, 28, 58, 91125)),
),
migrations.AlterField(
model_name='community',
name='message_time',
field=models.DateTimeField(default=datetime.datetime(2020, 6, 20, 14, 28, 58, 100133)),
),
migrations.AlterField(
model_name='gameplayed',
name='startedgame',
field=models.DateField(default=datetime.datetime(2020, 6, 20, 14, 28, 58, 97131)),
),
migrations.AlterField(
model_name='gamerating',
name='reviewtime',
field=models.DateField(default=datetime.datetime(2020, 6, 20, 14, 28, 58, 96129)),
),
migrations.AlterField(
model_name='notificationz',
name='notificationtime',
field=models.DateTimeField(default=datetime.datetime(2020, 6, 20, 14, 28, 58, 93126)),
),
migrations.AlterField(
model_name='report',
name='resondate',
field=models.DateField(default=datetime.datetime(2020, 6, 20, 14, 28, 58, 99132)),
),
migrations.AlterField(
model_name='requestexchange',
name='datetimeofrequest',
field=models.DateTimeField(default=datetime.datetime(2020, 6, 20, 14, 28, 58, 93126)),
),
]
|
#!/usr/bin/python3
import pprint
import re
import json
import time
import sys
import json
Lines = sys.stdin.readlines()
json_body = ""
for line in Lines:
json_body = json_body + line.strip('\n')
json_obj = json.loads(json_body)
i = 0
for files in json_obj['files']:
url = json_obj['files'][i]["url"]
i = i + 1
print (f'url: {url}')
#pprint.pprint(json_obj)
|
"""
LeetCode - Medium
"""
"""
Given a binary array, find the maximum number of consecutive 1s in this array if you can flip at most one 0.
Example 1:
Input: [1,0,1,1,0]
Output: 4
Explanation: Flip the first zero will get the the maximum number of consecutive 1s.
After flipping, the maximum number of consecutive 1s is 4.
"""
class Solution:
def findMaxConsecutiveOnes(self, nums):
max_count = 0
current_count = 0
flip = False
index, flip_index = 0, 0
while index < len(nums):
if nums[index] != 1 and flip is True:
max_count = max(max_count, current_count)
current_count = 0
index = flip_index
flip = False
elif nums[index] != 1 and flip is False:
current_count += 1
flip = True
flip_index = index
else:
current_count += 1
index += 1
max_count = max(max_count, current_count)
return max_count
if __name__ == '__main__':
nums = [1, 0, 1, 1, 0, 1, 1, 1]
print(Solution().findMaxConsecutiveOnes(nums))
|
'''
For Checking anomolies within data
'''
from datetime import datetime
from pathlib import Path
import json
import os
import sys
import pandas as pd
__author__ = 'Edward Chang'
class FormatChecker:
'''
Checks Excel File for Header format, Correct Units, and other fields
Also counts Withheld
'''
__slots__ = ['config']
def __init__(self, prefix):
'''Constructor for FormatChecker. Uses config based on data
Keyword Arguments:
prefix -- Prefix of the json file
'''
self.config = self.read_config(prefix)
def read_config(self, prefix):
'''Returns an decoded json file
Keyword Arguments:
prefix -- Prefix of the json file
'''
with open('config/' + prefix + 'config.json', 'r') as config:
return json.load(config)
def get_w_count(self, df):
'''Returns number of Ws found for Volume and Location
Keyword Arguments:
df -- A pandas DataFrame
'''
volume_w_count = 0
state_w_count = 0
# If Volume is present in df
if df.columns.contains('Volume'):
for entry in df['Volume']:
if entry == 'W':
volume_w_count += 1
# If State is present in df
if df.columns.contains('State'):
for entry in df['State']:
if entry == 'Withheld':
state_w_count += 1
# Returns Tuple of W count
return volume_w_count, state_w_count
def check_header(self, df):
'''Checks header for Order and missing or unexpected field names'''
default = self.config['header']
columns = df.columns
# Set of Unchecked columns.
unchecked_cols = set(columns)
for i, field in enumerate(default):
# Checks if Field in df and in correct column
if columns.contains(field):
if columns[i] == field:
print(field + ': True')
else:
print(field + ': Unexpected order')
unchecked_cols.remove(field)
else:
# Field not present in the df
print(field + ': Not Present')
# Prints all fields not in the format
if unchecked_cols:
print('\nNew Cols:', unchecked_cols)
for col in unchecked_cols:
if col.endswith(' ') or col.startswith(' '):
print('Whitespace found for: ' + col)
def check_unit_dict(self, df):
'''Checks commodities/products for New items or
Unexpected units of measurement
Keyword Arguments:
df -- A pandas DataFrame
replace -- Dictionary with values to replace
'''
default = self.config['unit_dict']
replace = self.config['replace_dict']
errors = 0
col = get_com_pro(df)
replaced_dict = {i:[] for i in replace.keys()}
is_replaced = False
if col == 'n/a':
return 'No Units Available'
for row in range(len(df[col])):
cell = df.loc[row, col]
if replace and replace.__contains__(cell):
replaced_dict.get(cell).append(row + 1)
is_replaced = True
continue
errors += self._check_unit(cell, default, row)
if is_replaced:
print('Items to replace: ', replaced_dict)
if errors <= 0:
print('All units valid :)')
return errors
def _check_unit(self, string, default, index):
'''Checks if item and unit in unit_dict'''
if string == '':
return 0
# Splits line by Item and Unit
line = split_unit(string)
# Checks if Item is valid and has correct units
if default.__contains__(line[0]):
if line[1] not in default.get(line[0]):
print('Row ' + str(index) + ': Unexpected Unit - (' + line[1]
+ ') [For Item: ' + line[0] + ']')
return 1
elif line[0] != '':
print('Row ' + str(index) + ': Unknown Item: ' + line[0])
return 1
return 0
def check_misc_cols(self, df):
'''Checks non-numerical columns for Unexpected Values'''
default = self.config['field_dict']
is_valid = True
if df.columns.contains('Calendar Year'):
self.check_year(df['Calendar Year'])
elif df.columns.contains('Fiscal Year'):
self.check_year(df['Fiscal Year'])
for field in default:
if df.columns.contains(field):
for row in range(len(df[field])):
cell = df.loc[row, field]
if cell not in default.get(field) and cell != '':
print(field + ' Row ' + str(row)
+ ': Unexpected Entry: ' + str(cell))
is_valid = False
if is_valid:
print('All fields valid :)')
return is_valid
def check_year(self, col):
'''Checks if year column is valid
Keyword Arguments:
col -- Column in which year is located
'''
current_year = datetime.now().year
years = {i for i in range(current_year, 1969, -1)}
for row, year in enumerate(col):
if year not in years:
print('Row ' + str(row + 2) + ': Invalid year ' + str(year))
def check_nan(self, df):
'''Checks if specific columns are missing values
'''
cols = self.config['na_check']
for col in cols:
if df.columns.contains(col):
for row in range(len(df.index)):
if df.loc[row, col] == '':
print('Row ' + str(row + 2) + ': Missing ' + col)
class Setup:
'''
For creating json files
'''
__slots__ = ['df']
def __init__(self, df):
'''Constructor for setup
Keyword Arguments:
df -- A pandas DataFrame
'''
self.df = df
# Returns Header List based on Excel DataFrame
def get_header(self):
return list(self.df.columns)
# Returns Unit Dictionary on Excel DataFrame
def get_unit_dict(self):
units = {}
col = get_com_pro(self.df)
if col == 'n/a':
return None
for row in self.df[col]:
# Key and Value split
line = split_unit(row)
key, value = line[0], line[1]
add_item(key, value, units)
return units
# Returns a dictionary of fields not listed in col_wlist
def get_misc_cols(self):
col_wlist = {'Revenue', 'Volume', 'Month', 'Production Volume',
'Total', 'Calendar Year'}
col_wlist.add(get_com_pro(self.df))
fields = {}
for col in self.df.columns:
if col not in col_wlist:
fields[col] = list({i for i in self.df[col]})
return fields
def get_na_check(self):
return ['Calendar Year', 'Corperate Name', 'Ficsal Year',
'Mineral Lease Type', 'Month', 'Onshore/Offshore', 'Volume']
def get_replace_dict(self):
return {'Mining-Unspecified' : 'Humate'}
def make_config_path(self):
'''Creates directory "config" if it does not exist'''
if not os.path.exists('config'):
print('No Config Folder found. Creating folder...')
os.mkdir('config')
def write_config(self, prefix):
'''Writes a json file based on the given Excel File
Keyword Arguments:
prefix -- Prefix of the new json file
'''
self.make_config_path()
with open('config/' + prefix + 'config.json', 'w') as config:
json_config = {'header' : self.get_header(),
'unit_dict' : self.get_unit_dict(),
'field_dict' : self.get_misc_cols(),
'replace_dict' : self.get_replace_dict(),
'na_check' : self.get_na_check(),
}
json.dump(json_config, config, indent=4)
def add_item(key, value, dct):
'''Adds key to dictionary if not present. Else adds value to key 'set'.
Keyword Arguments:
key -- Key entry for the dict, e.g. A commodity
value -- Value entry corresponding to key, e.g. Unit or Value
dictionary -- Reference to dictionary
'''
# Adds Value to Set if Key exists
if key in dct:
if value not in dct[key]:
dct[key].append(value)
# Else adds new key with value
else:
dct[key] = [value]
def get_prefix(name):
'''For naming config files
Keyword Arguments:
name -- Name of the Excel file
'''
lower = name.lower()
prefixes = ['cy', 'fy', 'monthly', 'company', 'federal', 'native',
'production', 'revenue', 'disbursements']
final_prefix = ''
for string in prefixes:
if string in lower:
final_prefix += string
return final_prefix + '_'
# Returns a list of the split string based on item and unit
def split_unit(string):
string = str(string)
# For general purpose commodities
if '(' in string:
split = string.rsplit(' (', 1)
split[1] = split[1].rstrip(')')
return split
# The comma is for Geothermal
elif ',' in string:
return string.split(', ', 1)
# In case no unit is found
return [string, '']
# Checks if 'Commodity', 'Product', both, or neither are present
def get_com_pro(df):
if not df.columns.contains('Product') and not df.columns.contains('Commodity'):
return 'n/a'
elif df.columns.contains('Commodity'):
return 'Commodity'
else:
return 'Product'
# Creates FormatChecker and runs methods
def do_check(df, prefix, name, export):
check = FormatChecker(prefix)
# Exports an Excel df with replaced entries
def export_excel(df, to_replace):
df.replace(to_replace, inplace=True)
writer = pd.ExcelWriter('../output/[new] ' + name, engine='xlsxwriter')
df.to_excel(writer, index=False, header=False)
workbook = writer.book
worksheet = writer.sheets['Sheet1']
header_format = workbook.add_format({
'align' : 'center',
'bold' : False,
'border' : 1,
'bg_color' : '#C0C0C0',
'valign' : 'bottom'
})
# cur_format = workbook.add_format({'num_format': '$#,##0.00'})
# num_format = workbook.add_format({'num_format': '#,##0.00'})
for col_num, value in enumerate(df.columns.values):
worksheet.write(0, col_num, value, header_format)
writer.save()
print('Exported new df to output')
check.check_header(df)
print()
check.check_unit_dict(df)
check.check_misc_cols(df)
check.check_nan(df)
w_count = check.get_w_count(df)
print('\n(Volume) Ws Found: ' + str(w_count[0]))
print('(Location) Ws Found: ' + str(w_count[1]))
if export:
export_excel(df, check.config['replace_dict'])
# Where all the stuff runs
def main():
prefix = get_prefix(sys.argv[-1])
df = pd.read_excel(sys.argv[-1]).fillna('')
if sys.argv[1] == 'setup':
config = Setup(df)
config.write_config(prefix)
else:
try:
do_check(df, prefix, sys.argv[-1], sys.argv[2] == 'export')
except FileNotFoundError:
print("Config not found! Please use setup for: " + prefix)
print('Done')
if __name__ == '__main__':
main()
|
def find_min_max(arr):
start_index = None
comparisons = 0
if len(arr) % 2 == 0:
if arr[0] > arr[1]:
max_val = arr[0]
min_val = arr[1]
else:
max_val = arr[1]
min_val = arr[0]
start_index = 2
comparisons += 1
else:
max_val = arr[0]
min_val = arr[0]
start_index = 1
for i in range(start_index, len(arr) - 1):
if arr[i] < arr[i + 1]:
if arr[i] < min_val:
min_val = arr[i]
if arr[i + 1] > max_val:
max_val = arr[i + 1]
comparisons += 2
else:
if arr[i + 1] < min_val:
min_val = arr[i + 1]
if arr[i] > max_val:
max_val = arr[i]
comparisons += 2
print(comparisons, len(arr))
return {'max': max_val, 'min': min_val}
example = find_min_max([40, 9, 3, 5, 10, 1, 7, 12])
print("Max: %d Min: %d" % (example['max'], example['min']))
|
# Generated by Django 2.2 on 2019-04-15 23:37
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('onlclass', '0019_auto_20190416_0834'),
]
operations = [
migrations.AlterField(
model_name='subject',
name='subject_type',
field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='onlclass.SubjectType', verbose_name='教科カテゴリ'),
),
]
|
# coding=utf-8
import os
import sys
from setuptools import find_packages
from setuptools import setup
assert sys.version_info[0] == 3 and sys.version_info[1] >= 6, "eosbase requires Python 3.6 or newer."
def readme_file():
return 'README.rst' if os.path.exists('README.rst') else 'README.md'
# yapf: disable
setup(
name='eosbase',
version='0.0.1',
description='Base Python Library for the EOS blockchain',
long_description=open(readme_file()).read(),
packages=find_packages(exclude=['scripts']),
setup_requires=['pytest-runner'],
tests_require=['pytest',
'pep8',
'pytest-pylint',
'yapf',
'sphinx',
'recommonmark',
'sphinxcontrib-restbuilder',
'sphinxcontrib-programoutput',
'pytest-console-scripts'],
install_requires=[
'ecdsa',
'pylibscrypt',
'scrypt',
'passlib',
'pycrypto',
'toolz',
'funcy',
])
|
import pandas as pd
import numpy as np
# from sklearn.linear_model import LogisticRegression
# from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier
# from sklearn.svm import SVC
# from xgboost import XGBClassifier
# from sklearn.tree import DecisionTreeClassifier
# from sklearn.dummy import DummyClassifier
from sklearn.linear_model import *
from sklearn.ensemble import *
from sklearn.svm import *
from xgboost import *
from sklearn.tree import *
from sklearn.dummy import *
from ggwp.EzModeling.Evaluation import Evaluation
class BenchMark(Evaluation):
def __init__(self):
super().__init__()
self.artifact_ = {}
def get_single_line(self, X_train, y_train, X_test, y_test, remark,
model_name, performance, artifact, method, id=None):
row, col = X_train.shape
columns = X_train.columns.to_list()
idx = self.idx
if method == 'add':
id = self.id
session = self.session
elif method == 'update':
id = int(id)
single_line_df = pd.DataFrame(
{
'id':id,
'session':session,
'remark': remark,
'model': model_name,
'performance': [performance.to_dict()],
'n_row':row,
'n_col':col,
'features': [columns],
'X_train': [X_train.to_dict()],
'y_train': [y_train.to_dict()],
'X_test': [X_test.to_dict()],
'y_test': [y_test.to_dict()],
},
index=[idx]
)
self.artifact_[id] = artifact
return single_line_df
def get_model(self, id):
return self.artifact_[id]
def add(self, X_train, y_train, X_test, y_test,
model_name, performance, artifact, remark="nope"):
single_line_df = self.get_single_line(X_train, y_train,
X_test, y_test, remark=remark,
model_name=model_name, performance=performance,
artifact=artifact, method='add', id=None)
self.get_id('add')
self.log = pd.concat([self.log,single_line_df],axis=0, ignore_index=True)
return self.log
def remove_session(self,session):
if self.log.shape[0] == 1:
self.log = pd.DataFrame()
elif self.log.shape[0] > 1:
self.log = self.log.loc[self.log['session'] != session]
self.log.index = np.arange(self.log.shape[0])
return self.log
# *design logic first*
# def update(self,data, remark="nope", id=None):
# single_line_df = self.get_single_line(data, remark, method='update', id=id)
# self.log.loc[self.log['id']==id] = single_line_df.values
# return self.log
def train_model(self, X_train, y_train, X_test, y_test, model_dict, probability='target'):
model_results = {}
model_artifacts = {}
for model_name, base_model in model_dict.items():
print(f"start {model_name}")
model = base_model
model.fit(X_train,y_train)
model_artifacts[model_name] = model
probabilities = model.predict_proba(X_test)
# if probability=='target':
# model_results[model_name] = probabilities[:,1]
# elif probability=='all':
# model_results[model_name] = probabilities[:,:]
# return model_artifacts, model_results
return model_artifacts
def benchmark(self, X_train, y_train, X_test, y_test, model_dict, remark, kind, cost, benefit):
# model_artifacts, model_results = self.train_model(X_train, y_train, X_test, y_test, model_dict)
model_artifacts = self.train_model(X_train, y_train, X_test, y_test, model_dict)
for model_name, artifact in model_artifacts.items():
if kind == 'classification':
performance = self.get_classification_report(model_name,y_test,artifact.predict_proba(X_test)[:,1],cost=cost,benefit=benefit)
elif kind == 'regression':
performance = self.get_regression_report(model_name,y_test,artifact.predict(X_test))
self.add(X_train=X_train, y_train=y_train, X_test=X_test, y_test=y_test,
model_name=model_name, performance=performance, artifact=artifact, remark=remark)
self.get_session(method='add')
def classification_benchmark(self, X_train, y_train, X_test, y_test, model_dict, cost=0, benefit=0,remark='nope'):
self.benchmark(X_train, y_train, X_test, y_test, model_dict, remark=remark, kind='classification', cost=cost, benefit=benefit)
return self.log
def regression_benchmark(self, X_train, y_train, X_test, y_test, model_dict, remark='nope'):
self.benchmark(X_train, y_train, X_test, y_test, model_dict, remark=remark, kind='regression')
return self.log
def get_data(self, id, kind='X_test'):
if kind in ['X_train','X_test']:
kind_df = pd.DataFrame(self.log.loc[self.log['id']==id, kind].values[0])
elif kind in ['y_train','y_test']:
kind_df = pd.Series(self.log.loc[self.log['id']==id, kind].values[0])
return kind_df
def get_performance(self, id):
kind_df = pd.DataFrame(self.log.loc[self.log['id']==id, 'performance'].values[0])
return kind_df
def model_performance(self, id=None, session=None):
if type(id) == int:
id = [id]
if type(session) == int:
session = [session]
if (id==None) & (session==None):
performance_df = self.log.loc[:, ['id','session','performance']]
elif (id==None) & (session!=None):
performance_df = self.log.loc[self.log['session'].isin(session), ['id','session','performance']]
elif (id!=None) & (session==None):
performance_df = self.log.loc[self.log['id'].isin(id), ['id','session','performance']]
else:
performance_df = self.log.loc[(self.log['id'].isin(id)) & (self.log['session'].isin(session)),
['id','session','performance']]
ids = performance_df['id'].unique()
final_df = pd.DataFrame()
for id in ids:
final_df = pd.concat([final_df,
self.get_performance(id=id)],
axis=0, ignore_index=True)
return final_df |
stk=[]
size=int(input('enter the size'))
top=0
n=0
def push():
global top,size
if(top>size):
print('stack is full')
else:
p=int(input('enter the element want to push'))
stk.append(p)
top+=1
def pop():
global top,size
if(top<=0):
print('stack is empty')
else:
stk.pop()
top-=1
def display():
print(stk)
while (n!=1):
print('enter the operation to perform')
print('1.push')
print('2.pop')
print('3.display')
while(n!=1):
print('enter the operation to perform')
option=int(input('press 1.push 2.pop 3.display')
if(option==2):
pop()
elif(option==3):
display()
|
import os
from util.class_property import ClassProperty
__all__ = ["FileStore"]
_GOOD_SONG_DIR_ENV = "GOOD_SONG_DIR"
_BAD_SONG_DIR_ENV = "BAD_SONG_DIR"
class FileStore(object):
@ClassProperty
@classmethod
def good_songs_dir(cls):
return FileStore.__get_song_dir(_GOOD_SONG_DIR_ENV)
@ClassProperty
@classmethod
def bad_songs_dir(cls):
return FileStore.__get_song_dir(_BAD_SONG_DIR_ENV)
@staticmethod
def __get_song_dir(env_var):
try:
return os.environ[env_var]
except KeyError:
raise RuntimeError("[{}] is not defined. Specify the path to this song directory in the environment "
"variables".format(env_var))
|
#import sys
#input = sys.stdin.readline
Q = 10**9+7
def getInv(N):#Qはmod
inv = [0] * (N + 1)
inv[0] = 1
inv[1] = 1
for i in range(2, N + 1):
inv[i] = (-(Q // i) * inv[Q%i]) % Q
return inv
def getFactorialInv(N):
inv = [0] * (N + 1)
inv[0] = 1
inv[1] = 1
ret = [1]*(N+1)
for i in range(2, N + 1):
inv[i] = (-(Q // i) * inv[Q%i]) % Q
ret[i] = ret[i-1]*inv[i]
return ret
def getFactorial(N):
ret = [1]*(N+1)
for i in range(2,N+1):
ret[i] = ret[i-1]*i%Q
return ret
def main():
r1, c1, r2, c2 = map( int, input().split())
F = getFactorial(2*(10**6))
J = getInv(2*(10**6))
I = [0]*(10**6+1)
I[0] = 1
I[1] = 1
for i in range(2,10**6+1):
I[i] = I[i-1]*J[i]%Q
#print(F[5]*I[5]%Q)
a = 0
b = 0
c = 0
d = 0
for i in range(1, c2+1):
a += F[r2+i+1]*I[i+1]%Q*I[r2]%Q-1
# print(F[r2+i+1]*I[i+1]%Q*I[r2]%Q-1)
a %= Q
if r1 == 1:
b = 0
else:
for i in range(1, c2+1):
b += F[r1+i]*I[i]%Q*I[r1]%Q-1
b %= Q
if c1 == 1:
c = 0
else:
for i in range(1, c1):
c += F[r2+i+1]*I[i+1]%Q*I[r2]%Q-1
c %= Q
if c1 == 1 or r1 == 1:
d = 0
else:
for i in range(1, c1):
d += F[r1+i]*I[i]%Q*I[r1]%Q-1
d %= Q
# print(a, b,c, d)
print((a-b-c+d)%Q)
if __name__ == '__main__':
main()
|
from django.urls import path
from .views import checkout,HomeView,ItemDetailView
app_name='core'
urlpatterns=[
path('product/<slug>',ItemDetailView.as_view(),name='product'),
path('',HomeView.as_view(),name='home'),
path('checkout/',checkout,name='checkout'),
] |
from utils import parse_to_tree, read_input
def get_metadata_sum(node):
return sum(node.metadata) + sum(map(get_metadata_sum, node.children))
if __name__ == '__main__':
tree = parse_to_tree(read_input())
print(get_metadata_sum(tree))
|
import copy
import os
import os.path as osp
from typing import Sequence, Union, List, Tuple, Type, Optional
from . import GaussianFilterLayer
from .layers import (
FilteredFieldLayer,
FilterFreeFieldLayer,
Layer,
PerfectBBLayer,
PerfectFieldLayer,
FilterFreeConeLayer,
PerfectConeLayer,
)
from .simulators import Simulator
from ..geometry import cos, sin
from ...picketfence import Orientation
def generate_lightrad(
file_out: str,
simulator: Simulator,
field_layer: Type[
Union[FilterFreeFieldLayer, FilteredFieldLayer, PerfectFieldLayer]
],
field_size_mm: (float, float) = (150, 150),
cax_offset_mm: (float, float) = (0, 0),
final_layers: List[Layer] = [
GaussianFilterLayer(),
],
bb_size_mm: float = 3,
bb_positions: ((float, float), ...) = (
(-40, -40),
(-40, 40),
(40, -40),
(40, 40),
(-65, -65),
(-65, 65),
(65, -65),
(65, 65),
),
) -> None:
"""Create a mock light/rad image with BBs.
Parameters
----------
simulator
The image simulator
field_layer
The primary field layer
file_out
The name of the file to save the DICOM file to.
final_layers
Optional layers to apply at the end of the procedure. Useful for noise or blurring.
bb_size_mm
The size of the phantom BBs
bb_positions
The position of the BBs relative to the CAX.
"""
# open field layer
simulator.add_layer(
field_layer(field_size_mm=field_size_mm, cax_offset_mm=cax_offset_mm)
)
# bbs
for bb in bb_positions:
simulator.add_layer(PerfectBBLayer(bb_size_mm=bb_size_mm, cax_offset_mm=bb))
if final_layers is not None:
for layer in final_layers:
simulator.add_layer(layer)
simulator.generate_dicom(file_out)
def generate_picketfence(
simulator: Simulator,
field_layer: Type[
Union[FilterFreeFieldLayer, FilteredFieldLayer, PerfectFieldLayer]
],
file_out: str,
final_layers: List[Layer] = None,
pickets: int = 11,
picket_spacing_mm: float = 20,
picket_width_mm: int = 2,
picket_height_mm: int = 300,
gantry_angle: int = 0,
orientation: Orientation = Orientation.UP_DOWN,
picket_offset_error: Optional[Sequence] = None,
) -> None:
"""Create a mock picket fence image. Will always be up-down.
Parameters
----------
simulator
The image simulator
field_layer
The primary field layer
file_out
The name of the file to save the DICOM file to.
final_layers
Optional layers to apply at the end of the procedure. Useful for noise or blurring.
pickets
The number of pickets
picket_spacing_mm
The space between pickets
picket_width_mm
Picket width parallel to leaf motion
picket_height_mm
Picket height parallel to leaf motion
gantry_angle
Gantry angle; sets the DICOM tag.
"""
picket_pos_mm = range(
-int((pickets - 1) * picket_spacing_mm / 2),
int((pickets - 1) * picket_spacing_mm / 2) + 1,
picket_spacing_mm,
)
for idx, pos in enumerate(picket_pos_mm):
if picket_offset_error is not None:
if len(picket_offset_error) != pickets:
raise ValueError(
"The length of the error array must be the same as the number of pickets."
)
pos += picket_offset_error[idx]
if orientation == orientation.UP_DOWN:
position = (0, pos)
layout = (picket_height_mm, picket_width_mm)
else:
position = (pos, 0)
layout = (picket_width_mm, picket_height_mm)
simulator.add_layer(field_layer(layout, cax_offset_mm=position))
if final_layers is not None:
for layer in final_layers:
simulator.add_layer(layer)
simulator.generate_dicom(file_out, gantry_angle=gantry_angle)
def generate_winstonlutz(
simulator: Simulator,
field_layer: Type[Layer],
dir_out: str,
field_size_mm: Tuple[float, float] = (30, 30),
final_layers: Optional[List[Layer]] = None,
bb_size_mm: float = 5,
offset_mm_left: float = 0,
offset_mm_up: float = 0,
offset_mm_in: float = 0,
image_axes: ((int, int, int), ...) = (
(0, 0, 0),
(90, 0, 0),
(180, 0, 0),
(270, 0, 0),
),
gantry_tilt: float = 0,
gantry_sag: float = 0,
clean_dir: bool = True,
) -> List[str]:
"""Create a mock set of WL images, simulating gantry sag effects. Produces one image for each item in image_axes.
Parameters
----------
simulator
The image simulator
field_layer
The primary field layer simulating radiation
dir_out
The directory to save the images to.
field_size_mm
The field size of the radiation field in mm
final_layers
Layers to apply after generating the primary field and BB layer. Useful for blurring or adding noise.
bb_size_mm
The size of the BB. Must be positive.
offset_mm_left
How far left (lat) to set the BB. Can be positive or negative.
offset_mm_up
How far up (vert) to set the BB. Can be positive or negative.
offset_mm_in
How far in (long) to set the BB. Can be positive or negative.
image_axes
List of axis values for the images. Sequence is (Gantry, Coll, Couch).
gantry_tilt
The tilt of the gantry that affects the position at 0 and 180. Simulates a simple cosine function.
gantry_sag
The sag of the gantry that affects the position at gantry=90 and 270. Simulates a simple sine function.
clean_dir
Whether to clean out the output directory. Useful when iterating.
"""
if not osp.isdir(dir_out):
os.mkdir(dir_out)
if clean_dir:
for pdir, _, files in os.walk(dir_out):
[os.remove(osp.join(pdir, f)) for f in files]
file_names = []
for (gantry, coll, couch) in image_axes:
sim_single = copy.copy(simulator)
sim_single.add_layer(
field_layer(
field_size_mm=field_size_mm,
cax_offset_mm=(gantry_tilt * cos(gantry), gantry_sag * sin(gantry)),
)
)
sim_single.add_layer(
PerfectBBLayer(
cax_offset_mm=(
-offset_mm_in,
-offset_mm_left * cos(gantry) - offset_mm_up * sin(gantry),
),
bb_size_mm=bb_size_mm,
)
)
if final_layers is not None:
for layer in final_layers:
sim_single.add_layer(layer)
file_name = f"WL G={gantry}, C={coll}, P={couch}; Field={field_size_mm}mm; BB={bb_size_mm}mm @ left={offset_mm_left}, in={offset_mm_in}, up={offset_mm_up}; Gantry tilt={gantry_tilt}, Gantry sag={gantry_sag}.dcm"
sim_single.generate_dicom(
osp.join(dir_out, file_name),
gantry_angle=gantry,
coll_angle=coll,
table_angle=couch,
)
file_names.append(file_name)
return file_names
def generate_winstonlutz_cone(
simulator: Simulator,
cone_layer: Union[Type[FilterFreeConeLayer], Type[PerfectConeLayer]],
dir_out: str,
cone_size_mm: float = 17.5,
final_layers: Optional[List[Layer]] = None,
bb_size_mm: float = 5,
offset_mm_left: float = 0,
offset_mm_up: float = 0,
offset_mm_in: float = 0,
image_axes: ((int, int, int), ...) = (
(0, 0, 0),
(90, 0, 0),
(180, 0, 0),
(270, 0, 0),
),
gantry_tilt: float = 0,
gantry_sag: float = 0,
clean_dir: bool = True,
) -> List[str]:
"""Create a mock set of WL images with a cone field, simulating gantry sag effects. Produces one image for each item in image_axes.
Parameters
----------
simulator
The image simulator
cone_layer
The primary field layer simulating radiation
dir_out
The directory to save the images to.
cone_size_mm
The field size of the radiation field in mm
final_layers
Layers to apply after generating the primary field and BB layer. Useful for blurring or adding noise.
bb_size_mm
The size of the BB. Must be positive.
offset_mm_left
How far left (lat) to set the BB. Can be positive or negative.
offset_mm_up
How far up (vert) to set the BB. Can be positive or negative.
offset_mm_in
How far in (long) to set the BB. Can be positive or negative.
image_axes
List of axis values for the images. Sequence is (Gantry, Coll, Couch).
gantry_tilt
The tilt of the gantry that affects the position at 0 and 180. Simulates a simple cosine function.
gantry_sag
The sag of the gantry that affects the position at gantry=90 and 270. Simulates a simple sine function.
clean_dir
Whether to clean out the output directory. Useful when iterating.
"""
if not osp.isdir(dir_out):
os.mkdir(dir_out)
if clean_dir:
for pdir, _, files in os.walk(dir_out):
[os.remove(osp.join(pdir, f)) for f in files]
file_names = []
for (gantry, coll, couch) in image_axes:
sim_single = copy.copy(simulator)
sim_single.add_layer(
cone_layer(
cone_size_mm=cone_size_mm,
cax_offset_mm=(gantry_tilt * cos(gantry), gantry_sag * sin(gantry)),
)
)
sim_single.add_layer(
PerfectBBLayer(
cax_offset_mm=(
-offset_mm_in,
-offset_mm_left * cos(gantry) - offset_mm_up * sin(gantry),
)
)
)
if final_layers is not None:
for layer in final_layers:
sim_single.add_layer(layer)
file_name = f"WL G={gantry}, C={coll}, P={couch}; Cone={cone_size_mm}mm; BB={bb_size_mm}mm @ left={offset_mm_left}, in={offset_mm_in}, up={offset_mm_up}; Gantry tilt={gantry_tilt}, Gantry sag={gantry_sag}.dcm"
sim_single.generate_dicom(
osp.join(dir_out, file_name),
gantry_angle=gantry,
coll_angle=coll,
table_angle=couch,
)
file_names.append(file_name)
return file_names
|
'''This module implements Picture Transfer Protocol (ISO 15740:2013(E))
It is transport agnostic and requires a transport layer to provide the missing
methods in the class :py:class`PTPDevice`.
Convenience structures are provided to pack messages. These are native-endian
and may need to be adapted to transport-endianness by calling
`_set_endian(endianness)` where `endianness` can be `'big'`, `'little'` or
`'native'`.
'''
from construct import (
Array, BitsInteger, Computed, Container, Enum, ExprAdapter, Int16sb,
Int16sl, Int16sn, Int16ub, Int16ul, Int16un, Int32sb, Int32sl, Int32sn,
Int32ub, Int32ul, Int32un, Int64sb, Int64sl, Int64sn, Int64ub, Int64ul,
Int64un, Int8sb, Int8sl, Int8sn, Int8ub, Int8ul, Int8un, Pass,
PrefixedArray, Struct, Switch,
)
from contextlib import contextmanager
from dateutil.parser import parse as iso8601
from datetime import datetime
import logging
import six
logger = logging.getLogger(__name__)
# Module specific
# _______________
__all__ = ('PTPError', 'PTPUnimplemented', 'PTP',)
__author__ = 'Luis Mario Domenzain'
# Exceptions
# ----------
class PTPError(Exception):
'''PTP implementation exceptions.'''
pass
class PTPUnimplemented(PTPError):
'''Exception to indicate missing implementation.'''
pass
class PTP(object):
'''Implement bare PTP device. Vendor specific devices should extend it.'''
# Base PTP protocol transaction elements
# --------------------------------------
_UInt8 = Int8un
_UInt16 = Int16un
_UInt32 = Int32un
_UInt64 = Int64un
_UInt128 = BitsInteger(128)
_Int8 = Int8sn
_Int16 = Int16sn
_Int32 = Int32sn
_Int64 = Int64sn
_Int128 = BitsInteger(128, signed=True)
def _Parameter(self):
'''Return desired endianness for Parameter'''
return self._UInt32
def _SessionID(self):
'''Return desired endianness for SessionID'''
return self._UInt32
def _TransactionID(self):
'''Return desired endianness for TransactionID'''
return Enum(
self._UInt32,
default=Pass,
NA=0xFFFFFFFF,
)
# TODO: Check if these Enums can be replaced with more general
# associations. Or even with Python Enums. Otherwise there is always a risk
# of a typo creeping in.
def _OperationCode(self, **vendor_operations):
'''Return desired endianness for known OperationCode'''
return Enum(
self._UInt16,
default=Pass,
Undefined=0x1000,
GetDeviceInfo=0x1001,
OpenSession=0x1002,
CloseSession=0x1003,
GetStorageIDs=0x1004,
GetStorageInfo=0x1005,
GetNumObjects=0x1006,
GetObjectHandles=0x1007,
GetObjectInfo=0x1008,
GetObject=0x1009,
GetThumb=0x100A,
DeleteObject=0x100B,
SendObjectInfo=0x100C,
SendObject=0x100D,
InitiateCapture=0x100E,
FormatStore=0x100F,
ResetDevice=0x1010,
SelfTest=0x1011,
SetObjectProtection=0x1012,
PowerDown=0x1013,
GetDevicePropDesc=0x1014,
GetDevicePropValue=0x1015,
SetDevicePropValue=0x1016,
ResetDevicePropValue=0x1017,
TerminateOpenCapture=0x1018,
MoveObject=0x1019,
CopyObject=0x101A,
GetPartialObject=0x101B,
InitiateOpenCapture=0x101C,
StartEnumHandles=0x101D,
EnumHandles=0x101E,
StopEnumHandles=0x101F,
GetVendorExtensionMapss=0x1020,
GetVendorDeviceInfo=0x1021,
GetResizedImageObject=0x1022,
GetFilesystemManifest=0x1023,
GetStreamInfo=0x1024,
GetStream=0x1025,
**vendor_operations
)
def _ResponseCode(self, **vendor_responses):
'''Return desired endianness for known ResponseCode'''
return Enum(
self._UInt16,
default=Pass,
Undefined=0x2000,
OK=0x2001,
GeneralError=0x2002,
SessionNotOpen=0x2003,
InvalidTransactionID=0x2004,
OperationNotSupported=0x2005,
ParameterNotSupported=0x2006,
IncompleteTransfer=0x2007,
InvalidStorageId=0x2008,
InvalidObjectHandle=0x2009,
DevicePropNotSupported=0x200A,
InvalidObjectFormatCode=0x200B,
StoreFull=0x200C,
ObjectWriteProtected=0x200D,
StoreReadOnly=0x200E,
AccessDenied=0x200F,
NoThumbnailPresent=0x2010,
SelfTestFailed=0x2011,
PartialDeletion=0x2012,
StoreNotAvailable=0x2013,
SpecificationByFormatUnsupported=0x2014,
NoValidObjectInfo=0x2015,
InvalidCodeFormat=0x2016,
UnknownVendorCode=0x2017,
CaptureAlreadyTerminated=0x2018,
DeviceBusy=0x2019,
InvalidParentObject=0x201A,
InvalidDevicePropFormat=0x201B,
InvalidDevicePropValue=0x201C,
InvalidParameter=0x201D,
SessionAlreadyOpened=0x201E,
TransactionCanceled=0x201F,
SpecificationOfDestinationUnsupported=0x2020,
InvalidEnumHandle=0x2021,
NoStreamEnabled=0x2022,
InvalidDataset=0x2023,
**vendor_responses
)
def _EventCode(self, **vendor_events):
'''Return desired endianness for known EventCode'''
return Enum(
self._UInt16,
default=Pass,
Undefined=0x4000,
CancelTransaction=0x4001,
ObjectAdded=0x4002,
ObjectRemoved=0x4003,
StoreAdded=0x4004,
StoreRemoved=0x4005,
DevicePropChanged=0x4006,
ObjectInfoChanged=0x4007,
DeviceInfoChanged=0x4008,
RequestObjectTransfer=0x4009,
StoreFull=0x400A,
DeviceReset=0x400B,
StorageInfoChanged=0x400C,
CaptureComplete=0x400D,
UnreportedStatus=0x400E,
**vendor_events
)
def _Event(self):
return Struct(
'EventCode' / self._EventCode,
'SessionID' / self._SessionID,
'TransactionID' / self._TransactionID,
'Parameter' / Array(3, self._Parameter),
)
def _Response(self):
return Struct(
'ResponseCode' / self._ResponseCode,
'SessionID' / self._SessionID,
'TransactionID' / self._TransactionID,
'Parameter' / Array(5, self._Parameter),
)
def _Operation(self):
return Struct(
'OperationCode' / self._OperationCode,
'SessionID' / self._SessionID,
'TransactionID' / self._TransactionID,
'Parameter' / Array(5, self._Parameter),
)
def _PropertyCode(self, **vendor_properties):
'''Return desired endianness for known OperationCode'''
return Enum(
self._UInt16,
default=Pass,
Undefined=0x5000,
BatteryLevel=0x5001,
FunctionalMode=0x5002,
ImageSize=0x5003,
CompressionSetting=0x5004,
WhiteBalance=0x5005,
RGBGain=0x5006,
FNumber=0x5007,
FocalLength=0x5008,
FocusDistance=0x5009,
FocusMode=0x500A,
ExposureMeteringMode=0x500B,
FlashMode=0x500C,
ExposureTime=0x500D,
ExposureProgramMode=0x500E,
ExposureIndex=0x500F,
ExposureBiasCompensation=0x5010,
DateTime=0x5011,
CaptureDelay=0x5012,
StillCaptureMode=0x5013,
Contrast=0x5014,
Sharpness=0x5015,
DigitalZoom=0x5016,
EffectMode=0x5017,
BurstNumber=0x5018,
BurstInterval=0x5019,
TimelapseNumber=0x501A,
TimelapseInterval=0x501B,
FocusMeteringMode=0x501C,
UploadURL=0x501D,
Artist=0x501E,
CopyrightInfo=0x501F,
**vendor_properties
)
# PTP Datasets for specific operations
# ------------------------------------
def _ObjectHandle(self):
'''Return desired endianness for ObjectHandle'''
return self._UInt32
def _ObjectFormatCode(self, **vendor_object_formats):
'''Return desired endianness for known ObjectFormatCode'''
return Enum(
self._UInt16,
default=Pass,
# Ancilliary
UndefinedAncilliary=0x3000,
Association=0x3001,
Script=0x3002,
Executable=0x3003,
Text=0x3004,
HTML=0x3005,
DPOF=0x3006,
AIFF=0x3007,
WAV=0x3008,
MP3=0x3009,
AVI=0x300A,
MPEG=0x300B,
ASF=0x300C,
QT=0x300D,
# Images
UndefinedImage=0x3800,
EXIF_JPEG=0x3801,
TIFF_EP=0x3802,
FlashPix=0x3803,
BMP=0x3804,
CIFF=0x3805,
GIF=0x3807,
JFIF=0x3808,
PCD=0x3809,
PICT=0x380A,
PNG=0x380B,
TIFF=0x380D,
TIFF_IT=0x380E,
JP2=0x380F,
JPX=0x3810,
DNG=0x3811,
**vendor_object_formats
)
def _DateTime(self):
'''Return desired endianness for DateTime'''
return ExprAdapter(
self._PTPString,
encoder=lambda obj, ctx:
# TODO: Support timezone encoding.
datetime.strftime(obj, '%Y%m%dT%H%M%S.%f')[:-5],
decoder=lambda obj, ctx: iso8601(obj),
)
def _PTPString(self):
'''Returns a PTP String constructor'''
return ExprAdapter(
PrefixedArray(self._UInt8, self._UInt16),
encoder=lambda obj, ctx:
[] if len(obj) == 0 else [ord(c) for c in six.text_type(obj)]+[0],
decoder=lambda obj, ctx:
u''.join(
[six.unichr(o) for o in obj]
).split('\x00')[0],
)
def _PTPArray(self, element):
return PrefixedArray(self._UInt32, element)
def _VendorExtensionID(self):
return Enum(
self._UInt32,
default=Pass,
EastmanKodak=0x00000001,
SeikoEpson=0x00000002,
Agilent=0x00000003,
Polaroid=0x00000004,
AgfaGevaert=0x00000005,
Microsoft=0x00000006,
Equinox=0x00000007,
Viewquest=0x00000008,
STMicroelectronics=0x00000009,
Nikon=0x0000000A,
Canon=0x0000000B,
FotoNation=0x0000000C,
PENTAX=0x0000000D,
Fuji=0x0000000E,
Sony=0x00000011, # Self-imposed.
NDD=0x00000012, # ndd Medical Technologies
Samsung=0x0000001A,
Parrot=0x0000001B,
Panasonic=0x0000001C,
)
def _DeviceInfo(self):
'''Return desired endianness for DeviceInfo'''
return Struct(
'StandardVersion' / self._UInt16,
'VendorExtensionID' / self._VendorExtensionID,
'VendorExtensionVersion' / self._UInt16,
'VendorExtensionDesc' / self._PTPString,
'FunctionalMode' / self._UInt16,
'OperationsSupported' / self._PTPArray(self._OperationCode),
'EventsSupported' / self._PTPArray(self._EventCode),
'DevicePropertiesSupported' / self._PTPArray(self._PropertyCode),
'CaptureFormats' / self._PTPArray(self._ObjectFormatCode),
'ImageFormats' / self._PTPArray(self._ObjectFormatCode),
'Manufacturer' / self._PTPString,
'Model' / self._PTPString,
'DeviceVersion' / self._PTPString,
'SerialNumber' / self._PTPString,
)
def _StorageType(self):
'''Return desired endianness for StorageType'''
return Enum(
self._UInt16,
default=Pass,
Undefined=0x0000,
FixedROM=0x0001,
RemovableROM=0x0002,
FixedRAM=0x0003,
RemovableRAM=0x0004,
)
def _FilesystemType(self, **vendor_filesystem_types):
'''Return desired endianness for known FilesystemType'''
return Enum(
self._UInt16,
default=Pass,
Undefined=0x0000,
GenericFlat=0x0001,
GenericHierarchical=0x0002,
DCF=0x0003,
**vendor_filesystem_types
)
def _AccessCapability(self):
'''Return desired endianness for AccessCapability'''
return Enum(
self._UInt16,
default=Pass,
ReadWrite=0x0000,
ReadOnlyWithoutObjectDeletion=0x0001,
ReadOnlyWithObjectDeletion=0x0002,
)
def _StorageInfo(self):
'''Return desired endianness for StorageInfo'''
return Struct(
'StorageType' / self._StorageType,
'FilesystemType' / self._FilesystemType,
'AccessCapability' / self._AccessCapability,
'MaxCapacity' / self._UInt64,
'FreeSpaceInBytes' / self._UInt64,
'FreeSpaceInImages' / self._UInt32,
'StorageDescription' / self._PTPString,
'VolumeLabel' / self._PTPString,
)
def _StorageID(self):
'''Return desired endianness for StorageID'''
# TODO: automatically set and parse PhysicalID and LogicalID
return self._UInt32
def _StorageIDs(self):
'''Return desired endianness for StorageID'''
# TODO: automatically set and parse PhysicalID and LogicalID
return self._PTPArray(self._StorageID)
def _DataTypeCode(self, **vendor_datatype_codes):
'''Return desired endianness for DevicePropDesc'''
return Enum(
self._UInt16,
default=Pass,
Undefined=0x0000,
Int128=0x0009,
Int128Array=0x4009,
Int16=0x0003,
Int16Array=0x4003,
Int32=0x0005,
Int32Array=0x4005,
Int64=0x0007,
Int64Array=0x4007,
Int8=0x0001,
Int8Array=0x4001,
UInt128=0x000a,
UInt128Array=0x400a,
UInt16=0x0004,
UInt16Array=0x4004,
UInt32=0x0006,
UInt32Array=0x4006,
UInt64=0x0008,
UInt64Array=0x4008,
UInt8=0x0002,
UInt8Array=0x4002,
String=0xFFFF,
**vendor_datatype_codes
)
def _DataType(self, **vendor_datatypes):
datatypes = {
'Int128': self._Int128,
'Int128Array': self._PTPArray(self._Int128),
'Int16': self._Int16,
'Int16Array': self._PTPArray(self._Int16),
'Int32': self._Int32,
'Int32Array': self._PTPArray(self._Int32),
'Int64': self._Int64,
'Int64Array': self._PTPArray(self._Int64),
'Int8': self._Int8,
'Int8Array': self._PTPArray(self._Int8),
'UInt128': self._UInt128,
'UInt128Array': self._PTPArray(self._UInt128),
'UInt16': self._UInt16,
'UInt16Array': self._PTPArray(self._UInt16),
'UInt32': self._UInt32,
'UInt32Array': self._PTPArray(self._UInt32),
'UInt64': self._UInt64,
'UInt64Array': self._PTPArray(self._UInt64),
'UInt8': self._UInt8,
'UInt8Array': self._PTPArray(self._UInt8),
'String': self._PTPString,
}
datatypes.update(vendor_datatypes if vendor_datatypes else {})
def DataTypeCode(ctx):
# Try to get the DataTypeCode from the parent contexts up to 20
# levels...
for i in range(20):
try:
return ctx.DataTypeCode
except AttributeError:
ctx = ctx._
return Switch(
DataTypeCode,
datatypes,
default=Pass
)
def _GetSet(self):
return Enum(
self._UInt8,
default=Pass,
Get=0x00,
GetSet=0x01,
)
def _FormFlag(self):
return Enum(
self._UInt8,
default=Pass,
NoForm=0x00,
Range=0x01,
Enumeration=0x02,
)
def _RangeForm(self, element):
return Struct(
'MinimumValue' / element,
'MaximumValue' / element,
'StepSize' / element,
)
def _EnumerationForm(self, element):
return PrefixedArray(self._UInt16, element)
def _Form(self, element):
return Switch(
lambda x: x.FormFlag,
{
'Range': 'Range' / self._RangeForm(element),
'Enumeration': 'Enumeration' / self._EnumerationForm(element),
'NoForm': Pass
},
default=Pass,
)
def _DevicePropDesc(self):
'''Return desired endianness for DevicePropDesc'''
return Struct(
'PropertyCode' / self._PropertyCode,
'DataTypeCode' / self._DataTypeCode,
'GetSet' / self._GetSet,
'FactoryDefaultValue' / self._DataType,
'CurrentValue' / self._DataType,
'FormFlag' / self._FormFlag,
'Form' / self._Form(self._DataType)
)
def _ProtectionStatus(self):
return Enum(
self._UInt16,
default=Pass,
NoProtection=0x0000,
ReadOnly=0x0001,
)
def _AssociationType(self, **vendor_associations):
return Enum(
self._UInt16,
default=Pass,
Undefined=0x0000,
GenericFolder=0x0001,
Album=0x0002,
TimeSequence=0x0003,
HorizontalPanoramic=0x0004,
VerticalPanoramic=0x0005,
Panoramic2D=0x0006,
AncillaryData=0x0007,
**vendor_associations
)
def _AssociationDesc(self, **vendor_associations):
return Enum(
self._UInt32,
default=Pass,
Undefined=0x00000000,
DefaultPlaybackData=0x00000003,
ImagesPerRow=0x00000006,
**vendor_associations
)
def _ObjectInfo(self):
'''Return desired endianness for ObjectInfo'''
return Struct(
'StorageID' / self._StorageID,
'ObjectFormat' / self._ObjectFormatCode,
'ProtectionStatus' / self._ProtectionStatus,
'ObjectCompressedSize' / self._UInt32,
'ThumbFormat' / self._ObjectFormatCode,
'ThumbCompressedSize' / self._UInt32,
'ThumbPixWidth' / self._UInt32,
'ThumbPixHeight' / self._UInt32,
'ImagePixWidth' / self._UInt32,
'ImagePixHeight' / self._UInt32,
'ImageBitDepth' / self._UInt32,
'ParentObject' / self._ObjectHandle,
'AssociationType' / self._AssociationType,
'AssociationDesc' / self._AssociationDesc,
'SequenceNumber' / self._UInt32,
'Filename' / self._PTPString,
'CaptureDate' / self._DateTime,
'ModificationDate' / self._DateTime,
'Keywords' / self._PTPString,
)
def _VendorExtensionMap(self):
'''Return desired endianness for VendorExtensionMap'''
# TODO: Integrate vendor extensions and their Enums to parse Native
# codes to their name.
return Struct(
'NativeCode' / self._UInt16,
'MappedCode' / self._UInt16,
'MappedVendorExtensionID' / self._VendorExtensionID,
)
def _VendorExtensionMapArray(self):
'''Return desired endianness for VendorExtensionMapArray'''
return PrefixedArray(
self._UInt64,
self._VendorExtensionMap,
)
# Helper to concretize generic constructors to desired endianness
# ---------------------------------------------------------------
def _set_endian(self, endian, explicit=None):
'''Instantiate constructors to given endianness'''
# All constructors need to be instantiated before use by setting their
# endianness. But only those that don't depend on endian-generic
# constructors need to be explicitly instantiated to a given
# endianness.
logger.debug('Set PTP endianness')
if endian == 'little':
self._UInt8 = Int8ul
self._UInt16 = Int16ul
self._UInt32 = Int32ul
self._UInt64 = Int64ul
self._UInt128 = BitsInteger(128, signed=False, swapped=True)
self._Int8 = Int8sl
self._Int16 = Int16sl
self._Int32 = Int32sl
self._Int64 = Int64sl
self._Int128 = BitsInteger(128, signed=True, swapped=True)
elif endian == 'big':
self._UInt8 = Int8ub
self._UInt16 = Int16ub
self._UInt32 = Int32ub
self._UInt64 = Int64ub
self._UInt128 = BitsInteger(128, signed=False, swapped=False)
self._Int8 = Int8sb
self._Int16 = Int16sb
self._Int32 = Int32sb
self._Int64 = Int64sb
self._Int128 = BitsInteger(128, signed=True, swapped=False)
elif endian == 'native':
self._UInt8 = Int8un
self._UInt16 = Int16un
self._UInt32 = Int32un
self._UInt64 = Int64un
self._UInt128 = BitsInteger(128, signed=False)
self._Int8 = Int8sn
self._Int16 = Int16sn
self._Int32 = Int32sn
self._Int64 = Int64sn
self._Int128 = BitsInteger(128, signed=True)
else:
raise PTPError(
'Only little and big endian conventions are supported.'
)
if explicit is not None and explicit:
logger.debug('Initialized explicit constructors only')
return
elif explicit is not None and not explicit:
logger.debug('Initialize implicit constructors')
# Implicit instantiation. Needs to happen after the above.
self._PTPString = self._PTPString()
self._DateTime = self._DateTime()
self._Parameter = self._Parameter()
self._VendorExtensionID = self._VendorExtensionID()
self._OperationCode = self._OperationCode()
self._EventCode = self._EventCode()
self._PropertyCode = self._PropertyCode()
self._ObjectFormatCode = self._ObjectFormatCode()
self._DeviceInfo = self._DeviceInfo()
self._SessionID = self._SessionID()
self._TransactionID = self._TransactionID()
self._ObjectHandle = self._ObjectHandle()
self._ResponseCode = self._ResponseCode()
self._Event = self._Event()
self._Response = self._Response()
self._Operation = self._Operation()
self._StorageID = self._StorageID()
self._StorageIDs = self._StorageIDs()
self._StorageType = self._StorageType()
self._FilesystemType = self._FilesystemType()
self._AccessCapability = self._AccessCapability()
self._StorageInfo = self._StorageInfo()
self._DataTypeCode = self._DataTypeCode()
self._DataType = self._DataType()
self._GetSet = self._GetSet()
self._FormFlag = self._FormFlag()
self._DevicePropDesc = self._DevicePropDesc()
self._VendorExtensionMap = self._VendorExtensionMap()
self._VendorExtensionMapArray = self._VendorExtensionMapArray()
self._AssociationType = self._AssociationType()
self._AssociationDesc = self._AssociationDesc()
self._ProtectionStatus = self._ProtectionStatus()
self._ObjectInfo = self._ObjectInfo()
def __init__(self, *args, **kwargs):
logger.debug('Init PTP')
# Session and transaction helpers
# -------------------------------
self._session = 0
self.__session_open = False
self.__transaction_id = 1
self.__has_the_knowledge = False
super(PTP, self).__init__(*args, **kwargs)
@property
def _transaction(self):
'''Give magical property for the latest TransactionID'''
current_id = 0
if self.__session_open:
current_id = self.__transaction_id
self.__transaction_id += 1
if self.__transaction_id > 0xFFFFFFFE:
self.__transaction_id = 1
return current_id
@_transaction.setter
def _transaction(self, value):
'''Manage reset of TransactionID'''
if value != 1:
raise PTPError(
'Current TransactionID should not be set. Only reset.'
)
else:
self.__transaction_id = 1
@property
def session_id(self):
'''Expose internat SessionID'''
return self._session
@session_id.setter
def session_id(self, value):
'''Ignore external modifications to SessionID'''
pass
@contextmanager
def session(self):
'''
Manage session with context manager.
Once transport specific interfaces are defined, this allows easier,
more nuclear sessions:
from ptpy import PTPy
camera = PTPy()
with camera.session():
camera.get_device_info()
'''
# TODO: Deal with devices that only support one session (where
# SessionID must be always 1, like some older Canon cameras.)
# TODO: Deal with devices that only support one arbitrary session where
# the ID is communicated to the initiator after an OpenSession attempt.
# This might also account for the above.
logger.debug('Session requested')
if not self.__session_open:
logger.debug('Open session')
try:
self.open_session()
yield
finally:
logger.debug('Close session')
if self.__session_open:
self.close_session()
else:
logger.debug('Using outer session')
yield
@contextmanager
def open_capture(self):
'''
Manage open capture with context manager.
This allows easier open capture with automatic closing
'''
# TODO: implement!
# Transport-specific functions
# ----------------------------
def send(self, ptp_container, payload):
'''Operation with dataphase from initiator to responder'''
try:
return super(PTP, self).send(ptp_container, payload)
except Exception as e:
logger.error(e)
raise e
def recv(self, ptp_container):
'''Operation with dataphase from responder to initiator'''
try:
return super(PTP, self).recv(ptp_container)
except Exception as e:
logger.error(e)
raise e
def mesg(self, ptp_container):
'''Operation with no dataphase'''
try:
return super(PTP, self).mesg(ptp_container)
except Exception as e:
logger.error(e)
raise e
def event(self, wait=False):
try:
return super(PTP, self).event(wait=wait)
except Exception as e:
logger.error(e)
raise e
# Operation-specific methods and helpers
# --------------------------------------
def _parse_if_data(self, response, constructor):
'''If the response contains data, parse it with constructor.'''
return (constructor.parse(response.Data)
if hasattr(response, 'Data') else None)
def _build_if_not_data(self, data, constructor):
'''If the data is not binary, build it with constructor.'''
return (constructor.build(data)
if isinstance(data, Container) else data)
def _name(self, name_or_code, constructor):
'''Helper method to get the code for an Enum constructor.'''
name = name_or_code
if isinstance(name_or_code, int):
try:
name = constructor.decoding[name_or_code]
except Exception:
pass
return name
def _code(self, name_or_code, constructor):
'''Helper method to get the code for an Enum constructor.'''
if isinstance(name_or_code, six.string_types):
try:
code = constructor.encoding[name_or_code]
except Exception:
raise PTPError('Unknown property name. Try with a number?')
else:
code = name_or_code
return code
def _obtain_the_knowledge(self):
'''Initialise an internal representation of device behaviour.'''
logger.debug('Gathering info about all device properties')
self.__device_info = self.get_device_info()
self.__prop_desc = {}
with self.session():
for p in self.__device_info.DevicePropertiesSupported:
# TODO: Update __prop_desc with arrival of events
# transparently.
self.__prop_desc[p] = self.get_device_prop_desc(p)
# TODO: Get info regarding ObjectHandles here. And update as
# events are received. This should be transparent for the user.
self.__has_the_knowledge = True
def _update_the_knowledge(self, props=None):
'''Update an internal representation of device behaviour.'''
logger.debug('Gathering info about extra device properties')
with self.session():
for p in props:
self.__prop_desc[p] = self.get_device_prop_desc()
self.__device_info.DevicePropertiesSupported.append(p)
def open_session(self):
self._session += 1
self._transaction = 1
ptp = Container(
OperationCode='OpenSession',
# Only the OpenSession operation is allowed to have a 0
# SessionID, because no session is open yet.
SessionID=0,
TransactionID=0,
Parameter=[self._session]
)
response = self.mesg(ptp)
if response.ResponseCode == 'OK':
self.__session_open = True
return response
def close_session(self):
ptp = Container(
OperationCode='CloseSession',
SessionID=self._session,
TransactionID=self._transaction,
Parameter=[]
)
response = self.mesg(ptp)
if response.ResponseCode == 'OK':
self.__session_open = False
return response
def reset_device(self):
ptp = Container(
OperationCode='ResetDevice',
SessionID=self._session,
TransactionID=self._transaction,
Parameter=[],
)
response = self.recv(ptp)
if response.ResponseCode == 'OK':
self.__session_open = False
return response
def power_down(self):
ptp = Container(
OperationCode='PowerDown',
SessionID=self._session,
TransactionID=self._transaction,
Parameter=[],
)
response = self.recv(ptp)
if response.ResponseCode == 'OK':
self.__session_open = False
return response
# TODO: Add decorator to check there is an open session.
def reset_device_prop_value(self, device_property, reset_all=False):
'''Reset given device property to factory default.
If `reset_all` is `True`, the device_property can be `None`.
'''
if isinstance(device_property, six.string_types):
try:
code = self._PropertyCode.encoding[device_property]
except Exception:
raise PTPError('Unknown property name. Try with a number?')
else:
code = device_property
ptp = Container(
OperationCode='ResetDevicePropValue',
SessionID=self._session,
TransactionID=self._transaction,
Parameter=[0xffffffff if reset_all else code],
)
response = self.recv(ptp)
return response
def get_device_info(self):
ptp = Container(
OperationCode='GetDeviceInfo',
SessionID=self._session,
# GetrDeviceInfo can happen outside a session. But if there is one
# running just use that one.
TransactionID=(self._transaction if self.__session_open else 0),
Parameter=[]
)
response = self.recv(ptp)
return self._parse_if_data(response, self._DeviceInfo)
def get_storage_ids(self):
ptp = Container(
OperationCode='GetStorageIDs',
SessionID=self._session,
TransactionID=self._transaction,
Parameter=[]
)
response = self.recv(ptp)
return self._parse_if_data(response, self._StorageIDs)
def get_storage_info(self, storage_id):
ptp = Container(
OperationCode='GetStorageInfo',
SessionID=self._session,
TransactionID=self._transaction,
Parameter=[storage_id]
)
response = self.recv(ptp)
return self._parse_if_data(response, self._StorageInfo)
def get_num_objects(
self,
storage_id,
object_format=0,
object_handle=0,
all_storage_ids=False,
all_formats=False,
in_root=False,
):
'''Total number of objects present in `storage_id`'''
if object_handle != 0 and in_root and object_handle != 0xffffffff:
raise ValueError(
'Cannot get both root and {}'.format(object_handle)
)
code = self._code(object_format, self._ObjectFormatCode)
ptp = Container(
OperationCode='GetNumObjects',
SessionID=self._session,
TransactionID=self._transaction,
Parameter=[
0xffffffff if all_storage_ids else storage_id,
0xffffffff if all_formats else code,
0xffffffff if in_root else object_handle
]
)
response = self.recv(ptp)
return response.Parameter[0] if response.Parameter else None
def get_object_handles(
self,
storage_id,
object_format=0,
object_handle=0,
all_storage_ids=False,
all_formats=False,
in_root=False,
):
'''Return array of ObjectHandles present in `storage_id`'''
if object_handle != 0 and in_root and object_handle != 0xffffffff:
raise ValueError(
'Cannot get both root and {}'.format(object_handle)
)
code = self._code(object_format, self._ObjectFormatCode)
ptp = Container(
OperationCode='GetObjectHandles',
SessionID=self._session,
TransactionID=self._transaction,
Parameter=[
0xffffffff if all_storage_ids else storage_id,
0xffffffff if all_formats else code,
0xffffffff if in_root else object_handle
]
)
response = self.recv(ptp)
return self._parse_if_data(
response,
self._PTPArray(self._ObjectHandle)
)
def __constructor(self, device_property):
'''Get the correct constructor using the latest GetDevicePropDesc.'''
builder = Struct(
'DataTypeCode' / Computed(
lambda ctx: self.__prop_desc[device_property].DataTypeCode
),
'Value' / self._DataType
)
return builder
def get_device_prop_desc(self, device_property):
'''Retrieve the property description.
Accepts a property name or a number.
'''
code = self._code(device_property, self._PropertyCode)
ptp = Container(
OperationCode='GetDevicePropDesc',
SessionID=self._session,
TransactionID=self._transaction,
Parameter=[code]
)
response = self.recv(ptp)
result = self._parse_if_data(response, self._DevicePropDesc)
# Update the knowledge on response.
if self.__has_the_knowledge and hasattr(response, 'Data'):
device_property = self._name(device_property, self._PropertyCode)
logger.debug(
'Updating knowledge of {}'
.format(
hex(device_property)
if isinstance(device_property, int) else device_property
)
)
self.__prop_desc[device_property] = result
return result
def get_device_prop_value(self, device_property):
code = self._code(device_property, self._PropertyCode)
ptp = Container(
OperationCode='GetDevicePropValue',
SessionID=self._session,
TransactionID=self._transaction,
Parameter=[code],
)
response = self.recv(ptp)
if self.__has_the_knowledge and hasattr(response, 'Data'):
device_property = self._name(device_property, self._PropertyCode)
c = self.__constructor(device_property)
response = c.parse(response.Data).Value
return response
def set_device_prop_value(self, device_property, value_payload):
code = self._code(device_property, self._PropertyCode)
# Attempt to use current knowledge of properties
if self.__has_the_knowledge:
device_property = self._name(device_property, self._PropertyCode)
c = self.__constructor(device_property)
value_payload = c.build(
Container(
Value=value_payload,
DataTypeCode=(
self.__prop_desc[device_property].DataTypeCode
)
)
)
ptp = Container(
OperationCode='SetDevicePropValue',
SessionID=self._session,
TransactionID=self._transaction,
Parameter=[code],
)
response = self.send(ptp, value_payload)
return response
def initiate_capture(self, storage_id=0, object_format=0):
'''Initiate capture with current camera settings.'''
code = self._code(object_format, self._ObjectFormatCode)
ptp = Container(
OperationCode='InitiateCapture',
SessionID=self._session,
TransactionID=self._transaction,
Parameter=[
storage_id,
code,
]
)
response = self.recv(ptp)
return response
def initiate_open_capture(self, storage_id=0, object_format=0):
'''Initiate open capture in `storage_id` of type `object_format`.'''
code = self._code(object_format, self._ObjectFormatCode)
ptp = Container(
OperationCode='InitiateOpenCapture',
SessionID=self._session,
TransactionID=self._transaction,
Parameter=[
storage_id,
code,
]
)
response = self.recv(ptp)
return response
def terminate_open_capture(self, transaction_id):
'''Terminate the open capture initiated in `transaction_id`'''
ptp = Container(
OperationCode='TerminateOpenCapture',
SessionID=self._session,
TransactionID=self._transaction,
Parameter=[
transaction_id,
]
)
response = self.recv(ptp)
return response
def get_object_info(self, handle):
'''Get ObjectInfo dataset for given handle.'''
ptp = Container(
OperationCode='GetObjectInfo',
SessionID=self._session,
TransactionID=self._transaction,
Parameter=[handle]
)
response = self.recv(ptp)
return self._parse_if_data(response, self._ObjectInfo)
def send_object_info(self, objectinfo):
'''Send ObjectInfo to responder.
The object should correspond to the latest SendObjectInfo interaction
between Initiator and Responder.
'''
objectinfo = self._build_if_not_data(objectinfo, self._ObjectInfo)
ptp = Container(
OperationCode='SendObjectInfo',
SessionID=self._session,
TransactionID=self._transaction,
Parameter=[]
)
return self.send(ptp, objectinfo)
def send_object(self, bytes_data):
'''Send object to responder.
The object should correspond to the latest SendObjectInfo interaction
between Initiator and Responder.
'''
ptp = Container(
OperationCode='SendObject',
SessionID=self._session,
TransactionID=self._transaction,
Parameter=[]
)
response = self.send(ptp, bytes_data)
if response.ResponseCode != 'OK':
response = self.send(ptp, bytes_data)
return response
def get_object(self, handle):
'''Retrieve object from responder.
The object should correspond to a previous GetObjectInfo interaction
between Initiator and Responder in the same session.
'''
ptp = Container(
OperationCode='GetObject',
SessionID=self._session,
TransactionID=self._transaction,
Parameter=[handle]
)
return self.recv(ptp)
def get_partial_object(self, handle, offset, max_bytes, until_end=False):
'''Retrieve partial object from responder.
The object should correspond to a previous GetObjectInfo interaction
between Initiator and Responder in the same session.
Size fields represent maximum size as opposed to the actual size.
The first response parameter represents the actual number of bytes sent
by responder.
'''
ptp = Container(
OperationCode='GetPartialObject',
SessionID=self._session,
TransactionID=self._transaction,
Parameter=[handle,
offset,
0xFFFFFFFF if until_end else max_bytes]
)
return self.recv(ptp)
def delete_object(
self,
handle,
object_format=0,
delete_all=False,
delete_all_images=False
):
'''Delete object for given handle.
Optionally delete all objects or all images.
'''
code = self._code(object_format, self._ObjectFormatCode)
# Do the most destruction:
if delete_all and delete_all_images:
delete_all_images = False
ptp = Container(
OperationCode='DeleteObject',
SessionID=self._session,
TransactionID=self._transaction,
Parameter=[
0xFFFFFFFF if delete_all else handle,
code,
]
)
return self.mesg(ptp)
def move_object(
self,
handle,
storage_id=0,
parent_handle=0,
):
'''Move object to parent.
Parent should be an Association. Default parent is the root directory
of `storage_id`
'''
ptp = Container(
OperationCode='MoveObject',
SessionID=self._session,
TransactionID=self._transaction,
Parameter=[
handle,
storage_id,
parent_handle,
]
)
return self.mesg(ptp)
def copy_object(
self,
handle,
storage_id=0,
parent_handle=0,
):
'''Copy object to parent.
Parent should be an Association. Default parent is the root directory
of `storage_id`
'''
ptp = Container(
OperationCode='CopyObject',
SessionID=self._session,
TransactionID=self._transaction,
Parameter=[
handle,
storage_id,
parent_handle,
]
)
return self.mesg(ptp)
def get_thumb(self, handle):
'''Retrieve thumbnail for object from responder.
'''
ptp = Container(
OperationCode='GetThumb',
SessionID=self._session,
TransactionID=self._transaction,
Parameter=[handle]
)
return self.recv(ptp)
def get_resized_image_object(self, handle, width, height=0):
'''Retrieve resized image object from responder.
The object should correspond to a previous GetObjectInfo interaction
between Initiator and Responder in the same session.
If width is provided then the aspect ratio may change. The device may
not support this.
'''
ptp = Container(
OperationCode='GetResizedImageObject',
SessionID=self._session,
TransactionID=self._transaction,
Parameter=[handle, width, height]
)
return self.recv(ptp)
def get_vendor_extension_maps(self, handle):
'''Get VendorExtension maps when supporting more than one extension.
'''
ptp = Container(
OperationCode='GetVendorExtensionMaps',
SessionID=self._session,
TransactionID=self._transaction,
Parameter=[]
)
response = self.recv(ptp)
return self._parse_if_data(
response,
self._VendorExtensionMapArray)
def get_vendor_device_info(self, extension):
'''Get VendorExtension maps when supporting more than one extension.
'''
code = self._code(extension, self._VendorExtensionID)
ptp = Container(
OperationCode='GetVendorDeviceInfo',
SessionID=self._session,
TransactionID=self._transaction,
Parameter=[code]
)
response = self.recv(ptp)
return self._parse_if_data(
response,
self._DeviceInfo)
# TODO: Implement automatic event management.
|
# -*- coding:utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
def get_variables_to_train(hypes):
"""Returns a list of variables to train.
Returns:
A list of variables to train by the optimizer.
"""
if hypes.trainable_scopes is None:
return tf.trainable_variables()
else:
scopes = [scope.strip() for scope in hypes.trainable_scopes.split(',')]
variables_to_train = []
for scope in scopes:
variables = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope)
variables_to_train.extend(variables)
return variables_to_train
|
# Generated by Django 2.0.2 on 2019-09-27 05:17
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app', '0005_auto_20190927_1008'),
]
operations = [
migrations.AddField(
model_name='marketer',
name='t_amount',
field=models.BigIntegerField(blank=True, null=True),
),
]
|
from selenium.webdriver.common.by import By
class BasePageLocators:
LOGIN_LINK = (By.CSS_SELECTOR, "#login_link")
BASKET = (By.XPATH, "//a[@class='btn btn-default']")
USER_ICON = (By.CSS_SELECTOR, ".icon-user")
class MainPageLocators:
...
class LoginPageLocators:
LOGIN_FORM = (By.CSS_SELECTOR, "#login_form")
REGISTER_FORM = (By.CSS_SELECTOR, "#register_form")
REGISTER_EMAIL = (By.CSS_SELECTOR, "#id_registration-email")
REGISTER_PASSWORD = (By.CSS_SELECTOR, "#id_registration-password1")
REGISTER_PASSWORD_CONFIRM = (By.CSS_SELECTOR, "#id_registration-password2")
REGISTER_BTN = (By.CSS_SELECTOR, "[name='registration_submit']")
class BasketPageLocators:
BASKET_FORMSET = (By.CSS_SELECTOR, "#basket_formset")
EMPTY_MSG = (By.XPATH, "//div/p")
class BookOrderLocators:
BTN_ADD_TO_BASKET = (By.CSS_SELECTOR, "[class='btn btn-lg btn-primary btn-add-to-basket']")
ADDED_BOOK = (By.XPATH, "//*[@id='messages']/div[1]/div/strong")
PRODUCT_TITLE = (By.XPATH, "//div[@class='col-sm-6 product_main']/h1")
PRODUCT_PRICE = (By.XPATH, "//p[@class='price_color']")
|
from .minimization import minimize
from .exceptions import LineSearchFailError, NotTangentVectorError
__all__ = ['minimize', 'LineSearchFailError', 'NotTangentVectorError']
__version__ = '1.0'
|
from myhdl import *
from sigmat import SignalMatrix, m_flat_top
import random
W0 = 9
matrix = SignalMatrix()
flati = matrix.get_flat_signal()
flato = matrix.get_flat_signal()
nbits = len(flati)
print nbits
clock = Signal(bool(0))
reset = ResetSignal(0, active=1, async=False)
sdo = Signal(bool(0))
def test_matrix(clock, reset, sdo):
@always(delay(10))
def clkgen():
clock.next = not clock
dut = m_flat_top( clock, reset, sdo)
gstk = matrix.m_stack(flati)
gflt = matrix.m_flatten(flato)
@instance
def tbsim():
yield clock.posedge
reset.next = 1
yield clock.posedge
reset.next = 0
yield clock.posedge
#flati.next = 160
#gstk_g_0_y.next = 160
yield clock.posedge
#sdi.next = 1
yield clock.posedge
#sdi.next = 0
yield clock.posedge
for j in range(512):
j = random.randrange(0,2**(W0-1))
print ("time %d j %d j %s") % (now(), j, hex(j))
flati.next = j
print ("time %d flati %s") % (now(), hex(flati))
yield clock.posedge
flati.next = j << 9
print ("time %d flati %s") % (now(), hex(flati))
yield clock.posedge
flati.next = j << 18
print ("time %d flati %s") % (now(), hex(flati))
yield clock.posedge
flati.next = j << 27
print ("time %d flati %s") % (now(), hex(flati))
yield clock.posedge
flati.next = j << 36
print ("time %d flati %s") % (now(), hex(flati))
yield clock.posedge
raise StopSimulation
return dut, clkgen, tbsim, gstk, gflt
tb_fsm = traceSignals(test_matrix, clock, reset, sdo)
sim = Simulation(tb_fsm)
sim.run()
|
#!/usr/bin/env python
import os
import sys
import inspect
import re
import argparse
import random
parser = argparse.ArgumentParser(description="""
Description
-----------
""",formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Authors
-------
Vincent Merel
""")
#Input files
parser.add_argument("--input", type=str, required=True, dest="input", default=None, help="the input file")
parser.add_argument("--Contig_size", type=str, required=True, dest="Contig_size", default=None, help="the Contig size file")
#Output file
parser.add_argument("--output", type=str, required=True, dest="output", default=None, help="the output file")
parser.add_argument("--spacing", type=str, required=True, dest="spacing", default=None, help="the spacing")
parser.add_argument("--reversing", type=str, required=True, dest="reversing", default=None, help="the reversing")
parser.add_argument("--karyotype", type=str, required=True, dest="karyotype", default=None, help="the karyotype")
parser.add_argument("--links", type=str, required=True, dest="links", default=None, help="links")
parser.add_argument("--radius", type=str, required=True, dest="radius", default=None, help="radius")
#Additional arg
parser.add_argument("--colors", type=str, required=True, dest="colors", default=None, help="the colors")
args = parser.parse_args()
output = open(args.output,"w")
#Importing colors
colors=args.colors
colors=colors.split(";")
#Creating a Dic of contig Size
Sizes={}
Contig_size=open(args.Contig_size,'r')
for line in Contig_size:
Sizes[line.split()[0]]=line.split()[1]
##############################################################################################################################
#########################################################To Sort##############################################################
##########################################Creating a Dictionnary of Dictionnary (Pos)#########################################
##################################Pos[R_Contig][Q_Contig]=[mean pos of aln 1, mean pos of aln 2, ...]#########################
##############################################################################################################################
######################################################To Reverse##############################################################
##############################################################################################################################
##########################################Creating a Dictionnary of Dictionnary (Sense)#######################################
##################################Sense[R_Contig][Q_Contig]=(R_End-Rstart)_aln1+(R_End-Rstart)_aln2+...#######################
##############################################################################################################################
#Creating an alignment Dictionnary
input = open(args.input,"r")
Pos = {}
Sense = {} #To choose contig to reverse
for line in input :
line=line[:-1]
R_Start=int(line.split()[0])
R_End=int(line.split()[1])
Q_Start=int(line.split()[2])
Q_End=int(line.split()[3])
R_Contig=line.split()[6]
Q_Contig=line.split()[7]
if (Q_End-Q_Start)==0:
print(line)
if R_Contig not in Pos : #New Reference Contig and so Query Contig
Pos[R_Contig]={}
Sense[R_Contig]={}
Pos[R_Contig][Q_Contig]=[(R_Start+R_End)/2]
Sense[R_Contig][Q_Contig]=(Q_End-Q_Start)/abs(Q_End-Q_Start)*abs(R_End-R_Start) #if Q_Start > Q_End (R_End < R_Start doesn't exist ?), (Q_End-Q_Start)/(Q_End-Q_Start)=-1, else (Q_End-Q_Start)/(Q_End-Q_Start)+1
elif Q_Contig not in Pos[R_Contig] : #Known Reference Contig but new Query Contig
Pos[R_Contig][Q_Contig]=[(R_Start+R_End)/2]
Sense[R_Contig][Q_Contig]=(Q_End-Q_Start)/abs(Q_End-Q_Start)*abs(R_End-R_Start)
else :
Pos[R_Contig][Q_Contig].append((R_Start+R_End)/2)
Sense[R_Contig][Q_Contig]=Sense[R_Contig][Q_Contig]+(Q_End-Q_Start)/abs(Q_End-Q_Start)*abs(R_End-R_Start)
##############################################################################################################################
##############################################################################################################################
##############################################################################################################################
##############################################################################################################################
##############################################################################################################################
##############################################################################################################################
##############################################################################################################################
##############################################################################################################################
##############################################################################################################################
# Calculate average Ref pos for each Q contig
# Python program to get average of a list
def Average(lst):
return sum(lst) / len(lst)
for key in Pos :
for i in Pos[key] :
Pos[key][i]=Average(Pos[key][i])
##############################################################################################################################
################################################Ideogram section <spacing>####################################################
##############################################################################################################################
spacing=open(args.spacing,"w")
spacing.write(" <spacing>"+'\n')
spacing.write(" default = 0.01r"+'\n')
for key in sorted(Pos.keys()):
plop=sorted(Pos[key], key=Pos[key].get, reverse=False)
for i in range(0, len(plop)):
if (i > 0):
spacing.write(" <pairwise dq_"+plop[i-1]+" dq_"+plop[i]+">"+'\n')
spacing.write(" spacing = 0r"+'\n')
spacing.write(" </pairwise>"+'\n')
spacing.write(" </spacing>"+'\n')
spacing.close()
##############################################################################################################################
##############################################################################################################################
##############################################################################################################################
##############################################################################################################################
################################################Radius####################################################
##############################################################################################################################
radius=open(args.radius,"w")
beginning="chromosomes_radius="
Text=[]
for key in Pos:
for key2 in Pos[key]:
Text.append("dq_"+key2+":1.05r")
radius.write(beginning+",".join(Text))
radius.close()
##############################################################################################################################
##############################################################################################################################
##############################################################################################################################
##############################################################################################################################
#########################################################To reverse###########################################################
##############################################################################################################################
reversing=open(args.reversing,"w")
ToReverse=""
beginning="chromosomes_reverse="
Text=[]
#All reference chromosomes are reversed
for key in sorted(Pos.keys(), reverse=True):
Text.append("dr_"+key)
for key in sorted(Pos.keys()):
plop=sorted(Pos[key], key=Pos[key].get, reverse=False)
for i in range(0, len(plop)):
if Sense[key][plop[i]]<0:
Text.append("dq_"+plop[i])
reversing.write(beginning+",".join(Text))
reversing.close()
##############################################################################################################################
##############################################################################################################################
##############################################################################################################################
##############################################################################################################################
#########################################################Karyotype############################################################
##############################################################################################################################
karyotype=open(args.karyotype,"w")
color_cpt=-1
Colors={}
for key in sorted(Pos.keys()):
color_cpt=color_cpt+1
plop=sorted(Pos[key], key=Pos[key].get, reverse=False)
for i in range(0, len(plop)):
splitted=plop[i].split("_")
while("" in splitted) :
splitted.remove("")
Colors[plop[i]]=colors[color_cpt]
karyotype.write("chr - dq_"+plop[i]+" "+splitted[len(splitted)-1]+" 0 "+Sizes[plop[i]]+" "+colors[color_cpt]+"\n")
chr=["4","X","3R","3L","2R","2L"]
print(colors)
for key in sorted(Pos.keys(), reverse=True):
print(key)
print(Sizes[key])
Colors[key]=colors[color_cpt]
karyotype.write("chr - dr_"+key+" "+key+" 0 "+Sizes[key]+" "+"255,255,255"+"\n") #185,199,205
color_cpt=color_cpt-1
'''
for key in sorted(Pos.keys(), reverse=True):
Colors[key]=color_cpt
karyotype.write("chr - dr_"+key+" "+key+" 0 "+Sizes[key]+" chr"+str(color_cpt)+"\n")
color_cpt=color_cpt-1
'''
karyotype.close()
##############################################################################################################################
##############################################################################################################################
##############################################################################################################################
##############################################################################################################################
#########################################################Links############################################################
##############################################################################################################################
links=open(args.links,"w")
input = open(args.input,"r")
cpt=0
for line in input :
cpt=cpt+1
Q_Contig=line.split()[7]
R_Contig=line.split()[6]
Q_Start=line.split()[2]
Q_End=line.split()[3]
R_Start=line.split()[0]
R_End=line.split()[1]
links.write(str(cpt)+" dr_"+R_Contig+" "+str(R_Start)+" "+str(R_End)+" color="+str(Colors[R_Contig])+"\n")
links.write(str(cpt)+" dq_"+Q_Contig+" "+str(Q_Start)+" "+str(Q_End)+" color="+str(Colors[Q_Contig])+"\n")
links.close()
##############################################################################################################################
##############################################################################################################################
##############################################################################################################################
|
import time
import board
import busio
import adafruit_adxl34x
i2c = busio.I2C(board.SCL, board.SDA)
accelerometer = adafruit_adxl34x.ADXL345(i2c)
while True:
print("%f %f %f" % accelerometer.acceleration)
time.sleep(0.2)
|
# encoding: utf-8
"""
@desc: compute ppl according to file generated by `fairseq-generate --score-reference`
"""
import argparse
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--file")
args = parser.parse_args()
total_score = 0
total_count = 0
with open(args.file) as fin:
for line in fin:
line = line.strip()
if not line.startswith("P"):
continue
scores = line.split("\t")[1]
scores = [float(x) for x in scores.split()]
for s in scores:
total_score += s
total_count += 1
print(f"total score: {total_score}, total words: {total_count}, average score: {total_score/total_count}")
if __name__ == '__main__':
main()
|
import abc
import time_util
from typing import IO
class Entry(abc.ABC):
def __init__(self, id_):
self.id = id_
def is_similar_all(self, *texts) -> bool:
result = True
for arg in texts:
if isinstance(arg, list) or isinstance(arg, set):
for text in arg:
result &= self.is_similar(text)
else:
result &= self.is_similar(arg)
return result
@abc.abstractmethod
def is_similar(self, text: str) -> bool:
raise NotImplementedError
@abc.abstractmethod
def serialize(self) -> str:
raise NotImplementedError
@abc.abstractmethod
def deserialize(self, string: str):
raise NotImplementedError
class Car(Entry):
def __init__(self, id_: int, price: float = None, brand: str = None, model: str = None, client: Entry = None,
rental_date: int = 0, image: bytes = None, image_bytes_len: int = 0, client_id: int = None):
super(Car, self).__init__(id_)
self.price = price
self.brand = brand
self.model = model
self.client = client
self.rental_date = rental_date
self.image = image
self.image_bytes_len = image_bytes_len if self.image is None else len(image)
self.client_id = client_id
self._image = None
@property
def image(self):
return self._image
@image.setter
def image(self, image: bytes = None):
self._image = image
if image is None:
self.image_bytes_len = 0
else:
self.image_bytes_len = len(image)
def is_rented(self) -> bool:
return self.client is not None
def to_pay(self) -> int:
diff = time_util.current_time_mills() - self.rental_date
hours = int(diff / 3600000)
if diff % 3600000 > 0:
hours += 1
return hours * self.price
def serialize(self) -> str:
return str(self.id) + "," \
+ str(self.price) + "," \
+ self.brand + "," \
+ self.model + "," \
+ ("-1" if self.client is None else str(self.client.id)) + "," \
+ str(self.rental_date) + "," \
+ str(self.image_bytes_len)
def deserialize(self, string: str):
if not string:
return None
splitted = string.split(",")
if len(splitted) < 7:
return None
try:
car = Car(int(splitted[0]))
car.price = float(splitted[1])
car.brand = splitted[2]
car.model = splitted[3]
car.client_id = int(splitted[4])
car.rental_date = int(splitted[5])
car.image_bytes_len = int(splitted[6])
return car
except ValueError:
return None
def is_similar(self, text: str) -> bool:
return self.brand.lower().startswith(text) or self.model.lower().startswith(text)
class Client(Entry):
def __init__(self, id_: int, first_name: str = None, last_name: str = None, phone_number: str = None,
post_code: str = None, city: str = None, street: str = None, building_number: str = 0,
flat_number: str = None, rented_cars=None):
super(Client, self).__init__(id_)
self.first_name = first_name
self.last_name = last_name
self.phone_number = phone_number
self.post_code = post_code
self.city = city
self.street = street
self.building_number = building_number
self.flat_number = flat_number
self.rented_cars = [] if rented_cars is None else rented_cars
def add_rented_car(self, car: Car, set_rental_date: bool = True):
if self.rented_cars.__contains__(car):
return
self.rented_cars.append(car)
car.client = self
if set_rental_date:
car.rental_date = time_util.current_time_mills()
def remove_rented_car(self, car: Car) -> bool:
if not self.rented_cars.__contains__(car):
return False
car.client = None
car.rental_date = 0
self.rented_cars.remove(car)
return True
def to_pay(self) -> int:
result = 0
for car in self.rented_cars:
result += car.to_pay()
return result
def serialize(self) -> str:
return str(self.id) + "," \
+ self.first_name + "," \
+ self.last_name + "," \
+ self.phone_number + "," \
+ self.post_code + "," \
+ self.city + "," \
+ ("" if self.street is None else self.street) + "," \
+ self.building_number + "," \
+ ("-1" if self.flat_number is None else self.flat_number)
def deserialize(self, string: str):
if not string:
return None
splitted = string.split(",")
if len(splitted) < 9:
return None
try:
client = Client(int(splitted[0]))
client.first_name = splitted[1]
client.last_name = splitted[2]
client.phone_number = splitted[3]
client.post_code = splitted[4]
client.city = splitted[5]
client.street = splitted[6]
client.building_number = splitted[7]
client.flat_number = splitted[8]
return client
except ValueError:
return None
def is_similar(self, text: str) -> bool:
return self.first_name.lower().startswith(text) or self.last_name.lower().startswith(text)
class Storage:
def __init__(self, max_id: int = 0):
self.max_id = max_id
self.entry_set = set()
def next_id(self) -> int:
self.max_id += 1
return self.max_id
def get(self, id: int):
if id is None:
return None
for entry in self.entry_set:
if entry.id == id:
return entry
return None
def get_all(self) -> set:
return self.entry_set
def add(self, entry: Entry):
self.max_id = max(entry.id, self.max_id)
self.entry_set.add(entry)
def add_all(self, entry_set: set):
if entry_set is None or len(entry_set) == 0:
return
self.max_id = max(self.max_id, max(entry_set, key=lambda entry: entry.id).id)
self.entry_set.update(self.entry_set, entry_set)
def remove(self, entry: Entry):
self.entry_set.remove(entry)
def clear(self):
self.entry_set.clear()
self.max_id = 0
def search_all(self, text: str) -> set:
return self.search(text, self.entry_set)
@staticmethod
def search(text: str, entry_set: set) -> set:
if not text:
return entry_set
words = set(filter(lambda word: word, text.lower().split(" ")))
return set(filter(lambda entry: entry.is_similar_all(words), entry_set))
class Data:
def __init__(self, file: IO, car_set: set = None, client_set: set = None):
self.file = file
self.car_set = set() if car_set is None else car_set
self.client_set = set() if client_set is None else client_set
def load(self):
if self.file is None:
return
header_bytes = self.file.read(12)
clients_amount: int = int.from_bytes(header_bytes[0:4], 'big')
cars_amount: int = int.from_bytes(header_bytes[4:8], 'big')
clients_serialized: list = []
clients_lines_amount: int = int.from_bytes(header_bytes[8:12], 'big')
for i in range(clients_lines_amount):
text_length = int.from_bytes(self.file.read(4), 'big')
text_bytes = self.file.read(text_length)
clients_serialized.append(text_bytes.decode("iso-8859-2"))
self.client_set = deserialize_all(clients_serialized, Client(-1))
car_worker = Car(-1)
for i in range(cars_amount):
car_bytes_amount = int.from_bytes(self.file.read(4), 'big')
car_bytes = self.file.read(car_bytes_amount)
car = deserialize(car_bytes.decode("iso-8859-2"), car_worker)
if car is None:
continue
if car.image_bytes_len > 0:
car.image = self.file.read(car.image_bytes_len)
self.car_set.add(car)
for car in self.car_set:
if car.client_id is None or car.client_id == -1:
continue
clients = list(filter(lambda client: client.id == car.client_id, self.client_set))
if len(clients) > 0:
clients[0].add_rented_car(car, False)
def save(self):
if self.file is None:
return
header_bytes: bytes = len(self.client_set).to_bytes(4, "big")
header_bytes += len(self.car_set).to_bytes(4, "big")
clients_serialized: list = serialize_all(self.client_set, 100)
header_bytes += len(clients_serialized).to_bytes(4, "big")
self.file.write(header_bytes)
for string in clients_serialized:
self.file.write(len(string).to_bytes(4, "big"))
self.file.write(string.encode("iso-8859-2"))
for car in self.car_set:
car_serialized = car.serialize()
self.file.write(len(car_serialized).to_bytes(4, "big"))
self.file.write(car_serialized.encode("iso-8859-2"))
if car.image is not None:
self.file.write(car.image)
def serialize(entry: Entry) -> str:
return entry.serialize()
def serialize_all(entry_set: set, buf: int = None) -> list:
string_list = []
if len(entry_set) < 1:
return string_list
if buf is None:
for entry in entry_set:
string_list.append(entry.serialize())
return string_list
if buf < 1:
return string_list
i = 0
temp = ""
for entry in entry_set:
if i >= buf:
string_list.append(temp)
temp = ""
i = 0
if i != 0:
temp += ";"
temp += entry.serialize()
i += 1
if temp:
string_list.append(temp)
return string_list
def deserialize(string: str, entry: Entry) -> Entry:
return entry.deserialize(string)
def deserialize_all(string_list: list, entry_worker: Entry) -> set:
entry_set = set()
if string_list is None or len(string_list) == 0 or entry_worker is None:
return entry_set
for string_line in string_list:
splitted = string_line.split(";")
for string in splitted:
entry = entry_worker.deserialize(string)
if entry is None:
continue
entry_set.add(entry)
return entry_set
|
from .server import RCNetwork, RCNeighbors
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.