blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
133
path
stringlengths
2
333
src_encoding
stringclasses
30 values
length_bytes
int64
18
5.47M
score
float64
2.52
5.81
int_score
int64
3
5
detected_licenses
listlengths
0
67
license_type
stringclasses
2 values
text
stringlengths
12
5.47M
download_success
bool
1 class
79a1048e696bcf2331711d32b09d8dd009c014f7
Python
jasonwyse2/marketmaker
/marketmaker/Sqlite3.py
UTF-8
7,760
2.671875
3
[]
no_license
import sqlite3 from marketmaker.tool import get_local_datetime import pandas as pd class Sqlite3: tableName = 'bitasset_order' def __init__(self, dataFile=None): if dataFile is None: self.conn = sqlite3.connect(":memory:") else: try: self.conn = sqlite3.connect(dataFile,check_same_thread=False) except sqlite3.Error as e: print("连接sqlite数据库失败:", e.args[0]) self.create_table() def getcursor(self): return self.conn.cursor() def drop(self, table): ''' if the table exist,please be carefull ''' if table is not None and table != '': cu = self.getcursor() sql = 'DROP TABLE IF EXISTS ' + table try: cu.execute(sql) except sqlite3.Error as why: print("delete table failed:", why.args[0]) return self.conn.commit() print("delete table successful!") cu.close() else: print("table does not exist!") def create_table(self,): ''' create databaseOperation table :param sql: :return: ''' tableName = self.tableName sql = 'create table if not exists '+tableName+' (' \ 'userId Int,' \ 'orderId CHAR(100),' \ 'datetime CHAR(50)' \ ')' if sql is not None and sql != '': cu = self.getcursor() try: cu.execute(sql) except sqlite3.Error as why: print("create table failed:", why.args[0]) return self.conn.commit() print("create table successful!") cu.close() else: print("sql is empty or None") def insert(self, userId,orderId): ''' insert data to the table :param sql: :param data: :return: ''' datetime = get_local_datetime() sql = 'INSERT INTO ' + self.tableName + '(userId,orderId,datetime) values (?,?,?)' if sql is not None and sql != '': if orderId !='': cu = self.getcursor() try: # for orderId in orderId_list: cu.execute(sql, [userId,orderId,datetime]) #if 'd' is an element, you should use [d] self.conn.commit() except sqlite3.Error as why: print("insert data failed:", why.args[0]) cu.close() else: print("sql is empty or None") def fetch_specific_num(self,userId, num,sql=''): ''' query all data :param sql: :return: ''' if sql == '': sql = 'SELECT orderId FROM ' + self.tableName +' where userId=? order by datetime limit ?' if sql is not None and sql != '': cu = self.getcursor() content = None try: cu.execute(sql,[userId,num]) content = cu.fetchall() except sqlite3.Error as why: print("fetchall data failed:", why.args[0]) cu.close() return content else: print("sql is empty or None") def fetch_by_userId(self,userId, num,sql=''): ''' query all data :param sql: :return: ''' if sql == '': sql = 'SELECT * FROM ' + self.tableName +' where userId=? order by orderId limit ?' if sql is not None and sql != '': cu = self.getcursor() content = None try: cu.execute(sql,[userId,num]) content = cu.fetchall() except sqlite3.Error as why: print("fetchall data failed:", why.args[0]) cu.close() return content else: print("sql is empty or None") def fetchall(self, sql=''): ''' query all data :param sql: :return: ''' if sql=='': # sql = 'SELECT * FROM ' + self.tableName+ ' order by orderId' sql = 'SELECT * FROM ' + self.tableName if sql is not None and sql != '': cu = self.getcursor() content = None try: cu.execute(sql) content = cu.fetchall() except sqlite3.Error as why: print("fetchall data failed:", why.args[0]) cu.close() return content else: print("sql is empty or None") def update(self, sql, data): ''' update the data :param sql: :param data: :return: ''' if sql is not None and sql != '': if data is not None: cu = self.getcursor() try: for d in data: cu.execute(sql, d) self.conn.commit() except sqlite3.Error as why: print("update data failed:", why.args[0]) cu.close() else: print ("sql is empty or None") def delete(self, sql, data=None): ''' delete the data :param sql: :param data: :return: ''' if sql is not None and sql != '': cu = self.getcursor() if data is not None: try: for d in data: cu.execute(sql, d) self.conn.commit() except sqlite3.Error as why: print("delete data failed:", why.args[0]) else: try: cu.execute(sql) self.conn.commit() except sqlite3.Error as why: print ("delete data failed:", why.args[0]) cu.close() else: print ("sql is empty or None") def delete_by_userId_orderIdlist(self, userId, orderId_list): sql = 'delete from ' + self.tableName + ' where userId=? and orderId= ?' for i in range(len(orderId_list)): cu = self.getcursor() try: cu.execute(sql, [userId, orderId_list[i]]) self.conn.commit() except sqlite3.Error as why: print("delete data failed:", why.args[0]) def delete_all(self,): sql = 'delete from '+self.tableName cu = self.getcursor() cu.execute(sql) self.conn.commit() cu.close() def __del__(self): self.conn.close() if __name__ == "__main__": # sql3 = Sqlite3(dataFile='/mnt/data/bitasset/bitasset.sqlite') sql3 = Sqlite3(dataFile="/mnt/data/bitasset/bitasset.sqlite") # userId = 123 # orderId_list = ['33444','2234'] # datetime = '3232-23-23 12:34:23' # sql3.insert(userId,orderId_list,datetime) res = sql3.fetchall() # res = sql3.fetch_specific_num(userId=666849,num=10) df = pd.DataFrame(res) print(df) print('fetch number',len(res)) # print('before delete',res) # sql3.delete_orders_by_userIdOrderId(userId=userId, orderId_list=['33444']) # res = sql3.fetchall() # print('after delete',res)
true
0aee5db8462a9f50bb266c894f0028cc3e72e015
Python
JohanCamiloL/general-algorithms
/linear-search/python/linear-search.py
UTF-8
507
4.53125
5
[]
no_license
def linearSearch(array, value): """ Linear search algorithm implementation. Parameters ---------- array: list List of elements where search will be made. value: int Value to be searched. Return ------ int Element index on array, if not found returns -1. """ for i in range(len(array)): if array[i] == value: return i return -1 array = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0] value = 5 print(linearSearch(array, value))
true
2c020bac5633736175928bfe17fed75cb945abf6
Python
esuteau/car_behavioral_cloning
/model.py
UTF-8
6,803
2.859375
3
[]
no_license
import csv import os import cv2 import numpy as np import sklearn import random from keras.models import Sequential from keras.layers import Flatten, Dense, Activation, Dropout from keras.layers import Convolution2D, Cropping2D from keras.layers.pooling import MaxPooling2D from keras.layers.core import Lambda from keras.preprocessing.image import img_to_array, load_img import matplotlib.pyplot as plt def ReadCsvLogFile(csv_path): """Read the CSV driving log created from the Udacity Simulator.""" samples = [] with open(csv_path) as csvfile: reader = csv.reader(csvfile) header = reader for idx, line in enumerate(reader): if idx > 0: samples.append(line) return samples def GetImageShape(): return (160, 320, 3) def PlotDataForDebugging(image_folder, samples): """Plot data for the debuggin""" nb_samples = len(samples) col_names = ['center', 'left', 'right'] random.shuffle(samples) images = [] for n in range(0, 2): batch_sample = samples[n] for col, camera in enumerate(col_names): # Parse Windows/Linux Filenames split_char = '/' if '\\' in batch_sample[col]: split_char = '\\' img_name = batch_sample[col].split(split_char)[-1] # Load Image image = cv2.imread(image_folder + img_name) images.append(image) # PLot Original Images plt.figure() for n_image, image in enumerate(images): plt.subplot(2, 3, n_image+1) plt.axis("off") plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB)) # Flip if necessary Original Images plt.figure() images_flip = [] for n_image, image in enumerate(images): # Apply Horizontal Flip Randomly on the data. # Reverse the steering angle in this case flip_img = random.random() > 0.5 if flip_img: image = cv2.flip(image, 1) images_flip.append(image) plt.subplot(2, 3, n_image+1) plt.axis("off") plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB)) # Crop Images plt.figure() for n_image, image in enumerate(images_flip): # Simulate cropping, just for the writeup image_cropped = image[65:135,:,:] plt.subplot(2, 3, n_image+1) plt.axis("off") plt.imshow(cv2.cvtColor(image_cropped, cv2.COLOR_BGR2RGB)) # Show all figures plt.show() def GetDataFromGenerator(image_folder, samples, batch_size=36): """Returns batches of center, left and right camera images using a generator. Randomly flips the images horizontally to remove steering bias and generalize the data.""" nb_samples = len(samples) col_names = ['center', 'left', 'right'] angle_correction = 0.15 camera_correction = {'center': 0, 'left': angle_correction, 'right': -angle_correction} batch_size_triplet = batch_size // 3 while 1: random.shuffle(samples) for offset in range(0, nb_samples, batch_size_triplet): batch_samples = samples[offset:offset+batch_size_triplet] images, angles = [], [] for batch_sample in batch_samples: for col, camera in enumerate(col_names): # Parse Windows/Linux Filenames split_char = '/' if '\\' in batch_sample[col]: split_char = '\\' img_name = batch_sample[col].split(split_char)[-1] # Load Image image = load_img(image_folder + img_name) image = img_to_array(image) # Apply Steering Correction steering_center = float(batch_sample[3]) steering = steering_center + camera_correction[camera] # Apply Horizontal Flip Randomly on the data. # Reverse the steering angle in this case if random.random() > 0.5: steering = -1*steering image = cv2.flip(image, 1) # Add image and angle to dataset images.append(image) angles.append(steering) X_train = np.array(images) y_train = np.array(angles) yield sklearn.utils.shuffle(X_train, y_train) def NormalizeImage(image): """Image Normalization""" return image / 255.0 - 0.5 def BuildModel(image_shape): """Neural Net Model based on Nvidia's model in https://devblogs.nvidia.com/parallelforall/deep-learning-self-driving-cars/""" model = Sequential() model.add(Lambda(NormalizeImage, input_shape=image_shape)) model.add(Cropping2D(cropping=((65,25), (0,0)))) model.add(Convolution2D(24,5,5,subsample=(2,2),activation="relu", input_shape=image_shape)) 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")) model.add(Flatten()) model.add(Dense(100)) model.add(Dense(50)) model.add(Dense(10)) model.add(Dense(1)) return model if __name__ == "__main__": from sklearn.model_selection import train_test_split print("--------------------------------------------") print("Project 3 - Behavioral Cloning") print("--------------------------------------------") csv_path = '../data/combined/driving_log.csv' image_folder = '../data/combined/IMG/' print("Loading Images from dataset") samples = ReadCsvLogFile(csv_path) train_samples, validation_samples = train_test_split(samples, test_size=0.2) img_shape = GetImageShape() print('Nb training samples: {}'.format(len(train_samples))) print('Nb validation samples: {}'.format(len(validation_samples))) print('Image Size: {}'.format(img_shape)) # For Debug only #train_data = PlotDataForDebugging(image_folder, train_samples) # Hyper Parameters: batch_size = 36 # Create Generators train_generator = GetDataFromGenerator(image_folder, train_samples, batch_size=batch_size) validation_generator = GetDataFromGenerator(image_folder, validation_samples, batch_size=batch_size) # Build Model print("Building the model") model = BuildModel(img_shape) # Train print("Starting Training") model.compile(loss='mse', optimizer='adam') model.fit_generator(train_generator, samples_per_epoch=len(train_samples), validation_data=validation_generator, nb_val_samples=len(validation_samples), nb_epoch=3) # Save print("Saving Model") model.save('model.h5')
true
cc901426651f5ae9f0e55986ee168e6593dcf900
Python
MrDetectiv/fb-labs-2020
/cp_4/cp-4_Litvinchuk_FB-81/main.py
UTF-8
4,924
3.203125
3
[]
no_license
import random def gen_random(a,b): return random.randint(a,b) def euclid_NSD(a,b): if a == 0: x, y = (0, 1) return b, x, y d, x1, y1 = euclid_NSD(b % a, a) x = y1 - (b // a) * x1 y = x1 return d, x, y def NSD(a,b): r = euclid_NSD(a,b) return r[0] def mod_pow(x, a, m): bin_nums = [int(n) for n in bin(a)[2:] ] r = 1 for n in bin_nums: r = r ** 2 % m r = r * (x ** n) % m return r def obernenyu(x,m): r = euclid_NSD(x,m) if r[0]==1: if x<=m: return r[1] if x>m: return r[2] else: return None def miller_rabin_iter(t, x): if NSD(t, x) != 1: return False d = t - 1 while d % 2 == 0: d //= 2 if (m := mod_pow(x, d, t)) == 1 or m == t - 1: return True while d < t - 1: iter_result = mod_pow(x, d, t) if iter_result == t - 1: return True if iter_result == 1: return False d *= 2 return False def Miller_Rabin_test(p): k=40 for i in range(0, k): x = gen_random(2, p - 1) if not miller_rabin_iter(p, x): return False else: return True def gen_prime(l): min = 2**(l-1)+1 max = 2**l-1 while True: x = gen_random(min,max) for i in range(0,(max-x+(1-x%2))//2): if x % 2 == 0: x+=1 if small_div_test(x): if Miller_Rabin_test(x): return x x+=2 def small_div_test(n): primes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47, 53,59,61,67,71,73,79,83,89,97,101,103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503] for i in primes: if n%i==0 and n//i!=1: return False return True def Gen_Pair_of_Keys(l): p = gen_prime(l) print(f"P = {p}") q = gen_prime(l) while p == q: q = gen_prime(l) print(f"Q = {q}") n = p*q phi_n = (p-1)*(q-1) e = gen_random(2,phi_n-1) while NSD(e,phi_n)!=1: e = gen_random(2,phi_n-1) d = obernenyu(e,phi_n) if d < 0: d = d + phi_n open_key = [e,n] private_key = [d,n] return [open_key,private_key] def Encrypt(M,open_key): return pow(M,open_key[0],open_key[1]) def Decrypt(M,private_key): return pow(M,private_key[0],private_key[1]) def Sign(M,private_key): s = Encrypt(M,private_key) s_m = [M,s] return s_m def Verify(s_m,open_key): if s_m[0] == pow(s_m[1],open_key[0],open_key[1]): return True else: return False def SendKey(M,private_key_A,open_key_B): e_m = Encrypt(M,open_key_B) s = Sign(M,private_key_A) e_s = Encrypt(s[1],open_key_B) return [e_m, e_s] def ReceiveKey(M,private_key_B,open_key_A): e_m = M[0] e_s = M[1] m = Decrypt(e_m,private_key_B) s = Decrypt(e_s,private_key_B) if Verify([m,s],open_key_A): return m else: return None print('ABONENT A:') A = Gen_Pair_of_Keys(256) print(f"E = {A[0][0]}") print(f"D = {A[1][0]}") print(f"N = {A[0][1]}\n") print('ABONENT B:') B = Gen_Pair_of_Keys(256) print(f"E = {B[0][0]}") print(f"D = {B[1][0]}") print(f"N = {B[0][1]}\n") mess = gen_prime(255) print(f"MESSAGE = {mess}") d_mess=Encrypt(mess,A[0]) print(f"ENCRYPTED MESSAGE WITH A PUB KEY = {d_mess}") print(f"DECRYPTED MESSAGE WITH A PRIV KEY = {Decrypt(d_mess,A[1])}") d_mess=Encrypt(mess,B[0]) print(f"ENCRYPTED MESSAGE WITH B PUB KEY = {d_mess}") print(f"DECRYPTED MESSAGE WITH B PRIV KEY = {Decrypt(d_mess,B[1])}\n") print('SIGN WITH A PRIVATE KEY:') s=Sign(mess,A[1]) print(f"MESSAGE = {s[0]}") print(f"SIGNATURE = {s[1]}") print(f"VERIFIED: {Verify(s,A[0])}\n") print('SENDKEY, RECEIVEKEY PROTOCOL (A TO B):') k = gen_prime(255) print(f"SHARED KEY = {k}") m=SendKey(k,A[1],B[0]) print(f"ENCRYPTED MESSAGE = {m[0]}") print(f"SIGNATURE = {m[1]}") print(f"KEY = {ReceiveKey(m,B[1],A[0])}\n\n") print('SENDKEY, RECEIVEKEY PROTOCOL (A TO SERVER):') n=int("0xD75B159AD05869959926A0BE751038E07C93B6FB11AF6BE21C1F24D7EE120B7D",16) e = int("0x10001",16) print(f"SERVER E = {e}") print(f"SERVER N = {n}") k = gen_prime(255) print(f"SHARED KEY = {k}") m = SendKey(k, A[1], [e,n]) print(f"ENCRYPTED MESSAGE = {m[0]}") print(f"SIGNATURE = {m[1]}\n") URL = 'http://asymcryptwebservice.appspot.com/rsa/receiveKey?key={}&signature={}&modulus={}&publicExponent={}'.format(hex(m[0])[2:], hex(m[1])[2:], hex(A[0][1])[2:], hex(A[0][0])[2:]) print(URL)
true
6ddf77a12196ce4589777bb113385173f2c982a5
Python
adm1n123/FoodOn_LOVE_model
/word2vec.py
UTF-8
5,802
2.734375
3
[]
no_license
""" Download glove word embeddings and convert then to get word2vec embeddings. """ import io import requests import zipfile import numpy as np import pandas as pd from gensim.models import Word2Vec, KeyedVectors from gensim.models.word2vec_inner import REAL from gensim.scripts.glove2word2vec import glove2word2vec from gensim.models.callbacks import CallbackAny2Vec import matplotlib.pylab as plt class WordEmbeddings: def __init__(self): self.file_dir = 'data/pretrain/' self.glove_files = ['glove.6B.50d.txt', 'glove.6B.100d.txt', 'glove.6B.200d.txt', 'glove.6B.300d.txt'] self.word2vec_files = ['word2vec.6B.50d.txt', 'word2vec.6B.100d.txt', 'word2vec.6B.200d.txt', 'word2vec.6B.300d.txt'] for i in range(len(self.glove_files)): self.glove_files[i] = self.file_dir+self.glove_files[i] self.word2vec_files[i] = self.file_dir+self.word2vec_files[i] # for training word embeddings self.summary_preprocessed_file = 'output/wikipedia_preprocessed.txt' self.summary_prep_col = 'summary_preprocessed' def download_glove(self): glove_zip_url = "http://nlp.stanford.edu/data/glove.6B.zip" r = requests.get(glove_zip_url) z = zipfile.ZipFile(io.BytesIO(r.content)) z.extractall(self.file_dir) return None def convert_glove_to_word2vec(self): for g_file, w_file in zip(self.glove_files, self.word2vec_files): glove2word2vec(g_file, w_file) return None def get_pretrain_vectors(self): # self.download_glove() # uncomment if glove vectors are not downloaded. self.convert_glove_to_word2vec() return None def train_embeddings(self): df_summary = pd.read_csv(self.summary_preprocessed_file, sep='\t') df_summary.fillna('', inplace=True) df_summary = df_summary[df_summary[self.summary_prep_col] != ''] sents = df_summary[self.summary_prep_col].tolist() sents = [sent.split() for sent in sents] print(f'Total sentences in wiki corpus: {len(sents)}') we_trainer = Word2vecTrainer() we_trainer.train(sents, self.word2vec_files[-1]) # using 300d word2vec file as pretrained vectors. we_trainer.save_model() we_trainer.save_vectors() we_trainer.save_loss() return None class Word2vecTrainer: def __init__(self): self.callback = CallbackOnEpoch() self.model = None self.epochs = 100 self.vector_size = 300 self.window = 10 self.min_count = 1 self.workers = 16 self.vectors_save_file = 'data/model/word2vec_trained.txt' self.model_save_file = 'data/model/word2vec_model.model' self.loss_save_file = 'data/model/train_loss.pdf' def train(self, sentences, pretrained_file=None): # retraining of pretrained vectors is not possible in gensim 4 word2vec model. self.model = Word2Vec( vector_size=self.vector_size, window=self.window, min_count=self.min_count, workers=self.workers) self.model.build_vocab(sentences) # initially update=False. words satisfying criteria added to vocab not all. total_sents = self.model.corpus_count self.model.wv.vectors_lockf = np.ones(len(self.model.wv), dtype=REAL) # gensim 4. BUG. initialize array manually for lock. if pretrained_file: vocab = self.model.wv.key_to_index.keys() pretrained_vocab = KeyedVectors.load_word2vec_format(pretrained_file).key_to_index.keys() common_words = list(set(vocab) & set(pretrained_vocab)) print('Intersecting %d common vocabularies for transfer learning', len(common_words)) # self.model.build_vocab([pretrained_vocab], update=True, min_count=1) # update=True: add new words and initialize their vectors, min_count=1: include every word because pretrained_vocab is list of unique words self.model.wv.intersect_word2vec_format(pretrained_file, lockf=1.0) # intersecting word vectors are replaced by pretrained vectors. lockf=1 means allow imported vectors to be trained. lockf=0 imported vectors are not trained. # TODO: before training on wiki train on brown etc. corpus and some food related corpus. # TODO: lock vectors then train and then unlock(load again) and train so that remaining vectors are trained according to pretrained and then every vectors trained. self.model.train( sentences, total_examples=total_sents, epochs=self.epochs, compute_loss=True, callbacks=[self.callback]) def save_model(self): self.model.save(self.model_save_file) def save_vectors(self): self.model.wv.save_word2vec_format(self.vectors_save_file) def save_loss(self): lists = sorted(self.callback.loss.items()) # sorted by key, return a list of tuples x, y = zip(*lists) # unpack a list of pairs into two tuples plt.plot(x, y) plt.xlabel('Epoch') plt.ylabel('Loss') plt.savefig(self.loss_save_file) class CallbackOnEpoch(CallbackAny2Vec): def __init__(self): self.epoch = 0 self.loss = {} self.previous_loss = 0 def on_epoch_end(self, model): loss = model.get_latest_training_loss() if self.epoch == 0: actual_loss = loss else: actual_loss = loss - self.previous_loss print('Loss after epoch %d: %d', self.epoch, actual_loss) self.loss[self.epoch] = actual_loss self.previous_loss = loss self.epoch += 1 if __name__ == '__main__': we = WordEmbeddings() # we.get_pretrain_vectors() we.train_embeddings()
true
efcec9948b66df86eb3c892a3c53c1208ccd3d1c
Python
sumonkhan79/DataScience-Random
/assignment1.py
UTF-8
134
3.265625
3
[]
no_license
def profit(revenue, expense): profit_made= revenue-expense return profit_made profit_2018 = profit(100, 90) print(profit_2018)
true
0b6e59dc34a33b978dbcf8b8704dd35cdf33c4d7
Python
nch101/thesis-traffic-signal-control
/projectTS/modeControl/automaticFlexibleTime.py
UTF-8
1,093
2.53125
3
[]
no_license
# ** automatic control mode ** # * Author: Nguyen Cong Huy * # **************************** # - *- coding: utf- 8 - *- import projectTS.vals as vals def automaticFlexibleTime(): for index in range(0, vals.nTrafficLights): if index%2: setTimeLight(vals.timeGreenFlexibleNS, vals.timeGreenFlexibleWS, index) else: setTimeLight(vals.timeGreenFlexibleWS, vals.timeGreenFlexibleNS, index) def setTimeLight(timeGreen, timeGreenForTimeRed, index): if ((vals.timeLight[index] == -1) and \ (vals.lightStatus[index] == 'red')): vals.timeLight[index] = timeGreen vals.lightStatus[index] = 'green' elif ((vals.timeLight[index] == -1) and \ (vals.lightStatus[index] == 'yellow')): vals.timeLight[index] = timeGreenForTimeRed + vals.timeYellow[index] + 2*vals.delta + 3 vals.lightStatus[index] = 'red' elif ((vals.timeLight[index] == -1) and \ (vals.lightStatus[index] == 'green')): vals.timeLight[index] = vals.timeYellow[index] vals.lightStatus[index] = 'yellow' else: pass
true
edb490956711249067a6d71d5e5d45e3477d4596
Python
evyadai/GSR
/InstancePieceWiseLinear.py
UTF-8
14,028
2.765625
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Tue Jul 26 19:11:00 2016 @author: Evyatar """ from math import * import numpy as np np.random.seed(1) import scipy from Instance import * from Linear import * from PieceWiseLinear import * import matplotlib import matplotlib.mlab as mlab # insert "%matplotlib tk" import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import pickle from matplotlib import cm class InstancePieceWiseLinear(Instance): def __init__(self, fr, fb, c): self.fr = fr self.fb = fb self.c = np.float64(c) self.times = fr.times self.norm_cost, self.norm_time = 1.0, 1.0 if self.fr[1] == self.fb[1] == 1: self.norm = True else: self.norm = False def __str__(self): s = "" for t, lr, lb in zip(self.times, self.fr.lins, self.fb.lins): s = s + "Time>= " + str(t) + ": Rent: " + str(lr) + " Buy: " + str(lb) + "\n" return s def intersection(self): eps_num = 1e-10 for i, t in enumerate(self.times): int_t = div(self.fb.lins[i].offset - self.fr.lins[i].offset, self.fr.lins[i].slope - self.fb.lins[i].slope) if i < (len(self.times) - 1): if int_t >= t and int_t <= self.times[i + 1]: return int_t elif int_t + eps_num >= t: return int_t def normalize(self): # we need to init new instance and return this intersect = self.intersection() if intersect is None: return val_inter = self.fr[intersect] # print intersect,val_inter # all slopes need to be updated (*intersections/val_intersect) # all times need to be updated (/intersection) # all offsets need to be updated (/val_inter) normTimes = [t / intersect for t in self.times] diagLinn = Linear(1.0, 0.0) normFr = [Linear(l.slope * intersect / val_inter, l.offset / val_inter) for l in self.fr.lins] normFb = [Linear(l.slope * intersect / val_inter, l.offset / val_inter) for l in self.fb.lins] for ind in range(len(normTimes)): next_t = normTimes[ind + 1] if ind < len(normTimes) - 1 else np.inf if 1. > normTimes[ind] and 1. <= next_t: ind_intersect = ind + 1 if 1.0 not in self.times: normTimes.insert(ind_intersect, 1.0) normFr.insert(ind_intersect, normFr[ind_intersect - 1]) normFb.insert(ind_intersect, normFb[ind_intersect - 1]) normed = InstancePieceWiseLinear(PieceWiseLinear(normFr, normTimes), PieceWiseLinear(normFb, normTimes), self.c / val_inter) normed.norm = True normed.norm_time = intersect normed.norm_cost = val_inter return normed def plot(self, num_fig=1): t_max = self.times[-1] * 2.0 tt = self.times[:] tt.append(t_max) cost_r = [self.fr[t] for t in tt] cost_b = [self.fb[t] for t in tt] xx = [t for t in tt] plt.figure(num_fig) plt.clf() plt.hold(True) plt.plot(xx, cost_r, 'r',linewidth=2) plt.plot(xx, cost_b, 'b',linewidth=2) plt.axis([0.0, xx[-1] * 1.0, 0.0, 1.1 * max(np.max(cost_r), np.max(cost_b))]) fs = 36 plt.xlabel("Time", fontsize=fs) plt.ylabel("Cost", fontsize=fs) # print cost_b,xx return plt def plot_q(self, eps, norm=True, num_fig=1): cr, q, T = self.approxOptStr(eps) Q = np.cumsum(q) if norm: xx = [t * self.norm_time for t in T] Q = Q * self.norm_cost else: xx = T[:] plt.figure(num_fig) plt.hold(True) plt.title("Instance") plt.plot(xx, Q, 'g') plt.legend(["Rent", "buy", "Probabilty"], loc=0) plt.xlabel("Time") plt.ylabel("Cost (Probabilty)") plt.text(xx[-2], self.norm_cost, "Probabilty 1.0") plt.text(xx[-2], 0.5 * self.norm_cost, "Probabilty 0.5") plt.show() print "plot_q", xx, Q def cr_z(self, z): if z == 0: return self.fb.lins[0].offset / self.fr.lins[0].offset elif z == np.inf: if self.fr.lins[-1].slope == self.fb.lins[-1].slope: return self.fr[np.inf] / self.fb[np.inf] return self.fr.lins[-1].slope / self.fb.lins[-1].slope else: raise Exception("Error in InstnacePieceWiseLinear.cr_z") def cr_0(self): return div(self.fb.lins[0].offset, self.fr.lins[0].offset) def cr_inf(self): return div(self.fr.lins[-1].slope, self.fb.lins[-1].slope) if self.fr.lins[-1].slope > 0 else self.fr( self.times[-1] + 10) / self.fb(self.times[-1] + 10) def cr_inf_overall(self): ts = self.times max_ts = np.max([self.fr(t)/self.fb(t) for t in ts]) max_inf = self.cr_inf() return np.max([max_ts,max_inf]) def zm(self): pass def cr_zm(self): return h(self.zm()) # todo - g in linear g(z)=max fr/fb(y) (y>z) def g(self, z): pass # todo -h(z)= (fr(z)+c)/fb(z) def h(self, z): pass # we iterate on all the lines and find if there is inersection between h and g # if there is we find the exact intersection # otherwise we return inf def intersection_time(self): # print "inter" for ind, t in enumerate(self.times): if t >= 1: # at point 1 g<h and then g always up # we need to divide to 2 parts: # 1.h decrese or not up - then we need only to look on the start and end # 2.h increase - then we need to solve # TODO - try to checjk sopes or use ratio g1 = self.fr[t] / self.fb[t] h1 = (self.fr[t] + self.c) / self.fb[t] if ind == len(self.times) - 1: next_t = np.inf g2_n, g2_d = self.fr[next_t], self.fb[next_t] if g2_d == np.inf: g2 = div(self.fr.lins[ind].slope, self.fb.lins[ind].slope) else: g2 = div(g2_n, g2_d) h2_n, h2_d = self.fr[next_t] + self.c, self.fb[next_t] if h2_d == np.inf: h2 = div(self.fr.lins[ind].slope, self.fb.lins[ind].slope) else: h2 = div(h2_n, h2_d) else: next_t = self.times[ind + 1] g2 = self.fr[next_t] / self.fb[next_t] h2 = (self.fr[next_t] + self.c) / self.fb[next_t] # print "inter",ind,g1,g2,h1,h2 # TODO - find intersection better (maybe the intersection function will do this) # if max(g1,g2) >=min(h1,h2): if True: # we have here intersection - what is the solve? # if g1<=g2 then the function is monotone - simple solve if g1 < g2: # we need to find zs: roots_intersection = ratio_intersection(self.fr.lins[ind], self.fb.lins[ind], self.fr.lins[ind] + self.c, self.fb.lins[ind]) if g1 >= g2: # then the function is const roots_intersection = ratio_intersection(Linear(0, g1), Linear(0, 1.0), self.fr.lins[ind] + self.c, self.fb.lins[ind]) inds = np.where((roots_intersection >= t) & (roots_intersection <= next_t))[0] if inds.size > 0: return roots_intersection[inds[0]] else: pass return float("inf") def middle_time_cr(self): z_s = self.intersection_time() # print "z_s at z_m",z_s # the competitve is always h(z) - we need to find the maximum cr_m = (self.fr[1] + self.c) / self.fb[1] z_m = 1.0 # because at each interval h always goes for ind, t in enumerate(self.times): if t >= 1 and t <= z_s: ht = (self.fr(t) + self.c) / self.fb(t) if ht < cr_m: z_m = t cr_m = ht # print "iter at z_m",ind,t,ht,cr_m # at the end we need to check z_s or np.inf if t < z_s: t = z_s ht = self.cr_inf() if z_s == np.inf else (self.fr(t) + self.c) / self.fb(t) if ht < cr_m: z_m = t cr_m = ht # print "last iter at z_m",ht,cr_m,self.cr_inf() if z_s==np.inf else (self.fr(t)+self.c)/self.fb(t),z_s==np.inf,self.fr(t),self.c,self.fb(t),t # print "middle_time_cr",(z_m,cr_m) return (z_m, cr_m) """ if ind==len(self.times)-1: next_t=min(np.inf,z_s) h2_n,h2_d = self.fr[next_t]+self.c,self.fb[next_t] if h2_d==np.inf: h2=div(self.fr.lins[ind].slope,self.fb.lins[ind].slope) else: h2=div(h2_n,h2_d) else: next_t=min(self.times[ind+1],z_s) h2 = (self.fr[next_t]+self.c)/self.fb[next_t] if cr_m > min(h1,h2): cr_m = min(h1,h2) if h1<=h2: z_m=self.times[ind] else: z_m=next_t return (z_m,cr_m) """ def middle_time(self): return self.middle_time_cr()[0] # todo def between(self, t, ind): if ind == len(self.times) - 1: if t >= self.times[ind]: return True elif (t >= self.times[ind]) and (t <= self.times[ind + 1]): return True return False def calc_t1(self, eps): # t1 # f_{r}(z)+c =(1+eps)(f_{rb}(0) +c+f_b(z) # frb(t1)-eps*f_b(t1)=(1+eps)f_{rb}(0)+eps*c # t1 = min(np.float64(1.0),) for ind in range(len(self.times)): if self.times[ind] >= 1.0: return 1.0 else: lin = self.fr.lins[ind] - self.fb.lins[ind] * (1.0 + eps) t1_candidate = lin.inverse((1 + eps) * self.f_rb(0.0) + eps * self.c) if (t1_candidate >= self.times[ind]) and (t1_candidate <= self.times[ind + 1]): return min(np.float64(1.0), t1_candidate) # todo # fix situation when the ratio raise def calc_t_N_minus_1(self, eps): global lin # t_{N-1}\gets \min\{f_{r}^{-1}(c/ \epsilon) ,\min\{x:x\geq 1,\forall y\geq x,\frac{f_r(x)}{f_b(x)}\geq (1+\epsilon)\frac{f_r(y)}{f_b(y)} \}\} $ if (self.c <= self.fr[1.0] * eps): return 1.0 val1 = max(1.0, self.fr.inverse(self.c / eps)) maxRatio = self.cr_inf() # print self.fr.lins[-1],val1,self.c/eps # print maxRatio/(1+eps),self.fr.inverse(self.c/eps) # print "val1",val1 if maxRatio < np.inf: maxRatioLin = [maxLin(self.fr.lins[ind - 1], self.fb.lins[ind - 1], self.times[ind - 1], self.times[ind])[0] for ind in range(1, len(self.times))] maxRatioLin.append(maxLin(self.fr.lins[-1], self.fb.lins[-1], self.times[-1], np.inf)[0]) # print maxRatioLin,maxLin(self.fr.lins[-1],self.fb.lins[-1],self.times[-1],np.inf) # fr = maxRatio/(1+eps) *fb # print "max Ratios",maxRatioLin for ind in range(len(self.times)): if self.times[ind] < 1.0: continue # TODO - if ratio is down we need to consider from (ind+1) else ind maxRatio = max(maxRatioLin[ind:]) # print ind,maxRatio,self.times[ind],eps lin_cond = self.fr.lins[ind] - self.fb.lins[ind] * (maxRatio / (1 + eps)) val2_candidate = lin_cond.inverse(0.0) # this is the point where the ratio is fine if (val2_candidate < self.times[ind]) and ( self.fr[self.times[ind]] / self.fb[self.times[ind]] >= maxRatio / (1 + eps)): # this case when the candidate is out of range (and we take the start of the range) # print "oor",val2_candidate,self.times[ind],maxRatio,self.fr.lins[ind],self.fb.lins[ind] val2_candidate = self.times[ind] # print self.between(val2_candidate,ind) if self.between(val2_candidate, ind): # (val2_candidate>=self.times[ind]) and (val2_candidate<= self.times[ind+1]) : val2_cand_ratio = self.fr[val2_candidate] / self.fb[val2_candidate] if (val2_cand_ratio + 1e-5 >= (maxRatio / (1 + eps))): # print "return",ind,min(val1,val2_candidate),val2_cand_ratio,maxRatio/(1+eps),val1,val2_candidate # print self.fr[50]/self.fb[50] return min(val1, val2_candidate) return val1 def valid(self): if min([self.times[1:][j] - self.times[:-1][j] for j in range(len(self.times) - 1)]) < 0.: return False if min([min(self.fr.lins[i].slope, self.fb.lins[i].slope) for i in range(len(self.times))]) < 0: return False return True
true
22421d0a55124e1ffe0095490d42f73d826ef6ff
Python
ShivamRohilllaa/python-basics
/20) List and functions.py
UTF-8
236
4.09375
4
[]
no_license
# Its starts with 0 grocery = ["Shivam", "rohilla", "text1", "text2" ] #print(grocery[1]) #print(grocery[1] + grocery[2]) #Sort the list means arrange the list in ascending order list = [1, 2, 88, 23, 56 ] list.sort() print(list)
true
02475b83a369c1a8eb50cc392360cbf585d401fb
Python
FHArchive/StegStash
/stegstash/lsb.py
UTF-8
3,338
2.984375
3
[ "MIT" ]
permissive
""" common lsb functions """ from random import SystemRandom from stegstash.utils import toBin, toFile, getMap, otp class LSB: """Perform lsb encoding and decoding on an array """ def __init__(self, array, pointer=0, data=None): self.array = array self.arrayLen = len(array) self.pointer = pointer self.data = toBin(data) def setLsb(self, bit): """ set lsb """ if self.pointer >= self.arrayLen: return self.array[self.pointer] = (self.array[self.pointer] & (2**16 - 2)) + bit self.pointer += 1 def getLsb(self): """ get lsb """ if self.pointer >= self.arrayLen: return 0 bit = self.array[self.pointer] & 1 self.pointer += 1 return bit def setLsb8(self, byte): """ set lsb8 """ for shift in range(8): self.setLsb(byte >> shift & 1) # Little endian def getLsb8(self): """ get lsb8 """ byte = 0 for shift in range(8): byte += self.getLsb() << shift # Little endian return byte, byte == 0 def setLsb8C(self, char): """ set lsb8 char""" return self.setLsb8(ord(char)) def getLsb8C(self): """ get lsb8 char """ byte, nullByte = self.getLsb8() return chr(byte), nullByte def simpleDecode(self, zeroTerm=True, file=None): """ decode a flat array with no encryption Args: zeroTerm (boolean, optional): stop decoding on \x00 (NUL). Defaults to True. file (<file>, optional): file pointer. Defaults to None. """ data = [] for _char in range(self.arrayLen // 8): char, zero = self.getLsb8() if zero and zeroTerm: break data.append(char) result = bytes(data) return toFile(result, file) if file else result def simpleEncode(self): """ encode a flat array with no encryption """ for char in self.data: if self.pointer >= self.arrayLen - 8: break self.setLsb8(char) self.setLsb8(0) # Null terminate the string return self.array def decode(self, mapSeed, password="", zeroTerm=True, file=None): """decode data from an array using lsb steganography Args: mapSeed (string): seed to generate the lsb map password (str, optional): password to encrypt the data with. Defaults to "". zeroTerm (boolean, optional): stop decoding on \x00 (NUL). Defaults to True. file (<file>, optional): file pointer. Defaults to None. Returns: bytes: data from the image """ lsbMap = getMap(self.array, mapSeed) data = [] while self.pointer in range(self.arrayLen): byte = 0 shift = 0 while shift < 8: if lsbMap[self.pointer] > 0: bit = self.getLsb() # Little endian byte += bit << shift shift += 1 else: self.pointer += 1 # Increment pointer anyway if byte == 0 and zeroTerm: break data.append(byte) result = otp(bytes(data), password, False) return toFile(result, file) if file else result def encode(self, mapSeed, password=""): """encode an array with data using lsb steganography Args: mapSeed (string): seed to generate the lsb map password (str, optional): password to encrypt the data with. Defaults to "". """ data = otp(self.data, password) + b"\x00" lsbMap = getMap(self.array, mapSeed) systemRandom = SystemRandom() for char in data: shift = 0 while shift < 8: if lsbMap[self.pointer] > 0: self.setLsb(char >> shift & 1) shift += 1 else: self.setLsb(systemRandom.randint(0, 1)) return self.array
true
9ba4a88d011864adb52140144afc41bc18aebc1d
Python
beeware/toga
/gtk/tests/widgets/utils.py
UTF-8
1,014
2.6875
3
[ "BSD-3-Clause" ]
permissive
class TreeModelListener: """useful to access paths and iterators from signals.""" def __init__(self, store=None): self.changed_path = None self.changed_it = None self.inserted_path = None self.inserted_it = None self.deleted_path = None if store is not None: self.connect(store) def on_change(self, model, path, it): self.changed_path = path self.changed_it = it def on_inserted(self, model, path, it): self.inserted_path = path self.inserted_it = it def on_deleted(self, model, path): self.deleted_path = path def connect(self, store): store.connect("row-changed", self.on_change) store.connect("row-inserted", self.on_inserted) store.connect("row-deleted", self.on_deleted) def clear(self): self.changed_path = None self.changed_it = None self.inserted_path = None self.inserted_it = None self.deleted_path = None
true
98d5caf14526d3ce3dde7f979a9170cea12aac6b
Python
hemae/neural_networks
/add_ex1_grad_des.py
UTF-8
1,431
3.140625
3
[]
no_license
import numpy as np import matplotlib.pyplot as plt import time def f(x): return x * x - 5 * x + 5 def df(x): return 2 * x - 5 N = 100 # число итераций xn = 0 # начальное значение x lmd = 0.8 # шаг сходимости (коэффициент) x_plt = np.arange(0, 5.0, 0.1) f_plt = [f(x) for x in x_plt] plt.ion() # включаем интерактивный режим fig, ax = plt.subplots() # создаем окно и оси для графика ax.grid(True) # отображаем сетку на графике (осях) ax.plot(x_plt, f_plt) # отображаем начальный график на осях point = ax.scatter(xn, f(xn), c='r') # отображаем начальную точку на графике mn = 100 for i in range(N): lmd = 1 / (min(i + 1, mn)) xn = xn - lmd * np.sign(df(xn)) # изменяем аргумент согласно алгоритму град.спуска point.set_offsets([xn, f(xn)]) # обновляем положение точки # перерисовываем график при задержке 20 мс fig.canvas.draw() fig.canvas.flush_events() time.sleep(0.002) plt.ioff() # выключаем интерактивный режим print(xn) ax.scatter(xn, f(xn), c='g') # отрисовываем конечное положение точки plt.show()
true
da0c4a75a88d1030e14d01006201711eaf476552
Python
VimalanKM/Tic-Tac_Toe-GAME
/playing_tictactoe.py
UTF-8
1,989
3.53125
4
[ "Apache-2.0" ]
permissive
import random import numpy as np #random.seed(1) def create_board(): return np.zeros((3,3),dtype=int) def place(board,player,position): board[position]=player def possibilities(board): indi=np.where(board==0) return (list(zip(indi[0],indi[1]))) def random_place(board,player): availablepos=possibilities(board) if len(availablepos)!=0: place(board,player,random.choice(availablepos)) def row_win(board,player): flag=0 for i in range(3): flag=0 for j in range(3): if board[i][j]==player: flag+=1 if flag==3: return True return False def col_win(board,player): for i in range(3): flag=0 for j in range(3): if board[j][i]==player: flag+=1 if flag==3: return True return False def diag_win(board,player): flag1,flag2=0,0 for i in range(3): if board[i][i]==player: flag1+=1 if board[i][3-i-1]==player: flag2+=1 if flag1==3 or flag2==3: return True return False def evaluate(board): winner = 0 for player in [1, 2]: # add your code here! if(row_win(board,player) or col_win(board,player) or diag_win(board,player)): winner = player pass if np.all(board != 0) and winner == 0: winner = -1 return winner def play_game(): board=create_board() player=1 while(np.any(board==0)): random_place(board,player) eval=evaluate(board) if eval!=0: return eval else: if player==1: player=2 else: player=1 results=[] count=0 for i in range(1000): temp=play_game() results.append(temp) if temp==1: count+=1 print("Winners:",results) print("Number of times player1 won:",count)
true
aabffba1d6138ad6cac53beaa334e752ddf0294b
Python
VishnuK11/Computer_Vision
/16 Face Train.py
UTF-8
1,497
3.078125
3
[ "MIT" ]
permissive
''' Face Recogition Training Create a list of images to train Detect a R.O.I - Region of Interest Train it Save classififier, features and labels ''' import os import cv2 as cv import numpy as np import matplotlib.pyplot as plt dir_path = os.getcwd()+'/data/images/' dir_face = os.getcwd()+'/data/face_recognition/' dir_train = os.getcwd()+'/data/face_recognition/train/' people =['Dicaprio','Tom','Natalie','Scarlett','Saoirse','Will','Beyonce'] features = [] labels = [] haar_cascade = cv.CascadeClassifier(dir_face+'face.xml') def create_train(): for person in people: path = os.path.join(dir_train,person) label = people.index(person) for img in os.listdir(path): img_path=os.path.join(path,img) img_array = cv.imread(img_path) gray = cv.cvtColor(img_array, cv.COLOR_BGR2GRAY) faces_rect = haar_cascade.detectMultiScale(gray,scaleFactor = 1.1, minNeighbors = 8) for (x,y,w,h) in faces_rect: faces_roi = gray[y:y+h,x:x+w] cv.imshow('Print',faces_roi) cv.waitKey(20) features.append(faces_roi) labels.append(label) create_train() # cv.waitKey(0) print(len(features),len(labels)) features = np.array(features,dtype='object') labels = np.array(labels) face_recognizer = cv.face.LBPHFaceRecognizer_create() # Train the recognizer on the feature list and labels list face_recognizer.train(features,labels) face_recognizer.save(dir_face+'face_trained.yml') np.save(dir_face+'features.npy',features) np.save(dir_face+'labels.npy',labels)
true
db7d8834d7518aa59f52f7e83e90c8212717722a
Python
ppershing/skripta-fmfi
/krypto2/utility/13_kryptoanalyza/linear.py
UTF-8
6,516
3.125
3
[]
no_license
#!/usr/bin/python # coding=utf-8 from cipher import *; def LAT(inputs, outputs): return int(round(sum(map(lambda x: (-1)**(parityOf(x & inputs) ^ parityOf(Sbox(x) & outputs)), range(16) )))) def get_LAT_color(value): value = max(0.75 -abs( value) / 10.0 ,0); return "\\color[rgb]{%f,%f,%f}" % (value,value,value) def GenerateLinearApproximationTable(f): # {{{ print >>f, "\\begin{table}[H]" print >>f, "\\begin{tabular}{" + 17*"r|" + "}" for i in range(16): print >>f, "&{\\bf %2d}" % i print >>f, "\\\\ \\hline" for i in range(KEY_MAX): print >>f, "{\\bf %2d}" % i for j in range(KEY_MAX): print >>f, " &{%s %3d}" % (get_LAT_color(LAT(i,j)), LAT(i,j)) print >>f, "\\\\ \hline" print >>f, "\\end{tabular}" print >>f, "\\caption{Lineárna aproximačná tabuľka pre S-box}"; print >>f, "\\label{tab:lat}" print >>f, "\\end{table}" # }}} def AnalyzeLinearApproximations(f, linear_combination): # {{{ total_balance = []; print >>f, "\\begin{itemize}" for round in range(3): inputs = linear_combination[round]; if (round>0): inputs = map(ShufflePosition, inputs); outputs = linear_combination[round+1]; in_array = [(x in inputs) for x in range(TOTAL_KEY_SIZE)] out_array = [(x in outputs) for x in range(TOTAL_KEY_SIZE)] balance = [] for sbox in range(SBOX_COUNT): in_tmp = BitsToHalfByte(in_array[sbox*4: sbox*4+4]) out_tmp = BitsToHalfByte(out_array[sbox*4: sbox*4+4]) balance += [LAT(in_tmp, out_tmp)/2.0/KEY_MAX]; b = reduce(mul, balance)*8.0; total_balance += [b] print >>f, "\\item {\\bf %d. kolo:}" % (round+1) print >>f, "Použijeme lineárnu aproximáciu" print >>f, "\\begin{equation*}" print >>f, "(", print >>f, " \\oplus ".join(["x_{%d,%d}" % (round+1,x) for x in inputs]) , print >>f, " ) \n \\oplus (", print >>f, " \\oplus ".join(["key_{%d,%d}" %(round+1,x) for x in inputs]), print >>f, ") \n \\approx (", print >>f, " \\oplus ".join(["y_{%d,%d}" % (round+1,x) for x in outputs]), print >>f, ")" print >>f, "\\end{equation*}" print >>f, "ktorá má balancie po jednotlivých S-boxoch $" print >>f, ",\ ".join(["%s" % x for x in balance]) print >>f, "$ čo podľa piling-up lemy dáva pravdepodobnosť " print >>f, "$1/2 + 2^3*(" , print >>f, ")*(".join(["%s" %x for x in balance]) , print >>f, ")=", (0.5 + b), "$. " print >>f, "Výsledná balancia je $%s$." % b print >>f, "" print >>f, "\\item {\\bf Spolu:} ", print >>f, "Máme lineárnu kombináciu " print >>f, "\\begin{equation*}" print >>f, "\\begin{split}" print >>f, "(", print >>f, " \\oplus ".join(["in_{%s}" %x for x in linear_combination[0]]), print >>f, ")" for r in range(3): print >>f, " & \\\\\n \\phantom{x} \\oplus (", print >>f, " \\oplus ".join(["key_{%s,%s}" % (r+1, o) for o in sorted([(o if (r == 0) else ShufflePosition(o)) for o in linear_combination[r] ])]), print >>f, ")" print >>f, " & \\approx (" print >>f, " \\oplus ".join([ "key_{%s,%s}" % (4,o) for o in sorted(map(ShufflePosition,linear_combination[3]))]) print >>f, " ) \\\\\n & \\phantom{\\approx} \\oplus (" print >>f, " \\oplus ".join(map(lambda x: "out_{%s}" % x, linear_combination[3])) print >>f, ")", print >>f, "\\end{split}" print >>f, "\\end{equation*}" print >>f, "Podľa piling-up lemy máme balanciu $4*" , print >>f, "*".join(map(lambda x: "%s" %x, total_balance)) , print >>f, "~= %.4f $." % (reduce(mul, total_balance)*4) print >>f, "\\end{itemize}" # }}} def AttackUsingLATHelper(f, linear_combination, keys, iterations): # {{{ plaintext = [[random.randint(0, 1) for j in range(TOTAL_KEY_SIZE)] for i in range(iterations)]; ciphertext = [Cipher(plaintext[i], keys) for i in range(iterations)] linear_in = linear_combination[0]; linear_out = map(ShufflePosition, linear_combination[3]) in_array = [x in linear_in for x in range(TOTAL_KEY_SIZE)] out_array = [x in linear_out for x in range(TOTAL_KEY_SIZE)] sboxes = dict([ (x/4,0) for x in linear_out]).keys() matching_key = [0 for i in range(TOTAL_KEY_MAX)] for i in range(iterations): for boxkey in range(KEY_MAX ** len(sboxes)): lastkey = [0 for x in range(TOTAL_KEY_SIZE)] boxkey_tmp = IntToBits(boxkey, KEY_SIZE*len(sboxes)) for x in range(len(sboxes)): lastkey[4*sboxes[x]:4*sboxes[x]+4] = boxkey_tmp[x*4: x*4+4] ct = InverseLastRound(ciphertext[i], lastkey) pt = plaintext[i] l1 = parityOf(BitsToInt(pt) & BitsToInt(in_array)) l2 = parityOf(BitsToInt(ct) & BitsToInt(out_array)) if not (l1^l2): matching_key[BitsToInt(lastkey)] = matching_key[BitsToInt(lastkey)] + 1 good_keys = [] for i in range(TOTAL_KEY_MAX): if matching_key[i]: good_keys.append(i); best = sorted([ (abs(matching_key[i] / 1.0 / iterations - 0.5), i) for i in good_keys], reverse=True) print >>f, " \\subtable[$key_5=%04x$]{" % BitsToInt(keys[4]) print >>f, " \\begin{tabular}{cc}" for (p,i) in best[0:10]: print >>f, " %.4f & %s \\\\" % (p, MaskedHex(i, sboxes)) print >>f, " \\end{tabular}"; print >>f, " }" # }}} def AttackUsingLAT(f, path): # {{{ key1 = IntToBits(0xfa3f, TOTAL_KEY_SIZE); key2 = IntToBits(0x0f39, TOTAL_KEY_SIZE); key3 = IntToBits(0x8db3, TOTAL_KEY_SIZE); key4 = IntToBits(0xf9b1, TOTAL_KEY_SIZE); print >>f, "\\begin{table}[h]" print >>f, " \\centering" key5 = IntToBits(random.randint(0, TOTAL_KEY_MAX), TOTAL_KEY_SIZE); keys = [key1,key2,key3,key4,key5]; AttackUsingLATHelper(f, path, keys, 1000) key5 = IntToBits(random.randint(0, TOTAL_KEY_MAX), TOTAL_KEY_SIZE); keys = [key1,key2,key3,key4,key5]; AttackUsingLATHelper(f, path, keys, 1000) print >>f, "\\end{table}" # }}}
true
7afda2050a995a0990b4b756c81a06bfb8976577
Python
sonkarsr/IPNV
/circles.py
UTF-8
159
2.609375
3
[]
no_license
image = np.zeros((512,512,3), np.uint8) cv2.circle(image, (350, 350), 100, (15,75,50), -1) cv2.imshow("Circle", image) cv2.waitKey(0) cv2.destroyAllWindows()
true
b98ea54e836635b150df9e96322b4be1bdfba2bf
Python
deepset-ai/haystack
/haystack/utils/preprocessing.py
UTF-8
8,303
2.953125
3
[ "Apache-2.0" ]
permissive
from typing import Callable, Dict, List, Optional import re import logging from pathlib import Path from haystack.schema import Document logger = logging.getLogger(__name__) def convert_files_to_docs( dir_path: str, clean_func: Optional[Callable] = None, split_paragraphs: bool = False, encoding: Optional[str] = None, id_hash_keys: Optional[List[str]] = None, ) -> List[Document]: """ Convert all files(.txt, .pdf, .docx) in the sub-directories of the given path to Documents that can be written to a Document Store. :param dir_path: The path of the directory containing the Files. :param clean_func: A custom cleaning function that gets applied to each Document (input: str, output: str). :param split_paragraphs: Whether to split text by paragraph. :param encoding: Character encoding to use when converting pdf documents. :param id_hash_keys: A list of Document attribute names from which the Document ID should be hashed from. Useful for generating unique IDs even if the Document contents are identical. To ensure you don't have duplicate Documents in your Document Store if texts are not unique, you can modify the metadata and pass [`"content"`, `"meta"`] to this field. If you do this, the Document ID will be generated by using the content and the defined metadata. """ # Importing top-level causes a circular import from haystack.nodes.file_converter import BaseConverter, DocxToTextConverter, PDFToTextConverter, TextConverter file_paths = [p for p in Path(dir_path).glob("**/*")] allowed_suffixes = [".pdf", ".txt", ".docx"] suffix2converter: Dict[str, BaseConverter] = {} suffix2paths: Dict[str, List[Path]] = {} for path in file_paths: file_suffix = path.suffix.lower() if file_suffix in allowed_suffixes: if file_suffix not in suffix2paths: suffix2paths[file_suffix] = [] suffix2paths[file_suffix].append(path) elif not path.is_dir(): logger.warning( "Skipped file %s as type %s is not supported here. " "See haystack.file_converter for support of more file types", path, file_suffix, ) # No need to initialize converter if file type not present for file_suffix in suffix2paths.keys(): if file_suffix == ".pdf": suffix2converter[file_suffix] = PDFToTextConverter() if file_suffix == ".txt": suffix2converter[file_suffix] = TextConverter() if file_suffix == ".docx": suffix2converter[file_suffix] = DocxToTextConverter() documents = [] for suffix, paths in suffix2paths.items(): for path in paths: logger.info("Converting %s", path) # PDFToTextConverter, TextConverter, and DocxToTextConverter return a list containing a single Document document = suffix2converter[suffix].convert( file_path=path, meta=None, encoding=encoding, id_hash_keys=id_hash_keys )[0] text = document.content if clean_func: text = clean_func(text) if split_paragraphs: for para in text.split("\n\n"): if not para.strip(): # skip empty paragraphs continue documents.append(Document(content=para, meta={"name": path.name}, id_hash_keys=id_hash_keys)) else: documents.append(Document(content=text, meta={"name": path.name}, id_hash_keys=id_hash_keys)) return documents def tika_convert_files_to_docs( dir_path: str, clean_func: Optional[Callable] = None, split_paragraphs: bool = False, merge_short: bool = True, merge_lowercase: bool = True, id_hash_keys: Optional[List[str]] = None, ) -> List[Document]: """ Convert all files (.txt, .pdf) in the sub-directories of the given path to Documents that can be written to a Document Store. :param merge_lowercase: Whether to convert merged paragraphs to lowercase. :param merge_short: Whether to allow merging of short paragraphs :param dir_path: The path to the directory containing the files. :param clean_func: A custom cleaning function that gets applied to each doc (input: str, output:str). :param split_paragraphs: Whether to split text by paragraphs. :param id_hash_keys: A list of Document attribute names from which the Document ID should be hashed from. Useful for generating unique IDs even if the Document contents are identical. To ensure you don't have duplicate Documents in your Document Store if texts are not unique, you can modify the metadata and pass [`"content"`, `"meta"`] to this field. If you do this, the Document ID will be generated by using the content and the defined metadata. """ try: from haystack.nodes.file_converter import TikaConverter except Exception as ex: logger.error("Tika not installed. Please install tika and try again. Error: %s", ex) raise ex converter = TikaConverter() paths = [p for p in Path(dir_path).glob("**/*")] allowed_suffixes = [".pdf", ".txt"] file_paths: List[Path] = [] for path in paths: file_suffix = path.suffix.lower() if file_suffix in allowed_suffixes: file_paths.append(path) elif not path.is_dir(): logger.warning( "Skipped file %s as type %s is not supported here. " "See haystack.file_converter for support of more file types", path, file_suffix, ) documents = [] for path in file_paths: logger.info("Converting %s", path) # TikaConverter returns a list containing a single Document document = converter.convert(path)[0] meta = document.meta or {} meta["name"] = path.name text = document.content pages = text.split("\f") if split_paragraphs: if pages: paras = pages[0].split("\n\n") # pop the last paragraph from the first page last_para = paras.pop(-1) if paras else "" for page in pages[1:]: page_paras = page.split("\n\n") # merge the last paragraph in previous page to the first paragraph in this page if page_paras: page_paras[0] = last_para + " " + page_paras[0] last_para = page_paras.pop(-1) paras += page_paras if last_para: paras.append(last_para) if paras: last_para = "" for para in paras: para = para.strip() if not para: continue # this paragraph is less than 10 characters or 2 words para_is_short = len(para) < 10 or len(re.findall(r"\s+", para)) < 2 # this paragraph starts with a lower case and last paragraph does not end with a punctuation para_is_lowercase = ( para and para[0].islower() and last_para and last_para[-1] not in r'.?!"\'\]\)' ) # merge paragraphs to improve qa if (merge_short and para_is_short) or (merge_lowercase and para_is_lowercase): last_para += " " + para else: if last_para: documents.append(Document(content=last_para, meta=meta, id_hash_keys=id_hash_keys)) last_para = para # don't forget the last one if last_para: documents.append(Document(content=last_para, meta=meta, id_hash_keys=id_hash_keys)) else: if clean_func: text = clean_func(text) documents.append(Document(content=text, meta=meta, id_hash_keys=id_hash_keys)) return documents
true
7d99f880d77a194488849bc0735d34e33d53e5a8
Python
shg9411/algo
/algo_py/boj/bj1275.py
UTF-8
1,226
2.875
3
[]
no_license
import math import sys input = sys.stdin.readline def init(arr, tree, node, s, e): #print(node, s, e) if s == e: tree[node] = arr[s] return tree[node] m = (s+e)//2 tree[node] = init(arr, tree, node*2, s, m) + \ init(arr, tree, node*2+1, m+1, e) return tree[node] def update(tree, node, s, e, idx, diff): if not s <= idx <= e: return tree[node] += diff if s != e: mid = (s+e)//2 update(tree, node*2, s, mid, idx, diff) update(tree, node*2+1, mid+1, e, idx, diff) def getValue(tree, node, s, e, left, right): if left > e or right < s: return 0 if left <= s and e <= right: return tree[node] mid = (s+e)//2 return getValue(tree, node*2, s, mid, left, right)+getValue(tree, node*2+1, mid+1, e, left, right) n, q = map(int, input().split()) arr = list(map(int, input().split())) tree = [0 for _ in range(2**(math.ceil(math.log2(n)+1)))] init(arr, tree, 1, 0, n-1) # print(tree) for _ in range(q): x, y, a, b = map(int, input().split()) if x > y: x, y = y, x print(getValue(tree, 1, 0, n-1, x-1, y-1)) diff = b-arr[a-1] arr[a-1] = b update(tree, 1, 0, n-1, a-1, diff)
true
d38ac3d576b17ea97f435453bb296a2897c34490
Python
VladyslavHnatchenko/python_magic_methods
/next_methods.py
UTF-8
4,032
4.03125
4
[]
no_license
from os.path import join class FileObject: """ The wrapper for the file object to ensure that the file will be closed upon deletion.""" def __init__(self, filepath='~', filename='sample.txt'): # Open file filename in read and write mode self.file = open(join(filepath, filename), 'r+') def __del__(self): self.file.close() del self.file class Word(str): """ The class for word s that defines a comparison by word length.""" def __new__(cls, word): # We have to use __new__, since the type of str is immutable # and we need to initialize it earlier (when creating) if ' ' in word: print("Value contains spaces. Trancating to first space.") word = word[:word.index(' ')] # Now Word is all characters up to first space return str.__new__(cls, word) def __gt__(self, other): return len(self) > len(other) def __lt__(self, other): return len(self) < len(other) def __ge__(self, other): return len(self) >= len(other) def __le__(self, other): return len(self) <= len(other) def __setattr__(self, key, value): self.name = value """ This's a recursion, because whenever any attribute is assigned a value, __setattr__() is called. That is, in fact, is equivalent to self.__setattr__('name', value). Since the method calls itself, the recursion will continue indefinitely, until everything falls """ def __setattr__(self, name, value): self.__dict__[name] = value """ Assignment of class variables to the dictionary. Further definition of arbitrary behavior. """ class AccessCounter(object): """ The class that contains the value attribute and implements an access counter for it. The counter is incremented every time the value changes. """ def __int__(self, val): super(AccessCounter, self).__setattr__('counter', 0) super(AccessCounter, self).__setattr__('value', val) def __setattr__(self, name, value): if name == 'value': super(AccessCounter, self).__setattr__('counter', self.counter + 1) # We won't make any condition here. # If you want to prevent other attributes from being modified, # throw an AttributeError(name) exception. super(AccessCounter, self).__setattr__(name, value) def __delattr__(self, name): if name == 'value': super(AccessCounter, self).__setattr__('counter', self.counter + 1) super(AccessCounter, self).__delattr__(name) class FunctionalList: """ Class wrapper over the list with some functional magic added: head, tail, last, drop, take. """ def __init__(self, values=None): if values is None: self.values = [] else: self.values = values def __len__(self): return len(self.values) def __getitem__(self, key): # if the value or key type is incorrect, the list throw an exception return self.values[key] def __setitem__(self, key, value): self.values[key] = value def __delitem__(self, key): del self.values[key] def __iter__(self): return iter(self.values) def __reversed__(self): return FunctionalList(reversed(self.values)) def append(self, value): self.values.append(value) def head(self): # return first element return self.values[0] def tail(self): # return all elements except 1st return self.values[1:] def init(self): # return all elements except the last return self.values[:-1] def last(self): # return the last element return self.values[-1] def drop(self, n): # all elements except n first elements return self.values[n:] def take(self, n): # first n elements return self.values[:n]
true
620040475e190de356d58aee06a85a60cdca0160
Python
n-simplex/Personal
/Image Processing/CircleMap.py
UTF-8
2,642
2.921875
3
[]
no_license
import random import math import turtle import winsound import smtplib import os import time import colorsys global password password = input('Enter password: ') os.system('cls') for i in range(0,100): print('\n') def email(): addr = 'iskym9@gmail.com' msg = "\r\n".join([ "From: iskym9@gmail.com", "To: iskym9@gmail.com", "Subject: COMPUTED!", '', '['+time.strftime('%H')+':'+time.strftime('%M')+':'+time.strftime('%S')+']' ]) server = smtplib.SMTP('smtp.gmail.com:587') server.ehlo() server.starttls() server.login(addr,password) server.sendmail(addr, addr, msg) server.quit() def circle(maxit, k, O, samplen, epsilon): l = [] for j in range(0, samplen): stheta = random.uniform(0,1) ntheta = stheta for i in range(0, maxit): ntheta = ntheta+O-(k/(2*math.pi))*math.sin(2*math.pi*ntheta) ntheta %= 1 if abs(ntheta-stheta) <= epsilon: time = i break elif i == maxit-1: time = maxit break l.append(time) return (sum(l)/len(l)) def colour(cyc): if cyc <= 10: return 'black' if cyc > 10 and cyc <= 50: return 'indigo' if cyc > 50 and cyc <= 100: return 'blue' if cyc > 100 and cyc <= 140: return 'green' if cyc > 140 and cyc <= 200: return 'yellow' if cyc > 200 and cyc <= 250: return 'orange' if cyc > 250: return 'red' def rerange(n,olrange,nerange): if n > olrange[1] or n < olrange[0]: return 'ERROR: n not within OLD RANGE' else: olperc = (n-olrange[0])/(olrange[1]-olrange[0]) return nerange[0]+olperc*(nerange[1]-nerange[0]) def circlemap(maxit, krange, Orange, samples, epsilon, width, height): for y in range(-int(height/2), int(height/2)): for x in range(-int(width/2), int(width/2)): currentk = rerange(y+(height/2),[0,height],krange) currentO = rerange(x+(width/2),[0,width],Orange) cycle = circle(maxit, currentk, currentO, samples, epsilon) turtle.up() turtle.goto(x-1,y) turtle.down() if cycle == 250: turtle.color('black') else: turtle.color(colorsys.hsv_to_rgb((cycle/250)**0.5,(cycle/250)**0.08,1)) turtle.forward(1) turtle.tracer(0,0) circlemap(250, [0, 2*math.pi], [0, 1], 500, 0.001, 500, 500) turtle.ht() turtle.update() winsound.Beep(10000,1000) email()
true
1373c94e96ebe2eaa9e386857230558ba703098d
Python
arushibutan11/ASA
/ASA/loki.py
UTF-8
2,230
2.578125
3
[]
no_license
# -*- coding: utf-8 -*- from __future__ import unicode_literals import serial import time from pynmea import nmea from django.shortcuts import render import string import math def loki(bound_lat, bound_lon, bound_radius): #Calculate Current Coordinates port = serial.Serial("/dev/ttyAMA0",9600, timeout=3.0) gpgga = nmea.GPGGA() gprmc = nmea.GPRMC() while True: rcvd = port.readline() if rcvd[0:6] == '$GPRMC': gprmc.parse(rcvd) if gprmc.data_validity == 'V': print "No Location Found" else: gprmc.parse(rcvd) latitude = gprmc.lat try: latitude = float(latitude) except ValueError: print "Lat Value Error" + latitude lat_direction = gprmc.lat_dir try: longitude = float(gprmc.lon) except ValueError: print "Longitude Value Error" + longitude lon_direction = gprmc.lon_dir gps_time = float(gprmc.timestamp) gps_hour = int(gps_time/10000.0) gps_min = gps_time%10000.0 gps_sec = gps_min%100.0 gps_min = int(gps_min/100.0) gps_sec = int(gps_sec) lat_deg = int(latitude/100.0) lat_min = latitude - (lat_deg*100) lat_dec_deg = lat_deg + (lat_min/60) lon_deg = int(longitude/100.0) lon_min = longitude - (lon_deg*100) lon_dec_deg = lon_deg + (lon_min/60) lon_sec = lon_min%100.0 lon_min = int(lon_min/100.0) print "Time: "+str(gps_hour)+":"+str(gps_min)+":"+str(gps_sec) print "Latitude: " + str(lat_dec_deg) + str(lat_direction) print "Longitude: " + str(lon_dec_deg) + str(lon_direction) #Calculate dist between bound_coord and current location latitude = 28.664227 longitude = 77.232989 earth_radius = 6371*1000 dLat = (latitude - bound_lat)*math.pi/180 dLon = (longitude - bound_lon)*math.pi/180 latitude = latitude*math.pi/180 bound_lat = bound_lat*math.pi/180 val = math.sin(dLat/2) * math.sin(dLat/2) + math.sin(dLon/2)*math.sin(dLon/2)*math.cos(bound_lat)*math.cos(latitude) ang = 2*math.atan2(math.sqrt(val), math.sqrt(1-val)) distance = earth_radius*ang if distance>bound_radius: print "Patient Lost" #Send Push Noti and Location else: print "Patient Found" #Send Location
true
9d471e893b97b10e565de25ab89d6f8bf64b76e7
Python
jlopez1328/Python
/Ejercicios_conceptos_basicos/cambio_moneda.py
UTF-8
147
3.25
3
[]
no_license
dolares = float(input ("Digite la cantidad dolares \n")) vdolares = 3981 cop = dolares * vdolares print("Total de cantidad de dolares a COP", cop)
true
0a1d027425c6d39ee76e58c1e067b814b8ef418f
Python
Hsuxu/vision
/torchvision/prototype/transforms/_presets.py
UTF-8
2,764
2.765625
3
[ "BSD-3-Clause", "CC-BY-NC-4.0" ]
permissive
""" This file is part of the private API. Please do not use directly these classes as they will be modified on future versions without warning. The classes should be accessed only via the transforms argument of Weights. """ from typing import List, Optional, Tuple, Union import PIL.Image import torch from torch import Tensor from . import functional as F, InterpolationMode __all__ = ["StereoMatching"] class StereoMatching(torch.nn.Module): def __init__( self, *, use_gray_scale: bool = False, resize_size: Optional[Tuple[int, ...]], mean: Tuple[float, ...] = (0.5, 0.5, 0.5), std: Tuple[float, ...] = (0.5, 0.5, 0.5), interpolation: InterpolationMode = InterpolationMode.BILINEAR, ) -> None: super().__init__() # pacify mypy self.resize_size: Union[None, List] if resize_size is not None: self.resize_size = list(resize_size) else: self.resize_size = None self.mean = list(mean) self.std = list(std) self.interpolation = interpolation self.use_gray_scale = use_gray_scale def forward(self, left_image: Tensor, right_image: Tensor) -> Tuple[Tensor, Tensor]: def _process_image(img: PIL.Image.Image) -> Tensor: if self.resize_size is not None: img = F.resize(img, self.resize_size, interpolation=self.interpolation) if not isinstance(img, Tensor): img = F.pil_to_tensor(img) if self.use_gray_scale is True: img = F.rgb_to_grayscale(img) img = F.convert_image_dtype(img, torch.float) img = F.normalize(img, mean=self.mean, std=self.std) img = img.contiguous() return img left_image = _process_image(left_image) right_image = _process_image(right_image) return left_image, right_image def __repr__(self) -> str: format_string = self.__class__.__name__ + "(" format_string += f"\n resize_size={self.resize_size}" format_string += f"\n mean={self.mean}" format_string += f"\n std={self.std}" format_string += f"\n interpolation={self.interpolation}" format_string += "\n)" return format_string def describe(self) -> str: return ( "Accepts ``PIL.Image``, batched ``(B, C, H, W)`` and single ``(C, H, W)`` image ``torch.Tensor`` objects. " f"The images are resized to ``resize_size={self.resize_size}`` using ``interpolation={self.interpolation}``. " f"Finally the values are first rescaled to ``[0.0, 1.0]`` and then normalized using ``mean={self.mean}`` and " f"``std={self.std}``." )
true
6cc32fa383273440fa56b4a4af0190bcccc47240
Python
dgoyard/caps-clindmri
/clindmri/plot/polar.py
UTF-8
3,771
2.75
3
[]
no_license
########################################################################## # NSAp - Copyright (C) CEA, 2013 - 2016 # Distributed under the terms of the CeCILL-B license, as published by # the CEA-CNRS-INRIA. Refer to the LICENSE file or to # http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html # for details. ########################################################################## # System import import numpy as np import json import os import matplotlib.pyplot as plt def polarplot(individual_stats, cohort_stats, snapfile, name=None): """ Display a polar plot with some summary values (statistics) Parameters ---------- individual_stats, cohort_stats: dict (mandatory) structure describing the measure by regions on the cohort and on the individual. snapfile: str (mandatory) the name of the generated polar snap. name: str (optional, default None) the name of the polar plot. """ fig = plt.figure(figsize=(45, 18)) fig.subplots_adjust(wspace=0.25, hspace=0.20, top=0.85, bottom=0.05) color_ok = 1 color_out = 255 sigma_thr = 2 nb_cols = 4 nb_rows = len(individual_stats) / nb_cols if len(individual_stats) % nb_cols != 0: nb_rows += 1 # Go through measure nb_subplots = 0 for measure_name, measure_item in individual_stats.items(): # Calculate evenly-spaced axis angles nb_regions = len(measure_item) angle = np.linspace(0, 2 * np.pi, nb_regions, endpoint=False) # Rotate theta such that the first axis is at the top angle += np.pi/2 angle = angle.tolist() angle.append(angle[0]) # Create plor subplot for the measure nb_subplots += 1 ax = fig.add_subplot(nb_rows, nb_cols, nb_subplots, projection="polar") ax.set_title(measure_name, weight="bold", size="medium", position=(0.5, 1.1), horizontalalignment="center", verticalalignment="center") # Go through regions _data = [] _color = [] _bound_max = [sigma_thr + 3, ] * (len(measure_item) + 1) _bound_min = [3 - sigma_thr, ] * (len(measure_item) + 1) _mean = [3, ] * (len(measure_item) + 1) _regions = [] for region_name, indstats in measure_item.items(): indmeasure = indstats["m"] stats = cohort_stats[measure_name][region_name] if stats["s"] == 0: normalize_value = 0 else: normalize_value = (indmeasure - stats["m"]) / stats["s"] + 3 if normalize_value < 0: normalize_value = 0 _data.append(normalize_value) if normalize_value > sigma_thr + 3 or normalize_value < 3 - sigma_thr: _color.append(color_out) else: _color.append(color_ok) _regions.append(region_name) _data.append(_data[0]) _color.append(_color[0]) # Create a polar subplot plt.scatter(angle, _data, c=_color, s=100, cmap=plt.cm.bwr) plt.plot(angle, _bound_max, "r") plt.plot(angle, _bound_min, "r") plt.plot(angle, _mean, "g--", linewidth=2) ax.fill(angle, _data, facecolor="b", alpha=0.25) ax.set_thetagrids(np.degrees(angle), _regions, fontsize="small") ax.set_yticks(range(0, 6, 1)) ax.set_yticklabels([r"-3$\sigma$", r"-2$\sigma$", r"-$\sigma$", r"$\mu$", r"+$\sigma$", r"+2$\sigma$", r"+3$\sigma$"]) # Set figure title plt.figtext(0.5, 0.965, name or "", ha="center", color="black", weight="bold", size="large") plt.savefig(snapfile)
true
f89a1f3985043c1aeb2490457ab83c9567c88801
Python
cloud76508/Group_Learning
/single_digit/DeepLearning/show_images.py
UTF-8
371
2.625
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Tue Jan 26 13:02:36 2021 @author: ASUS """ import matplotlib.pyplot as plt import load_mat_single_digit as load_data [x_train, y_train, x_val, y_val, x_test, y_test] = load_data.load_data(2) # pick a sample to plot sample = 5 image = x_train[sample] # plot the sample #fig = plt.figure plt.imshow(image, cmap='gray') #plt.show()
true
f6f891f0ff70200667c4c1613e1ba2789aa32b45
Python
LiXin-Ren/Algorithm_Examination
/8.25头条笔试/5yueshuChaxun.py
UTF-8
827
3.234375
3
[]
no_license
""" 已知一些形如"y = 4 - x"的约束条件,查询形如y-x的值 输入: 第一行为两个整数n,m,表示有n个已知的约束条件,有m个查询 接下来n行,形如"y = k - x",表示约束条件y = k - x,其中等号和剑豪前后一定有空格。y和x是变量名,由英文小写字母组成,长度不超过4 k是一个偶数(注意可能为负,负数的负号后没有空格) 接下来m行,形如"y-x",表示查询y-x的值。其中减号前后一定有空格。y与x是变量名,规则同上。输入数据保证不会产生冲突,不会无解。 输出: 对于每个查询,输出一个整数,表示y-x的值 若输入数据不足以推导出结果,则输出"cannot_answer" 示例: input: 3 2 a = 0 - b b = 2 - c c = 4 - d b - d b - c 输出: -3 cannot_answer """
true
cf50a7876274ab66ed66d22a5ef821383aeb04e9
Python
adafruit/circuitpython
/tests/micropython/viper_types.py
UTF-8
412
3.765625
4
[ "MIT", "GPL-1.0-or-later" ]
permissive
# test various type conversions import micropython # converting incoming arg to bool @micropython.viper def f1(x: bool): print(x) f1(0) f1(1) f1([]) f1([1]) # taking and returning a bool @micropython.viper def f2(x: bool) -> bool: return x print(f2([])) print(f2([1])) # converting to bool within function @micropython.viper def f3(x) -> bool: return bool(x) print(f3([])) print(f3(-1))
true
31ebd5a93b402261842eb0ba828c6a4be8f116e0
Python
meshidenn/nlp100
/chap_3/23.py
UTF-8
402
3.046875
3
[]
no_license
import re f = open('jawiki-england.txt','r') g = open('jawiki-england-level-name.txt','w') section = re.compile(r"=(=+)(.+)=\1") for line in f: m = re.match(section, line) if m: level = int(line.count('=')/2 - 1) # name = re.sub("=",'', m.group(1)) print('%s,level:%d' % (m.group(2),level)) g.write('%s,level:%d\n' % (name,level)) f.close() g.close()
true
a552f1c68ee863da2db2b1cb17b5da54662f433e
Python
SuguruChhaya/SA-Volume-calculator
/final akashi project.py
UTF-8
7,440
3.0625
3
[]
no_license
import math from tkinter import * from PIL import Image, ImageTk root = Tk() class Sphere(): def framework(self, root): root.title("SA/V calculator") # * Images self.sphere_image = ImageTk.PhotoImage(Image.open('Sphere.png')) self.pyramid_image = ImageTk.PhotoImage(Image.open('pyramid.png')) self.cylinder_image = ImageTk.PhotoImage(Image.open('cylinder.png')) # * Basic self.image_label = Label(root, image=self.sphere_image) self.image_label.grid(row=1, column=1, columnspan=2) self.title = Label(root, text="Sphere") self.title.grid(row=0, column=1, columnspan=2) # *Side Buttons self.next = Button( root, text=">>", command=lambda: SquarePyramid.framework(self, root)) self.next.grid(row=1, column=3) self.back = Button(root, text="<<", state=DISABLED) self.back.grid(row=1, column=0) # *Radius self.radius_frame = LabelFrame(root) self.radius_label = Label(self.radius_frame, text="Radius: ") self.radius_label.grid(row=0, column=0) self.radius_entry = Entry(self.radius_frame) self.radius_entry.grid(row=0, column=1) self.radius_frame.grid(row=2, column=1, columnspan=2) # *Side self.side_frame = LabelFrame(root) self.side_label = Label(self.side_frame, text="Base\nlength: ") self.side_label.grid(row=0, column=0) self.side_entry = Entry(self.side_frame) self.side_entry.grid(row=0, column=1) # self.side_frame.grid(row=3, column=1, columnspan=2) # *Height self.height_frame = LabelFrame(root) self.height_label = Label(self.height_frame, text="Height: ") self.height_label.grid(row=0, column=0) self.height_entry = Entry(self.height_frame) self.height_entry.grid(row=0, column=1) # self.height_frame.grid(row=4, column=1, columnspan=2) # *SA self.sa_frame = LabelFrame(root) self.sa_button = Button(self.sa_frame, text="Calculate \nSurface Area", padx=5, command=lambda: Sphere.sa_calculator(self)) self.sa_button.grid(row=0, column=0) self.sa_label = Label(self.sa_frame, text="") self.sa_label.grid(row=1, column=0) self.sa_frame.grid(row=5, column=1, sticky=E) # *Volume self.v_frame = LabelFrame(root) self.v_button = Button(self.v_frame, text="Calculate\nVolume", padx=8, command=lambda: Sphere.v_calculator(self)) self.v_button.grid(row=0, column=0) self.v_label = Label(self.v_frame, text="") self.v_label.grid(row=1, column=0) self.v_frame.grid(row=5, column=2, sticky=W) def sa_calculator(self): try: radius = float(self.radius_entry.get()) sa = str(round(4 * math.pi * radius ** 2, 5)) except ValueError: sa = "" self.sa_label.config(text=sa) def v_calculator(self): try: radius = float(self.radius_entry.get()) v = str(round(4 * math.pi * radius ** 3 / 3, 5)) except ValueError: v = "" self.v_label.config(text=v) def all_forget(self): self.radius_entry.delete(0, "end") self.height_entry.delete(0, "end") self.side_entry.delete(0, "end") self.title.grid_forget() self.image_label.grid_forget() self.next.grid_forget() self.back.grid_forget() self.radius_frame.grid_forget() self.height_frame.grid_forget() self.side_frame.grid_forget() self.sa_label.config(text="") self.sa_label.config(text="") return Sphere.framework(self, root) def reset(self): #!This clears the entry self.radius_entry.delete(0, "end") self.height_entry.delete(0, "end") self.side_entry.delete(0, "end") self.sa_label.config(text="") self.v_label.config(text="") class SquarePyramid(Sphere): def framework(self, root): # * Reset answers using inheritance SquarePyramid.reset(self) # * Basic self.image_label.config(image=self.pyramid_image) self.title.config(text="Square Pyramid") # *Side Buttons self.next.config( state=NORMAL, command=lambda: Cylinder.framework(self, root)) self.back.config( state=NORMAL, command=lambda: Sphere.all_forget(self)) # *Radius self.radius_frame.grid_forget() # * Side self.side_frame.grid(row=3, column=1, columnspan=2) # *Height self.height_frame.grid(row=4, column=1, columnspan=2) # * Calculate self.sa_button.config( command=lambda: SquarePyramid.sa_calculator(self)) self.v_button.config(command=lambda: SquarePyramid.v_calculator(self)) #!I have to define a new definition or else it will use the one from Sphere def sa_calculator(self): try: side = float(self.side_entry.get()) height = float(self.height_entry.get()) base_area = side ** 2 slant_height = math.sqrt(((side / 2) ** 2) + (height ** 2)) side_area = side * slant_height / 2 * 4 sa = str(round(base_area + side_area, 5)) except ValueError: sa = "" self.sa_label.config(text=sa) def v_calculator(self): try: side = float(self.side_entry.get()) height = float(self.height_entry.get()) v = str(round(1 / 3 * side ** 2 * height, 5)) except ValueError: v = "" self.v_label.config(text=v) class Cylinder(SquarePyramid): # def __init__(self, root): #SquarePyramid.__init__(self, root) def framework(self, root): # * Reset answer Cylinder.reset(self) # *Basic self.image_label.config(image=self.cylinder_image) self.title.config(text="Cylinder") # *Side Buttons self.next.config(state=DISABLED) self.back.config(command=lambda: SquarePyramid.framework(self, root)) # *Base length self.side_frame.grid_forget() # *Radius self.radius_frame.grid(row=3, column=1, columnspan=2) # *SA/V self.sa_button.config(command=lambda: Cylinder.sa_calculator(self)) self.v_button.config(command=lambda: Cylinder.v_calculator(self)) def sa_calculator(self): try: radius = float(self.radius_entry.get()) height = float(self.height_entry.get()) base_area = math.pi * radius ** 2 * 2 side_area = 2 * math.pi * radius * height sa = str(round(base_area + side_area, 5)) except ValueError: sa = "" self.sa_label.config(text=sa) def v_calculator(self): try: radius = float(self.radius_entry.get()) height = float(self.height_entry.get()) v = str(round(math.pi * radius ** 2 * height, 5)) except ValueError: v = "" self.v_label.config(text=v) a = Sphere() a.framework(root) root.mainloop()
true
b3a493071051fedc8352267aabb6455096ba77d6
Python
chopper6/MPRI_community_detection
/page_rank.py
UTF-8
1,435
2.59375
3
[]
no_license
import random as rd from util import * import numpy as np def surf(G,params): # where G should be a networkx DiGraph # initialized with: node['rank'] = 0 for all nodes # and seed should be a set of nodes damping = params['damping'] seeds = G.graph['seeds'] node = rd.choice(seeds) #start_node num_dead_ends = 0 for i in range(params['iters']): G.nodes[node]['rank'] += 1 out_edges = list(G.out_edges(node)) # note: did not trim dead-ends, since still want to rank them # side-effect: this effectively increases the damping param if out_edges == [] or rd.random() < damping: #i.e dead-end or randomly chose to restart node = rd.choice(seeds) if out_edges == []: num_dead_ends += 1 else: next_edge = rd.choice(out_edges) node = next_edge[1] nodes = np.array(G.nodes()) orig_ranks = np.array([G.nodes[nodes[i]]['rank'] for i in rng(nodes)]) temp = orig_ranks.argsort() top_k_nodes = nodes[temp[:params['community_size']]] ranks = np.empty_like(temp) ranks[temp] = np.arange(len(orig_ranks)) minn = [] for i in rng(nodes): if ranks[i]!=0: minn+=[ranks[i]] minn = min(minn) for i in rng(nodes): if ranks[i]==0: ranks[i]=minn G.nodes[nodes[i]]['cardinal_rank'] = 1/ranks[i] #max_rank = max([G.nodes[node]['rank'] for node in G.nodes()]) #for node in G.nodes(): #G.nodes[node]['rank'] /= params['iters'] # G.nodes[node]['rank'] /= max_rank return top_k_nodes
true
b70599474775b42171be1f6ddc2e109f1f78fc14
Python
PBDCA/changaizakhtar
/testListCalculater.py
UTF-8
1,915
2.78125
3
[]
no_license
import unittest from ListCalculater import (addMap,addReduce,addfilter,SubtractMap,SubtractReduce,MultiplyMap,MultiplyReduce,divideMap,divideReduce ,ExponentMap,ExponentReduce,MaxMap,MinReduce,SquareMap) class TestCalculator(unittest.TestCase): def testAddMap(self): self.assertEqual([8,0],addMap([4,0],[4,0])) self.assertEqual([-8,0],addMap([-4,0],[-4,0])) self.assertEqual([0,0],addMap([4,0],[-4,0])) def testaddReduce(self): self.assertEqual(3,addReduce([1,2])) self.assertEqual(-4,addReduce([-2,-2])) def testaddfilter(self): self.assertEqual([4],addfilter([1,3,4,5])) def testSubtractmap(self): self.assertEqual([0,1],SubtractMap([2,5],[2,4])) self.assertEqual([4,3],SubtractMap([2,5],[-2,2])) self.assertEqual([4,0],SubtractMap([2,0],[-2,0])) def testSubtractReduce(self): self.assertEqual(0,SubtractReduce([2,2])) self.assertEqual(6,SubtractReduce([4,-2])) def testMultiplyMap(self): self.assertEqual([4,20],MultiplyMap([2,5],[2,4])) self.assertEqual([-4,10],MultiplyMap([2,5],[-2,2])) def testMultiplyReduce(self): self.assertEqual(4,MultiplyReduce([2,2])) self.assertEqual(-8,MultiplyReduce([4,-2])) def testDivisonMap(self): self.assertEqual([1,5],divideMap([2,10],[2,2])) self.assertEqual([-1,2],divideMap([2,-6],[-2,-3])) def testDivisonReduce(self): self.assertEqual(1,divideReduce([2,2])) self.assertEqual(-2,divideReduce([4,-2])) def testExpontMap(self): self.assertEqual([4,625],ExponentMap([2,5],[2,4])) def testExpontReduce(self): self.assertEqual(4,ExponentReduce([2,2])) def testMaxMap(self): self.assertEqual([2,4],MaxMap([2,3],[1,4])) def testMinReduce(self): self.assertEqual(2,MinReduce([2,3])) def testsequarMap(self): self.assertEqual([4,16],SquareMap([2,4])) if __name__=='__main__': unittest.main()
true
23fd4ab94deed973cc038549505f525d6ab9cec5
Python
sergeyerr/DCHelper_1.0
/DCPlatform/ActiveHelper/MethodsSuggester.py
UTF-8
6,993
2.640625
3
[]
no_license
from sklearn.preprocessing import StandardScaler from sklearn.neighbors import NearestNeighbors from pymfe.mfe import MFE from openml.tasks import TaskType import pandas as pd def get_features(task: TaskType, cached_metafeatures: pd.DataFrame, target: str = None): """ Возвращает метапризнаки данного датасета task: TaskType: Тип решаемой задачи машинного обучения cached_metafeatures: pd.DataFrame: заранее предпосчитанные признаки датасета target: str: при наличии, целевая колонка в датасете для решаемой задачи """ categorical_barrier = 20 features = {} is_superv = task == TaskType.SUPERVISED_CLASSIFICATION or TaskType.SUPERVISED_REGRESSION if is_superv and not target: raise Exception("not target for supervised task") if task == TaskType.SUPERVISED_CLASSIFICATION: if len(pd.unique(cached_metafeatures[target])) > categorical_barrier: raise Exception('too many values for classification') features['MajorityClassSize'] = cached_metafeatures.groupby(target).count().max()[0] features['MinorityClassSize'] = cached_metafeatures.groupby(target).count().min()[0] features['NumberOfClasses'] = len(cached_metafeatures[target].unique()) if task == TaskType.SUPERVISED_REGRESSION: if cached_metafeatures[target].dtype != 'float64' and \ cached_metafeatures[target].dtype != 'int64' and \ cached_metafeatures[target].dtype != 'float32' and cached_metafeatures[target].dtype != 'int32': raise Exception('target is not numeric attribute') features['target_max'] = cached_metafeatures[target].max() features['target_min'] = cached_metafeatures[target].min() features['targets_q_0.25'] = cached_metafeatures[target].quantile(0.25) features['targets_q_0.5'] = cached_metafeatures[target].quantile(0.5) features['targets_q_0.75'] = cached_metafeatures[target].quantile(0.75) features['targets_skewness'] = cached_metafeatures[target].skew() features['targets_kurtosis'] = cached_metafeatures[target].kurt() if is_superv: cached_metafeatures = cached_metafeatures.copy().drop([target], axis=1) features['NumberOfBinaryFeatures'] = len([col for col in cached_metafeatures if cached_metafeatures[col].dropna().value_counts().index.isin([0, 1]).all()]) features['NumberOfFeatures'] = len(cached_metafeatures.columns) - 1 if is_superv else 0 features['NumberOfInstances'] = len(cached_metafeatures) features['NumberOfInstancesWithMissingValues'] = cached_metafeatures.shape[0] - cached_metafeatures.dropna().shape[0] features['NumberOfNumericFeatures'] = len( cached_metafeatures.select_dtypes(include=['float64', 'int64', 'float32', 'int32']).columns) # MFE фичи подсчитываются в дата-сервисе # mfe = MFE('all') # mfe.fit(data.values) # ft = mfe.extract() # for k, v in zip(ft[0], ft[1]): # features[k] = v return features # запуски с OpenML runs = pd.read_csv('ActiveHelper/all_you_need_runs.csv') class_features = pd.read_csv('ActiveHelper/classification_data.csv') reg_features = pd.read_csv('ActiveHelper/regression_data.csv') class_scaler = StandardScaler() reg_scaler = StandardScaler() class_features = class_features[class_features['var_mean'] < class_features['var_mean'].quantile(0.8)] class_features_ = class_scaler.fit_transform(class_features.drop(['did'], axis=1)) reg_features = reg_features[reg_features['var_mean'] < reg_features['var_mean'].quantile(0.8)] reg_features_ = reg_scaler.fit_transform(reg_features.drop(['did'], axis=1)) class_features[class_features.drop(['did'], axis=1).columns] = class_features_ reg_features[reg_features.drop(['did'], axis=1).columns] = reg_features_ def suggest_methods(task: TaskType, dataset: pd.DataFrame, data_metafeatures : dict, target : str = None) -> list: """ Предлагает методы решения задачи МО для данного датасета task: TaskType: задача машинного обучения dataset: pd.DataFrame: датасет data_metafeatures: dict: предподсчитанные метапризнаки датасета target: str: целевая колонка """ def place(x): x['place'] = range(1, len(x) + 1) return x target_features = pd.DataFrame([{**get_features(task, dataset, target), **data_metafeatures}]).dropna(axis=1) print(target_features) comparison_metric = {TaskType.SUPERVISED_CLASSIFICATION: 'area_under_roc_curve', TaskType.SUPERVISED_REGRESSION: 'mean_absolute_error'} if task == TaskType.CLUSTERING: raise Exception('alarm') if task == TaskType.SUPERVISED_CLASSIFICATION: data_features = class_features data = data_features[target_features.columns] class_scaler.fit(data) target_features_ = class_scaler.transform(target_features) elif task == TaskType.SUPERVISED_REGRESSION: data_features = reg_features data = data_features[target_features.columns] reg_scaler.fit(data) target_features_ = reg_scaler.transform(target_features) else: raise Exception('alarm') target_features[:] = target_features_ # target_features = target_features.dropna(axis=1) data.loc[:, 'did'] = data_features['did'] neigh = NearestNeighbors(n_neighbors=len(data) // 3) data = data.dropna() neigh.fit(data.drop(['did'], axis=1)) dist, ind = neigh.kneighbors(target_features) ind = ind.reshape(-1) dist = dist.reshape(-1) dists_frame = pd.DataFrame() dists_frame['did'] = data.iloc[ind, :]['did'] dists_frame['dist'] = dist req_runs = runs[runs['did'].isin(data.iloc[ind, :]['did'])].copy() tmp = req_runs[req_runs[comparison_metric[task]].notna()].groupby(['task_id', 'name']) tmp = tmp.apply(lambda x: x.sort_values(ascending=False, by='area_under_roc_curve')) # выбираем самые лучшие попытки tmp = tmp.reset_index(drop=True).groupby(['task_id', 'name']).first().reset_index() # сортируем алгосы по крутости в рамках задачи tmp = tmp.groupby(['task_id']).apply( lambda x: x.sort_values(ascending=False, by=comparison_metric[task])).reset_index(drop=True) # места по крутости на задаче tmp = tmp.groupby(['task_id']).apply(lambda x: place(x)) tmp = tmp.join(dists_frame.set_index('did'), on='did') tmp['weighted_place'] = tmp['place'] * tmp['dist'] tmp = tmp.groupby(['name'])['weighted_place'].mean().dropna() tmp = tmp.sort_values() return list(zip(tmp.index, list(tmp)))
true
f7720ada6d8384b5dfa20c205c6dfbd4b809f7d3
Python
tanhaipeng/XAPM
/ext-src/local_debug.py
UTF-8
2,149
2.78125
3
[ "Apache-2.0" ]
permissive
# -*- coding: utf-8 -*- """ Created on 2017-12-27 12:46 @summary: XAPM Extension Log Parse Agent @author: tanhp@outlook.com """ import json LOG_FILE = "/tmp/trace.log" def parse_log(path): """ parse trace log :param path: :return: """ trace_list = [] trace_one = [] with open(path) as file: while True: line = file.readline() if not line: break line = line.strip("\n") if not line: continue info = line.split("\t") if len(info) == 2: if info[1] == "xapm_trace_start": trace_one = [] elif info[1] == "xapm_trace_end": trace_list.append(map_trace(trace_one)) else: if info[1].isdigit(): trace_one.append(info[1]) else: trace_one.append(line) return trace_list def map_trace(trace): """ map trace :param trace: :return: """ sorts = [] stack = [] result = [] for idx, val in enumerate(trace): if not val.isdigit(): stack.append(json.dumps({val: idx})) else: sorts.append({ stack.pop(): int(val) }) sorts.sort(cmp=cmp_trace) for elem in sorts: key = elem.keys()[0] val = elem.values()[0] result.append(split_detail(json.loads(key).keys()[0]) + "\t" + str(val) + "ms") return result def split_detail(detail): """ split detail :param detail: :return: """ info_list = detail.split("*") if len(info_list) >= 2: return "\t".join(info_list) return "" def cmp_trace(x, y): """ compare trace :param x: :param y: :return: """ jx = x.keys()[0] jy = y.keys()[0] return json.loads(jx).values()[0] - json.loads(jy).values()[0] if __name__ == "__main__": traces = parse_log(LOG_FILE) for elem in traces: print "xapm_trace_start" for tmp in elem: print tmp print "xapm_trace_end\n"
true
5d7bf10b0521a99a96f2082d6886bef153a1a1ab
Python
burtr/reu-cfs
/reu-cfs-2018/svn/simple/separated-int.py
UTF-8
1,235
3.6875
4
[]
no_license
import numpy as np # a program to find two integers with a given difference, given # a set of integers # hint: first sort the set of integers. then maintain two indices, i <= j, # as j moves forward the gap between l[i] and l[j] increases, and as # i moves forward the gap between l[i] and l[j] decreases. # now search by moving either i or j forward according to whether the # gap is more or less than the desired difference def separated_int(l,dist): # given a list of integers l, and a distance, dist # find two numbers l[i], l[j] with l[i]-l[j]==d, # or return None l_s = sorted(l) i, j = 0 , 0 while j<len(l): # complete return (0,0) # this is an example, and to get it to compile return None ### test program ### HI_INT = 100 def make_random_list(n): return [ np.random.randint(HI_INT) for i in range(n) ] def test_separated_int(t): tl = [2,6,9,5,11] for i in [1,2,3]: int_pair = separated_int(tl,i) if (int_pair[1]-int_pair[0]) != i: return False for i in range(t): tl = make_random_list(20) int_pair = separated_int(tl,4) if int_pair: if (int_pair[1]-int_pair[0]) != 4: return False return True if test_separated_int(10): print ("Success") else: print ("Test failed")
true
9a76fbe3e67feb68bc1d0636c32c6effb901374c
Python
8140171224/python3-learning
/ex4.1.py
UTF-8
388
4.15625
4
[]
no_license
# The range() Function Few example. for i in range(6): print(i) # below line '\n' means new lines print('\n') #range(5, 10) for i in range(5, 10): print(i) # below line '\n' means new lines print('\n') #range(0, 20, 2) for i in range(0, 22, 2): print(i) # below line '\n' means new lines print('\n') #range(-20, -200, -30) for i in range(-20, -100, -30): print(i)
true
8476664887edd2bb96d287263c5555b7c439f733
Python
ryfeus/lambda-packs
/LightGBM_sklearn_scipy_numpy/source/sklearn/utils/tests/test_fixes.py
UTF-8
695
2.671875
3
[ "MIT" ]
permissive
# Authors: Gael Varoquaux <gael.varoquaux@normalesup.org> # Justin Vincent # Lars Buitinck # License: BSD 3 clause import pickle from sklearn.utils.testing import assert_equal from sklearn.utils.testing import assert_array_equal from sklearn.utils.fixes import divide from sklearn.utils.fixes import MaskedArray def test_divide(): assert_equal(divide(.6, 1), .600000000000) def test_masked_array_obj_dtype_pickleable(): marr = MaskedArray([1, None, 'a'], dtype=object) for mask in (True, False, [0, 1, 0]): marr.mask = mask marr_pickled = pickle.loads(pickle.dumps(marr)) assert_array_equal(marr.data, marr_pickled.data) assert_array_equal(marr.mask, marr_pickled.mask)
true
70a004ef6282c6cdd923e7897660d142e1eb5324
Python
Ouack23/FdL_Karna
/games/simon.py
UTF-8
3,886
3.078125
3
[]
no_license
import logging, DMX, random, time, sys from collections import OrderedDict from array import array from game import Game def get_mode_list(): return ["RPI", "PC"] class Simon(Game): def __init__(self, mode="PC"): Game.__init__(self, "Simon") if mode in get_mode_list(): self.mode = mode else: logging.error("This mode (" + str(mode) + ") isn't supported") sys.exit(0) self.mode = mode self.universe = 0 self.duration = 1 self.channels = 4 self._DMX = DMX.DMX(self.universe, self.duration, self.channels) self.seq = [] self.fail = False self.input_seq = "" self.dmx_color1 = array('B', [255, 0, 0, 0]) self.dmx_color2 = array('B', [0, 255, 0, 0]) self.dmx_color3 = array('B', [0, 0, 255, 0]) self.dmx_color4 = array('B', [255, 255, 0, 0]) self.dmx_colors = dict(r=self.dmx_color1, g=self.dmx_color2, b=self.dmx_color3, y=self.dmx_color4) if self.mode == "RPI": gpio_dict = dict(r=22, g=27, b=4, y=17) self.pins = None self.build_pins(gpio_dict) logging.debug("Successfully instantiated SIMON game ! :)") def run(self): if self.mode == "PC": logging.info("Running Simon game") self.seq.append(self.dmx_colors.keys()[random.randrange(0, self.channels - 1)]) while not self.fail: for i in range(len(self.seq)): if self.mode == "RPI": self.pins.set_color_and_black(self.seq[i], self.duration) self._DMX.send_dmx_and_black(self.dmx_colors[self.seq[i]]) if self.mode == "PC": self.input_seq = raw_input("Type color sequence and press enter : ").lower()[:len(self.seq)] for j in range(len(self.input_seq)): if self.input_seq[i] != self.seq[i]: self.fail = True elif self.mode == "RPI": for i in range(len(self.seq)): go_next = False while not self.fail and not go_next: for j in range(self.channels): if self.pins.is_pressed(self.pins.get_keys()[j]): if self.pins.get_keys()[j] == self.seq[i]: logging.info("Good input !!" + str(self.pins.get_values()[j])) go_next = True while self.pins.is_pressed(self.pins.get_keys()[j]): pass break else: logging.info("Bad input !!" + str(self.pins.get_values()[j])) self.fail = True break if self.fail: break if not self.fail: self.seq.append(self.dmx_colors.keys()[random.randrange(0, self.channels - 1)]) logging.debug("Good sequence, appending a new color : " + str(self.seq)) logging.info("That wasn't the right sequence, I am restarting the game !") self.stop() def build_pins(self, gpio_dict): tmp = OrderedDict() import pins if len(gpio_dict) != len(self.dmx_colors): logging.error("GPIO array and DMX colors don't have the same size !") sys.exit(0) for i in gpio_dict.keys(): if not tmp.has_key(i): tmp[i] = gpio_dict.get(i) self.pins = pins.Pins(tmp) def stop(self): self.reset() time.sleep(5) self.run() def reset(self): self.seq = [] self.fail = False self.input_seq = ""
true
1c2896e74136b561bb786f0bc67da46dcea77b44
Python
wieczorekm/xml2json
/src/lexer.py
UTF-8
4,993
3.09375
3
[]
no_license
from src.tokens import * WHITESPACES = (' ', '\t', '\n') class Lexer: def __init__(self, source): self.source = source self.cursor = 0 def get_next_token(self): self._shift_cursor_igonoring_whitespaces() if self.cursor == len(self.source): return EndOfTextToken() try: return self._do_get_next_token() except IndexError: self._throw_unexpected_token_exception() def get_text_until_open_of_tag(self): text = "" while self.source[self.cursor] != '<': text += self.source[self.cursor] self.cursor += 1 return text # also returns read whitespaces as they may be necessary for parser def is_next_nonempty_char_an_open_of_tag(self): buffer = "" while self.source[self.cursor] in WHITESPACES: buffer += self.source[self.cursor] self.cursor += 1 return self.source[self.cursor] == "<", buffer def get_comment(self): comment_body = "" while self.source[self.cursor:self.cursor+3] != "-->": comment_body += self.source[self.cursor] self.cursor += 1 return comment_body def get_current_cursor_pos(self): return self.cursor def _do_get_next_token(self): if self.source[self.cursor] == "<": return self._do_get_open_token() elif self.source[self.cursor] == "/": return self._do_get_close_with_slash_token() elif self.source[self.cursor] == "?": return self._do_get_close_prolog_token() elif self.source[self.cursor] == ">": return self._do_get_close_token() elif self.source[self.cursor] == "=": return self._do_get_equals_token() elif self.source[self.cursor] == '"': return self._do_get_double_quoted_id_token() elif self.source[self.cursor] == "\'": return self._do_get_single_quoted_id_token() elif self.source[self.cursor] == "-": return self._do_get_close_of_comment_tag() else: return self._do_get_id_token() def _do_get_open_token(self): if self.cursor == len(self.source) - 1 or self.source[self.cursor + 1] not in ["/", "?", "!"]: self.cursor += 1 return OpenOfTagToken() elif self.source[self.cursor + 1] == "?": self.cursor += 2 return OpenOfPrologTagToken() elif self.source[self.cursor + 1 : self.cursor+4] == "!--": self.cursor += 4 return OpenOfCommentTagToken() else: self.cursor += 2 return OpenOfTagWithSlashToken() def _do_get_close_with_slash_token(self): if self.source[self.cursor + 1] == ">": self.cursor += 2 return CloseOfTagWithSlashToken() else: self._throw_unexpected_token_exception() def _do_get_close_prolog_token(self): if self.source[self.cursor + 1] == ">": self.cursor += 2 return CloseOfPrologTagToken() else: self._throw_unexpected_token_exception() def _do_get_close_token(self): self.cursor += 1 return CloseOfTagToken() def _do_get_equals_token(self): self.cursor += 1 return EqualsToken() def _do_get_id_token(self): return IdToken(self._read_id_from_input()) def _do_get_double_quoted_id_token(self): return QuotedIdToken(self._read_quoted_id_from_input_until_char("\"")) def _do_get_single_quoted_id_token(self): return QuotedIdToken(self._read_quoted_id_from_input_until_char("\'")) def _do_get_close_of_comment_tag(self): if self.source[self.cursor + 1:self.cursor + 3] == "->": self.cursor += 3 return CloseOfCommentTagToken() else: self._throw_unexpected_token_exception() def _read_id_from_input(self): id = "" while self.source[self.cursor] not in WHITESPACES and self.source[self.cursor] not in [">", "/", "="]: id += self.source[self.cursor] self.cursor += 1 return id def _read_quoted_id_from_input_until_char(self, char): quoted_id = "" self.cursor += 1 while self.source[self.cursor] != char: quoted_id += self.source[self.cursor] self.cursor += 1 self.cursor += 1 return quoted_id def _throw_unexpected_token_exception(self): print("[LEXER] Unexpected end of text near " + str(self.cursor) + " char") raise LexerException("Unexpected end of text") def _shift_cursor_igonoring_whitespaces(self): while self.cursor < len(self.source) and self.source[self.cursor] in WHITESPACES: self.cursor += 1 class LexerException(Exception): def __init__(self, message): super(LexerException, self).__init__() self.message = message
true
bac13d240d03a8d6fec788b95c8e2df3f785ce7a
Python
whitedevil369/Wautomsg-b0t
/Wautomsg-b0t.py
UTF-8
6,318
3.015625
3
[]
no_license
import pyautogui import time import sys from pyfiglet import Figlet import argparse #from positionfinder import positions #from pynput.mouse import Listener parser = argparse.ArgumentParser() parser.add_argument("-s","--senderNumber", help="Enter your whatsapp number in the format <country_code><your_number> without starting with +/0 and without any spaces in between") parser.add_argument("-r","--recipientFile", help="Enter the path of the .txt file containing the list of recipient phone numbers in the same format as the sender number") parser.add_argument("-m","--mode", help="Set the mode of entry of the messege (file/cli)") parser.add_argument("-f","--fileMessege", help="enter the path of file containing the messege") args = parser.parse_args() def br(): pyautogui.hotkey('shift', 'enter') def exit_timer(): t=0 cl=3 print("Quitting in 3 seconds...") time.sleep(1) for t in range(0,3): print(cl) time.sleep(1) t=t+1 cl=cl-1 print("Quiting...") def alert(): t=0 cl=3 print("ALERT! The b0t will start in 3 seconds.") time.sleep(1) for t in range(0,3): print(cl) time.sleep(1) t=t+1 cl=cl-1 print("b0t STARTED...") ''' def on_click(x, y, button, pressed): if pressed: global pos_x pos_x = x global pos_y pos_y = y if not pressed: return False ''' def home(): f1 = Figlet(font='rounded') f2 = Figlet(font='digital') print ("Name: Wautomsg-b0t") print ("version: 1.0") print ("@whitedevil369") print (f1.renderText('Wautomsg-b0t')) print (f2.renderText("Made by Poornesh Adhithya")) print ("\nWELCOME TO Wautomsg-b0t\nWautomsg-b0t is a WHATSAPP MASS/BULK MESSAGE SENDER\n(WITHOUT SAVING THE PHONE NUMBERS IN CONTACTS)\n") input("\nPRESS ENTER TO CONTINUE.\n\nb0t:~#> ") home() if(args.senderNumber==None): print ("\nENTER SENDER PHONE NUMBER: ") print ("format: <country_code><phone_number> (without + or 00 or spaces)") print ("Eg. 911234567890\nWhere 91 is the Country Code and 1234567890 is phone number") sender_ph = input("\nb0t:~#> ") print("\n") else: sender_ph = args.senderNumber if not sender_ph.isdigit() or '\n' in sender_ph: print("PHONE NUMBER SHOULD CONTAIN ONLY DIGITS") exit_timer() exit() if(args.recipientFile==None): print ("\nENTER THE SOURCE LOCATION OF THE PHONE NUMBERS LIST: ") print ("Eg. /root/Desktop/contacts.txt\nIf it exists in the same dirctory of the file then,\nEg. contacts.txt") src = input("\nb0t:~#> ") print("\n") else: src = args.recipientFile try: phone_file=open(src) phone=phone_file.readlines() except: print("RECIPIENT FILE DOESN'T EXIST!") exit_timer() exit() if not src.endswith('.txt'): print("ONLY .txt FILE FORMAT IS ACCEPTED") exit_timer() exit() counter=0 for p in phone: x=p.split('\n') p=x[0] if p and p.isdigit(): counter += 1 else: print("PHONE NUMBERS SHOULD CONTAIN ONLY DIGITS") exit_timer() exit() if(args.mode == None): print ("\nENTER YOUR MODE OF MESSAGING (cli/file): ") print ("cli to enter Message in the terminal.\nfile to import the location of the file") c = input("\nb0t:~#> ") print("\n") else: c = args.mode if c=='file': if(args.fileMessege==None): print ("\nENTER THE SOURCE LOCATION OF THE MESSAGE: ") print ("Eg. /root/Desktop/samplemsg.txt\nIf it exists in the same dirctory of the file then,\nEg. samplemsg.txt") loc = input("\nb0t:~#> ") else: loc = args.fileMessege if not loc.endswith('.txt'): print("ONLY .txt FILE FORMAT IS ACCEPTED") exit_timer() exit() try: msg_file=open(loc) msg=msg_file.readlines() message='' except: print("FILE DOESN'T EXIST!") exit_timer() exit() elif c=='cli': print ("\nTYPE THE MESSAGE: ") print ("Once you are done, Press ENTER and then Ctrl+D to end the Message") print ("\nb0t:~#> ") message=sys.stdin.read() msg='' m='' else: print("INVALID CHOICE!") exit_timer() exit() ''' print("Place your mouse pointer on the text of latest/recent message from the WhatsApp chatbox and click on it") print("(Eg. place your mouse pointer on the text of 'Hi' message which was entered earlier during the setup phase)") input("\nPRESS ENTER AND THEN CLICK THE MESSAGE. AFTER CLICKING IT PRESS ENTER AGAIN! (MAKE SURE TO CLICK AFTER 3 Seconds)\n\nb0t:~#> ") with Listener( on_click=on_click, ) as listener: listener.join() ''' #<-----------------------------------------------------> #positions pos_x = 1441 # value of x in positionfinder.py pos_y = 959 # value of y in positionfinder.py #THIS IS FOR 1600x900 RESOLUTION, VALUES MAY CHANGE ACCORDING TO YOUR PCs RESOLUTION. (use positionfinder.py tool to find your mouse position) #Change These Values Before Executing #<-----------------------------------------------------> input("\nPRESS Enter To Start The b0t and then Switch to WhatsApp Web.\n\nb0t:~#> ") print("\nYou have 5 seconds to switch to WhatsApp Web.....") time.sleep(5) print("Switch to WhatsApp Web, Your running out of time...\n") alert() time.sleep(1) pyautogui.typewrite('Wa.me/'+sender_ph) pyautogui.press('enter') position = pos_x,pos_y pyautogui.click(position) time.sleep(1) pyautogui.press('esc') time.sleep(2) pyautogui.press('esc') time.sleep(1) pyautogui.typewrite('Test Message') pyautogui.press('enter') i=0 try: for number in phone: time.sleep(2) pyautogui.typewrite('Wa.me/'+number) pyautogui.press('enter') pyautogui.click(position) time.sleep(1) pyautogui.press('esc') time.sleep(2) pyautogui.press('esc') time.sleep(1) #pyautogui.typewrite('Write Something') #br() #Use This to go to new line without sending the message for m in msg: pyautogui.typewrite(m) pyautogui.typewrite(message) time.sleep(1) pyautogui.press('enter') time.sleep(3) pyautogui.press('tab') pyautogui.press('tab') pyautogui.typewrite(sender_ph) pyautogui.press('enter') i=i+1 print ("Message has been sent to "+str(i)+" of "+str(counter)+" Recipients") time.sleep(2) pyautogui.typewrite("Messages Sent Successfully!") br() pyautogui.typewrite("Thank-You! See You Next Time.") br() pyautogui.typewrite("Good Bye!") pyautogui.press('enter') print ("\nMessages Sent Successfully!") print("\nHOPE THIS TOOL HELPED YOU!\nTHANKS FOR USING THIS TOOL.") except: print("\nProcess Terminating...") msg_file.close() phone_file.close() exit()
true
afe44b29090b5738ab4e21893297b6663b95e6f4
Python
Quantumgame/dronestorm
/dronestorm/data_util.py
UTF-8
12,631
2.859375
3
[]
no_license
"""Defines utilities for processing data""" import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation from scipy.signal import convolve from scipy.io.wavfile import read as wav_read from scipy.io.wavfile import write as wav_write AUDIO_SAMPLE_RATE = 44100 # standard 44.1kHz recording rate AUDIO_SAMPLE_DT = 1./AUDIO_SAMPLE_RATE def _load_spike_data(fname_spikes): """Utility function to load in spike data Parameters ---------- fname_spikes: string input spike data text filename first column is sim time second column is real time subsequent columns are each neuron's spikes as would be recorded in the nengo simulator """ file_data = np.loadtxt(fname_spikes) sim_time = file_data[:, 0] real_time = file_data[:, 1] spk_data_raw = file_data[:, 2:] return sim_time, real_time, spk_data_raw def _filter_nrn_idx_yticks(yticks, n_neurons): """Removes non-integer and out-of-range ticks""" tol = 0.001 ret_ticks = [] for ytick in yticks: ret_tick = int(np.round(ytick)) if abs(ret_tick - ytick) < tol and ytick >=0 and ytick < n_neurons: ret_ticks += [ret_tick] return ret_ticks def animate_spike_raster( fname_spikes, fname_movie_out, nrn_idx=None, time_mode="real", time_stop=None, time_window=1.0, fps=30): """Generate a movie from the spike raster Parameters ---------- fname_spikes: string input spike data text filename first column is sim time second column is real time subsequent columns are each neuron's spikes as would be recorded in the nengo simulator fname_movie_out: string if string, filename of output movie nrn_idx: list-like or none indices of neurons to use to generate wav file if None, uses all neurons, one per wav file channel time_mode: "real" or "sim" Whether to use the spike's real or simulation time time_stop: float or None if float, movie ends time_window after time_stop if None, movie ends after time_window past last spike time_window: float Size of time window over which to view spikes fps: int frames per second """ sim_time, real_time, spk_data_raw = _load_spike_data(fname_spikes) if nrn_idx is not None: spk_data_raw = spk_data_raw[:, nrn_idx] n_samples, n_neurons = spk_data_raw.shape if time_mode == "real": time = real_time elif time_mode == "sim": time = sim_time spk_times = [] for nrn_idx in range(n_neurons): spk_idx = np.nonzero(spk_data_raw[:, nrn_idx])[0] spk_times.append(time[spk_idx]) fig = plt.figure() colors = plt.rcParams['axes.prop_cycle'].by_key()['color'] ax = fig.add_subplot(111) y_range = 0.8 last_spk_time = 0. for nrn_idx in range(n_neurons): y_mid = nrn_idx y_min = y_mid - y_range/2. y_max = y_mid + y_range/2. spk_idx = np.nonzero(spk_data_raw[:, nrn_idx])[0] spk_times = time[spk_idx] last_spk_time = np.max(spk_times.tolist() + [last_spk_time]) ax.vlines(spk_times, y_min, y_max, colors[nrn_idx%len(colors)]) ax.set_ylim(-y_range/1.5, n_neurons-1+y_range/1.5) ax.set_title("Spike Raster") ax.set_xlabel("Time (s)") ax.set_ylabel("Neuron Index") ax.set_yticks(_filter_nrn_idx_yticks(ax.get_yticks(), n_neurons)) time_start = -time_window if time_stop is None: time_stop = last_spk_time+time_window else: time_stop = time_stop+time_window animation_time_total = time_stop - time_start - time_window animation_dt = 1./fps n_frames = int(np.round(animation_time_total*fps)) moviewriter = animation.FFMpegWriter(fps=fps) with moviewriter.saving(fig, fname_movie_out, dpi=100): for frame_idx in range(n_frames): time_since_start = frame_idx*animation_dt ax.set_xlim(time_start+time_since_start, time_start+time_since_start+time_window) moviewriter.grab_frame() def animate_tuning( fname_tuning_data, fname_input_data, fname_movie_out, input_data_col=2, time_mode="real", fps=30, label=True, xlabel="Input"): """Generate a movie from the spike raster Parameters ---------- fname_tuning: string tuning data filename first column is the input stimulus used to generate the tuning data remaining columns are the tuning data fname_input_data: string input data filename first column is sim time first column is real time subsequent columns are each inputs dimension fname_movie_out: string if string, filename of output movie nrn_idx: list-like or none indices of neurons to use to generate wav file if None, uses all neurons, one per wav file channel time_mode: "real" or "sim" Whether to use the spike's real or simulation time fps: int frames per second label: boolean whether or not to label the tuning curves and display a legend xlabel: string x axis label """ fig, ax = plot_tuning(fname_tuning_data, show=False, label=label, xlabel=xlabel) ylim = ax.get_ylim() file_data = np.loadtxt(fname_input_data) sim_time = file_data[:, 0] real_time = file_data[:, 1] input_data = file_data[:, input_data_col] if time_mode == "real": time = real_time elif time_mode == "sim": time = sim_time n_frames = int(np.round(time[-1]*fps)) time_idx = 0 len_time = len(time) in_dat_line = ax.plot( [input_data[time_idx], input_data[time_idx]], [ylim[0], ylim[1]], 'r:')[0] ax.set_ylim(ylim) moviewriter = animation.FFMpegWriter(fps=fps) with moviewriter.saving(fig, fname_movie_out, dpi=100): for frame_idx in range(n_frames): curr_time = frame_idx / fps moved = False while time[time_idx] <= curr_time: time_idx += 1 moved = True if moved: time_idx -= 1 if time_idx < len_time: in_dat_line.set_data( [input_data[time_idx], input_data[time_idx]], [ylim[0], ylim[1]]) moviewriter.grab_frame() def make_spike_wav( fname_spikes, fname_wav, nrn_idx=None, time_mode = "real", fname_spike_kernel=None, wav_dtype=np.int32, plot=False): """Create a wav audio file from the spike data Parameters ---------- fname_spikes: string input spike data text filename first column is time subsequent columns are each neuron's spikes as would be recorded in the nengo simulator fname_wav: string filename of output wav data nrn_idx: list-like or none indices of neurons to use to generate wav file if None, uses all neurons, one per wav file channel time_mode: "real" or "sim" Whether to use the spike's real or simulation time fname_spike_kernel: string or None if string, wav file name of kernel to convolve spikes with to generate different sounds wav_dtype: numpy dtype data type to be used in the wav file """ assert isinstance(fname_spikes, str) assert isinstance(fname_wav, str) assert time_mode in ["real", "sim"] sim_time, measured_time, spk_data_raw = _load_spike_data(fname_spikes) if nrn_idx is not None: spk_data_raw = spk_data_raw[:, nrn_idx] n_samples, n_neurons = spk_data_raw.shape if time_mode == "real": time = measured_time elif time_mode == "sim": time = sim_time n_resamples = int(np.ceil(time[-1]*AUDIO_SAMPLE_RATE)) spk_data = np.zeros((n_resamples, n_neurons)) for nrn_idx in range(n_neurons): spk_idx = np.nonzero(spk_data_raw[:, nrn_idx])[0] spk_times = time[spk_idx] spk_resampled_idx = np.round(spk_times * AUDIO_SAMPLE_RATE).astype(int) spk_data[spk_resampled_idx, nrn_idx] = AUDIO_SAMPLE_RATE # impulse as 1/dt if fname_spike_kernel is not None: assert isinstance(fname_spike_kernel, str) spike_kernel_sample_rate, spk_kernel_data = wav_read(fname_spike_kernel) assert spike_kernel_sample_rate == AUDIO_SAMPLE_RATE, ( "spike_kernel wav file sample rate must match AUDIO_SAMPLE_RATE") assert len(spk_kernel_data.shape) == 1, "spike_kernel wav data must have a single channel" spk_kernel_data = spk_kernel_data shift_idx = np.argmax(np.abs(spk_kernel_data)) # find peak of kernel for later alignment spk_data_preconv = spk_data.copy() spk_data_postconv = np.zeros((spk_data.shape[0]+len(spk_kernel_data)-1, n_neurons)) for nrn_idx in range(n_neurons): spk_data_postconv[:, nrn_idx] = convolve( spk_data[:, nrn_idx], spk_kernel_data, mode="full") spk_data = spk_data_postconv spk_data = spk_data[shift_idx:] # align with original waveform spk_data = spk_data[:n_resamples] # clip to original length np.clip(spk_data, np.iinfo(wav_dtype).min, np.iinfo(wav_dtype).max, spk_data) spk_data = spk_data.astype(wav_dtype) wav_write(fname_wav, AUDIO_SAMPLE_RATE, spk_data) if plot: spk_data_fig = plt.figure() time_resampled = np.arange(n_resamples)*AUDIO_SAMPLE_DT if fname_spike_kernel is not None: ax = spk_data_fig.add_subplot(211) ax.plot(time_resampled, spk_data_preconv) ax.set_ylabel("raw spike waveform") ax.set_title("spike waveforms") ax = spk_data_fig.add_subplot(212, sharex=ax) ax.plot(time_resampled, spk_data) ax.set_ylabel("filtered spike waveform") ax.set_xlabel("time (s)") time_kernel = np.arange(len(spk_kernel_data))*AUDIO_SAMPLE_DT spk_kernel_fig = plt.figure() ax = spk_kernel_fig.add_subplot(111) ax.plot(time_kernel, spk_kernel_data) ax.set_title("spike kernel waveform") ax.set_xlabel("time (s)") else: ax = spk_data_fig.add_subplot(111) ax.plot(spk_data) plt.show() def plot_timing(fname_spikes, fname_plot_out=None): """Plot the simulation timing data""" file_data = np.loadtxt('spikes.txt') sim_time = file_data[:, 0] measured_time = file_data[:, 1] fig = plt.figure(figsize=(8, 6)) ax = fig.add_subplot(211) ax.plot(measured_time, label="measured") ax.plot(sim_time, label="simulation") ax.legend(loc="lower right") ax.set_ylabel('cumulative time (s)') ax.set_title("Simulation Timing") ax = fig.add_subplot(212, sharex=ax) ax.plot(np.diff(measured_time), label="measured") ax.plot(np.diff(sim_time), label="simulation") ax.legend(loc="upper right") ax.set_ylabel('delta t (s)') ax.set_xlabel('Simulation step index') if fname_plot_out is not None: assert isinstance(fname_plot_out, str) plt.savefig(fname_plot_out) else: plt.show() def plot_tuning( fname_tuning_data, fname_plot_out=None, show=True, label=False, xlabel="Input", **kwargs): """Plot the tuning data Returns the figure and axis handle of the plot Parameters ---------- fname_tuning_data: string input tuning data filename first column is the input stimulus used to generate the tuning data remaining columns are the tuning data show: boolean whether or not to show the plot label: boolean whether or not to label the tuning curves and display a legend xlabel: string x axis label fname_plot_out: string or None filename to save the plot to if not None if None, shows the plot live Remaining keywords will be passed along to matplotlib for plotting """ file_data = np.loadtxt(fname_tuning_data) stim = file_data[:, 0] tuning = file_data[:, 1:] fig = plt.figure() ax = fig.add_subplot(111) if label: for nrn_idx in range(tuning.shape[1]): ax.plot(stim, tuning[:, nrn_idx], label="Neuron %d"%nrn_idx, **kwargs) ax.legend(loc="best") else: ax.plot(stim, tuning, **kwargs) ax.set_xlabel(xlabel) ax.set_ylabel('Spike Rate (Hz)') ax.set_title("Tuning Curves") if fname_plot_out is not None: assert isinstance(fname_plot_out, str) plt.savefig(fname_plot_out) if show: plt.show() return fig, ax
true
0ae04e76f4e09aaae0fc631dfadfdeb6bbc5266a
Python
mdaif/rock-paper-scissors
/rock_paper_scissors.py
UTF-8
1,965
2.65625
3
[ "Apache-2.0" ]
permissive
import argparse import logging.config from components import ConsoleUserChoice, ConsoleResultHandler from constants import SUPPORTED_GAME_FLAVORS from engine import Engine def get_game_rules(flavor): return SUPPORTED_GAME_FLAVORS[flavor][0]() def get_game_description(flavor): return SUPPORTED_GAME_FLAVORS[flavor][1] def get_supported_flavors_choices(): return list(SUPPORTED_GAME_FLAVORS.keys()) def get_supported_flavors_descriptions(): return "".join([val[1] for val in SUPPORTED_GAME_FLAVORS.values()]) def _configure_logging(): configs = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'local': { 'format': '%(asctime)s %(message)s', } }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'formatter': 'local', }, }, 'loggers': { '': { 'handlers': ['console'], 'level': 'DEBUG', } } } logging.config.dictConfig(configs) def main(rounds: int, flavor: str): flavor_rules = get_game_rules(flavor) engine = Engine( rounds=rounds, game_rules=flavor_rules, user_choice=ConsoleUserChoice(), result_handler=ConsoleResultHandler(), ) engine.play_n_rounds(rounds) print('That was fun ! bye !') if __name__ == '__main__': _configure_logging() parser = argparse.ArgumentParser( description='Play a game of Rock-Paper-Scissors') parser.add_argument( '--rounds', type=int, help='Number of rounds to play', required=True) parser.add_argument( '--flavor', default=get_supported_flavors_choices()[0], help=f'Game flavors: {get_supported_flavors_descriptions()}', choices=get_supported_flavors_choices(), ) args = parser.parse_args() main(args.rounds, args.flavor)
true
5209b6201b59d86ec998a28a58184183ad14c925
Python
yiming1012/MyLeetCode
/LeetCode/双指针(two points)/面试题 16.06. 最小差.py
UTF-8
1,585
3.953125
4
[]
no_license
""" 面试题 16.06. 最小差 给定两个整数数组a和b,计算具有最小差绝对值的一对数值(每个数组中取一个值),并返回该对数值的差   示例: 输入:{1, 3, 15, 11, 2}, {23, 127, 235, 19, 8} 输出:3,即数值对(11, 8)   提示: 1 <= a.length, b.length <= 100000 -2147483648 <= a[i], b[i] <= 2147483647 正确结果在区间 [0, 2147483647] 内 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/smallest-difference-lcci 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ from typing import List class Solution: def smallestDifference(self, a: List[int], b: List[int]) -> int: """ 思路:双指针 1. 先对两个数组排序 2. 再利用双指针交替计算最小值 @param a: @param b: @return: """ a.sort() b.sort() m, n = len(a), len(b) res = float('inf') i, j = 0, 0 while i < m and j < n: res = min(res, abs(a[i] - b[j])) if a[i] < b[j]: i += 1 else: j += 1 return res if __name__ == '__main__': a = [1, 3, 15, 11, 2] b = [23, 127, 235, 19, 8] print(Solution().smallestDifference(a, b)) import bisect a = [1, 4, 6, 8, 12] position1 = bisect.bisect(a, 13) position2 = bisect.bisect_left(a, 13) position3 = bisect.bisect_right(a, 13) print(position1) print(position2) print(position3) print(inf)
true
62df48bd12e12aab9c901efcf91fcd0b5b237356
Python
nicovandenhooff/project-euler
/solutions/p17.py
UTF-8
4,278
4.4375
4
[]
no_license
# Project Euler: Problem 17 # Large sum # Author: Nico Van den Hooff # Github: https://github.com/nicovandenhooff/project-euler # Problem: https://projecteuler.net/problem=17 # Note: This could likely be done with a combinatorics solution, # but I decided to brute force it for fun so that I could # practice working with logic and strings. # dictionary of numbers and words needed to represent # the first 1000 numbers in words numbers = { 1: "one", 2: "two", 3: "three", 4: "four", 5: "five", 6: "six", 7: "seven", 8: "eight", 9: "nine", 10: "ten", 11: "eleven", 12: "twelve", 13: "thirteen", 14: "fourteen", 15: "fifteen", 16: "sixteen", 17: "seventeen", 18: "eighteen", 19: "nineteen", 20: "twenty", 30: "thirty", 40: "forty", 50: "fifty", 60: "sixty", 70: "seventy", 80: "eighty", 90: "ninety", 100: "hundred", 1000: "thousand", } def num_digits(n): """Counts the number of digits in a number. Parameters ---------- n : int The number. Returns ------- int The number of digits. """ return len(str(n)) def extract_digits(n): """Simple function to return a tuple of digits for each digit in a number. Parameters ---------- n : int The number, for example 793. Returns ------- tuple of int Tuple of digits, for example (7, 9, 3) """ return tuple(int(digit) for digit in str(n)) def string_words(start, stop): """Converts a range of numbers from 1 up to 1000 from numbers to their string equivalent. Parameters ---------- start : int The starting value, must be >= 1. stop : int The ending value, must be <= 1000. Returns ------- words: list of str A list of string representations of each number. """ # the word list words = [] for i in range(start, stop): digit_string = "" # if between 1-20 append dictionary value if i in range(1, 21): words.append(numbers[i]) # two digit numbers elif num_digits(i) == 2: # extract individual digits first, second = extract_digits(i) # if second digit is zero append dictionary value if second == 0: words.append(numbers[i]) # othewise append two digit string representation else: digit_string += numbers[first * 10] digit_string += numbers[second] words.append(digit_string) # three digit numbers elif num_digits(i) == 3: # extract individual digits first, second, third = extract_digits(i) # "num" + "hundred" digit_string += numbers[first] digit_string += numbers[100] # if second, third, digits are zero append result if second == 0 and third == 0: words.append(digit_string) # if second is zero, append "and" + respective number elif second == 0: digit_string += "and" digit_string += numbers[third] words.append(digit_string) # if second is one, append "and" + respective teens number elif second == 1: digit_string += "and" digit_string += numbers[third + 10] words.append(digit_string) # if second not zero but third is append "and" and multiple of 10 elif second != 0 and third == 0: digit_string += "and" digit_string += numbers[second * 10] words.append(digit_string) # otherwise append three digit string representation else: digit_string += "and" digit_string += numbers[second * 10] digit_string += numbers[third] words.append(digit_string) # four digit numbers - got lazy here lol else: digit_string += numbers[1] digit_string += numbers[1000] words.append(digit_string) return words print(len("".join(string_words(1, 1001))))
true
88527352a81581adb60af798afdc751adda3caaa
Python
khammernik/medutils
/medutils/optimization/base_optimizer.py
UTF-8
992
2.546875
3
[ "Apache-2.0" ]
permissive
""" This file is part of medutils. Copyright (C) 2023 Kerstin Hammernik <k dot hammernik at tum dot de> I31 - Technical University of Munich https://www.kiinformatik.mri.tum.de/de/hammernik-kerstin """ import numpy as np class BaseOptimizer(object): def __init__(self, mode, lambd, beta=None, tau=None): self.mode = mode self.lambd = lambd self.beta = beta self.tau = tau if self.mode == '1d': self.ndim = 1 elif self.mode == '2d': self.ndim = 2 elif self.mode in ['2dt', '3d']: self.ndim = 3 elif self.mode in ['3dt', '4d']: self.ndim = 4 else: raise ValueError(f'ndim for mode {mode} not defined') def solve(self, f, max_iter): raise NotImplementedError class BaseReconOptimizer(BaseOptimizer): def __init__(self, A, AH, mode, lambd, beta=None, tau=None): self.A = A self.AH = AH super().__init__(mode, lambd, beta, tau)
true
ce6d068438d20162b81b7de12f78acae1fdc521b
Python
Drymander/Halo-5-Visualizaing-Skill-and-Predicting-Match-Outcomes
/unused files/get_player_list.py
UTF-8
520
3.4375
3
[]
no_license
# Function to combine all gamertags from the match and prepare them in string # format for the next API call def get_player_list(df): # Create list from our df['Gamertag'] column and remove the brackets player_list = str(list(df['Gamertag']))[1:-1] # Format string for API player_list = player_list.replace(', ',',') player_list = player_list.replace("'",'') player_list = player_list.replace(' ','+') # Return in one full string return player_list # get_player_list(df)
true
a23f6d1656ceab873cc19921fd9e82ba44339a20
Python
Aasthaengg/IBMdataset
/Python_codes/p02844/s351087158.py
UTF-8
525
2.5625
3
[]
no_license
N=int(input()) S=input() code=list(set(list(S))) ans=0 for i in code: for j in code: for k in code: count=0 for s in S: if count==0: if s==i: count+=1 elif count==1: if s==j: count+=1 elif count==2: if s==k: count+=1 if count==3: ans+=1 break print(ans)
true
9a5c641985c8fd840d5c600c2185b7984dd7a60e
Python
yejiin/Python-Study
/algorithm/Programmers/Lv1/체육복.py
UTF-8
403
2.65625
3
[]
no_license
def solution(n, lost, reserve): answer = 0 data = [1] * (n + 2) for i in lost: if i in reserve: reserve.remove(i) else: data[i] = 0 reserve.sort() for i in reserve: if data[i - 1] == 0: data[i - 1] = 1 elif data[i + 1] == 0: data[i + 1] = 1 answer = n - data.count(0) return answer
true
efea7190b02bc29602a44598b380a25cd9817d22
Python
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_135/3229.py
UTF-8
536
3.15625
3
[]
no_license
def solve(ix): R0 = int(raw_input().strip()) M0 = [map(int, raw_input().strip().split()) for _ in range(4)] R1 = int(raw_input().strip()) M1 = [map(int, raw_input().strip().split()) for _ in range(4)] intersect = list(set(M0[R0-1]) & set(M1[R1-1])) if len(intersect) == 1: ans = intersect[0] elif len(intersect) > 1: ans = "Bad magician!" else: ans = "Volunteer cheated!" print 'Case #%d: %s' % (ix, ans) N = int(raw_input()) for ix in range(N): solve(ix+1)
true
b1cc81a37c30396f46397a7b505c9e34a9d568f0
Python
EoinDavey/Competitive
/AdventOfCode2020/d11.py
UTF-8
1,702
3.28125
3
[]
no_license
import sys from collections import defaultdict def lines(): return [line.strip() for line in sys.stdin] mvs = [(0, 1), (1, 0), (0, -1), (-1, 0), (1, 1), (1, -1), (-1, 1), (-1, -1)] ogboard = [list(x) for x in lines()] H = len(ogboard) W = len(ogboard[0]) def valid(x, y): return 0 <= x < H and 0 <= y < W def newState(x, y, board, grph, lim): cnt = sum([board[nx][ny] == '#' for nx, ny in grph[x, y]]) if board[x][y] == 'L' and cnt == 0: return '#' if board[x][y] == '#' and cnt >= lim: return 'L' return board[x][y] def solve(grph, lim): board = [x.copy() for x in ogboard] while True: mut = False newboard = [x.copy() for x in board] for x in range(H): for y in range(W): if board[x][y] == '.': continue old = board[x][y] new = newState(x, y, board, grph, lim) if old != new: mut = True newboard[x][y] = new board = newboard if not mut: break return sum([x.count('#') for x in board]) def partA(): grph = defaultdict(list) for x in range(H): for y in range(W): if ogboard[x][y] == '.': continue for dx, dy in mvs: nx, ny = x + dx, y + dy if not valid(nx, ny): continue grph[x, y].append((nx, ny)) print(solve(grph, 4)) def partB(): grph = defaultdict(list) for x in range(H): for y in range(W): if ogboard[x][y] == '.': continue for dx, dy in mvs: nx, ny = x + dx, y + dy while valid(nx, ny): if ogboard[nx][ny] != '.': grph[x, y].append((nx, ny)) break nx += dx ny += dy print(solve(grph, 5)) partA() partB()
true
d96d1f1113343f658eb39be0d5db2c59bd0f2072
Python
ahmed3moustafa/COVID-19-CNN
/audio_convolutional.py
UTF-8
4,399
3.015625
3
[]
no_license
import json import numpy as np from sklearn.model_selection import train_test_split import tensorflow.keras as keras import matplotlib.pyplot as plt DATASET_PATH = "data.json" def load_data(dataset_path): with open(dataset_path, "r") as fp: data = json.load(fp) # convert json to numpy array inputs = np.array(data["mfcc"]) targets = np.array(data["labels"]) print(inputs) print(targets) return inputs, targets def plot_history(history): """Plots accuracy/loss for training/validation set as a function of the epochs :param history: Training history of model :return: """ fig, axs = plt.subplots(2) # create accuracy sublpot axs[0].plot(history.history["accuracy"], label="train accuracy") axs[0].plot(history.history["val_accuracy"], label="test accuracy") axs[0].set_ylabel("Accuracy") axs[0].legend(loc="lower right") axs[0].set_title("Accuracy eval") # create error sublpot axs[1].plot(history.history["loss"], label="train error") axs[1].plot(history.history["val_loss"], label="test error") axs[1].set_ylabel("Error") axs[1].set_xlabel("Epoch") axs[1].legend(loc="upper right") axs[1].set_title("Error eval") plt.show() def prepare_datasets(test_size, validation_size): x, y = load_data(DATASET_PATH) X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=test_size) X_train, X_validation, y_train, y_validation = train_test_split(X_train, y_train, test_size=validation_size) X_train = X_train[..., np.newaxis] X_validation = X_validation[..., np.newaxis] X_test = X_test[..., np.newaxis] return X_train, X_validation, X_test, y_train, y_validation, y_test # noinspection PyCallByClass def build_model(input_shape): model = keras.Sequential() # 1st layer model.add(keras.layers.Conv2D(32, (3, 3), activation = 'relu', input_shape = input_shape)) model.add(keras.layers.MaxPool2D((3, 3), strides=(2, 2), padding='same')) model.add(keras.layers.BatchNormalization()) # 2nd layer model.add(keras.layers.Conv2D(32, (3, 3), activation='relu')) model.add(keras.layers.MaxPool2D((3, 3), strides=(2, 2), padding='same')) model.add(keras.layers.BatchNormalization()) # 3rd layer model.add(keras.layers.Conv2D(32, (2, 2), activation='relu')) model.add(keras.layers.MaxPool2D((2, 2), strides=(2, 2), padding='same')) model.add(keras.layers.BatchNormalization()) # flatten model.add(keras.layers.Flatten()) model.add(keras.layers.Dense(64, activation='relu')) model.add(keras.layers.Dropout(0.3)) # output layer model.add(keras.layers.Dense(2, activation='softmax')) return model def predict(model, X, y): # add a dimension to input data for sample - model.predict() expects a 4d array in this case X = X[np.newaxis, ...] # array shape (1, 130, 13, 1) # perform prediction prediction = model.predict(X) # get index with max value predicted_index = np.argmax(prediction, axis=1) print("Target: {}, Predicted label: {}".format(y, predicted_index)) if __name__ == "__main__": # create train, validation, test sets X_train, X_validation, X_test, y_train, y_validation, y_test = prepare_datasets(0.2, 0.2) # build cnn net input_shape = (X_train.shape[1], X_train.shape[2], X_train.shape[3]) model = build_model(input_shape) # compile the cnn optimizer = keras.optimizers.Adam(learning_rate=0.0001) model.compile(optimizer=optimizer, loss="sparse_categorical_crossentropy", metrics=['accuracy']) # train history = model.fit(X_train, y_train, validation_data=(X_validation, y_validation), batch_size=5, epochs=1000) # plot accuracy/error for training and validation plot_history(history) # evaluation test_error, test_accuracy = model.evaluate(X_test, y_test, verbose=1) print("Accuracy on the test is: {}".format(test_accuracy)) model.save("audio_model") # predict predict(model, X_test[5], y_test[5]) predict(model, X_test[2], y_test[2]) predict(model, X_test[7], y_test[7]) predict(model, X_test[12], y_test[12]) predict(model, X_test[10], y_test[10]) predict(model, X_test[1], y_test[1])
true
7ac1c19b8a2fba92213269cd683e407fa69924a4
Python
BastianRamos/proyectoGrupo3
/webprocess/core/models.py
UTF-8
2,967
2.625
3
[]
no_license
from django.db import models # Create your models here. #Declaramos una clase por cada tabla de nuestro modelo de datos. #Django genera una ID automatica y autoincrementable para cada tabla. #python manage.py makemigrations <--- Lee el archivo models y crea una migración. #python manage.py migrate <--- Toma las migraciones pendientes y las enlaza con la base de datos. #python manage.py createsuperuser <--- Creamos un super usuario para la administración del sitio con Django. class UnidadInterna(models.Model): nombre = models.CharField(max_length=50) descripcion = models.CharField(max_length=300) def __str__(self): return self.nombre # LIST PARA ROL DE EMPLEADO rol_funcionarios = [ # Creamos una lista para almacenar en tuplas las opciones de ROL de la tabla Empleado (1, 'Funcionario Gerente'), # Accedemos al elemento a traves del index (2, 'Funcionario Jefe'), (3, 'Funcionario Subordinado'), (4, 'Diseñador de Procesos') ] class Empleado(models.Model): rut = models.CharField(max_length=10, unique=True) nombre = models.CharField(max_length=20) apellido = models.CharField(max_length=20) correo = models.CharField(max_length=50) telefono = models.IntegerField() rol = models.IntegerField( # Se visualiza como un Select en Django null=False, blank=False, choices=rol_funcionarios # Indicamos que las opciones del Select estan en la lista rol_funcionarios ) unidadInterna = models.ForeignKey(UnidadInterna, on_delete=models.PROTECT, verbose_name='Unidad Interna') def __str__(self): string = self.nombre + " " + self.apellido return string class Usuario(models.Model): nombre = models.CharField(max_length=15) password = models.CharField(max_length=10, verbose_name="Contraseña") # En Django se visualizara como Contraseña en vez de password empleado = models.ForeignKey(Empleado, on_delete=models.PROTECT) def __str__(self): return self.nombre # LIST PARA ESTADO DE TAREA estado_tarea = [ (1, 'En Desarrollo'), (2, 'Completada'), (3, 'Atrasada') ] class Tarea(models.Model): nombre = models.CharField(max_length=50) plazo = models.DateField() descripcion = models.CharField(max_length=300) estado = models.IntegerField( null=False, blank=False, choices=estado_tarea ) responsable = models.ForeignKey(Empleado, on_delete=models.PROTECT) def __str__(self): return self.nombre class FlujoTarea(models.Model): nombre = models.CharField(max_length=100) descripcion = models.CharField(max_length=500) responsable = models.ForeignKey(Empleado, on_delete=models.PROTECT) def __str__(self): return self.nombre class Notificacion(models.Model): asunto = models.CharField(max_length=300) descripcion = models.CharField(max_length=300) fecha = models.DateField() def __str__(self): return self.asunto
true
fa4253ee4c4ce5dc9a005f6da1ddd6ee81141a8c
Python
paulywog13/web-scraping-challenge
/Mission_to_Mars/app.py
UTF-8
1,441
2.625
3
[]
no_license
from flask import Flask, render_template, redirect from flask_pymongo import PyMongo import mars_facts import mars_news import mars_space_images import mars_hemispheres # Create an instance of Flask app = Flask(__name__) # Use PyMongo to establish Mongo connection mongo = PyMongo(app, uri="mongodb://localhost:27017/mars_app") # Route to render index.html template using data from Mongo @app.route("/") def home(): # Find one record of data from the mongo database mars_data=mongo.db.mars_facts_html.find_one() print(mars_data) # Return template and data return render_template("index.html", mars_mission=mars_data) # Route that will trigger the scrape function @app.route("/scrape") def scrape(): # Run the scrape function and save the results to variables mars_mission = mongo.db.mars_facts_html mars_new_news = mars_news.scrape_info() mars_info = mars_facts.scrape_info() mars_hemis = mars_hemispheres.scrape_info() mars_img = mars_space_images.scrape_info() data = { "news_title": mars_new_news["latest_title"], "news_teaser": mars_new_news["latest_teaser"], "mars_facts": mars_info, "featured_image": mars_img["featured_image"], "mars_hemispheres": mars_hemis } mars_mission.update({}, data, upsert=True) # Redirect back to home page return redirect("/") if __name__ == "__main__": app.run(debug=True)
true
d5b98c2eb6e28755c8cfc6903ec1f269fbe93002
Python
thdk0302/Python-Libraries
/lib/log.py
UTF-8
1,162
2.875
3
[ "MIT" ]
permissive
# -*- coding: utf-8 -*- def write(text=' '): import datetime, os time = datetime.datetime.today() path = "./log/new/" + time.strftime("%Y//%m//%d") if not os.path.exists(path): os.makedirs(path) f = open(time.strftime("./log/new/%Y/%m/%d/%H:%M.log"), 'a') f.write(text) f.close() def wprint(text=' '): import datetime time = datetime.datetime.today() write("[" + time.strftime("%H:%M.%S") + "] " + text + "と出力しました\n") print(text) def wprintf(text=' '): import datetime, sys time = datetime.datetime.today() write("[" + time.strftime("%H:%M.%S") + "] " + text + "と出力しました\n") sys.stdout.write("\r" + text) sys.stdout.flush() def archive(): import shutil, os if not os.path.exists("./log/archive/old.zip"): shutil.make_archive('./log/archive/old', 'zip', root_dir='./log/', base_dir='./new/') write("ログファイルを圧縮しました") else: os.remove("./log/archive/old.zip") shutil.make_archive('./log/archive/old', 'zip', root_dir='./log/', base_dir='./new/') write("ログファイルを圧縮しました")
true
e044f3ddb82eda1edfeb7984f1ebc514cc38e0d1
Python
roblevy/async-and-sync
/test.py
UTF-8
1,981
3.359375
3
[]
no_license
""" See https://stackoverflow.com/questions/58564687/test-if-coroutine-was-awaited-or-not/58567980#58567980 """ import asyncio import pytest from functools import wraps class Wrapper: def __init__(self, _func, *args, **kwargs): self._conn = None self._func = _func self.args = args self.kwargs = kwargs async def __aenter__(self): self._conn = await self._func(*self.args, **self.kwargs) return self._conn async def __aexit__(self, *_): await self._conn.close() def __await__(self): return self._func( *self.args, **self.kwargs ).__await__() # https://stackoverflow.com/a/33420721/1113207 def connection_context_manager(func): @wraps(func) def wrapper(*args, **kwargs): return Wrapper(func, *args, **kwargs) return wrapper @connection_context_manager async def connect(uri): """ I don't want to touch this function, other than to decorate it with `@connection_context_manager` """ class Connection: def __init__(self, uri): self.uri = uri self.open = True print("Connected ", self.uri) async def close(self): await asyncio.sleep(0.3) self.open = False print(f"Connection {self.uri} closed") await asyncio.sleep(0.3) return Connection(uri) @pytest.mark.asyncio async def test_connect_normally(): connect_is_coroutine = asyncio.iscoroutine(connect) no_context = await connect("without context") # Now it's open assert no_context.open await no_context.close() # Now it's closed assert not no_context.open @pytest.mark.asyncio async def test_connect_with_context_manager(): async with connect("with context uri") as no_context: # Now it's open assert no_context.open # Now it's closed assert not no_context.open if __name__ == "__main__": asyncio.run(test_connect())
true
bc2dd63977be08619068c82a91ed65db0463b8dd
Python
gupy-io/mentoria-python
/palestras-conversas/testador_de_codigo/testa_v1.py
UTF-8
1,899
2.8125
3
[ "MIT" ]
permissive
import importlib import inspect import sys import os import re from collections import defaultdict from pathlib import Path from pprint import pprint def testa_v1_coletador(pasta): testes = [] lista_nome_dos_testes = [] for arquivo_de_teste in Path(pasta).glob("teste_*.py"): modulo_de_testes = importlib.import_module( re.sub(".py", "", re.sub(os.sep, "." , str(arquivo_de_teste))) ) testes_encontrados =[ teste for nome, teste in inspect.getmembers(modulo_de_testes) if nome.startswith("teste_") and callable(teste) ] lista_nome_dos_testes = [teste.__name__ for teste in testes_encontrados] testes.append((arquivo_de_teste, testes_encontrados)) return testes, lista_nome_dos_testes def executa_teste(pasta): resultados = [] testes_encontrados, _ = testa_v1_coletador(pasta) for modulo, testes in testes_encontrados: for teste in testes: resultado_de_um_teste = {"modulo": modulo, "nome": teste.__name__} try: teste() except AssertionError: resultado_de_um_teste["estado"] = "falhou" else: resultado_de_um_teste["estado"] = "passou" resultados.append(resultado_de_um_teste) return resultados def rodar_os_teste(pasta="./testes"): falhas: int = 0 sucesso: int = 0 for res in executa_teste(pasta): pprint(f"> {res['modulo']}:{res['nome']} - {res['estado']}") pprint(f"{'---'*20}") if res["estado"] == 'falhou': falhas += 1 if res["estado"] == "passou" : sucesso += 1 pprint(f"numero de testes coletados {falhas + sucesso}") if falhas > 0: pprint(f"ERROOOOOOOUUU ARRUMA ESSE TESTE AI IRMAO") sys.exit(1) if __name__ == "__main__": rodar_os_teste()
true
8e2edca4c167da0f3bc013f0d25653c32f4141e2
Python
Rallkus/DjangoRestFrameworkReactMobX
/backend/conduit/apps/contact/serializers.py
UTF-8
1,454
2.78125
3
[]
no_license
from rest_framework import serializers class ContactSerializer(serializers.Serializer): email = serializers.CharField(max_length=255) subject = serializers.CharField(max_length=255) message = serializers.CharField(max_length=255) def validate(self, data): print "*************" print data email = data.get('email', None) subject = data.get('subject', None) message = data.get('message', None) print subject # As mentioned above, an email is required. Raise an exception if an # email is not provided. if email is None: raise serializers.ValidationError( 'A valid email address is required' ) # As mentioned above, a password is required. Raise an exception if a # password is not provided. if subject is None: raise serializers.ValidationError( 'A subject is required' ) if message is None: raise serializers.ValidationError( 'A message is required and has to be at least 20 characters long' ) # The `validate` method should return a dictionary of validated data. # This is the data that is passed to the `create` and `update` methods # that we will see later on. return { 'email': email, 'subject': subject, 'message': message }
true
f67614a4024c7dc5698881c7b2332ea05ffeea08
Python
JasonYG/capital-one-technical-assessment
/main.py
UTF-8
2,577
3.375
3
[]
no_license
# Capital One Technical Assessment # Created by Jason Guo # # This program, alongside the AnalyzeCode class, was my interpretation of # the Capital One technical assessment. # # In the context of automation and continuous deployment, this program # was written to take in the source code files as command-line arguments. # You may supply in an arbitrary number of source code files as arguments, # in the form of file paths. # # In the spirit of modularity, I've added a 'programming languages schema', # which defines the programming language and its commenting syntax. This program # is thus easily scalable to allow for different programming languages. # # The format is: # file_extension,single_line_comment,begin_multi_line_comment,end_multi_line_comment # e.g. .java,//,/*,*/ # # (See supported_languages.csv as an example) # # To run the program: # python main.py [source code file names] schema_file # # An example command would be: # python main.py sample.html sample.java sample.js sample.js supported_languages.csv # For command-line arguments import argparse from AnalyzeCode import AnalyzeCode # Instantiate argument parser parser = argparse.ArgumentParser(description='Analyze some source files') parser.add_argument('file_names', metavar='file_name', type=str, nargs='*', help='the file names of the source code files') parser.add_argument('supported_languages', metavar='comment_schema', type=str, help='the supported programming languages and their commenting syntax') args = parser.parse_args() # Check for valid supported languages file try: open(args.supported_languages) except: print("Invalid supported languages schema file") quit() # Process each source code file for file_name in args.file_names: print(f'##### {file_name.upper()} #####') # Instantiate AnalyzeCode object for code parsing analyzer = AnalyzeCode(file_name, args.supported_languages) try: analyzer.parse_file() except: # If either the file can't be found, or if it's not defined in the supported languages print("Invalid source file\n") continue # Output print(f'Total # of lines: {analyzer.total_lines()}') print(f'Total # of comment lines: {analyzer.comment_lines()}') print(f'Total # of single line comments: {analyzer.single_line_comments()}') print(f'Total # of comment lines within within block comments: {analyzer.comments_in_blocks()}') print(f'Total # of block line comments: {analyzer.block_comments()}') print(f'Total # of TODO\'s: {analyzer.count_todos()}\n')
true
4ab3521ac08a91d547c109b962b0fde47bb84762
Python
cosmos454b/notebooks
/DataPreprocessing.py
UTF-8
1,733
3.359375
3
[]
no_license
### Common Steps to preprocess data for machine learning ### Import Libraries import numpy as np import pandas as pd from sklearn.preprocessing import Imputer from sklearn.preprocessing import StandardScaler from sklearn.preprocessing import OneHotEncoder,LabelEncoder from sklearn.model_selection import train_test_split ### Import Dataset data = pd.read_csv("mpg.csv", na_values=['na']); #dataLines = [] #with open ("mpg.csv", "r") as dataFile: # fileContents = dataFile.read().split("\n"); # for line in fileContents: # dataLines.append(line) #data = pd.DataFrame(dataLines) # Subset raw data to get dataframe df = data.iloc[:,0:] ####Inorder to drop missing values, do this on the main dataframe. df = df.dropna(axis=0) ###### SECTION 2 : GENERATE FEATURE MATRIX # Subset feature matrix with dependent variable X = df[['cylinders','displacement','horsepower','weight','acceleration']] ### Cleanse feature matrix X=X.apply(pd.to_numeric,errors='coerce') ### Fill missing data imputer = Imputer(missing_values="NaN",strategy="mean",axis=0) X=imputer.fit_transform(X) y = df[['mpg']].values ### Encode Categorical Data #labelEncoder_X = LabelEncoder() #X[:,3] = labelEncoder_X.fit_transform(X[:,3]) #onehotEncoder = OneHotEncoder(categorical_features=[3]) #X = onehotEncoder.fit_transform(X).toarray() #### Split data into train and test X_train,X_test,Y_train,Y_test = train_test_split(X,y,test_size=0.2,random_state=0) ### Standardize features scale. SCale both x and y, expect if y is categorical Xscaler = StandardScaler() X_train = Xscaler.fit_transform(X_train) X_test = Xscaler.transform(X_test) Yscaler = StandardScaler() X_train = Yscaler.fit_transform(X_train) X_test = Yscaler.transform(X_test)
true
84199e8ae8b5f443ea8980ae788a5804502095c3
Python
johSchm/bayesLearner
/src/fileParser.py
UTF-8
712
3.375
3
[]
no_license
# parser for any file # read file and save output in 2D array # @return: 2D array def readFile(filePath): with open(filePath, 'r') as file: line_array = file.read().splitlines() cell_array = [line.split() for line in line_array] file.close() return cell_array # store data in file def writeFile(filePath, data, append=False): if not append: with open(filePath, 'w+') as file: for element in data: file.write(str(element) + '\t') else: with open(filePath, 'a+') as file: file.write('\n') for element in data: file.write(str(element) + '\t') file.close()
true
83633a9b08c6289af0f0436bdedc7cb63ec982d6
Python
Wizmann/ACM-ICPC
/Leetcode/Algorithm/python/3000/02278-Percentage of Letter in String.py
UTF-8
150
3.109375
3
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
class Solution(object): def percentageLetter(self, s, letter): n = len(s) c = s.count(letter) return 100 * c / n
true
4d8e9110fb18849031778092648c6bf9634df4bf
Python
jlongtine/cfn-python-lint
/test/module/conditions/test_condition.py
UTF-8
11,902
2.5625
3
[ "MIT-0" ]
permissive
""" Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from cfnlint import conditions from testlib.testcase import BaseTestCase class TestCondition(BaseTestCase): """ Test Good Condition """ def test_basic_condition(self): """ Test getting a condition setup """ template = { 'Conditions': { 'myCondition': { 'Fn::Equals': [{'Ref': 'AWS::Region'}, 'us-east-1'] } } } result = conditions.Condition(template, 'myCondition') self.assertTrue(result.test({'36305712594f5e76fbcbbe2f82cd3f850f6018e9': 'us-east-1'})) self.assertFalse(result.test({'36305712594f5e76fbcbbe2f82cd3f850f6018e9': 'us-west-1'})) def test_basic_condition_w_int(self): """ Test getting a condition setup """ template = { 'Conditions': { 'myCondition1': { 'Fn::Equals': [{'Ref': 'myParameter'}, 1] }, 'myCondition2': { 'Fn::Equals': [1, {'Ref': 'myParameter'}] } } } result = conditions.Condition(template, 'myCondition1') self.assertFalse(result.test({'410f41081170ebc3bc99d8f424ad8e01633f444a': '2'})) self.assertTrue(result.test({'410f41081170ebc3bc99d8f424ad8e01633f444a': '1'})) result = conditions.Condition(template, 'myCondition2') self.assertFalse(result.test({'410f41081170ebc3bc99d8f424ad8e01633f444a': '2'})) self.assertTrue(result.test({'410f41081170ebc3bc99d8f424ad8e01633f444a': '1'})) def test_not_condition(self): """ Test getting a condition setup """ template = { 'Conditions': { 'myCondition': { 'Fn::Equals': [{'Ref': 'AWS::Region'}, 'us-east-1'] }, 'notCondition': {'Fn::Not': [{'Condition': 'myCondition'}]} } } result = conditions.Condition(template, 'notCondition') self.assertFalse(result.test({'36305712594f5e76fbcbbe2f82cd3f850f6018e9': 'us-east-1'})) self.assertTrue(result.test({'36305712594f5e76fbcbbe2f82cd3f850f6018e9': 'us-west-1'})) def test_or_condition(self): """ Test getting a condition setup """ template = { 'Conditions': { 'condition1': { 'Fn::Equals': [{'Ref': 'AWS::Region'}, 'us-east-1'] }, 'condition2': { 'Fn::Equals': [{'Ref': 'AWS::Region'}, 'us-west-1'] }, 'orCondition': {'Fn::Or': [{'Condition': 'condition1'}, {'Condition': 'condition2'}]} } } result = conditions.Condition(template, 'orCondition') self.assertTrue(result.test({'36305712594f5e76fbcbbe2f82cd3f850f6018e9': 'us-east-1'})) self.assertTrue(result.test({'36305712594f5e76fbcbbe2f82cd3f850f6018e9': 'us-west-1'})) self.assertFalse(result.test({'36305712594f5e76fbcbbe2f82cd3f850f6018e9': 'us-west-2'})) def test_direct_condition(self): """ Test direction condition""" template = { 'Conditions': { 'condition1': { 'Fn::Equals': [{'Ref': 'AWS::Region'}, 'us-east-1'] }, 'directcondition': {'Condition': 'condition1'} } } result = conditions.Condition(template, 'directcondition') self.assertTrue( result.test({'36305712594f5e76fbcbbe2f82cd3f850f6018e9': 'us-east-1'})) self.assertFalse( result.test({'36305712594f5e76fbcbbe2f82cd3f850f6018e9': 'us-west-1'})) def test_and_condition(self): """ Test getting a condition setup """ template = { 'Conditions': { 'condition1': { 'Fn::Equals': [{'Ref': 'AWS::Region'}, 'us-east-1'] }, 'condition2': { 'Fn::Equals': [{'Ref': 'myEnvironment'}, 'prod'] }, 'andCondition': {'Fn::And': [{'Condition': 'condition1'}, {'Condition': 'condition2'}]} } } result = conditions.Condition(template, 'andCondition') self.assertTrue( result.test({ '36305712594f5e76fbcbbe2f82cd3f850f6018e9': 'us-east-1', 'd60d12101638186a2c742b772ec8e69b3e2382b9': 'prod'})) self.assertFalse( result.test({ '36305712594f5e76fbcbbe2f82cd3f850f6018e9': 'us-east-1', 'd60d12101638186a2c742b772ec8e69b3e2382b9': 'dev'})) self.assertFalse( result.test({ '36305712594f5e76fbcbbe2f82cd3f850f6018e9': 'us-west-1', 'd60d12101638186a2c742b772ec8e69b3e2382b9': 'prod'})) def test_two_function_condition(self): """ Test getting a condition setup """ template = { 'Conditions': { 'myCondition': { 'Fn::Equals': [{'Ref': 'AWS::Region'}, {'Ref': 'PrimaryRegion'}] } } } result = conditions.Condition(template, 'myCondition') self.assertFalse(result.test({'36305712594f5e76fbcbbe2f82cd3f850f6018e9': 'us-east-1'})) self.assertTrue(result.test({'36305712594f5e76fbcbbe2f82cd3f850f6018e9': '36cf15035d5be0f36e03d67b66cddb6081f5855d'})) def test_empty_string_in_equals(self): """ Empty String in Condition """ template = { 'Conditions': { 'isSet': {'Fn::Equals': [{'Ref': 'myEnvironment'}, '']} }, 'Resources': {} } result = conditions.Condition(template, 'isSet') self.assertEqual(result.And, []) # No And self.assertEqual(result.Or, []) # No Or self.assertEqual(result.Not, []) # No Not self.assertIsNotNone(result.Equals) self.assertEqual(result.Influenced_Equals, {'d60d12101638186a2c742b772ec8e69b3e2382b9': {''}}) class TestBadConditions(BaseTestCase): """Test Badly Formmated Condition """ def test_bad_format_condition(self): """ Badly formmated Condition """ template = { 'Conditions': { 'isProduction': [{'Fn::Equals': [{'Ref:' 'myEnvironment'}, 'prod']}] }, 'Resources': {} } result = conditions.Condition(template, 'isProduction') self.assertEqual(result.And, []) # No And self.assertEqual(result.Or, []) # No Or self.assertEqual(result.Not, []) # No Not self.assertIsNone(result.Equals) self.assertEqual(result.Influenced_Equals, {}) def test_bad_format_condition_2(self): """ Badly formmated Condition """ template = { 'Conditions': { 'isProduction': {'Fn::Equals': [[{'Ref:' 'myEnvironment'}], 'prod']} }, 'Resources': {} } result = conditions.Condition(template, 'isProduction') self.assertEqual(result.And, []) # No And self.assertEqual(result.Or, []) # No Or self.assertEqual(result.Not, []) # No Not self.assertIsNone(result.Equals) self.assertEqual(result.Influenced_Equals, {}) def test_bad_format_condition_3(self): """ Badly formmated Condition """ template = { 'Conditions': { 'isProduction': {'Fn::Equals': [{'Ref': 'myEnvironment', 'Ref1': 'myEnvironment'}, 'prod']} }, 'Resources': {} } result = conditions.Condition(template, 'isProduction') self.assertEqual(result.And, []) # No And self.assertEqual(result.Or, []) # No Or self.assertEqual(result.Not, []) # No Not self.assertIsNone(result.Equals) self.assertEqual(result.Influenced_Equals, {}) def test_bad_format_condition_bad_equals_dict(self): """ Badly formmated Condition """ template = { 'Conditions': { 'isProduction': {'Fn::Equals': {'Ref': 'myEnvironment', 'Value': 'prod'}} }, 'Resources': {} } result = conditions.Condition(template, 'isProduction') self.assertEqual(result.And, []) # No And self.assertEqual(result.Or, []) # No Or self.assertEqual(result.Not, []) # No Not self.assertIsNone(result.Equals) self.assertEqual(result.Influenced_Equals, {}) def test_bad_format_condition_bad_equals_size(self): """ Badly formmated Condition """ template = { 'Conditions': { 'isProduction': {'Fn::Equals': [{'Ref': 'myEnvironment'}, 'Value', 'prod']} }, 'Resources': {} } result = conditions.Condition(template, 'isProduction') self.assertEqual(result.And, []) # No And self.assertEqual(result.Or, []) # No Or self.assertEqual(result.Not, []) # No Not self.assertIsNone(result.Equals) self.assertEqual(result.Influenced_Equals, {}) def test_nested_conditions(self): """ Test getting a condition setup """ template = { 'Conditions': { 'condition1': { 'Fn::Equals': [{'Ref': 'AWS::Region'}, 'us-east-1'] }, 'condition2': { 'Fn::Equals': [{'Ref': 'myEnvironment'}, 'prod'] }, 'orCondition': {'Fn::Or': [ {'Fn::And': [{'Condition': 'condition1'}, {'Condition': 'condition2'}]}, {'Fn::Or': [ {'Fn::Equals': [{'Ref': 'AWS::Region'}, 'us-west-2']}, {'Fn::Equals': [{'Ref': 'AWS::Region'}, 'eu-north-1']}, ]} ]} } } result = conditions.Condition(template, 'orCondition') self.assertEqual( result.Influenced_Equals, { '36305712594f5e76fbcbbe2f82cd3f850f6018e9': {'us-east-1', 'us-west-2', 'eu-north-1'}, 'd60d12101638186a2c742b772ec8e69b3e2382b9': {'prod'} } ) self.assertTrue( result.test({ '36305712594f5e76fbcbbe2f82cd3f850f6018e9': 'us-east-1', 'd60d12101638186a2c742b772ec8e69b3e2382b9': 'prod'})) self.assertFalse( result.test({ '36305712594f5e76fbcbbe2f82cd3f850f6018e9': 'us-east-1', 'd60d12101638186a2c742b772ec8e69b3e2382b9': 'dev'})) self.assertFalse( result.test({ '36305712594f5e76fbcbbe2f82cd3f850f6018e9': 'us-west-1', 'd60d12101638186a2c742b772ec8e69b3e2382b9': 'prod'})) self.assertTrue( result.test({ '36305712594f5e76fbcbbe2f82cd3f850f6018e9': 'us-west-2', 'd60d12101638186a2c742b772ec8e69b3e2382b9': 'dev'}))
true
dca4c5d9009525d9c67d864514a7d16a16e20db4
Python
sstuteja/UDACITY_CARND
/Term1/Project5/lesson_functions.py
UTF-8
11,751
2.71875
3
[]
no_license
import matplotlib.image as mpimg import numpy as np import cv2 from skimage.feature import hog ############################################################################### # Define a function to return HOG features and visualization def get_hog_features(img, orient, pix_per_cell, cell_per_block, vis=False, feature_vec=True): # Call with two outputs if vis==True if vis == True: features, hog_image = hog(img, orientations=orient, pixels_per_cell=(pix_per_cell, pix_per_cell), cells_per_block=(cell_per_block, cell_per_block), transform_sqrt=True, visualise=vis, feature_vector=feature_vec) return features, hog_image # Otherwise call with one output else: features = hog(img, orientations=orient, pixels_per_cell=(pix_per_cell, pix_per_cell), cells_per_block=(cell_per_block, cell_per_block), transform_sqrt=True, visualise=vis, feature_vector=feature_vec) return features ############################################################################### # Define a function to compute binned color features def bin_spatial(img, size=(32, 32)): # Use cv2.resize().ravel() to create the feature vector features = cv2.resize(img, size).ravel() # Return the feature vector return features ############################################################################### # Define a function to compute color histogram features # NEED TO CHANGE bins_range if reading .png files with mpimg! def color_hist(img, nbins=32, bins_range=(0, 256)): # Compute the histogram of the color channels separately channel1_hist = np.histogram(img[:,:,0], bins=nbins, range=bins_range) channel2_hist = np.histogram(img[:,:,1], bins=nbins, range=bins_range) channel3_hist = np.histogram(img[:,:,2], bins=nbins, range=bins_range) # Concatenate the histograms into a single feature vector hist_features = np.concatenate((channel1_hist[0], channel2_hist[0], channel3_hist[0])) # Return the individual histograms, bin_centers and feature vector return hist_features ############################################################################### # Define a function to extract features from a list of images # Have this function call bin_spatial() and color_hist() def extract_features(imgs, color_space='RGB', spatial_size=(32, 32), hist_bins=32, orient=9, pix_per_cell=8, cell_per_block=2, \ spatial_feat=True, hist_feat=True, hog_feat=True, \ hog_channel='ALL'): # Create a list to append feature vectors to features = [] # Iterate through the list of images for file in imgs: file_features = [] # Read in each one by one image = cv2.imread(file) image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # apply color conversion if other than 'RGB' if color_space != 'RGB': if color_space == 'HSV': feature_image = cv2.cvtColor(image, cv2.COLOR_RGB2HSV) elif color_space == 'LUV': feature_image = cv2.cvtColor(image, cv2.COLOR_RGB2LUV) elif color_space == 'HLS': feature_image = cv2.cvtColor(image, cv2.COLOR_RGB2HLS) elif color_space == 'YUV': feature_image = cv2.cvtColor(image, cv2.COLOR_RGB2YUV) elif color_space == 'YCrCb': feature_image = cv2.cvtColor(image, cv2.COLOR_RGB2YCrCb) else: feature_image = np.copy(image) if spatial_feat == True: spatial_features = bin_spatial(feature_image, size=spatial_size) file_features.append(spatial_features) if hist_feat == True: # Apply color_hist() hist_features = color_hist(feature_image, nbins=hist_bins) file_features.append(hist_features) if hog_feat == True: # Call get_hog_features() with vis=False, feature_vec=True if hog_channel == 'ALL': hog_features = [] for channel in range(feature_image.shape[2]): hog_features.append(get_hog_features(feature_image[:,:,channel], orient, pix_per_cell, cell_per_block, vis=False, feature_vec=True)) hog_features = np.ravel(hog_features) else: hog_features = get_hog_features(feature_image[:,:,hog_channel], orient, pix_per_cell, cell_per_block, vis=False, feature_vec=True) # Append the new feature vector to the features list file_features.append(hog_features) features.append(np.concatenate(file_features)) # Return list of feature vectors return features ############################################################################### # Define a function to draw bounding boxes def draw_boxes(img, bboxes, color=(0, 0, 255), thick=6): # Make a copy of the image imcopy = np.copy(img) # Iterate through the bounding boxes for bbox in bboxes: # Draw a rectangle given bbox coordinates cv2.rectangle(imcopy, bbox[0], bbox[1], color, thick) # Return the image copy with boxes drawn return imcopy ############################################################################### # HOG Subsampling Window Search def find_cars(img, ystart, ystop, svc, X_scaler, orient, pix_per_cell, cell_per_block, spatial_size, hist_bins, scale=1, color_space='RGB', \ spatial_feat=True, hist_feat=True, hog_feat=True, \ hog_channel='ALL'): #img = img.astype(np.float32)/255 img_tosearch = img[ystart:ystop, :, :] #ctrans_tosearch = np.copy(img_tosearch) if color_space != 'RGB': if color_space == 'HSV': ctrans_tosearch = cv2.cvtColor(img_tosearch, cv2.COLOR_RGB2HSV) elif color_space == 'LUV': ctrans_tosearch = cv2.cvtColor(img_tosearch, cv2.COLOR_RGB2LUV) elif color_space == 'HLS': ctrans_tosearch = cv2.cvtColor(img_tosearch, cv2.COLOR_RGB2HLS) elif color_space == 'YUV': ctrans_tosearch = cv2.cvtColor(img_tosearch, cv2.COLOR_RGB2YUV) elif color_space == 'YCrCb': ctrans_tosearch = cv2.cvtColor(img_tosearch, cv2.COLOR_RGB2YCrCb) else: ctrans_tosearch = np.copy(img_tosearch) if scale != 1: ctrans_tosearch = cv2.resize(ctrans_tosearch, (0, 0), fx=1/scale, fy=1/scale) chlist = [ctrans_tosearch[:, :, 0], ctrans_tosearch[:, :, 1], ctrans_tosearch[:, :, 2]] # Define blocks and steps nxblocks = (chlist[0].shape[1]//pix_per_cell) - 1 nyblocks = (chlist[0].shape[0]//pix_per_cell) - 1 #nfeat_per_block = orient * cell_per_block**2 window = 64 cells_per_step = 2 nblocks_per_window = (window//pix_per_cell) - 1 nxsteps = (nxblocks - nblocks_per_window) // cells_per_step nysteps = (nyblocks - nblocks_per_window) // cells_per_step #Compute individual HOG features for the entire image if hog_channel == 'ALL': hoglist = [get_hog_features(chlist[0], orient, pix_per_cell, cell_per_block, feature_vec=False), \ get_hog_features(chlist[1], orient, pix_per_cell, cell_per_block, feature_vec=False), \ get_hog_features(chlist[2], orient, pix_per_cell, cell_per_block, feature_vec=False)] else: hoglist = [get_hog_features(chlist[hog_channel], orient, pix_per_cell, cell_per_block, feature_vec=False)] bbox_list = [] for xb in range(nxsteps): for yb in range(nysteps): xpos = xb * cells_per_step ypos = yb * cells_per_step feature_list = [] xleft = xpos*pix_per_cell ytop = ypos*pix_per_cell #Extract the image patch subimg = cv2.resize(ctrans_tosearch[ytop:ytop+window, xleft:xleft+window], (64, 64)) #Get color features if spatial_feat == True: spatial_features = bin_spatial(subimg, size=spatial_size) feature_list.append(np.hstack(spatial_features)) if hist_feat == True: hist_features = color_hist(subimg, nbins=hist_bins) feature_list.append(np.hstack(hist_features)) # Extract HOG for this patch if hog_feat == True: if hog_channel == 'ALL': hog_feat_list = [hoglist[0][ypos:ypos+nblocks_per_window, xpos:xpos+nblocks_per_window].ravel(), \ hoglist[1][ypos:ypos+nblocks_per_window, xpos:xpos+nblocks_per_window].ravel(), \ hoglist[2][ypos:ypos+nblocks_per_window, xpos:xpos+nblocks_per_window].ravel()] else: hog_feat_list = [hoglist[hog_channel][ypos:ypos+nblocks_per_window, xpos:xpos+nblocks_per_window].ravel()] feature_list.append(np.hstack(hog_feat_list)) #Scale features and make a prediction #These features need to be the same features that were used to train the classifier test_features = X_scaler.transform(np.hstack(feature_list).reshape(1, -1).astype(np.float64)) test_prediction = svc.predict(test_features) if test_prediction == 1: xbox_left = np.int(xleft * scale) ytop_draw = np.int(ytop * scale) win_draw = np.int(window * scale) thisTopLeft = (xbox_left, ytop_draw+ystart) thisBottomRight = (xbox_left+win_draw, ytop_draw+win_draw+ystart) bbox_list.append((thisTopLeft, thisBottomRight)) return bbox_list ############################################################################### def add_heat(heatmap, bbox_list): #Iterate through list of boxes for box in bbox_list: # Add +=1 for all pixels inside each bbox # Each box takes the form ((x1, y1), (x2, y2)) heatmap[box[0][1]:box[1][1], box[0][0]:box[1][0]] += 1 return heatmap ############################################################################### def apply_heatmap_threshold(heatmap, threshold): #Zero out pixels below the threshold heatmap[heatmap <= threshold] = 0 return heatmap ############################################################################### def draw_labeled_bboxes(img, labels): # Iterate through all detected cars for car_number in range(1, labels[1]+1): # Find pixels with each car_number label value nonzero = (labels[0] == car_number).nonzero() # Identify x and y values of those pixels nonzeroy = np.array(nonzero[0]) nonzerox = np.array(nonzero[1]) # Define a bounding box based on min/max x and y bbox = ((np.min(nonzerox), np.min(nonzeroy)), (np.max(nonzerox), np.max(nonzeroy))) # Draw the box on the image cv2.rectangle(img, bbox[0], bbox[1], (0,0,255), 6) # Return the image return img
true
e1272331e5405e263242cf3240f971ed4e08f8c5
Python
arifikhsan/python-dicoding
/conditional/else.py
UTF-8
346
3.703125
4
[]
no_license
amount = int(input("Enter amount: ")) if amount < 1000: discount = amount * 0.05 print("Discount", discount) else: discount = amount * 0.10 print("Discount", discount) print ("Net payable:",amount-discount) a = 8 if a % 2 == 0: print('bilangan {} adalah genap'.format(a)) else: print('bilangan {} adalah ganjil'.format(a))
true
be94469be48faa8f5c0d91484d8bd7da17757bf7
Python
MehdiJenab/first_spark_code
/q5_b.py
UTF-8
1,384
2.734375
3
[ "MIT" ]
permissive
from pyspark.sql import SparkSession from pyspark.sql.functions import * from pyspark.sql.types import * spark = SparkSession.builder.master("local[1]") \ .appName("Q5_a") \ .getOrCreate() spark.sparkContext.setLogLevel("WARN") # to turn off annoying INFO log printed out on terminal schema_user = StructType([\ StructField("userid", IntegerType(), True),\ StructField("age", IntegerType(), True),\ StructField("gender", StringType(), True),\ StructField("occupation", StringType(), True),\ StructField("zipcode", IntegerType(), True)]) df_uuser = spark.read.format("csv").option("delimiter", "|").option("header","false").schema(schema_user).load("u.user") df_uuser.createOrReplaceTempView('user') schema_data = StructType([\ StructField("userid", IntegerType(), True),\ StructField("itemid", IntegerType(), True),\ StructField("rating", IntegerType(), True),\ StructField("time", IntegerType(), True)]) df_uuser = spark.read.format("csv").option("delimiter", "\t").option("header","false").schema(schema_data).load("u.data") df_uuser.createOrReplaceTempView('data') df2= spark.sql("""SELECT DISTINCT (u.occupation), COUNT(d.userid) AS count from user AS u, data as d WHERE u.userid = d.userid AND u.occupation <> "other" AND u.occupation <> "none" GROUP BY occupation ORDER BY count DESC""") df2.show() print (df2.collect())
true
324d30f70d167c4246d31e8ea65f64b0c7fa7800
Python
Kawser-nerd/CLCDSA
/Source Codes/AtCoder/abc041/D/4201470.py
UTF-8
940
2.6875
3
[]
no_license
# coding:utf-8 import sys from collections import deque, defaultdict INF = float('inf') MOD = 10 ** 9 + 7 def LI(): return [int(x) for x in sys.stdin.readline().split()] def LI_(): return [int(x) - 1 for x in sys.stdin.readline().split()] def LS(): return sys.stdin.readline().split() def II(): return int(sys.stdin.readline()) def SI(): return input() n, m = LI() G = [[] for _ in range(n)] for _ in range(m): x, y = LI_() G[x].append(y) # dp[????S]: S?????????????????? dp = [0] * (1 << n) dp[0] = 1 for s in range(1 << n): for i in range(n): if s >> i & 1 == 0: continue # S - {v} others = s ^ (1 << i) for to in G[i]: # ???????v??S - {v}???????? # -> ??v??????? if others & (1 << to): break else: # v???????? dp[s] += dp[others] print(dp[-1])
true
00598b57b0319a972a8fe8b6a7fa4342c5351b5e
Python
Minta-Ra/wk02_d2_Pet_Shop_Classes_Lab
/classes/customer.py
UTF-8
703
4
4
[]
no_license
class Customer: def __init__(self, name, cash): # Instance variables / properties self.name = name self.cash = cash # Add list of pets to the customer self.pets = [] def reduce_cash(self, amount): self.cash -= amount def pet_count(self): # Return the length of the list return len(self.pets) def add_pet(self, pet): self.pets.append(pet) def get_total_value_of_pets(self): total = 0 # loop through the list for pet in self.pets: # We get pet price from Pet class self.price # .price is a property on the pet total += pet.price return total
true
0ed33339265c6172eca4fc241f204de42ef655dd
Python
bertdecoensel/noysim
/noysim/emission.py
UTF-8
42,011
2.8125
3
[ "MIT", "LicenseRef-scancode-free-unknown" ]
permissive
# Noysim -- Noise simulation tools for Aimsun. # Copyright (c) 2010-2011 by Bert De Coensel, Ghent University & Griffith University. # # Noise emission model functions and classes import warnings import random import numpy import pylab from geo import Point, Direction, asPoint, asDirection from acoustics import LOWDB, fromdB, TertsBandSpectrum import numeric #--------------------------------------------------------------------------------------------------- # Basic classes #--------------------------------------------------------------------------------------------------- class Vehicle(object): """ base class defining a vehicle, containing all properties that could have an influence on noise emissions """ def __init__(self, vid, length, width, height, weight, cat, axles, doublemount, studs, fuel, cc, maxspeed, maxdecel, maxaccel, position = Point(0.0,0.0,0.0), direction = Direction(0.0,0.0), speed = 0.0, acceleration = 0.0): object.__init__(self) # unique vehicle ID self._vid = vid # size properties self._length = length # in m self._width = width # in m self._height = height # in m self._weight = weight # in kg # emission related properties self._cat = cat # emission category (usually an integer), to be interpreted by the emission models self._axles = axles # integer, number of axles of vehicle self._doublemount = doublemount # boolean, true for double-mounted tires (for trucks) self._studs = studs # boolean, true if the vehicle has winter tires self._fuel = fuel # the type of fuel the vehicle uses (string, e.g. 'petrol', 'diesel', 'electric') self._cc = cc # the cilinder capacity (cc) # kinematic properties self._maxspeed = maxspeed # in km/h self._maxdecel = maxdecel # in m/s^2 (negative value) self._maxaccel = maxaccel # in m/s^2 # dynamic properties self._position = position # position Point(x,y,z) - center of bottom plane - in m self._direction = direction # Direction(bearing,gradient) of the vehicle, in degrees (0-360) self._speed = speed # velocity (km/h) self._acceleration = acceleration # acceleration (m/s^2) def vid(self): return self._vid def length(self): return self._length def width(self): return self._width def height(self): return self._height def weight(self): return self._weight def cat(self): return self._cat def axles(self): return self._axles def doublemount(self): return self._doublemount def studs(self): return self._studs def fuel(self): return self._fuel def cc(self): return self._cc def maxspeed(self): return self._maxspeed def maxdecel(self): return self._maxdecel def maxaccel(self): return self._maxaccel def position(self): return self._position def direction(self): return self._direction def speed(self): return self._speed def acceleration(self): return self._acceleration def __str__(self): """ return a string representation of the vehicle """ s = '[ID %s: %.1fx%.1fx%.1fm, %dkg, ' % (str(self.vid()), self.length(), self.width(), self.height(), int(self.weight())) s += 'c=%s, ax=%d, dm=%s, ' % (str(self.cat()), self.axles(), str(self.doublemount())) s += 'stud=%s, %s, %dcc,' % (str(self.studs()), self.fuel(), int(self.cc())) s += '\n max=(%.1f,%.1f,%.1f), ' % (self.maxspeed(), self.maxdecel(), self.maxaccel()) s += 'p=%s, d=%s, v=%.1f, a=%.1f]' % (str(self.position()), str(self.direction()), self.speed(), self.acceleration()) return s def copy(self, cls = None): """ create a copy of the vehicle """ if cls == None: cls = Vehicle return cls(vid = self._vid, length = self._length, width = self._width, height = self._height, weight = self._weight, cat = self._cat, axles = self._axles, doublemount = self._doublemount, studs = self._studs, fuel = self._fuel, cc = self._cc, maxspeed = self._maxspeed, maxdecel = self._maxdecel, maxaccel = self._maxaccel, position = self._position.copy(), direction = self._direction.copy(), speed = self._speed, acceleration = self._acceleration) def move(self, dx = 0.0, dy = 0.0, dz = 0.0): """ move the location of the vehicle """ self._position.x += dx self._position.y += dy self._position.z += dz class Roadsurface(object): """ base class defining a road surface, containing all properties that could have an influence on noise emissions """ def __init__(self, cat, temperature, chipsize, age, wet, tc): object.__init__(self) self._cat = cat # surface category, to be interpreted by the various emission models self._temperature = temperature # temperature of air above road surface (degrees celsius) self._chipsize = chipsize # road surface chip size (in mm) self._age = age # road surface age (in years) self._wet = wet # boolean, true if the surface is wet self._tc = tc # road surface temperature coefficient (in dB/degree) def cat(self): return self._cat def temperature(self): return self._temperature def chipsize(self): return self._chipsize def age(self): return self._age def wet(self): return self._wet def tc(self): return self._tc def __str__(self): """ return a string representation of the road surface """ s = '[c=%s, t=%.1fC, chip=%dmm, ' % (str(self.cat()), self.temperature(), int(self.chipsize())) s += 'age=%dy, wet=%s, tc=%.2f]' % (int(self.age()), str(self.wet()), self.tc()) return s class Source(object): """ base source class, which serves as the output of an emission model """ def __init__(self, position, direction, emission, directivity = lambda theta, phi, f: 0.0): object.__init__(self) self.position = position # Point(x,y,z) in m self.direction = direction # Direction(bearing,gradient) of the source, in degrees (0-360) self.emission = emission # source emission spectrum self.directivity = directivity # function (or function object) for the directivity pattern of the source # (correction on source power level as a function of theta, phi and frequency) def __str__(self): """ return a string representation of the source """ # only prints the A-weighted level return '[p=%s, d=%s, e=%.2f dBA]' % (str(self.position), str(self.direction), self.emission.laeq()) def copy(self): """ return a copy of the source """ return Source(position = self.position.copy(), direction = self.direction.copy(), emission = self.emission.copy(), directivity = self.directivity) class EmissionModel(object): """ base emission model interface - to be filled in by derived classes """ def __init__(self): object.__init__(self) def __str__(self): """ return a string representation of the emission model """ return '[EmissionModel]' def categoryNames(self): """ return a list with the names of the vehicle categories that the model supports """ raise NotImplementedError def sources(self, vehicle, road): """ calculate the list of emission sources associated with the given vehicle and road surface """ raise NotImplementedError def emission(self, vehicle, road): """ shorthand function, calculating the total emission associated with the given vehicle and road surface """ raise NotImplementedError class Viewport(object): """ viewport function object, acting as a vehicle filter should return True for each vehicle that has to be taken into account in subsequent processing """ def __init__(self): object.__init__(self) def __str__(self): """ return a string representation of the viewport """ return '[Viewport]' def __call__(self, vehicle): """ should return True only if the vehicle has to be taken into account """ return True # the default is to consider all vehicles #--------------------------------------------------------------------------------------------------- # Specialized vehicle and road surface classes #--------------------------------------------------------------------------------------------------- # The constants in these predefined classes were taken from the Queensland vehicles defined in the Griffith Univ. Aimsun file, # with missing values (e.g. weight or cc) filled in by best guess (these additional values do not have an influence on noise anyhow) class QLDCar(Vehicle): """ Queensland car (CAR_QLD) with default values for all parameters (Imagine category 1) """ def __init__(self, vid = 0, length = 4.0, width = 2.0, height = 1.5, weight = 800.0, cat = 1, axles = 2, doublemount = False, studs = False, fuel = 'petrol', cc = 1600, maxspeed = 110.0, maxdecel = -6.5, maxaccel = 2.8, position = Point(0.0,0.0,0.0), direction = Direction(0.0,0.0), speed = 0.0, acceleration = 0.0): Vehicle.__init__(self, vid, length, width, height, weight, cat, axles, doublemount, studs, fuel, cc, maxspeed, maxdecel, maxaccel, position, direction, speed, acceleration) def copy(self): return Vehicle.copy(self, cls = QLDCar) class QLDVan(Vehicle): """ Queensland van (HV) with default values for all parameters (Imagine category 1) """ def __init__(self, vid = 0, length = 7.0, width = 2.0, height = 2.0, weight = 2000.0, cat = 1, axles = 2, doublemount = False, studs = False, fuel = 'petrol', cc = 2500, maxspeed = 110.0, maxdecel = -5.0, maxaccel = 2.5, position = Point(0.0,0.0,0.0), direction = Direction(0.0,0.0), speed = 0.0, acceleration = 0.0): Vehicle.__init__(self, vid, length, width, height, weight, cat, axles, doublemount, studs, fuel, cc, maxspeed, maxdecel, maxaccel, position, direction, speed, acceleration) def copy(self): return Vehicle.copy(self, cls = QLDVan) class QLDLightTruck(Vehicle): """ Queensland light truck (LT) with default values for all parameters (Imagine category 2) """ def __init__(self, vid = 0, length = 12.0, width = 2.5, height = 2.5, weight = 5000.0, cat = 2, axles = 2, doublemount = True, studs = False, fuel = 'petrol', cc = 4000, maxspeed = 110.0, maxdecel = -3.0, maxaccel = 1.5, position = Point(0.0,0.0,0.0), direction = Direction(0.0,0.0), speed = 0.0, acceleration = 0.0): Vehicle.__init__(self, vid, length, width, height, weight, cat, axles, doublemount, studs, fuel, cc, maxspeed, maxdecel, maxaccel, position, direction, speed, acceleration) def copy(self): return Vehicle.copy(self, cls = QLDLightTruck) class QLDSemiTrailer(Vehicle): """ Queensland semi-trailer (ST) with default values for all parameters (Imagine category 3) """ def __init__(self, vid = 0, length = 19.0, width = 2.5, height = 3.0, weight = 10000.0, cat = 3, axles = 4, doublemount = True, studs = False, fuel = 'petrol', cc = 5000, maxspeed = 110.0, maxdecel = -2.9, maxaccel = 1.0, position = Point(0.0,0.0,0.0), direction = Direction(0.0,0.0), speed = 0.0, acceleration = 0.0): Vehicle.__init__(self, vid, length, width, height, weight, cat, axles, doublemount, studs, fuel, cc, maxspeed, maxdecel, maxaccel, position, direction, speed, acceleration) def copy(self): return Vehicle.copy(self, cls = QLDSemiTrailer) class QLDBDouble(Vehicle): """ Queensland B-Double heavy vehicle (BD) with default values for all parameters (Imagine category 3) """ def __init__(self, vid = 0, length = 25.0, width = 2.5, height = 3.5, weight = 30000.0, cat = 3, axles = 4, doublemount = True, studs = False, fuel = 'petrol', cc = 8000, maxspeed = 110.0, maxdecel = -2.75, maxaccel = 0.8, position = Point(0.0,0.0,0.0), direction = Direction(0.0,0.0), speed = 0.0, acceleration = 0.0): Vehicle.__init__(self, vid, length, width, height, weight, cat, axles, doublemount, studs, fuel, cc, maxspeed, maxdecel, maxaccel, position, direction, speed, acceleration) def copy(self): return Vehicle.copy(self, cls = QLDBDouble) class QLDMotorcycle(Vehicle): """ Queensland motorcycle with default values for all parameters (Imagine category 4b - here 5) """ def __init__(self, vid = 0, length = 1.5, width = 0.5, height = 1.5, weight = 200.0, cat = 5, axles = 2, doublemount = False, studs = False, fuel = 'petrol', cc = 1000, maxspeed = 110.0, maxdecel = -6.0, maxaccel = 4.0, position = Point(0.0,0.0,0.0), direction = Direction(0.0,0.0), speed = 0.0, acceleration = 0.0): Vehicle.__init__(self, vid, length, width, height, weight, cat, axles, doublemount, studs, fuel, cc, maxspeed, maxdecel, maxaccel, position, direction, speed, acceleration) def copy(self): return Vehicle.copy(self, cls = QLDMotorcycle) class ReferenceRoadsurface(Roadsurface): """ Harmonoise/Imagine reference road surface """ def __init__(self, cat = 'REF', temperature = 20.0, chipsize = 11.0, age = 2.0, wet = False, tc = 0.08): Roadsurface.__init__(self, cat, temperature, chipsize, age, wet, tc) #--------------------------------------------------------------------------------------------------- # Specialized viewport classes #--------------------------------------------------------------------------------------------------- class RectangularViewport(Viewport): """ viewport that takes into account the vehicles that are situated in a rectangular area """ def __init__(self, minx, miny, maxx, maxy): Viewport.__init__(self) (self.minx, self.miny, self.maxx, self.maxy) = (minx, miny, maxx, maxy) def __str__(self): """ return a string representation of the viewport """ return '[RectangularViewport (%s, %s, %s, %s)]' % (self.minx, self.miny, self.maxx, self.maxy) def __call__(self, vehicle): """ check if the vehicle is situated inside the rectangular area """ p = vehicle.position() if (self.minx <= p.x) and (p.x <= self.maxx) and (self.miny <= p.y) and (p.y <= self.maxy): return True return False # TODO: # - define the class below # - uncomment the line in Configuration.viewport so it is used # class DynamicViewport(RectangularViewport): # """ special case of a rectangular viewport, for which the dimensions are automatically tailored # to give optimal tradeoff between speed and accuracy, based on various network and receiver properties # """ # def __init__(self): # # perform calculations for minx, miny, maxx, maxy # # finally create the viewport # RectangularViewport.__init__(minx, miny, maxx, maxy) #--------------------------------------------------------------------------------------------------- # Imagine road traffic noise emission model #--------------------------------------------------------------------------------------------------- # model constants (LOWDB is used to fill in the values that are not supplied by Imagine, i.e. at 20 Hz and at 12kHz and above) IMAGINE = {# Light motor vehicles 1: {'AR': numpy.asarray([LOWDB, 69.9, 69.9, 69.9, 74.9, 74.9, 74.9, 79.3, 82.0, 81.2, 80.9, 78.9, 78.8, 80.5, 85.0, 87.9, 90.9, 93.3, 92.8, 91.5, 88.5, 84.9, 81.8, 78.7, 74.9, 71.8, 69.1, 65.6,LOWDB,LOWDB,LOWDB]), 'BR': numpy.asarray([ 0.0, 33.0, 33.0, 33.0, 30.0, 30.0, 30.0, 41.0, 41.2, 42.3, 41.8, 38.6, 35.5, 32.9, 25.0, 25.0, 27.0, 33.4, 36.7, 37.0, 37.5, 37.5, 38.6, 39.6, 40.0, 39.9, 40.2, 40.3, 0.0, 0.0, 0.0]), 'AP': numpy.asarray([LOWDB, 87.0, 87.0, 87.0, 87.9, 90.8, 89.9, 86.9, 82.6, 81.9, 82.3, 83.9, 83.3, 82.4, 80.6, 80.2, 77.8, 78.0, 81.4, 82.3, 82.6, 81.5, 80.2, 78.5, 75.6, 73.3, 71.0, 68.1,LOWDB,LOWDB,LOWDB]), 'BP': numpy.asarray([ 0.0, 0.0, 0.0, 0.0, 0.0, -3.0, 0.0, 8.0, 6.0, 6.0, 7.0, 8.0, 8.0, 8.0, 8.0, 8.0, 8.0, 8.0, 8.0, 8.0, 8.0, 8.0, 8.0, 8.0, 8.0, 8.0, 8.0, 8.0, 0.0, 0.0, 0.0]), 'CP': numpy.asarray([ 0.0, 4.0, 4.0, 4.0, 7.0, 7.0, 7.0, 7.0, 7.0, 7.0, 7.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 0.0, 0.0, 0.0])}, # Medium heavy vehicles: 2: {'AR': numpy.asarray([LOWDB, 76.5, 76.5, 76.5, 78.5, 79.5, 79.5, 82.5, 84.3, 84.7, 84.3, 87.4, 87.8, 89.8, 91.6, 93.5, 94.6, 92.4, 89.6, 88.1, 85.9, 82.7, 80.7, 78.8, 76.8, 76.7, 75.7, 74.5,LOWDB,LOWDB,LOWDB]), 'BR': numpy.asarray([ 0.0, 33.0, 33.0, 33.0, 30.0, 30.0, 30.0, 32.9, 35.9, 38.1, 36.5, 33.5, 30.6, 27.7, 21.9, 23.8, 28.4, 31.1, 35.4, 35.9, 36.7, 36.3, 37.7, 38.5, 39.8, 39.9, 40.2, 40.3, 0.0, 0.0, 0.0]), 'AP': numpy.asarray([LOWDB, 93.9, 93.9, 94.1, 95.0, 97.3, 96.1, 92.5, 91.9, 90.4, 93.4, 94.4, 94.2, 93.0, 90.8, 92.1, 92.5, 94.1, 94.5, 92.4, 90.1, 87.6, 85.8, 83.8, 81.4, 80.0, 77.2, 75.4,LOWDB,LOWDB,LOWDB]), 'BP': numpy.asarray([ 0.0, 0.0, 0.0, 0.0, 0.0, -4.0, 0.0, 4.0, 5.0, 5.5, 6.0, 6.5, 6.5, 6.5, 6.5, 6.5, 6.5, 6.5, 6.5, 6.5, 6.5, 6.5, 6.5, 6.5, 6.5, 6.5, 6.5, 6.5, 0.0, 0.0, 0.0]), 'CP': numpy.asarray([ 0.0, 5.0, 5.0, 5.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 0.0, 0.0, 0.0])}, # Heavy vehicles 3: {'AR': numpy.asarray([LOWDB, 79.5, 79.5, 79.5, 81.5, 82.5, 82.5, 85.5, 87.3, 87.7, 87.3, 89.5, 90.5, 93.8, 95.9, 97.3, 98.0, 95.6, 93.2, 91.9, 88.9, 85.5, 84.1, 82.2, 79.8, 78.6, 77.5, 76.8,LOWDB,LOWDB,LOWDB]), 'BR': numpy.asarray([ 0.0, 33.0, 33.0, 33.0, 30.0, 30.0, 30.0, 31.4, 32.8, 36.0, 34.6, 32.7, 29.3, 26.4, 24.2, 25.9, 30.4, 32.3, 36.5, 36.8, 38.0, 36.8, 38.5, 38.9, 38.5, 40.2, 40.8, 41.0, 0.0, 0.0, 0.0]), 'AP': numpy.asarray([LOWDB, 95.7, 94.9, 94.1, 96.8,101.8, 98.6, 95.5, 96.2, 95.7, 97.2, 96.3, 97.2, 95.8, 95.9, 96.8, 95.1, 95.8, 95.0, 92.7, 91.2, 88.7, 87.6, 87.2, 84.2, 82.7, 79.7, 77.6,LOWDB,LOWDB,LOWDB]), 'BP': numpy.asarray([ 0.0, 0.0, 0.0, 0.0, -4.0, 0.0, 4.0, 3.0, 3.0, 3.0, 4.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 0.0, 0.0, 0.0]), 'CP': numpy.asarray([ 0.0, 5.0, 5.0, 5.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 0.0, 0.0, 0.0])}, # Powered two-wheelers 4a (mopeds < 50cc) 4: {'AR': LOWDB*numpy.ones(31), 'BR': numpy.zeros(31), 'AP': numpy.asarray([LOWDB, 88.7, 87.6, 85.5, 85.8, 81.5, 80.7, 82.0, 85.6, 81.6, 81.4, 85.5, 86.3, 87.9, 88.7, 89.9, 91.8, 91.2, 92.4, 95.0, 94.1, 92.9, 90.4, 89.1, 87.4, 84.9, 84.4, 82.2,LOWDB,LOWDB,LOWDB]), 'BP': numpy.asarray([ 0.0, -2.2, -0.1, 1.7, 5.9, 1.9, 3.3, 0.9, 17.3, 14.5, 5.0, 14.6, 9.9, 9.7, 12.7, 12.3, 13.9, 16.6, 17.2, 17.9, 19.3, 20.6, 19.9, 20.8, 20.5, 21.0, 21.0, 19.3, 0.0, 0.0, 0.0]), 'CP': numpy.asarray([ 0.0, 4.0, 4.0, 4.0, 7.0, 7.0, 7.0, 7.0, 7.0, 7.0, 7.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 0.0, 0.0, 0.0])}, # Powered two-wheelers 4b (motorcycles > 50cc) 5: {'AR': LOWDB*numpy.ones(31), 'BR': numpy.zeros(31), 'AP': numpy.asarray([LOWDB, 90.8, 88.9, 89.2, 90.5, 89.2, 90.7, 93.2, 93.2, 90.0, 88.4, 87.6, 87.7, 87.0, 87.4, 89.4, 89.9, 90.1, 89.7, 89.8, 88.2, 86.5, 85.8, 85.1, 85.1, 82.7, 81.7, 80.4,LOWDB,LOWDB,LOWDB]), 'BP': numpy.asarray([ 0.0, 2.1, 3.1, 1.2, 2.3, 2.8, 4.2, 6.2, 4.8, 7.3, 11.3, 10.6, 13.9, 13.5, 11.0, 10.8, 11.4, 11.4, 11.7, 13.4, 11.6, 12.2, 10.9, 10.5, 12.0, 12.0, 12.0, 12.0, 0.0, 0.0, 0.0]), 'CP': numpy.asarray([ 0.0, 4.0, 4.0, 4.0, 7.0, 7.0, 7.0, 7.0, 7.0, 7.0, 7.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 0.0, 0.0, 0.0])}} # correction values for studded tires STUDS = {'A': numpy.asarray([ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.3, 1.4, 1.5, 0.9, 1.2, 1.5, 1.9, 1.8, 0.8, 0.5, 0.2, -0.2, -0.4, 0.5, 0.8, 0.9, 2.1, 5.0, 7.3, 10.0, 0.0, 0.0, 0.0]), 'B': numpy.asarray([ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -4.1, -6.0, -8.5, -4.1, 1.7, 0.6, -4.6, -3.9, -2.7, -4.2,-11.7,-11.7,-14.9,-17.6,-21.8,-21.6,-19.2,-14.6, -9.9,-10.2, 0.0, 0.0, 0.0])} class ImagineDirectivity(object): """ function object implementing the Harmonoise/Imagine directivity pattern once an object of this class is created, it behaves like a function (thanks to the '__call__' method) """ def __init__(self, cat, h): """ create the directivity function, for the given vehicle category and source height """ object.__init__(self) self.cat = cat # vehicle category self.h = h # source height def __call__(self, theta, phi, f): """ return the directivity correction for the given angles, at the given frequency """ # theta: horizontal angle between travelling direction of vehicle and reciever (0 degrees means receiver in front of vehicle) # phi: vertical angle between travelling direction of vehicle and receiver (0 degrees means receiver in front of vehicle) # NOTE: for readability reasons, other symbols are used than in the Imagine document # restrict the angles to the correct range while theta < 0.0: theta += 360.0 while theta > 360.0: theta -= 360.0 while phi < -180.0: phi += 360.0 while phi > 180.0: phi -= 360.0 # enforce horizontal and vertical symmetry if theta > 180.0: theta = 360.0 - theta if phi < 0.0: phi = -phi if phi > 90.0: phi = 180.0 - phi # calculate shorthands thetaRad = (numpy.pi/180.0)*theta phiRad = (numpy.pi/180.0)*phi pi2theta = numpy.pi/2.0 - thetaRad sinpi2theta = numpy.sin(pi2theta) sqrtcosphi = numpy.sqrt(numpy.cos(phiRad)) # calculate horizontal directivity (formulas from Harmonoise model, depending on source height, independent of vehicle category) if self.h == 0.01: # horn effect, only for certain frequency range if (1600.0 <= f) and (f <= 6300.0): horizontal = (-1.5 + 2.5*abs(sinpi2theta)) * sqrtcosphi else: horizontal = 0.0 elif self.h == 0.30: horizontal = 0.0 elif self.h == 0.75: # screening by the body of the heavy vehicle horizontal = (1.546*(pi2theta**3) - 1.425*(pi2theta**2) + 0.22*pi2theta + 0.6) * sqrtcosphi else: raise Exception('no directivity defined for sources at height %.2f' % self.h) # calculate vertical directivity (approximations from Imagine model, depending on vehicle category, independent of source height) if self.cat == 1: vertical = -abs(phi/20.0) # phi in degrees elif self.cat in (2, 3): vertical = -abs(phi/30.0) else: vertical = 0.0 # no corrections for categories 4 and 5 return horizontal + vertical class ImagineModel(EmissionModel): """ Imagine road traffic noise emission model """ def __init__(self): EmissionModel.__init__(self) # parameters self.vref = 70.0 self.vinterval = (0.1, 160.0) # flags for applying different types of corrections - to be adjusted after object creation if necessary self.correction = {'acceleration': True, 'gradient': False, 'temperature': False, 'surface': False, 'wetness': False, 'axles': True, 'fleet': False} self.fleet = {'diesel': 19.0, 'tirewidth': 187.0, 'vans': 10.5, 'iress': (1.0, 35.0), 'studs': False} def __str__(self): """ return a string representation of the emission model """ return '[Imagine emission model]' def categoryNames(self): return ['Light', 'Medium', 'Heavy', 'Moped', 'Motorcycle'] def rollingNoise(self, vehicle, road): # calculate base rolling noise v = numpy.clip(vehicle.speed(), *self.vinterval) z = IMAGINE[vehicle.cat()]['AR'] + IMAGINE[vehicle.cat()]['BR']*numpy.log10(v/self.vref) # apply corrections if self.correction['temperature'] == True: z += self.temperatureCorrection(vehicle, road) if self.correction['surface'] == True: z += self.surfaceCorrection(vehicle, road) if self.correction['wetness'] == True: z += self.wetnessCorrection(vehicle, road) if self.correction['axles'] == True: z += self.axlesCorrection(vehicle, road) if self.correction['fleet'] == True: z += self.fleetCorrectionRolling(vehicle, road) return z def propulsionNoise(self, vehicle, road): # calculate base propulsion noise v = numpy.clip(vehicle.speed(), *self.vinterval) z = IMAGINE[vehicle.cat()]['AP'] + IMAGINE[vehicle.cat()]['BP']*((v - self.vref)/self.vref) # apply corrections if self.correction['acceleration'] == True: z += self.accelerationCorrection(vehicle, road) if self.correction['gradient'] == True: z += self.gradientCorrection(vehicle, road) if self.correction['fleet'] == True: z += self.fleetCorrectionPropulsion(vehicle, road) return z def accelerationCorrection(self, vehicle, road): # restrict acceleration maxaccel = {1: 2.0, 2: 1.0, 3: 1.0, 4: 4.0, 5: 4.0}[vehicle.cat()] a = numpy.clip(vehicle.acceleration(), -1.0, maxaccel) return IMAGINE[vehicle.cat()]['CP'] * a def gradientCorrection(self, vehicle, road): # calculate gradient as a percentage alpha = 100.0*numpy.tan(asDirection(vehicle.direction()).gradientRadians()) cp = IMAGINE[vehicle.cat()]['CP'] g = 9.81 if vehicle.cat() in [1, 4, 5]: if alpha >= -2.0: return cp * g * (alpha/100.0) if (-8.0 < alpha) and (alpha < -2.0): return cp * g * (-2.0/100.0) if alpha <= -8.0: return -cp * g * ((alpha + 10.0)/100.0) if vehicle.cat() in [2, 3]: if alpha >= -2.0: return cp * g * (alpha/100.0) if alpha < -2.0: return -cp * g * ((alpha + 4.0)/100.0) raise Exception('Imagine model: condition for gradient correction not found') def temperatureCorrection(self, vehicle, road): factor = {1: 1.0, 2: 0.5, 3: 0.5, 4: 1.0, 5: 1.0}[vehicle.cat()] # half temperature coefficient for cats 2 and 3 return factor * road.tc() * (20.0 - road.temperature()) def surfaceCorrection(self, vehicle, road): """ corrections for road surfaces belonging to the reference cluster (DAC and SMA) """ # check for vehicle type and surface type if vehicle.cat() in [2, 3]: return 0.0 # no correction for heavy vehicles if not (road.cat() in ['REF', 'DAC', 'SMA']): return 0.0 # surface not in reference cluster chipsize = numpy.clip(road.chipsize(), 8.0, 16.0) # surface chipsize and type correction z = 0.25*(chipsize - 11.0) z += {'REF': 0.0, 'DAC': -0.3, 'SMA': 0.3}[road.cat()] return z def wetnessCorrection(self, vehicle, road): # check for vehicle type and wetness if not (road.wet() and (vehicle.cat() == 1)): return 0.0 # retrieve applicable model constants v = numpy.clip(vehicle.speed(), *self.vinterval) return max(0.0, 15.0*numpy.log10(numpy.asarray(FTERTS)) - 12.0*numpy.log10(v/self.vref) - 48.0) def axlesCorrection(self, vehicle, road): if not (vehicle.cat() == 3): return 0.0 # correction only for heavy trucks if not vehicle.doublemount(): return 6.8*numpy.log10(vehicle.axles()/4.0) else: return 9.1*numpy.log10(vehicle.axles()/4.0) + 0.8 def fleetCorrectionRolling(self, vehicle, road): z = 0.0 # correction for tire width if vehicle.cat() == 1: z += 0.04 * (self.fleet['tirewidth'] - 187.0) # correction for percentage of delivery vans if vehicle.cat() == 1: z += 1.0 * (self.fleet['vans'] - 10.5)/100.0 # correction for winter/studded tires if (self.fleet['studs'] == True) and (vehicle.cat() == 1): v = numpy.clip(vehicle.speed(), 50.0, 90.0) z += STUDS['A'] + STUDS['B']*numpy.log10(v/self.vref) return z def fleetCorrectionPropulsion(self, vehicle, road): z = 0.0 # correction for percentage of diesel vehicles if vehicle.cat() == 1: z += 3.0 * (self.fleet['diesel'] - 19.0)/100.0 # correction for percentage of delivery vans if vehicle.cat() == 1: z += 5.0 * (self.fleet['vans'] - 10.5)/100.0 # correction for illegal replacement exhaust silencer systems (IRESS) if vehicle.cat() in [1, 2, 3]: piress = (self.fleet['iress'][0] - 1.0)/100.0 else: piress = (self.fleet['iress'][1] - 35.0)/100.0 z += (29.0 * piress) - (24.0 * piress**2) return z def sources(self, vehicle, road = ReferenceRoadsurface()): # calculate position of sources pos = vehicle.position() h = {1: (0.01, 0.30), 2: (0.01, 0.75), 3: (0.01, 0.75), 4: (0.30, 0.30), 5: (0.30, 0.30)}[vehicle.cat()] lopos = Point(pos[0], pos[1], pos[2] + h[0]) hipos = Point(pos[0], pos[1], pos[2] + h[1]) # calculate rolling and propulsion noise r = fromdB(self.rollingNoise(vehicle, road)) p = fromdB(self.propulsionNoise(vehicle, road)) # calculate low and high noise lonoise = 10.0*numpy.log10(0.8*r + 0.2*p) hinoise = 10.0*numpy.log10(0.2*r + 0.8*p) # construct sources return [Source(position = lopos, direction = asDirection(vehicle.direction()), emission = TertsBandSpectrum(lonoise), directivity = ImagineDirectivity(cat = vehicle.cat(), h = h[0])), Source(position = hipos, direction = asDirection(vehicle.direction()), emission = TertsBandSpectrum(hinoise), directivity = ImagineDirectivity(cat = vehicle.cat(), h = h[1]))] def emission(self, vehicle, road = ReferenceRoadsurface()): """ return the total emission as a single spectrum, assuming that all is emitted by the same source """ return TertsBandSpectrum(10.0*numpy.log10(fromdB(self.rollingNoise(vehicle,road)) + fromdB(self.propulsionNoise(vehicle,road)))) #--------------------------------------------------------------------------------------------------- # Random corrected road traffic noise emission models #--------------------------------------------------------------------------------------------------- class ImagineCorrectionModel(ImagineModel): """ Road traffic noise emission model with random corrections on the emissions This model uses the Imagine model as a base, but adds a random (frequency-independent) sound power level correction to each vehicle, in order to model a realistic distribution of louder/quiter vehicles within the same emission class. """ def __init__(self, seed = None): ImagineModel.__init__(self) numeric.seed(seed) self.corrections = {} # dict with a random correction for each vehicle, filled during simulation self.generators = {} # dict with correction generators for each vehicle category, to be filled in by subclasses def __str__(self): """ return a string representation of the emission model """ return '[Random correction emission model]' def getCorrection(self, vehicle): """ return the correction for a given vehicle """ (vid, cat) = (vehicle.vid(), vehicle.cat()) if vid in self.corrections: # vehicle was encountered before, so use the same correction corr = self.corrections[vid] else: # new vehicle, so calculate a new correction and save it corr = self.generators[cat].generate() self.corrections[vid] = corr return corr def sources(self, vehicle, road = ReferenceRoadsurface()): """ overload the ImagineModel implementation """ # calculate the sources using the Imagine model result = ImagineModel.sources(self, vehicle, road) # get the sound power level correction and apply it to the sources corr = self.getCorrection(vehicle) for source in result: source.emission.correct(corr) return result def emission(self, vehicle, road = ReferenceRoadsurface()): """ overload the ImagineModel implementation """ # calculate the emission using the Imagine model result = ImagineModel.emission(self, vehicle, road) # get the sound power level correction and apply it to the emission corr = self.getCorrection(vehicle) result.correct(corr) return result class SkewedNormalImagineCorrectionModel(ImagineCorrectionModel): """ Emission model that samples random corrections from a skewed normal distribution """ def __init__(self, stdev = (0.0,0.0,0.0,0.0,0.0), skew = (0.0,0.0,0.0,0.0,0.0), seed = None): ImagineCorrectionModel.__init__(self, seed=seed) assert (len(stdev) == 5) and (len(skew) == 5) for i in range(5): self.generators[i+1] = numeric.SkewedNormalCorrectionGenerator(stdev = stdev[i], skew = skew[i]) def __str__(self): """ return a string representation of the emission model """ return '[Skewed normal correction emission model]' # Distributions of sound power levels from Australian study # (Brown & Tomerini, Road & Transport Research, 20(3):50-63, 2011) AUSTDIST = {1: numpy.asarray([89, 188, 207, 386, 438, 437, 556, 596, 821, 797, 905, 1099, 1369, 1567, 1727, 2184, 2674, 3426, 3502, 3522, 3123, 2455, 1696, 1238, 832, 468, 362, 286, 195, 126, 74, 77, 32, 34, 14, 14, 11, 6, 6, 4, 5, 6, 3, 2, 5, 8, 0, 0, 0, 0, 0], dtype=float), 2: numpy.asarray([4, 8, 12, 27, 33, 39, 36, 55, 55, 67, 82, 70, 103, 87, 91, 94, 152, 258, 301, 369, 459, 568, 687, 622, 574, 486, 344, 296, 241, 168, 134, 80, 61, 50, 34, 28, 21, 12, 4, 4, 2, 1, 5, 0, 2, 3, 0, 0, 0, 0, 0], dtype=float), 3: numpy.asarray([14, 120, 81, 194, 307, 277, 306, 319, 328, 345, 404, 436, 488, 456, 507, 514, 473, 584, 611, 668, 679, 711, 919, 1083, 1430, 1662, 2007, 2018, 1872, 1696, 1268, 935, 547, 378, 261, 197, 102, 77, 60, 40, 24, 32, 22, 11, 13, 16, 1, 0, 0, 0, 2], dtype=float), 4: numpy.asarray([0, 0, 2, 5, 8, 5, 9, 8, 9, 19, 22, 24, 20, 32, 34, 48, 54, 58, 78, 74, 72, 70, 50, 52, 34, 33, 43, 26, 21, 13, 14, 14, 4, 3, 5, 4, 5, 2, 0, 2, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0], dtype=float), 5: numpy.asarray([0, 0, 2, 5, 8, 5, 9, 8, 9, 19, 22, 24, 20, 32, 34, 48, 54, 58, 78, 74, 72, 70, 50, 52, 34, 33, 43, 26, 21, 13, 14, 14, 4, 3, 5, 4, 5, 2, 0, 2, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0], dtype=float)} class DistributionImagineCorrectionModel(ImagineCorrectionModel): """ Emission model that samples random corrections from a predefined distribution """ def __init__(self, corrdist = AUSTDIST, seed = None, zeropoint='meanEn'): # corrdist = dict with correction distributions (in bins of 1dB) for each Imagine vehicle class ImagineCorrectionModel.__init__(self, seed=seed) for cat, values in corrdist.iteritems(): self.generators[cat] = numeric.TabulatedCorrectionGenerator(values = values, dx = 1.0, zeropoint=zeropoint) def __str__(self): """ return a string representation of the emission model """ return '[Distribution correction emission model]' #--------------------------------------------------------------------------------------------------- # Lookup table road traffic noise emission model #--------------------------------------------------------------------------------------------------- # TODO: Implement lookup table model, for which the following has to be done # - create a class LookupModel, that is a subclass from ImagineModel, and overload the 'sources' and 'emission' methods # (same way as the DistributionModel class above); a subclass from the Imagine model is necessary because the Lookup model # may use the shape of the emission spectrum as from the Imagine model # - add necessary values to the default configuration (CFGEMODEL, see above) and create a new default configuration file, # by running this script from the command line with the flag MAIN_CONFIG set to True # - update the method 'Configuration.emodel' (see below) such that a LookupModel object is created when appropriate #--------------------------------------------------------------------------------------------------- # Test code #--------------------------------------------------------------------------------------------------- if __name__ == '__main__': # test emission correction generator if 1: vClass = 3 pylab.figure() g = numeric.TabulatedCorrectionGenerator(values = AUSTDIST[vClass], zeropoint='meanEn') g.plotData() # measured distribution g.plot() # fitted distribution # plot of Imagine emission spectrum at different vehicle speeds if 0: road = ReferenceRoadsurface() model = ImagineModel() cat = 1 pylab.figure() speeds = [30, 40, 50, 60, 70, 80, 90, 100, 110, 120] markers = ['circle grey', 'diamond black', 'square white', 'triangle grey', 'circle black', 'diamond white', 'square grey', 'triangle black', 'circle white', 'diamond grey'] for v, m in zip(speeds, markers): model.emission(QLDCar(cat = cat, speed = v, acceleration = 0.0)).plot(m = m, interval = (60.0, 110.0)) pylab.legend([('%d km/h' % v) for v in speeds]) pylab.title('Imagine emission spectrum at different vehicle speeds') # reproduction of Figure 25 of Imagine report (emission spectra for rolling and propulsion noise, and total emission spectrum) if 0: road = ReferenceRoadsurface() model = ImagineModel() vList = {1: range(10, 161), 2: range(10, 101), 3: range(10, 101)} yRange = {1: (70, 115), 2: (75, 115), 3: (75, 115)} pylab.figure() for cat in [1, 2, 3]: p = [TertsBandSpectrum(model.propulsionNoise(QLDCar(cat = cat, speed = v, acceleration = 0.0), road)).laeq() for v in vList[cat]] r = [TertsBandSpectrum(model.rollingNoise(QLDCar(cat = cat, speed = v, acceleration = 0.0), road)).laeq() for v in vList[cat]] e = [model.emission(QLDCar(cat = cat, speed = v, acceleration = 0.0)).laeq() for v in vList[cat]] pylab.subplot(2, 2, cat) pylab.plot(vList[cat], p) pylab.plot(vList[cat], r) pylab.plot(vList[cat], e) # adjust y-axis a = pylab.axis() pylab.axis([a[0], a[1], yRange[cat][0], yRange[cat][1]]) # reproduction of Figure 5.32 of Harmonoise report (directivity functions for source heights 0.1m and 0.75m) if 0: cat = 1 # vehicle category of interest f = 2000.0 # frequency of interest thetas = numpy.arange(0.0, 180.0) pylab.figure() for h in [0.01, 0.75]: func = [ImagineDirectivity(cat = cat, h = h)(theta = theta, phi = 0.0, f = f) for theta in thetas] pylab.plot((numpy.pi/180.0)*thetas, func) # adjust y-axis a = pylab.axis() pylab.axis([0.0, 3.5, -10.0, 4.0]) # draw grid pylab.gca().xaxis.grid(color='gray', linestyle='dashed') pylab.gca().yaxis.grid(color='gray', linestyle='dashed') # plot of Harmonoise/Imagine directivity patterns as polar plot if 0: warnings.simplefilter('ignore', UserWarning) cat = 1 f = 2000.0 pylab.figure() iplot = 0 for h in [0.01, 0.30, 0.75]: for phi in [0.0, 30.0, 60.0, 90.0]: directivity = ImagineDirectivity(cat = cat, h = h) thetas = numpy.arange(0.0, 360.0) Lcorrs = [directivity(theta = theta, phi = phi, f = f) for theta in thetas] # level corrections iplot += 1 pylab.subplot(3, 4, iplot, polar = True) pylab.polar((numpy.pi/180.0)*thetas, numpy.zeros(360), color = 'black', linestyle = '--') # draw the zero line pylab.polar((numpy.pi/180.0)*thetas, Lcorrs) pylab.ylim(-10.0, 4.0) try: pylab.show() except: pass
true
cb085cce2d89348e57220c30a0f9afa88fa52f3e
Python
lpenzey/gilded_rose
/test_gilded_rose.py
UTF-8
3,558
2.953125
3
[]
no_license
import unittest from gilded_rose import Item, GildedRose, ItemType class GildedRoseTest(unittest.TestCase): def test_quality_decreases_by_1(self): items = [Item("foo", 2, 10)] gilded_rose = GildedRose(items) gilded_rose.update_quality() self.assertEquals(9, items[0].quality) def test_sell_by_decreases_by_1(self): items = [Item("foo", 2, 10)] gilded_rose = GildedRose(items) gilded_rose.update_quality() self.assertEquals(9, items[0].quality) def test_quality_degrades_2x_after_sell_by_date_passes(self): items = [Item("foo", 0, 10)] gilded_rose = GildedRose(items) gilded_rose.update_quality() self.assertEquals(8, items[0].quality) def test_quality_is_never_negative(self): items = [Item("foo", 0, 0)] gilded_rose = GildedRose(items) gilded_rose.update_quality() self.assertEquals(0, items[0].quality) def test_brie_increases_in_quality(self): items = [Item("Aged Brie", 5, 49)] gilded_rose = GildedRose(items) gilded_rose.update_quality() self.assertEquals(50, items[0].quality) def test_quality_never_exceeds_50(self): items = [Item("Aged Brie", 0, 50)] gilded_rose = GildedRose(items) gilded_rose.update_quality() self.assertEquals(50, items[0].quality) def test_sulfurus_quality_remains_at_80(self): items = [Item("Sulfuras, Hand of Ragnaros", 10, 80)] gilded_rose = GildedRose(items) gilded_rose.update_quality() self.assertEquals(80, items[0].quality) def test_backstagepass_increases_in_quality_by_1(self): items = [Item("Backstage passes to a TAFKAL80ETC concert", 15, 10)] gilded_rose = GildedRose(items) gilded_rose.update_quality() self.assertEquals(11, items[0].quality) def test_backstagepass_increases_by_2_when_between_5_and_10_days_left(self): items = [Item("Backstage passes to a TAFKAL80ETC concert", 10, 10)] gilded_rose = GildedRose(items) gilded_rose.update_quality() self.assertEquals(12, items[0].quality) def test_backstagepass_increases_by_3_when_less_than_6_days_left(self): items = [Item("Backstage passes to a TAFKAL80ETC concert", 5, 10)] gilded_rose = GildedRose(items) gilded_rose.update_quality() self.assertEquals(13, items[0].quality) def test_backstagepass_is_worthless_after_sell_by_date(self): items = [Item("Backstage passes to a TAFKAL80ETC concert", 0, 40)] gilded_rose = GildedRose(items) gilded_rose.update_quality() self.assertEquals(0, items[0].quality) def test_conjured_items_quality_decrease_by_2(self): items = [Item("Conjured", 10, 10)] gilded_rose = GildedRose(items) gilded_rose.update_quality() self.assertEquals(8, items[0].quality) def test_item_type_assigns_a_category(self): new_item = [ItemType("foo", 2, 10, "conjured")] #gilded_rose = GildedRose(items) #gilded_rose.update_quality() self.assertEquals("conjured", new_item[0].category) def test_item_type_inherits_from_type(self): new_item = [ItemType("foo", 2, 10, "conjured")] #gilded_rose = GildedRose(items) #gilded_rose.update_quality() self.assertEquals("foo", new_item[0].name) if __name__ == '__main__': unittest.main()
true
c461975f6f755f2e1d3b496ba7a9b172899b543c
Python
csjxsw/MyPythonProject
/leetcode/1_twosum/twosum.py
UTF-8
653
3.40625
3
[]
no_license
#!/usr/bin/env python # coding=utf-8 class Solution: def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ dict = {} numslen = len(nums) for index in range(numslen): num = nums[index] if num in dict: return [dict.get(num), index] else: dict[target-num] = index if __name__ == '__main__': #print ("------begin--------") s = Solution() num = [2, 7, 11, 15] target = 18 reults = s.twoSum(num, target) print reults #print ("------end--------")
true
be13f080f60a978d901545289a1caaac6de9f9be
Python
ATNF/yandasoft
/tests/data/simulation/synthregression/facetingtest.py
UTF-8
3,316
2.625
3
[ "MIT" ]
permissive
# regression tests of faceting # some fixed parameters are given in wtermtest_template.in from synthprogrunner import * def analyseResult(spr): ''' spr - synthesis program runner (to run imageStats) throws exceptions if something is wrong, otherwise just returns ''' src_offset = 0.006/math.pi*180. psf_peak=[-172.5,-45] true_peak=sinProjection(psf_peak,src_offset,src_offset) stats = spr.imageStats('image.field1.restored') print("Statistics for restored image: ",stats) disterr = getDistance(stats,true_peak[0],true_peak[1])*3600. if disterr > 8: raise RuntimeError("Offset between true and expected position exceeds 1 cell size (8 arcsec), d=%f, true_peak=%s" % (disterr,true_peak)) if abs(stats['peak']-1.)>0.3: raise RuntimeError("Peak flux in the image is notably different from 1 Jy, F=%f" % stats['peak']) stats = spr.imageStats('image.field1.facet.0.1') print("Statistics for modelimage: ",stats) disterr = getDistance(stats,true_peak[0],true_peak[1])*3600. if disterr > 8: raise RuntimeError("Offset between true and expected position exceeds 1 cell size (8 arcsec), d=%f, true_peak=%s" % (disterr,true_peak)) stats = spr.imageStats('psf.field1.facet.0.1') print("Statistics for psf image: ",stats) # 256 is facetstep of 512 divided by 2, cell is 4 arcsec facet_offset = 4.*256./3600. facet_psf_peak = sinProjection(psf_peak,facet_offset,facet_offset) disterr = getDistance(stats,facet_psf_peak[0],facet_psf_peak[1])*3600. if disterr > 8: raise RuntimeError("Offset between true and expected position exceeds 1 cell size (8 arcsec), d=%f, true_peak=%s" % (disterr,true_peak)) stats = spr.imageStats('psf.image.field1.facet.0.1') print("Statistics for preconditioned psf image: ",stats) disterr = getDistance(stats,facet_psf_peak[0],facet_psf_peak[1])*3600. if disterr > 8: raise RuntimeError("Offset between true and expected position exceeds 1 cell size (8 arcsec), d=%f, true_peak=%s" % (disterr,true_peak)) if abs(stats['peak']-1.)>0.01: raise RuntimeError("Peak flux in the preconditioned psf image is notably different from 1.0, F=%f" % stats['peak']) stats = spr.imageStats('weights.field1.facet.0.1') print("Statistics for weight image: ",stats) if abs(stats['rms']-stats['peak'])>0.1 or abs(stats['rms']-stats['median'])>0.1 or abs(stats['peak']-stats['median'])>0.1: raise RuntimeError("Weight image is expected to be constant for SphFunc gridder") stats = spr.imageStats('residual.field1.facet.0.1') print("Statistics for residual image: ",stats) if stats['rms']>0.01 or abs(stats['median'])>0.0001: raise RuntimeError("Residual image has too high rms or median. Please verify") spr = SynthesisProgramRunner(template_parset = 'facetingtest_template.in') spr.runSimulator() print("Testing faceting with overlap") spr.addToParset("Cimager.Images.shape = [1024,1024]") spr.addToParset("Cimager.Images.image.field1.facetstep = 512") spr.runImager() analyseResult(spr) print("Testing faceting with padding") spr.initParset() spr.addToParset("Cimager.Images.shape = [512,512]") spr.addToParset("Cimager.gridder.padding = 2") spr.runImager() analyseResult(spr) #clean up import os os.system("rm -rf *field1* temp_parset.in")
true
571a6bd975a54dc8fabeb8e4fc54d254544b6d7e
Python
AdamantLife/aldb2
/aldb2/SeasonCharts/sql.py
UTF-8
2,930
2.828125
3
[]
no_license
## This Module from aldb2.Core.sql import util from aldb2 import SeasonCharts from aldb2.SeasonCharts import gammut def gammut_main(connection, season = None, year = None, output = gammut.DEFAULTOUTPUT): """ Runs gammut's main function and then imports the results into the database. """ gammut.main(season = season, year = year, output = output) shows = SeasonCharts.load_serialized(output) def checktitle(title): """ subfunction for checking titles """ matches = getshowbytitle(connection,title = title) matches = [mat for mat in matches if mat['season'] == season and mat['year'] == year] ## This is a little obnoxious, but we'll just have to assume we're only going to get one match at this point if matches: return matches[0] for show in shows: match = None for title in [show.japanese_title,show.romaji_title,show.english_title]+show.additional_titles: match = checktitle(title) ## If we found a title, we can stop if match: break if not match: ## If no match, we add to database addshow(show) else: ## Otherwise, we update updatebyshow(connection, match['scshowid'],show) ################ SeasonCharts_Shows @util.row_factory_saver def getshowbytitle(connection, title): """ Gets shows with a matching title """ liketitle = f"%{title}%" shows = connection.execute(""" SELECT scshowid,animeseasonid,season,year,japanesetitle,romajititle,englishtitle,additionaltitles,medium,continuing,summary FROM "SeasonCharts_shows" WHERE japanesetitle =:title OR romajititle =:title OR englishtitle =:title OR additionaltitles LIKE :liketitle;""",dict(title = title, liketitle = liketitle)).fetchall() if not shows: return return [{"scshowid":show[0],"animeseasonid":show[1],"season":show[2],"year":show[3],"japanesetitle":show[4], "romajititle":show[5],"englishtitle":show[6],"additionaltitles":show[7],"medium":show[8],"continuing":show[9],"summary":show[10]} for show in shows] def addshow(connection,show): """ Adds a show object to the database """ connection.execute(""" INSERT INTO "SeasonCharts_shows" (season,year,japanesetitle,romajititle,englishtitle,additionaltitles,medium,continuing,summary) VALUES (:season,:year,:japanese_title,:romaji_title,:english_title:additionaltitles,:medium,:continuing,:summary);""", dict(season = show.season, year = show.year, japanese_title = show.japanese_title, english_title = show.english_title, additionaltitles = ", ".join(show.additional_titles), medium = show.medium, continuing = int(show.continuing), summary = show.summary)) def updatebyshow(connection,showid,show): """ Uses a show object to update a database entry """ connection.execute(""" UPDATE "SeasonCharts_shows" SET WHERE scshowid = :scshowid """)
true
792b0dff03d4e404dd1dbf6d541b01dd74f46ed3
Python
omkarmoghe/Scurvy
/MainMenu.py
UTF-8
4,924
3.1875
3
[]
no_license
from Globals import * # This represents a selectable item in the menu. class MenuItem(pygame.font.Font): def __init__(self, text, index, count, func): pygame.font.Font.__init__(self, menu_font, menu_item_font_size) self.text = text self.font_size = menu_item_font_size self.font_color = WHITE self.label = self.render(self.text, True, self.font_color) self.rect = self.label.get_rect() pos_x = (WIDTH / 2) - (self.rect.width / 2) pos_y = 200 + ((HEIGHT - 220) / count) * index self.rect.x = pos_x self.rect.y = pos_y self.func = func def is_mouse_selection(self, (pos_x, pos_y)): return self.rect.collidepoint(pos_x, pos_y) def set_selected(self, selected): if selected: self.font_color = BLACK else: self.font_color = WHITE self.label = self.render(self.text, True, self.font_color) class GameMenu(): def __init__(self, items): self.bg_color = BLACK self.clock = pygame.time.Clock() self.items = [] count = len(items) for index, item in enumerate(items): menu_item = MenuItem(item, index, count, items[item]) self.items.append(menu_item) self.mouse_is_visible = True self.cur_item = None def set_mouse_visibility(self): if self.mouse_is_visible: pygame.mouse.set_visible(True) else: pygame.mouse.set_visible(False) def set_keyboard_selection(self, key): for item in self.items: # Return all to neutral item.set_selected(False) if self.cur_item is None: self.cur_item = 0 else: # Find the chosen item if key == pygame.K_UP and \ self.cur_item > 0: self.cur_item -= 1 elif key == pygame.K_UP and \ self.cur_item == 0: self.cur_item = len(self.items) - 1 elif key == pygame.K_DOWN and \ self.cur_item < len(self.items) - 1: self.cur_item += 1 elif key == pygame.K_DOWN and \ self.cur_item == len(self.items) - 1: self.cur_item = 0 self.items[self.cur_item].set_selected(True) # Finally check if Enter or Space is pressed if key == pygame.K_SPACE or key == pygame.K_RETURN: pygame.mouse.set_visible(True) self.items[self.cur_item].func() pygame.display.set_caption(application_name) # If escape, quit. if key == pygame.K_ESCAPE: quit() def run(self): mainloop = True menu_background = pygame.image.load(menu_background_image) menu_background_rect = menu_background.get_rect() title_label = pygame.font.Font(menu_font, 100).render('{0}'.format(application_name), True, WHITE) title_rect = title_label.get_rect() title_rect.centerx = WIDTH * 1 / 2 title_rect.centery = HEIGHT * 1 / 5 boat_image = classic_ship_location + "PlayerShip337.5.png" # TODO: Make boat animation boat = pygame.image.load(boat_image) boat = pygame.transform.scale(boat, (menu_ship_scale, menu_ship_scale)) boat_rect = boat.get_rect() boat_rect.centerx = WIDTH * 4 / 5 boat_rect.centery = HEIGHT * 2 / 5 while mainloop: m_pos = pygame.mouse.get_pos() for event in pygame.event.get(): if event.type == pygame.QUIT: mainloop = False if event.type == pygame.KEYDOWN: self.mouse_is_visible = False self.set_keyboard_selection(event.key) if event.type == pygame.MOUSEBUTTONUP and event.button == LEFT: for item in self.items: if item.is_mouse_selection(m_pos): item.func() pygame.display.set_caption(application_name) if pygame.mouse.get_rel() != (0, 0): self.mouse_is_visible = True self.cur_item = None self.set_mouse_visibility() # Redraw the background screen.blit(menu_background, menu_background_rect) screen.blit(title_label, title_rect) screen.blit(boat, boat_rect) for item in self.items: if self.mouse_is_visible: set_mouse_selection(item, m_pos) screen.blit(item.label, item.rect) pygame.display.flip() def set_mouse_selection(item, m_pos): """Marks the MenuItem the mouse cursor hovers on.""" if item.is_mouse_selection(m_pos): item.set_selected(True) else: item.set_selected(False) # item.set_italic(False)
true
ca0f3a35fcd4fdc3ecbaa05a9af4e96cd2d38fe4
Python
Jacobo-Arias/Sistemas-Distribuidos
/servidores/socket_server1.py
UTF-8
588
3.0625
3
[]
no_license
import socket import time mi_socket = socket.socket() mi_socket.bind(('localhost',8000)) mi_socket.listen(1) conexion, addr = mi_socket.accept() print('Nueva conexion establecida') print (addr) solinombre = "Digame su nombre" conexion.send(solinombre.encode("ascii")) peticion = conexion.recv(1024) decodpeticion = peticion.decode("ascii") hora = time.strftime("%X") fecha = time.strftime("%x") envio = 'Hola '+ str(decodpeticion)+' usted ha ingresado el '+str(fecha)+' a las '+str(hora) conexion.send(envio.encode("ascii")) conexion.close() mi_socket.close()
true
722e465c200d8ca25e8a379f97408eb1ae04f839
Python
natdjaja/qbb2019-answers
/day4-homework/timecourse.py
UTF-8
2,217
2.84375
3
[]
no_license
#!/usr/bin/env python3 """ Usage ./02-timecourse.py <t_name> <samples.csv>, <FPKMs> Create a timecourse of a given transcript for females ./timecourse.py FBtr0331261 ~/qbb2019/data/samples.csv all.csv """ import sys import pandas as pd import matplotlib.pyplot as plt import os def get_fpkm_data(fpkms,columns): fpkms = fpkms.drop(fpkms.columns[list(columns)],axis=1) fpkms = fpkms.drop(columns="gene_name") return fpkms def get_replicate_fpkm_data(ctab_data_dir,metadata_file,sex_): fpkm = [ ] for i, line in enumerate(open(metadata_file)): if i == 0: continue fields = line.split(",") srr_id = fields[0] sex = fields[1] if sex != sex_: continue stage = fields[2] ctab_path = os.path.join(ctab_data_dir, srr_id, "t_data.ctab") # print(ctab_path) df = pd.read_csv(ctab_path, sep="\t", index_col="t_name") fpkm.append(df.loc["FBtr0331261","FPKM"]) return fpkm t_name = sys.argv[1] # tname samples = pd.read_csv(sys.argv[2])# samples csv fpkm_file = sys.argv[3] #all csv df = pd.read_csv(fpkm_file, index_col="t_name") fpkms1 = get_fpkm_data(df,range(9,17)) fpkms2 = get_fpkm_data(df,range(1,9)) samples = pd.read_csv(sys.argv[2]) #samples csv #fpkms = pd.read_csv(sys.argv[3], index_col="t_name") my_data = (fpkms1.loc[t_name,:]) my_data2 = (fpkms2.loc[t_name,:]) male_rep_data = get_replicate_fpkm_data(sys.argv[5],sys.argv[4],"male") female_rep_data = get_replicate_fpkm_data(sys.argv[5],sys.argv[4],"female") print(male_rep_data) print(female_rep_data) fig, ax = plt.subplots() ax.plot(range(8),my_data, color="blue", label='male') ax.plot(range(8),my_data2, color="red", label='female') ax.plot(range(4,8),male_rep_data,'x', color="blue") ax.plot(range(4,8),female_rep_data,'x', color="red") ax.set_title("Sxl") ax.set_xlabel("Developmental Expression") ax.set_xticks([0,1,2,3,4,5,6,7]) ax.set_xticklabels(['10', '11', '12', '13', '14A', '14B', '14C', '14D'], rotation=90) ax.set_ylabel("mRNA Abundance (FPKM)") plt.legend(loc='upper left') plt.show() fig.savefig("timecourse.png") plt.close(fig)
true
3fc51c0ec0b7f745d73fc906984bb7390db97e68
Python
anuchakradhar/python_starter
/variables.py
UTF-8
614
4.40625
4
[]
no_license
# A variable is a container for a value, which can be of various types ''' This is a multiline comment or docstring (used to define a functions purpose) can be single or double quotes ''' """ VARIABLE RULES: - Variable names are case sensitive (name and NAME are different variables) - Must start with a letter or an underscore - Can have numbers but can not start with one """ X = 1 #int y = 2.5 #float name = 'Anu' #Str is_Alive = True #bool #Multiple Assignment x, y, name, is_Alive = (1, 2.5, 'Anu', True) print("Hello World") print(x, y, name, is_Alive)
true
0c602cc27ac7276daef098d7813e9e7a108557d8
Python
chongminggao/WeChat_Big_Data_Challenge_DeepCTR-Torch_baseline_zsx
/mmoe1.py
UTF-8
5,498
2.640625
3
[]
no_license
import torch import torch.nn as nn from deepctr_torch.models.basemodel import BaseModel from deepctr_torch.inputs import combined_dnn_input from deepctr_torch.layers import DNN, PredictionLayer class MMOELayer(nn.Module): def __init__(self, input_dim, num_tasks, num_experts, output_dim, device, seed=6666): super(MMOELayer, self).__init__() self.num_experts = num_experts self.num_tasks = num_tasks self.output_dim = output_dim self.seed = seed w = torch.Tensor(torch.rand(input_dim, self.num_experts * self.output_dim)) torch.nn.init.normal_(w) self.expert_kernel = nn.Parameter(w).to(device) self.gate_kernels = [] for i in range(self.num_tasks): w = torch.Tensor(torch.rand(input_dim, self.num_experts)) torch.nn.init.normal_(w) self.gate_kernels.append(nn.Parameter(w).to(device)) def forward(self, inputs): outputs = [] expert_out = torch.mm(inputs, self.expert_kernel) expert_out = torch.reshape(expert_out, (-1, self.output_dim, self.num_experts)) for i in range(self.num_tasks): gate_out = torch.mm(inputs, self.gate_kernels[i]) gate_out = torch.nn.functional.softmax(gate_out, dim=1) gate_out = torch.unsqueeze(gate_out, dim=1).repeat(1, self.output_dim, 1) output = torch.sum(torch.mul(expert_out, gate_out), dim=2) outputs.append(output) return outputs class MMOE(BaseModel): """Instantiates the Multi-gate Mixture-of-Experts architecture. :param dnn_feature_columns: An iterable containing all the features used by deep part of the model. :param num_tasks: integer, number of tasks, equal to number of outputs, must be greater than 1. :param tasks: list of str, indicating the loss of each tasks, ``"binary"`` for binary logloss, ``"regression"`` for regression loss. e.g. ['binary', 'regression'] :param num_experts: integer, number of experts. :param expert_dim: integer, the hidden units of each expert. :param dnn_hidden_units: list,list of positive integer or empty list, the layer number and units in each layer of shared-bottom DNN :param l2_reg_embedding: float. L2 regularizer strength applied to embedding vector :param l2_reg_dnn: float. L2 regularizer strength applied to DNN :param init_std: float,to use as the initialize std of embedding vector :param task_dnn_units: list,list of positive integer or empty list, the layer number and units in each layer of task-specific DNN :param seed: integer ,to use as random seed. :param dnn_dropout: float in [0,1), the probability we will drop out a given DNN coordinate. :param dnn_activation: Activation function to use in DNN :param dnn_use_bn: bool. Whether use BatchNormalization before activation or not in DNN :param device: str, ``"cpu"`` or ``"cuda:0"`` :return: A PyTorch model instance. """ def __init__(self, dnn_feature_columns, num_tasks, tasks, num_experts=4, expert_dim=8, dnn_hidden_units=(128, 128), l2_reg_embedding=1e-5, l2_reg_dnn=0, init_std=0.0001, task_dnn_units=None, seed=1024, dnn_dropout=0, dnn_activation='relu', dnn_use_bn=False, device='cpu'): super(MMOE, self).__init__(linear_feature_columns=[], dnn_feature_columns=dnn_feature_columns, l2_reg_embedding=l2_reg_embedding, seed=seed, device=device) if num_tasks <= 1: raise ValueError("num_tasks must be greater than 1") if len(tasks) != num_tasks: raise ValueError("num_tasks must be equal to the length of tasks") for task in tasks: if task not in ['binary', 'regression']: raise ValueError("task must be binary or regression, {} is illegal".format(task)) self.tasks = tasks self.task_dnn_units = task_dnn_units self.dnn = DNN(self.compute_input_dim(dnn_feature_columns), dnn_hidden_units, activation=dnn_activation, l2_reg=l2_reg_dnn, dropout_rate=dnn_dropout, use_bn=dnn_use_bn, init_std=init_std, device=device) self.mmoe_layer = MMOELayer(dnn_hidden_units[-1], num_tasks, num_experts, expert_dim, device) if task_dnn_units is not None: self.task_dnn = nn.ModuleList([DNN(expert_dim, dnn_hidden_units) for _ in range(num_tasks)]) self.tower_network = nn.ModuleList([nn.Linear(expert_dim, 1, bias=False) for _ in range(num_tasks)]) self.out = nn.ModuleList([PredictionLayer(task) for task in self.tasks]) self.to(device) def forward(self, X): sparse_embedding_list, dense_value_list = self.input_from_feature_columns(X, self.dnn_feature_columns, self.embedding_dict) dnn_input = combined_dnn_input(sparse_embedding_list, dense_value_list) dnn_output = self.dnn(dnn_input) mmoe_outs = self.mmoe_layer(dnn_output) if self.task_dnn_units is not None: mmoe_outs = [self.task_dnn[i](mmoe_out) for i, mmoe_out in enumerate(mmoe_outs)] task_outputs = [] for i, mmoe_out in enumerate(mmoe_outs): logit = self.tower_network[i](mmoe_out) output = self.out[i](logit) task_outputs.append(output) task_outputs = torch.cat(task_outputs, -1) return task_outputs
true
aae019536a269639765ec5d75a9f2bd1555bafa8
Python
FaustinCarter/Labber_Drivers
/MagCycle_Relay/MagCycle_Relay.py
UTF-8
2,559
2.796875
3
[]
no_license
import numpy as np import PyDAQmx as mx import InstrumentDriver class Driver(InstrumentDriver.InstrumentWorker): def performSetValue(self, quant, value, sweepRate=0.0, options={}): """Create task, set value, close task.""" if quant.name == 'Relay Position': if value == 'Mag Cycle': channel = 'ADR_DIO/port2/line6' elif value == 'Regulate': channel = 'ADR_DIO/port2/line7' else: assert False, "Error, bad value" #Create a new task writeChan = mx.Task() writeChan.CreateDOChan(channel, '', mx.DAQmx_Val_ChanPerLine) setVal0 = np.array([0], dtype=np.uint8) setVal1 = np.array([1], dtype=np.uint8) sampsPer = mx.int32() #Send a 100 ms pulse to the appropriate channel (0 is on) writeChan.WriteDigitalLines(1, mx.bool32(True), 0, mx.DAQmx_Val_GroupByScanNumber, setVal0, mx.byref(sampsPer), None) self.wait(0.1) #Set it back to low (1 is off) writeChan.WriteDigitalLines(1, mx.bool32(True), 0, mx.DAQmx_Val_GroupByScanNumber, setVal1, mx.byref(sampsPer), None) #Memory Management! writeChan.ClearTask() else: assert False, "Requesting unknown quantity" return value def performGetValue(self, quant, options={}): """Create task, get value, close task.""" if quant.name == 'Relay Position': #Create some values to put things in retVal = np.zeros(2, dtype=np.uint8) sampsPer = mx.int32() numBytesPer = mx.int32() #Create a new task readChan = mx.Task() readChan.CreateDIChan('ADR_DIO/port2/line4:5', '', mx.DAQmx_Val_ChanPerLine) #This does the measurement and updates the values created above readChan.ReadDigitalLines(1, 0, mx.DAQmx_Val_GroupByScanNumber, retVal, 2, mx.byref(sampsPer), mx.byref(numBytesPer), None) #Memory management! readChan.ClearTask() assert not all(retVal) and any(retVal), "Both channels should not be the same!" if all(retVal == [0,1]): value = "Mag Cycle" elif all(retVal == [1,0]): value = "Regulate" else: assert False, "Error: unexpected value returned "+repr(retVal) else: assert False, "Error: Unknown quantity" return value
true
696bffa941af936e86c3115b1495c4ef30fdf6f6
Python
Harrisonyong/ChartRoom-For-Python
/chartroom_service.py
UTF-8
1,938
2.96875
3
[]
no_license
""" author:harrisonyong email:122023352@qq.com time:2020-08-20 env:python3.6 socket and epoll """ from socket import * from select import * HOST = "0.0.0.0" POST = 8000 ADDR = (HOST, POST) # 服务端套接字启动,采用epoll方法进行监听 sockfd = socket() sockfd.setblocking(False) sockfd.bind(ADDR) sockfd.listen(5) # epoll方法监听 ep = epoll() ep.register(sockfd) map = {sockfd.fileno():sockfd} usr = {} # 循环监听客户端连接进行处理 class Chart(): def __init__(self,connfd,addre,name = None): self.connfd = connfd self.addre = addre self.name = name def join(self,index): if index[0] == "NAME": for n in usr.values(): if n.name == index[1]: self.connfd.send(b"Fail") return else: self.name = index[1] self.connfd.send(b"ok") def start(self): while True: data = self.connfd.recv(1024*10).decode() index = data.split(" ",1) print(index) self.join(index) def main(): # 循环监听触发事件 while True: events = ep.poll() for fileno,event in events: # 判断连接事件 if map[fileno] == sockfd: connfd,addre = sockfd.accept() print("connect is",addre) connfd.setblocking(False) ep.register(connfd) map[connfd.fileno()] = connfd # 存储连接客户端对象,对象中包含客户端信息和客户端使用方法 usr[connfd.fileno()] = Chart(connfd,addre) else: # 如果客户端连接,启动客户端处理类进行处理 try: usr[fileno].start() except BlockingIOError: continue if __name__ == '__main__': main()
true
53266a4b26a11989a673f1af69e628616d3fe09d
Python
Ampersandnz/UnifyIdCodingChallenge
/GenerateImage.py
UTF-8
3,518
3.03125
3
[]
no_license
from urllib import request, parse from urllib.error import HTTPError, URLError from socket import timeout from PIL import Image # HTTP request timeout, in seconds. TIMEOUT = 300 # Can request a maximum of 10,000 numbers at a time via the API, so loop and split the request until we have enough MAX_NUMBERS_IN_REQUEST = 10000 WIDTH = 128 HEIGHT = 128 class APIRequest: def __init__(self, base_url, params): self.base_url = base_url self.params = params def get_url(self): return self.base_url + '?' + parse.urlencode(self.params) def main(): # Random.org's API has a quota of how much data you're allowed to use. If exceeded, all requests will return 503 if check_quota(): print('Quota is fine, proceeding with image generation') generate_random_image(WIDTH, HEIGHT) else: print('Quota exceeded, not sending a request') def generate_random_image(width, height): print('Generating a random image of size ' + str(width) + 'x' + str(height)) num_pixels = width * height # Generate three random values per pixel in the image raw_values = generate_int_values(0, 255, num_pixels * 3) # Split the response array into three equal sets r_values = raw_values[:num_pixels] g_values = raw_values[num_pixels:num_pixels * 2] b_values = raw_values[num_pixels * 2:] image = Image.new('RGB', (width, height)) raw_pixels = image.load() n = 0 # Iterate over all pixels in the image, setting their RGB values for i in range(image.size[0]): for j in range(image.size[1]): raw_pixels[i, j] = (r_values[n], g_values[n], b_values[n]) #TODO: Add alpha channel? n += 1 # Display the generated image and write it to a file on disk image.show() image.save('Output.bmp', 'bmp') def generate_int_values(rand_min, rand_max, num_to_generate): output = '' while num_to_generate != 0: num_to_request = num_to_generate if num_to_generate < MAX_NUMBERS_IN_REQUEST else MAX_NUMBERS_IN_REQUEST print('Requesting ' + str(num_to_request) + ' random integers') response = send_request(APIRequest('https://www.random.org/integers/', {'min': str(rand_min), 'max': str(rand_max), 'num': str(num_to_request), 'col': '1', 'format': 'plain', 'base': '10', 'rnd': 'new'})) output = output + ' ' + response num_to_generate -= num_to_request return list(map(int, output.split())) # Returns the count of how many bits I'm still allowed to request today def check_quota(): response = send_request(APIRequest('https://www.random.org/quota/', {'format': 'plain'})) decoded = int(response) return decoded > 0 # Considered doing this asynchronously, but there's no point at the moment # since the tool can't do anything until it hears back anyway def send_request(req): try: return request.urlopen(req.get_url(), timeout=TIMEOUT).read().decode('utf-8') except (HTTPError, URLError) as error: print('Request for ' + req.get_url() + ' caused an error!\n' + str(error)) except timeout: print('Request for ' + req.get_url() + ' timed out!') if __name__ == '__main__': main()
true
f07cd2a623d18d6fdeedb91c03cc832d928d7483
Python
anshajk/covid-vaccinations
/vaccinations.py
UTF-8
1,940
2.890625
3
[ "MIT" ]
permissive
import streamlit as st import urllib import pandas as pd import altair as alt def get_vaccination_data(): DATA_URL = "https://raw.githubusercontent.com/owid/covid-19-data/master/public/data/vaccinations/vaccinations.csv" df = pd.read_csv(DATA_URL) df["date"] = pd.to_datetime(df["date"]) df["date"] = df["date"].dt.date return df st.title("Covid19 vaccination and infection data") try: df = get_vaccination_data() selected_locations = st.multiselect( "Select countries", df["location"].unique().tolist(), default=["India"], ) if len(selected_locations) > 5: st.warning( "Please select a maximum of 5 locations while comparing to see the results clearly" ) df = df[df["location"].isin(selected_locations)] daily_vaccination_chart = ( alt.Chart(df) .mark_line() .encode( x=alt.X("date:T", axis=alt.Axis(title="Date")), y=alt.X("daily_vaccinations:Q", axis=alt.Axis(title="Daily vaccinations")), tooltip=["date", "daily_vaccinations"], color="location", ) .interactive() .properties(width=800, height=400) ) st.header("Daily covid19 vaccination count") st.write(daily_vaccination_chart) daily_vaccination_chart = ( alt.Chart(df) .mark_line() .encode( x=alt.X("date:T", axis=alt.Axis(title="Date")), y=alt.X("daily_vaccinations:Q", axis=alt.Axis(title="Daily vaccinations")), tooltip=["date", "daily_vaccinations"], color="location", ) .interactive() .properties(width=800, height=400) ) except urllib.error.URLError as e: st.error( """ **This demo requires internet access.** Connection error: %s """ % e.reason ) st.text("Data courtesy: Our world in data - https://ourworldindata.org/coronavirus")
true
30e3ba6f1dc61c7816386bd7d896ec5ad5cac528
Python
Sorade/Forest_level_Potion
/classes.py
UTF-8
79,910
2.953125
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Sat Apr 23 10:35:10 2016 @author: Julien """ import pygame, sys, random import functions as fn import variables as var from pygame.locals import * import itertools import numpy as np from operator import attrgetter '''shadow casting imports''' import PAdLib.shadow as shadow import PAdLib.occluder as occluder class spritesheet(object): def __init__(self, filename): try: self.sheet = pygame.image.load(filename).convert_alpha() except pygame.error, message: print 'Unable to load spritesheet image:', filename raise SystemExit, message # Load a specific image from a specific rectangle def image_at(self, rectangle, colorkey = None): "Loads image from x,y,x+offset,y+offset" rect = pygame.Rect(rectangle) image = pygame.Surface(rect.size).convert() image.set_colorkey((0,0,0)) image.blit(self.sheet, (0, 0), rect) #var.screen.blit(self.sheet, (0,0), rect) # if colorkey is not None: # if colorkey is -1: # colorkey = image.get_at((0,0)) # image.set_colorkey(colorkey, pygame.RLEACCEL) return image # Load a whole bunch of images and return them as a list def images_at(self, rects, colorkey = None): "Loads multiple images, supply a list of coordinates" return [self.image_at(rect, colorkey) for rect in rects] # Load a whole strip of images # def load_strip(self, rect, image_count, colorkey = None): # "Loads a strip of images and returns them as a list" # tups = [(rect[0]+rect[2]*x, rect[1], rect[2], rect[3]) # for x in range(image_count)] # return self.images_at(tups, colorkey) def load_strip(self,spacing, rect, image_count, colorkey = None): "Loads a strip of images and returns them as a list" # tups = [(rect[0]+rect[2]*x, rect[1], rect[2], rect[3]) # for x in range(image_count)]: tups = [] for x in range(image_count): if x != 0: tups += [(rect[0]+(rect[2]+spacing)*x, rect[1], rect[2], rect[3])] else: tups += [(rect[0]+rect[2]*x, rect[1], rect[2], rect[3])] return self.images_at(tups, colorkey) class SpriteStripAnim(object): """sprite strip animator This class provides an iterator (iter() and next() methods), and a __add__() method for joining strips which comes in handy when a strip wraps to the next row. """ def __init__(self, filename, spacing, rect, count, colorkey=None, loop=False, frames=1): """construct a SpriteStripAnim filename, rect, count, and colorkey are the same arguments used by spritesheet.load_strip. loop is a boolean that, when True, causes the next() method to loop. If False, the terminal case raises StopIteration. frames is the number of ticks to return the same image before the iterator advances to the next image. """ #self.filename = filename #ss = spritesheet(filename) ss = filename self.images = ss.load_strip(spacing, rect, count, colorkey) self.i = 0 self.loop = loop self.frames = frames self.f = frames def iter(self): self.i = 0 self.f = self.frames return self def next(self): if self.i >= len(self.images): if not self.loop: raise StopIteration else: self.i = 0 image = self.images[self.i] self.f -= 1 if self.f == 0: self.i += 1 self.f = self.frames return image def __add__(self, ss): self.images.extend(ss.images) return self class Level(object): def __init__(self, lvl_num): var.current_level = self var.level_list.append(self) self.do_once = True self.lvl_num = lvl_num self.run = False #create sprite groups self.player_list = pygame.sprite.Group() self.char_list = pygame.sprite.Group() self.ennemi_list = pygame.sprite.Group() self.item_list = pygame.sprite.Group() self.building_list = pygame.sprite.Group() self.projectile_list = pygame.sprite.Group() self.projectile_ennemy_list = pygame.sprite.Group() self.all_sprites_list = pygame.sprite.Group() self.deleted_list = pygame.sprite.Group() self.dead_sprites_list = pygame.sprite.Group() self.message_list = pygame.sprite.Group() self.to_blit_list = pygame.sprite.Group() self.sprite_group_list = [] self.sprite_group_list.extend([self.player_list,self.char_list, self.projectile_list, self.dead_sprites_list, self.ennemi_list, self.item_list,self.building_list, self.all_sprites_list, self.to_blit_list, self.deleted_list]) def assign_occluders(self,iterator): '''assigning occluders to shadow sources''' '''get's all the occluders in the level''' lvl_occluders = [o.occlude for o in self.building_list if isinstance(o,Building)] '''loops through all shadow object in the level and set the lvl_occluders to it''' for light in [x for x in iterator if isinstance(x, Illuminator)]: light.source.set_occluders(lvl_occluders) def assign_radius(self,iterator): for light in [x for x in iterator if isinstance(x, Illuminator)]: light.source.set_radius(float(light.radius)) def go_to(self,new_lvl, pair): '''change level''' new_level = var.level_list[new_lvl-1] paired_portal_list = [y for y in [x for x in new_level.all_sprites_list if isinstance (x,Level_Change)] if y.pair == pair] if len(paired_portal_list) > 0: player = [x for x in self.player_list][0] self.run = False player.level = new_level new_level.run = True var.current_level = new_level dest_port = random.choice(paired_portal_list) #select a random destination amongst the paired portals refx = dest_port.rect.bottomright[0]-var.screenWIDTH/2 refy = dest_port.rect.bottomright[1]+50-var.screenHEIGHT/2 for sprite in new_level.all_sprites_list: sprite.rect = sprite.rect.move(-refx,-refy) new_level.scroll_map.rect = new_level.scroll_map.rect.move(-refx,-refy) player.rect.center = (var.screenWIDTH/2,var.screenHEIGHT/2) player.dest = player.rect.topleft def execute(self): var.current_level = self [x for x in self.player_list][0].level = self [x for x in self.player_list][0].check_lvlup() #random obstacles def add_obstacles(self,int,obs_list): count = 0 while count < 75: choice = random.choice(obs_list) choice = choice if random.randint(0,1) == 1 else pygame.transform.flip(choice, True, False) w = Building('obstacles',0,choice,random.randint(25,1800),random.randint(75,1800),1000) old_rect = w.rect w.rect = w.rect.inflate(150,150) test = pygame.sprite.spritecollideany(w, self.all_sprites_list, collided = None) if test is None: w.rect = old_rect self.building_list.add(w) self.all_sprites_list.add(w) count += 1 #Random ennemies def add_ennemies(self,int,list): count = 0 while count < 10: #number of wanted enemies o = random.choice(list)(random.randint(450,1500),random.randint(450,1000)) if random.randint(0,1) == 1: o.equipement.contents.append(Potion(random.randint(7,10),random.randint(-10,20))) test = pygame.sprite.spritecollideany(o, self.all_sprites_list, collided = None) if test is None: count += 1 self.char_list.add(o) self.ennemi_list.add(o) self.all_sprites_list.add(o) for item in o.equipement.contents: self.all_sprites_list.add(item) for item in o.inventory.contents: self.all_sprites_list.add(item) #random objects def add_chests(self,int,chest,obj): count = 0 while count < int: collides = False chest_contents = [] for n in range(0,random.randint(1,3)): chest_contents.append(random.choice(obj)) pos = Rect(random.randint(50,var.background.get_rect()[2]),random.randint(80,var.background.get_rect()[3]),var.chest_img.get_rect().width,var.chest_img.get_rect().height) w = chest(0,0, chest_contents) w.rect = pos for c in self.all_sprites_list: if isinstance(c,chest) and w.rect.colliderect((c.rect.inflate(750,750))) == True: collides = True break test = pygame.sprite.spritecollideany(w, self.all_sprites_list, collided = None) if test is None and collides == False: self.building_list.add(w) self.all_sprites_list.add(w) for item in w.inventory.contents: self.all_sprites_list.add(item) count +=1 class StatsMenu(Level): def __init__(self): self.run = False self.rain_y = -600 self.do_once = True def execute(self,new_level,character): if character.level.run == True: character.level.run = False self.run = True while self.run == True: if self.do_once == True: self.do_once = False exit_reset = False validate_but = Button('Validate', 50,550,75,50) x, y = 50, 50 accessible_list = [] unaccessible_list = [] ini_skill_num = 0 for skill in character.skills: '''makes the button and binds the skill to it''' b = Button(skill.name, x,y,75,50) y += 50 if y >= 400: x+= 120 y = 50 b.binded = skill is_accessible = True '''check if skills requiers other skills if it does, checks if the player has the skills, if he does the skill remains accessible, otherwise it become unaccessible''' if skill.has == True: #player already has the skill and can't remove it is_accessible = False b.selected = True b.txt_color = (0,200,0) ini_skill_num += 1 elif skill.pre_req is not None: for v in skill.pre_req: ls = [s for s in character.skills if isinstance(s,type(v))] if ls[0].has == False:#player doesn't possess the skill is_accessible = False break '''based on wether the skill is accessible or not assigns it to a list''' if is_accessible == True: accessible_list.append(b) else: #if unaccessible unaccessible_list.append(b) if skill.has == False: b.txt_color = (120,120,120) for event in pygame.event.get(): #setting up quit if event.type == QUIT: pygame.quit() sys.exit() print 'has quit' '''Background of menu''' var.screen.blit(var.inv_bg,(0,0)) '''compute number of selected buttons''' num_selected = len([skill for skill in character.skills if skill.has == True]) '''Menu buttons''' for b in itertools.chain(accessible_list,unaccessible_list): if character.level_up_pts > 0 and (b in accessible_list) == True: b.check_select() if num_selected-ini_skill_num >= character.level_up_pts: b.txt_color = (0,0,0) b.selected = False #extracts the skills from the Character wich match the binded item gen = (s for s in character.skills if isinstance(s,type(b.binded))) if b.selected == True: for x in gen: x.has = True else: for x in gen: x.has = False b.display() #new for loop needed to blit over labels for b in itertools.chain(accessible_list,unaccessible_list): if pygame.mouse.get_pressed()[2] == False and b.rect.collidepoint(pygame.mouse.get_pos()): b.binded.tooltip(b.rect.topright) validate_but.check_select() validate_but.display() '''skill details''' m_pos = pygame.mouse.get_pos() r_click = pygame.mouse.get_pressed()[2] for b in itertools.chain(accessible_list,unaccessible_list): if b.rect.collidepoint(m_pos) and r_click == True: '''blits a semi-transparent overlay over the menu''' alpha_overlay = var.inv_bg alpha_overlay.set_alpha(200) var.screen.blit(alpha_overlay,(0,0)) '''Gets the lists of aval and amont skills of the right clicked skill''' aval_ls = fn.get_skills_aval(character.skills,b) if b.binded.pre_req is not None: amount_ls = b.binded.pre_req else: amount_ls = [] '''displays the skills amount aval''' fn.display_x(amount_ls, Button, var.screenHEIGHT/3) fn.display_x(aval_ls, Button, var.screenHEIGHT/3*2) main_but = Button(b.binded.name,var.screenWIDTH/2-b.rect.width/2,var.screenHEIGHT/2,0,0) main_but.display() break if validate_but.selected == True: self.do_once = True if ini_skill_num < num_selected: character.level_up_pts -= (num_selected-ini_skill_num) if pygame.key.get_pressed()[pygame.K_s] == False: exit_reset = True if exit_reset == True and pygame.key.get_pressed()[pygame.K_s] == True: self.run = False self.do_once = True if ini_skill_num < num_selected: character.level_up_pts -= (num_selected-ini_skill_num) new_level.run = True new_level.do_once = True print 'leave menu' pygame.display.update() class Lifebar(object): def __init__(self,character): '''make black circle mask''' mask = pygame.Surface((156,165)) mask.fill((255,255,255)) # circle(Surface, color, pos, radius, width=0) pygame.draw.circle(mask, (0,0,0), mask.get_rect().center, 82,0) mask.set_colorkey((255,255,255)) mask_h = 165-int(character.hp*165.0/character.hp_max) '''get the hud''' var.screen.blit(var.hp_hud,(0,var.screenHEIGHT-188)) #188 is the height of the hud image var.screen.blit(mask,(0+112,var.screenHEIGHT-188+8),(0,0,mask.get_rect().width,mask_h))#144,2 are the x and y of the mask compared to the hud var.screen.blit(var.hp_partial_hud,(0,var.screenHEIGHT-188)) #188 is the height of the hud image class HUDbar(object): def __init__(self,character): '''get the hud''' image = var.bar_hud rect = image.get_rect() rect.midbottom = (var.screenWIDTH/2,var.screenHEIGHT) image = image rect = rect '''checks for weapons to display''' weapon = max([y for y in character.equipement.contents if isinstance (y,Weapon)], key=attrgetter('dmg')) '''blits bar''' var.screen.blit(image,rect.topleft) '''blits weapon onto bar''' icon_slot_center = (306+31,6+30) icon_slot_blit_pos = fn.tulpe_scale(icon_slot_center,(-weapon.icon.get_rect().height/2,-weapon.icon.get_rect().width/2)) var.screen.blit(weapon.icon,fn.tulpe_scale(rect.topleft,icon_slot_blit_pos)) class MySprite(pygame.sprite.Sprite): def __init__(self,image,x,y): # Call the parent class (Sprite) constructor super(MySprite, self).__init__() self.image = image self.rect = self.image.get_rect().move(x, y) #initial placement self.top_cp = (self.rect[0]+self.rect[2]/2,self.rect[1]) self.bot_cp = (self.top_cp[0],self.rect[1]+self.rect[3]) self.left_cp = (self.rect[0],self.rect[1]+self.rect[3]/2) self.right_cp = (self.left_cp[0]+self.rect[2],self.left_cp[1]) self.center = self.rect.center self.pos = self.rect.topleft self.blit_order = 1 self.level = var.current_level #Level(1)#level to which sprite belongs self.blit_order = 0 def pop_around(self,item,xzone,yzone): collides = True while collides == True: item.rect = Rect((random.randint(self.rect.x-xzone,self.rect.x+self.rect.width+xzone),random.randint(self.rect.y-yzone,self.rect.y+self.rect.height+yzone)),(item.rect.width,item.rect.height)) for c in self.level.all_sprites_list: if c.rect.inflate(-5,-5).collidepoint(item.rect.center) == False and self.rect.inflate(xzone,yzone).contains(item.rect) == True: collides = False break return item.rect def highlight(self): pygame.draw.circle(var.screen, (255,0,0,80), self.rect.center, 20, 0) def delete(self): for group in self.level.sprite_group_list: #removes sprites from all groups if self in group: group.remove(self) print 'sprite deleted' print self.level.item_list self.level.deleted_list.add(self) #adds the sprite to deleted list class Character(MySprite): def __init__(self, hp, walk_images, attack_images, speed, x, y, CC, CT): self.walk_images = walk_images self.attack_images = attack_images self.image_list = self.attack_images[0] self.image = self.image_list[0] self.dead_image = var.dead_ennemi if random.randint(0,1) == 0 else pygame.transform.flip(var.dead_ennemi, True, False) # Call the parent class (Sprite) constructor super(Character, self).__init__(self.image,x,y) self.speed = int(speed) self.hp_max = hp self.hp = hp self.dest = (self.rect[0],self.rect[1]) self.move_speed = self.speed self.inventory = Inventory() self.equipement = Inventory() '''Experience''' self.xp = 0 self.lvlup_threshold = 100 self.totalxp = 0 self.xp_reward = 100 self.skill_lvl = 1 self.level_up_pts = 0 '''stats''' self.stats_menu = StatsMenu() self.skills = [Sniper(), Fast_shooter(), Power_shot(), Power_blow(), Ambidextrous(), Duelist(), Chain_attack()] self.CC = CC self.CT = CT self.attack_time = pygame.time.Clock() self.attack_time_left = 0 self.attack_speed = 750 self.flee_test = True self.E = 35 self.F = 30 '''anim timer''' self.anim_time = pygame.time.Clock() self.anim_time_left = 0 self.anim_speed = 100 self.anim_counter = 0 self.orientation = 0 self.has_attack = False self.anim_shot = False '''setting dest timer''' self.dest_time = pygame.time.Clock() self.dest_time_left = 0 self.dest_speed = 2000 '''Mvt timer''' self.mvt_time = pygame.time.Clock() self.mvt_time_left = 0 self.mvt_speed = int(1000/(var.FPS*0.7)) self.is_moving = False '''inventory opening attributes''' self.do_once = True self.buttons_list = [] self.selected_button = 0 self.selected = False self.start_pos = (0,0) self.inventory_opened = False self.m_down = False self.m_up = True self.inv_time = pygame.time.Clock() self.inv_time_left = 0 self.inv_delay = 400 @property def skill_lvl(self): return self._skill_lvl @skill_lvl.setter def skill_lvl(self, skill_lvl): self.lvlup_threshold = (skill_lvl)*100+(skill_lvl)**3 self.totalxp += self.xp self.xp = 0 self._skill_lvl = skill_lvl def check_lvlup(self): dxp = self.xp - self.lvlup_threshold if dxp >= 0: self.skill_lvl += 1 self.xp = dxp #to transfer excess xp self.level_up_pts += 1 print 'Reached Level {}'.format(self.skill_lvl) def merge_ammo(self): self.inventory.combine_ammo() #merges all the ammo in the inventory only '''merges the ammo from inv with equipped ammo''' inv_projs = [x for x in self.inventory.contents if isinstance (x,Projectile)] equiped = [y for y in self.equipement.contents if isinstance (y,Projectile)] if len(equiped) > 0: equiped = equiped[0] for proj in inv_projs: if type(equiped) == type(proj): equiped.ammo += proj.ammo self.inventory.contents.remove(proj) # equiped.name = '{} {}'.format(equiped.ammo,equiped.raw_name) def anim_move(self): #updates anim timer self.anim_time.tick() self.anim_time_left += self.anim_time.get_time() #checks which anim to display based on the direction and if sprite is moving and alive if self.anim_time_left >= self.anim_speed and self.is_alive() == True: #checks time to animate if self.orientation >= 140 and self.orientation <= 220: #checks orientation if self.anim_counter >= 4: self.anim_counter = 0 self.image = self.image_list[self.anim_counter] if self.pos == self.rect.topleft:# and self.has_attack == False: self.image = self.image_list[0] elif self.orientation >= 220 and self.orientation <= 320: #checks orientation if self.anim_counter >= 4: self.anim_counter = 0 self.image =self.image_list[self.anim_counter+4] if self.pos == self.rect.topleft:# and self.has_attack == False: self.image = self.image_list[4] elif self.orientation >= 320 or self.orientation <= 40: #checks orientation if self.anim_counter >= 4: self.anim_counter = 0 self.image = self.image_list[self.anim_counter+8] if self.pos == self.rect.topleft:# and self.has_attack == False: self.image = self.image_list[8] elif self.orientation >= 40 and self.orientation <= 140: #checks orientation if self.anim_counter >= 4: self.anim_counter = 0 self.image = self.image_list[self.anim_counter+12] if self.pos == self.rect.topleft:# and self.has_attack == False: self.image = self.image_list[12] self.anim_time_left = 0 self.anim_counter += 1 def get_dest(self): self.dest = pygame.mouse.get_pos() #mouse position tracker new_x = self.dest[0]-self.image.get_rect()[2] #adds offset to center player new_y = self.dest[1]-self.image.get_rect()[3] #adds offset to center player self.dest = (new_x,new_y) xp = self.rect.x yp = self.rect.y #print xp,yp xm = self.dest[0] ym = self.dest[1] var.dx = xm-xp var.dy= ym-yp def get_offset(self): speed = self.speed #player's speed xp = self.rect.x#(var.screenWIDTH/2)-(self.image.get_rect()[2]/2.) yp = self.rect.y#(var.screenHEIGHT/2)-(self.image.get_rect()[3]/2.) #print xp,yp xm = self.dest[0] ym = self.dest[1] dx = float(xm-xp) dy = float(ym-yp) #dist = (var.dx**2+var.dy**2)**0.5 #get lenght to travel #calculates angle and sets quadrant if dx == 0 or dy == 0: angle_rad = 0#np.pi/2 if dx == 0 and ym > yp: xoffset = 0 yoffset = -speed self.orientation = 180 elif dx == 0 and ym < yp: xoffset = 0 yoffset = speed self.orientation = 0 elif dy == 0 and xm > xp: xoffset = 0 yoffset = -speed self.orientation = 90 elif dy == 0 and xm < xp: xoffset = 0 yoffset = speed self.orientation = 270 else: xoffset, yoffset = 0,0 self.orientation = 180 elif xm > xp and ym > yp: angle_rad = np.arctan((abs(dy)/abs(dx))) xoffset = -np.cos(angle_rad)*speed yoffset = -np.sin(angle_rad)*speed self.orientation = angle_rad*(180.0/np.pi)+90 elif xm < xp and ym > yp: angle_rad = np.arctan((abs(dx)/abs(dy))) xoffset = np.sin(angle_rad)*speed yoffset = -np.cos(angle_rad)*speed self.orientation = angle_rad*(180.0/np.pi)+180 elif xm < xp and ym < yp: angle_rad = np.arctan((abs(dy)/abs(dx))) xoffset = np.cos(angle_rad)*speed yoffset = np.sin(angle_rad)*speed self.orientation = angle_rad*(180.0/np.pi)+270 else:# xm > xp and ym < yp: angle_rad = np.arctan((abs(dx)/abs(dy))) xoffset = -np.sin(angle_rad)*speed yoffset = np.cos(angle_rad)*speed self.orientation = angle_rad*(180.0/np.pi) var.xoffset = int(xoffset) var.yoffset = int(yoffset) if var.dx <= 3 and var.dx >= -3: var.dx = 0 var.xoffset = 0 if var.dy <= 3 and var.dy >= -3: var.dy = 0 var.yoffset = 0 if var.has_shot == True: var.dy, var.dx = 0,0 var.yoffset, var.xoffset = 0,0 var.has_shot = False self.anim_shot = True def open_inventory(self): while self.inventory_opened == True: var.screen.blit(self.inventory.inv_bg, self.inventory.inv_bg.get_rect()) if self.do_once == True: exitenable = False self.merge_ammo() self.inventory.create(self,10,10,0,50) self.equipement.create(self,var.screenWIDTH/2+50,10,0,50) self.dropbut = Button('discard', 50,450,50,20) self.do_once = False for b in self.buttons_list: b.display() self.dropbut.display() for event in pygame.event.get(): #setting up quit if event.type == QUIT: pygame.quit() sys.exit() if event.type == MOUSEBUTTONDOWN: self.m_down = True self.m_up = False if event.type == MOUSEBUTTONUP: self.m_up = True self.m_down = False #print 'mouse up' if self.selected == False and self.m_down == True: for b in self.buttons_list: if b.rect.collidepoint(pygame.mouse.get_pos()): self.selected = True self.selected_button = self.buttons_list.index(b) self.start_pos = pygame.mouse.get_pos() x,y = pygame.mouse.get_pos() if self.selected == True and self.m_down == True: width = self.buttons_list[self.selected_button].rect.width height = self.buttons_list[self.selected_button].rect.height self.buttons_list[self.selected_button].rect = Rect(x-width/2,y-height/2,self.buttons_list[self.selected_button].rect[2],self.buttons_list[self.selected_button].rect[3]) if self.m_up == True: if self.selected == True: if self.start_pos[0]<var.screenWIDTH/2: '''performing actions on inventory items''' if isinstance(self.inventory.contents[self.selected_button], Potion): self.inventory.contents[self.selected_button].drink(self) print 'attempts potion drinking from inv' if self.buttons_list[self.selected_button].rect.colliderect(self.dropbut.rect) and self.start_pos[0]<var.screenWIDTH/2: #removes item from inv print 'removing inv item' self.inventory.contents[self.selected_button].rect[0] = self.rect.move(random.randint(0,20)+5,0)[0] self.inventory.contents[self.selected_button].rect[1] = self.rect.move(0,random.randint(0,20)+10)[1] self.level.deleted_list.remove(self.buttons_list[self.selected_button]) #put's sprite back in game self.level.item_list.add(self.inventory.contents[self.selected_button]) #add's sprite back to item list for it to behave as item in game self.inventory.drop(self.inventory.contents[self.selected_button],self) #removes item in player's iventory located at the index specified by the position of the button corresponding to this item in the button list self.buttons_list.pop(self.selected_button) elif self.buttons_list[self.selected_button].rect.colliderect(self.dropbut.rect) and self.start_pos[0]>var.screenWIDTH/2: #remove item from equipemnt print 'removing eq item' self.level.deleted_list.remove(self.buttons_list[self.selected_button]) #put's sprite back in game self.level.item_list.add(self.equipement.contents[self.selected_button-len(self.buttons_list)]) #add's sprite back to item list for it to behave as item in game self.equipement.contents[self.selected_button-len(self.buttons_list)].rect[0] = self.rect.move(random.randint(0,20)+5,0)[0] self.equipement.contents[self.selected_button-len(self.buttons_list)].rect[1] = self.rect.move(0,random.randint(0,20)+10)[1] self.equipement.drop(self.equipement.contents[self.selected_button-len(self.buttons_list)],self) #removes item in player's iventory located at the index specified by the position of the button corresponding to this item in the button list self.buttons_list.pop(self.selected_button) elif self.start_pos[0]>var.screenWIDTH/2 and self.buttons_list[self.selected_button].rect[0]<var.screenWIDTH/2 and len(self.inventory.contents) < 32: #moving item from equipement to inv print 'moving from eq to inv' self.inventory.add(self.equipement.contents[self.selected_button-len(self.buttons_list)],self) #add's item to inv self.equipement.contents.pop(self.selected_button-len(self.buttons_list)) #removes item in player's equipment located at the index specified by the position of the button corresponding to this item in the button list self.buttons_list.pop(self.selected_button) #remove's the item from it's button list position elif self.start_pos[0]<var.screenWIDTH/2 and self.buttons_list[self.selected_button].rect[0]>var.screenWIDTH/2: #moving item from inv to eq print 'moving from inv to eq' if isinstance(self.inventory.contents[self.selected_button],Armor): #checks if item is an armor x = [item for item in self.equipement.contents if isinstance(item,Armor) == True] #creates a list of all armor items already in the equipment already_has = False # assumes the player doesn't have any of that armor category for armor in x: #checks if the item to be added is already contained in the equipment if isinstance(armor,Helm)==True and isinstance(self.inventory.contents[self.selected_button],Helm) == True: print 'already has helm' already_has = True break elif isinstance(armor,Torso_armor)==True and isinstance(self.inventory.contents[self.selected_button],Torso_armor) == True: print 'already has torso' already_has = True break if len(x) != 2 and already_has == False: # if the total number of armor items in the equipment is less than 2 and the player doesn't have one of the type it is added to the equ and removed from the inv print 'armor piece added to eq' self.equipement.contents.append(self.inventory.contents[self.selected_button]) #add's item to inv self.inventory.contents.pop(self.selected_button) #removes item in player's equipment located at the index specified by the position of the button corresponding to this item in the button list self.buttons_list.pop(self.selected_button) #remove's the item from it's button list position elif isinstance(self.inventory.contents[self.selected_button],Weapon): #checks if item is an armor x = [item for item in self.equipement.contents if isinstance(item,Weapon) == True] #creates a list of all weapon items already in the equipment already_has = False for weapon in x: if weapon.wield == 'two_handed': already_has = True # doesn't actually have it but can't have more than one 2 handed weapon print 'Already has a two-handed weapon' if self.inventory.contents[self.selected_button].wield == 'two_handed' and weapon.wield == 'one_handed': already_has = True # doesn't actually have it but can't have more than one 2 handed weapon print 'Can t have both a two and one handed weapon' if len(x) != 2 and already_has == False: print 'weapon added to eq' self.equipement.contents.append(self.inventory.contents[self.selected_button]) #add's item to eq self.inventory.contents.pop(self.selected_button) #removes item in player's equipment located at the index specified by the position of the button corresponding to this item in the button list self.buttons_list.pop(self.selected_button) #remove's the item from it's button list position elif already_has == True: '''send item in eq to inv''' if self.inventory.contents[self.selected_button].wield == 'two_handed': for item in x: #removes all weapons in eq self.inventory.contents.append(item) #add's item to inv self.equipement.contents.remove(item) #removes item in player's equipment located at the index specified by the position of the button corresponding to this item in the button list else: #i.e. one handed self.inventory.contents.append(x[0]) #add's item to inv self.equipement.contents.remove(x[0]) #removes item in player's equipment located at the index specified by the position of the button corresponding to this item in the button list '''adds item to eq''' self.equipement.contents.append(self.inventory.contents[self.selected_button]) #add's item to eq self.inventory.contents.pop(self.selected_button) #removes item in player's inv located at the index specified by the position of the button corresponding to this item in the button list self.buttons_list.pop(self.selected_button) #remove's the item from it's button list position elif isinstance(self.inventory.contents[self.selected_button],Projectile): #checks if item is a projectile x = [item for item in self.equipement.contents if isinstance(item,Projectile) == True] #creates a list of all projectile items already in the equipment if len(x) == 0: print 'projectile added to eq' self.equipement.contents.append(self.inventory.contents[self.selected_button]) #add's item to inv self.inventory.contents.pop(self.selected_button) #removes item in player's equipment located at the index specified by the position of the button corresponding to this item in the button list self.buttons_list.pop(self.selected_button) #remove's the item from it's button list position self.buttons_list = [] #clears buttonlist self.inventory.create(self,10,10,0,50) #resets buttons and button list self.equipement.create(self,var.screenWIDTH/2+50,10,0,50) self.selected = False '''displaying tooltips''' if pygame.mouse.get_pressed()[2] == True: for b in self.buttons_list: if b.rect.collidepoint(pygame.mouse.get_pos()): b.binded.tooltip(b.rect.topright) for msg in self.level.message_list: msg.show() pygame.display.update() if pygame.key.get_pressed()[pygame.K_i] == False: exitenable = True if exitenable == True and pygame.key.get_pressed()[pygame.K_i]: self.buttons_list = [] #clear's buttons list self.do_once = True # to insure buttons are populated again at next inventory opening self.inventory_opened = False self.level.do_once = True def offset(self,): if (var.dx == 0 and var.dy == 0) == False: self.rect = self.rect.move(var.xoffset,var.yoffset) def is_alive(self): if self.hp > 0: return True else: self.kill() self.level.dead_sprites_list.add(self) #adds the character to the deleted sprite list self.level.all_sprites_list.add(self) self.image = self.dead_image return False def weapon_xchange(self,type_a,type_b): #attempt_exchange(char,item_a,item_b,inv_a,inv_b): inv_ls = [x for x in [y for y in self.inventory.contents if isinstance (y,Weapon)] if x.type == type_a] eq_ls = [p for p in [m for m in self.equipement.contents if isinstance (m,Weapon)] if p.type == type_b] if len(inv_ls) > 0 and len(eq_ls) > 0: inv_item = max([x for x in [y for y in self.inventory.contents if isinstance (y,Weapon)] if x.type == type_a], key=attrgetter('dmg')) eq_item = max([p for p in [m for m in self.equipement.contents if isinstance (m,Weapon)] if p.type == type_b], key=attrgetter('dmg')) if inv_item.wield == 'two_handed': '''removes all weapons from eq to inv''' [fn.move_item(self,j,self.equipement.contents,self.inventory.contents) for j in self.equipement.contents if isinstance (j,Weapon)] fn.move_item(self,inv_item,self.inventory.contents,self.equipement.contents) else: print 'before',eq_item,self.inventory.contents fn.exchange_item(self,inv_item,eq_item,self.inventory.contents,self.equipement.contents) print 'after',eq_item,self.inventory.contents #return False def attack(self, Character, cat): self.attack_time.tick() self.attack_time_left += self.attack_time.get_time() if self.attack_time_left >= self.attack_speed: # needs to be added as a variable self.has_attack = False #to prevent endless animation if cat == 'CC' and Character.is_alive() == True and self.is_alive() == True: self.has_attack = True test = random.randint(1,100) <= self.CC if test == True: dmg = sum([x.random_dmg() for x in self.equipement.contents if isinstance(x, Weapon) == True]) #sum of the values of all weapons in equipement arm = sum([x.arm for x in Character.equipement.contents if isinstance(x, Armor) == True]) #sum of the values of all weapons in equipement if (dmg+self.F/10)-(arm+Character.E/10) < 0: dmg = 0 else: dmg = (dmg+self.F/10)-(arm+Character.E/10) Character.hp -= dmg print 'mob deals {} dmg'.format(dmg) self.attack_time_left = 0 return True elif cat == 'CT' and Character.is_alive() == True and self.is_alive() == True and len([y for y in [x for x in self.equipement.contents if isinstance (x,Projectile)] if y.ammo > 0]) > 0:#checks clicks ennemi and has ammo self.has_attack = True '''creates an instance by getting the type of the proj in eq''' proj_used = type([y for y in [x for x in self.equipement.contents if isinstance (x,Projectile)] if y.ammo > 0][0])(0) for proj in [x for x in self.equipement.contents if isinstance (x,Projectile)]: if proj.ammo > 0: proj.ammo -= 1 break wep_used = [x for x in [y for y in self.equipement.contents if isinstance (y,Weapon)] if x.type == 'CT'][0] proj_used.dmg += wep_used.dmg proj_used.fire(self,(var.screenWIDTH/2,var.screenHEIGHT/2),self.level.projectile_ennemy_list) #in this function the pojectile level attribute needs to be already set self.attack_time_left = 0 return True def set_rand_dest(self): dest_rect = self.rect.inflate(200,200) self.dest = (random.randint(dest_rect[0],dest_rect[0]+dest_rect[2]),random.randint(dest_rect[1],dest_rect[1]+dest_rect[3])) def set_charge_dest(self,charge_target): '''Charge destination randomly changed to allow the seek behaviour due to the move_collision function''' self.dest = charge_target.rect.x+random.randint(-10,10),charge_target.rect.y+random.randint(-10,10) def set_flee_dest(self,attacker): '''sends the char away from the attack at speed''' flee_dist = 1000 if self.rect.inflate(400,400).colliderect(attacker.rect): if self.rect.centerx > attacker.rect.centerx\ and self.rect.centery > attacker.rect.centery: self.dest = (self.rect.x+flee_dist,self.rect.y+flee_dist) if self.rect.centerx < attacker.rect.centerx\ and self.rect.centery > attacker.rect.centery: self.dest = (self.rect.x-flee_dist,self.rect.y+flee_dist) if self.rect.centerx < attacker.rect.centerx\ and self.rect.centery < attacker.rect.centery: self.dest = (self.rect.x-flee_dist,self.rect.y-flee_dist) if self.rect.centerx > attacker.rect.centerx\ and self.rect.centery < attacker.rect.centery: self.dest = (self.rect.x+flee_dist,self.rect.y-flee_dist) print 'has fled' def behaviour(self,Character): '''Managing Attack AI''' CT_eq = [x for x in [y for y in self.equipement.contents if isinstance (y,Weapon)] if x.type == 'CT'] CT_inv = [x for x in [y for y in self.inventory.contents if isinstance (y,Weapon)] if x.type == 'CT'] CT_list = CT_eq + CT_inv has_CT = False if len(CT_list) > 0: has_CT = True range_CT = max(CT_list, key=attrgetter('dmg')).range CC_eq = [x for x in [y for y in self.equipement.contents if isinstance (y,Weapon)] if x.type == 'CC'] CC_inv =[x for x in [y for y in self.inventory.contents if isinstance (y,Weapon)] if x.type == 'CC'] CC_list = CC_eq + CC_inv has_CC = False if len(CC_list) > 0: has_CC = True range_CC = max(CC_list, key=attrgetter('dmg')).range if has_CC and Character.rect.colliderect(self.rect.inflate(range_CC,range_CC)): if len(CC_eq) == 0: self.weapon_xchange('CC','CT') self.attack(Character, 'CC') elif has_CT and self.rect.inflate(range_CT,range_CT).colliderect(Character.rect) \ and self.rect.inflate(275,275).colliderect(Character.rect) == False \ and fn.in_sight(self,Character, range_CT, self.level.building_list): if len(CT_eq) == 0: self.weapon_xchange('CT','CC') self.attack(Character, 'CT') if self.has_attack == True: self.dest = self.rect.topleft '''managing fleeing AI''' if self.hp <= 5: if self.flee_test == True: self.flee_test = False if self.speed < 5: self.speed *= 5 self.set_flee_dest(Character) elif self.hp > 5 and self.flee_test == False: self.flee_test = True '''Managing movement AI''' self.dest_time.tick() self.dest_time_left += self.dest_time.get_time() if self.dest_time_left >= self.dest_speed and self.has_attack == False: # checks if time to set new dest self.dest_time_left = 0 #resets timer if has_CC and self.rect.inflate(250,250).colliderect(Character.rect) == True: if self.speed < 2: self.speed *= 2 self.set_charge_dest(Character) elif self.rect.inflate(500,500).colliderect(Character.rect) == True: if self.speed > int(48.0/(var.FPS*0.7)): self.speed = int(48.0/(var.FPS*0.7)) my_list = [self.set_charge_dest(Character),self.set_charge_dest(Character),self.set_charge_dest(Character),self.set_rand_dest()] random.choice(my_list) else: if self.speed > int(48.0/(var.FPS*0.7)): self.speed = int(48.0/(var.FPS*0.7)) self.set_rand_dest() def move_collision(self,EW,SN): test_rect = Rect(self.rect.midleft,(self.rect.width,self.rect.height/2)) for obstacle in itertools.chain.from_iterable([self.level.building_list,self.level.player_list]): if test_rect.colliderect(obstacle.rect.inflate(-obstacle.rect.width/10,-obstacle.rect.height/10)) == True:#len([x for x in char_col_points if obstacle.rect.collidepoint(x)]) >= 1: if EW == True: if self.dest[1] > self.rect.y: mvt = self.speed else: mvt = -self.speed self.rect = self.rect.move(-self.move_speed,mvt) elif SN == True: if self.dest[0] > self.rect.x: mvt = self.speed else: mvt = -self.speed self.rect = self.rect.move(mvt,-self.move_speed) break def move_NS(self): self.rect = self.rect.move(0, self.move_speed) # Check for Collisions self.move_collision(False,True) def move_EW(self): self.rect = self.rect.move(self.move_speed,0) # Check for Collisions self.move_collision(True,False) def move(self):#,mouse_pos, screen, background #updates mvt timer self.mvt_time.tick() self.mvt_time_left += self.mvt_time.get_time() if self.mvt_time_left >= self.mvt_speed:# checks time to animate if self.pos != self.dest: # cheks pos animate self.is_moving = True self.mvt_time_left = 0 if self.dest[0] > self.rect[0]: #move E self.move_speed = self.speed self.move_EW() #moves player self.orientation = 90 if self.dest[0] < self.rect[0]: #move W self.move_speed = -self.speed self.move_EW() #moves player self.orientation = 270 if self.dest[1] < self.rect[1]: self.move_speed = -self.speed self.move_NS() #moves player self.orientation = 0 if self.dest[1] > self.rect[1]: self.move_speed = self.speed self.move_NS() #moves player self.orientation = 180 if self.rect.collidepoint(self.dest): #check position reset self.pos = self.rect.topleft else: self.anim_time_left = 0 self.is_moving = False def loot(self,Character): if self.rect.collidepoint(pygame.mouse.get_pos()) == True and Character.rect.colliderect(self.rect.inflate(5,5)) == True: has_looted = False for inv in [self.inventory.contents,self.equipement.contents]: if len(inv) >= 1: has_looted = True for item in inv: self.pop_around(item, 50,50) self.level.item_list.add(item) #add's sprite back to item list for it to behave as item in game inv.remove(item) #removes item from chest if has_looted == False: w = 150 h = 30 msg = Message('Nothing to loot !!',500, 0,0,w,h) msg.image = pygame.transform.scale(msg.image, (w, h)) msg.rect.center = (var.screenWIDTH/2,25) self.level.message_list.add(msg) class Button(pygame.sprite.Sprite): def __init__(self, text, x,y,w,h ): super(Button, self).__init__() self.text = text self.image = var.but_bg self.text_pos = ((x+w/2),(y+h/2)) self.rect2 = 0 self.txt_color = (50,40,10) #self.surface = pygame.draw.rect(var.screen, self.color , self.rect) self.smallText = pygame.font.SysFont('initial', 18, bold=True, italic=False) self.textSurf = self.smallText.render(self.text, True, self.txt_color) self.rect2 = self.textSurf.get_rect() self.rect2.center = self.text_pos self.image = pygame.transform.scale(self.image, (int(self.rect2.width*1.5),int(self.rect2.height*3))) self.rect = Rect(x,y,self.image.get_rect().width,self.image.get_rect().height) self.selected = False self.m_released = True self.binded = None def check_select(self): m_pos = pygame.mouse.get_pos() over_but = self.rect.collidepoint(m_pos) if pygame.mouse.get_pressed()[0] ==1 and over_but == 1 and self.selected == False and self.m_released == True: self.selected = True self.txt_color = (0,200,0) self.m_released = False elif pygame.mouse.get_pressed()[0] == 1 and over_but == 1 and self.selected == True and self.m_released == True: self.selected = False self.txt_color = (0,0,0) self.m_released = False if pygame.mouse.get_pressed()[0] == 0: self.m_released = True def display(self): '''needed to update color''' self.textSurf = self.smallText.render(self.text, True, self.txt_color) var.screen.blit(self.image,self.rect) var.screen.blit(self.textSurf, Rect(self.rect[0]+(self.rect.centerx-self.rect[0])*0.4,self.rect[1]+self.rect[3]/4,self.rect[2],self.rect[3])) #Rect(self.rect[0]+self.rect[2]/8,self.rect[1]+20,self.rect[2],self.rect[3]) class Message(Button): def __init__(self, text, display_time, x,y,w,h ): super(Message, self).__init__(text, x,y,w,h) self.display_time = pygame.time.Clock() self.display_time_to = display_time def show(self): self.display_time.tick() self.display_time_to -= self.display_time.get_time() if (self.display_time_to <= 0) == False: self.display() class Inventory(object): def __init__(self): self.contents = [] self.inv_bg = var.inv_bg def combine_ammo(self): all_projectiles = [x for x in self.contents if isinstance (x,Projectile)] for item in all_projectiles: temp_projectiles = all_projectiles temp_projectiles.remove(item) other_projectiles = temp_projectiles print other_projectiles for other in other_projectiles: if type(item) == type(other): item.ammo += other.ammo self.contents.remove(other) # item.name = '{} {}'.format(item.ammo,item.raw_name) def add(self, item, character): if len(self.contents) < 32: item.kill()#remove's item from all groups character.level.all_sprites_list.add(item) self.contents.append(item) item.check_pickdrop(character) item.inv_pos = len(self.contents) def drop(self, item, character): try: self.contents.remove(item) item.check_pickdrop(character) item.kill()#remove's item from all groups character.level.all_sprites_list.add(item) character.level.item_list.add(item) except: print 'item not in inventory' def create(self,Character,x,y, dx, dy): xstart = x ystart = y for i in range(0,len(self.contents)): b = Button(self.contents[i].name,x,y,100,50) b.binded = self.contents[i] if i == 7: x = xstart+110 y = ystart-50 if i == 15: x = xstart+220 y = ystart-50 if i == 23: x = xstart+330 y = ystart-50 x += dx y += dy Character.buttons_list.append(b) class Item(MySprite): def __init__(self, name, value, image, x, y): # Call the parent class (Sprite) constructor super(Item, self).__init__(image, x, y) self.name = name self.value = value self.inv_pos = -1 def offset(self): if (var.dx == 0 and var.dy == 0) == False: self.rect = self.rect.move(var.xoffset,var.yoffset) def check_pickdrop(self,character): pass def use(self,player): #needs to be ckecked when E key is down AKA object mode if self.rect.inflate(10,10).collidepoint(pygame.mouse.get_pos()) and player.rect.inflate(10,10).colliderect(self.rect) and pygame.key.get_pressed()[pygame.K_e]: player.inventory.add(self, player) self.delete() #sends to deleted_sprite_list #needs a description attr and icon attr def tooltip(self,pos): if pos[1] > var.screenHEIGHT-var.screenHEIGHT/3: pos = fn.tulpe_scale(pos,(10,-var.screenHEIGHT/3+5)) else: pos = fn.tulpe_scale(pos,(10,5)) txtrect = pygame.Rect(pos, (35*6,int(len(self.description)/35.0*20))) #35 is number of character per line and 10 estimated char height and 5 estimated char width '''drawing bg''' bg = pygame.transform.smoothscale(var.but_bg, (txtrect.width+5, txtrect.height+self.icon.get_rect().height+15)) var.screen.blit(bg, fn.tulpe_scale((txtrect.left, txtrect.top),(-5,-5))) '''drawing icon''' var.screen.blit(self.icon, fn.tulpe_scale(txtrect.topleft,(0,txtrect.height+5))) '''drawing text''' fontobject = pygame.font.SysFont('initial', 15, bold=True, italic=False) fn.drawText(var.screen, self.description, (50,40,10), txtrect, fontobject, aa=False, bkg=None) class No_item(object): #creates a blank item def __init__(self): self.name = 'none' def d10(int): rng = range(0,int) total = 0 for x in rng: total += random.randint(0,10) return total class Weapon(Item): def __init__(self, name, value, image, icon, x, y, dmg, dmg_modif): super(Weapon, self).__init__(name, value, image, x, y) self.dmg_modif = dmg_modif self.dmg = dmg self.icon = icon self.icon.set_colorkey(None) def random_dmg(self): attack_dmg = self.dmg+d10(self.dmg_modif) return attack_dmg class Armor(Item): def __init__(self, name, value, image, icon, x, y, arm): super(Armor, self).__init__(name, value, image, x, y) self.arm = arm self.icon = icon self.icon.set_colorkey(None) class Helm(Armor): def __init__(self): #name, value, image, x, y, dmg self.name = 'Helm' self.value = 10 self.arm = 2 self.image = var.helm_img self.icon = var.weapon_icons.image_at(pygame.Rect(2,600,56,56)) self.description = 'A helmet offering protection of 2.' super(Helm, self).__init__(self.name, self.value, self.image, self.icon, 200, 150, self.arm) class Torso_armor(Armor): def __init__(self,name,value,image,icon,arm): #name, value, image, x, y, dmg self.name = name self.value = value self.arm = arm self.description = 'A chest armor offering protection of {}.'.format(arm) super(Torso_armor, self).__init__(self.name, self.value, image,icon, 200, 150, self.arm) class Illuminator(Item): def __init__(self, name, value, image, radius): self.radius = radius super(Illuminator, self).__init__(name, value, image, 150, 225) self.source = shadow.Shadow() self.source.set_radius(self.radius) self.falloff = var.surf_falloff self.mask = 0 self.pos = 0 self.is_carried = False self.is_lit = True self.carrier = None self.m_released = False def onoff(self): if pygame.key.get_pressed()[pygame.K_o] and self.is_lit == False and self.m_released: self.is_lit = True self.m_released = False if pygame.key.get_pressed()[pygame.K_o] and self.is_lit == True and self.m_released: self.is_lit = False self.m_released = False if pygame.key.get_pressed()[pygame.K_o] == False: self.m_released = True def set_carrier(self,character): if self.is_carried == False: self.carrier = character '''will only work for the player at the screen center''' self.rect.center = character.rect.center self.blit_order = -1 self.is_carried = True else: self.carrier = None self.blit_order = 0 self.is_carried = False def check_pickdrop(self,character): self.set_carrier(character) class Potion(Item): def __init__(self, value, regen): if regen == 0: regen = 1 if random.randint(0,4) != 0: if 0 < regen <= 4: self.name = 'Weak Health Potion' elif 4 < regen <= 7: self.name = 'Health Potion' elif 7 < regen <= 10: self.name = 'Strong Health Potion' elif 10 < regen: self.name = 'Health Elixir' elif regen < 0: self.name = 'Poison' else: self.name = 'Unknown potion' if 'Health' in self.name: self.image = var.health_potion_img self.icon = var.weapon_icons.image_at(pygame.Rect(182,600,56,56)) self.description = 'An revigorating potion.' elif self.name == 'Poison': self.image = var.poison_potion_img self.icon = var.weapon_icons.image_at(pygame.Rect(242,600,56,56)) self.description = 'A maleficiant poison.' else: self.image = var.unknown_potion_img self.icon = var.weapon_icons.image_at(pygame.Rect(302,600,56,56)) self.description = 'A potion with unknown effect to you.' super(Potion, self).__init__(self.name, value, self.image, 150, 225) self.regen = regen self.confirm = False self.timer = pygame.time.Clock() self.timer_left = 0 self.reset_time = 10000 #10 seconds self.icon.set_colorkey(None) def drink(self,Character): if Character.hp < Character.hp_max: self.timer.tick() self.timer_left += self.timer.get_time() print self.timer_left if self.timer_left >= self.reset_time: # check if confirm needs to be rest self.confirm = False print 'confirm reset' if self.confirm == False: w = 150 h = 30 msg = Message('Clic again to drink', 2000, 0,0,w,h) msg.image = pygame.transform.scale(msg.image, (w, h)) msg.rect.center = (var.screenWIDTH/2,25) self.level.message_list.add(msg) self.confirm = True self.timer_left = 0 elif self.confirm == True and self.timer_left > 100: Character.hp = min([Character.hp + self.regen,Character.hp_max]) Character.inventory.drop(self,Character)#contents.remove(self) self.kill() print 'potion restores hp to {}'.format(Character.hp) class Building(Item): def __init__(self, name, value, image, x, y, hp): super(Building, self).__init__(name, value, image, x, y) self.hp = hp '''might need to define occluder points as [x,y] lists''' self.occlude = occluder.Occluder([self.rect.topleft, self.rect.topright, self.rect.bottomright, self.rect.bottomleft]) class Projectile(Item): def __init__(self, name, value, image, x, y, speed, dmg, dmg_modif, ammo, range_): super(Projectile, self).__init__(name, value, image, x, y) self.dest = (self.rect[0],self.rect[1]) self.speed = speed self.dmg_modif = dmg_modif self.dmg = dmg self.orientation = 0 self.range = range_ self.ammo = ammo self.icon = var.weapon_icons.image_at(pygame.Rect(362,600,56,56)) self.icon.set_colorkey(None) self.description = 'A set of {}. Damage of {}d10+{}.'.format(self.name,self.dmg_modif,self.dmg) @property def ammo(self): return self._ammo @ammo.setter def ammo(self, ammo): raw_name = ''.join([i for i in self.name if not i.isdigit()]) self.name = str(ammo) + raw_name self.description = 'A set of {}. Damage of 1d10+1. Range of 400+2d10'.format(self.name) self._ammo = ammo def random_dmg(self): attack_dmg = self.dmg+d10(self.dmg_modif) return attack_dmg def fire(self,shooter, target_pos, dest_list): self.rect.center = shooter.rect.center#place's the projectile at shooter's position self.dest = target_pos#pygame.mouse.get_pos() #set's destination, will need to be offset self.dmg = int(shooter.F/10.0) self.image = var.arrow_img dest_list.add(self) #for player firing : self.level.projectile_list, for mobs self.level.projectile_ennemy_list var.has_shot = True def hit_test(self,character): test = pygame.sprite.spritecollideany(self, self.level.building_list, collided = None) if self.rect.colliderect(character.rect.inflate(-character.rect.width/4,-character.rect.height/4)) == True: arm = sum([x.arm for x in character.equipement.contents if isinstance(x, Armor) == True]) #sum of the values of all weapons in equipement dmg = self.random_dmg() - (character.E/10+arm) if dmg < 0: dmg = 0 character.hp -= dmg self.kill() print 'has hit ! and dealt = {}'.format(dmg) elif test is not None: if test.rect.collidepoint(self.rect.center): self.kill() def move(self): if self.rect.inflate(2,5).collidepoint(self.dest) == True: self.kill() m_pos = self.dest speed = float(self.speed) xp = self.rect[0]-self.rect[2] yp = self.rect[1]-self.rect[3] xm = m_pos[0]-self.rect[2] ym = m_pos[1]-self.rect[3] dx = xm-xp dy = ym-yp #dist = (dx**2+dy**2)**0.5 #get lenght to travel #calculates angle and sets quadrant if dx == 0 or dy == 0: angle_rad = 0#np.pi/2 if dx == 0 and ym > yp: xoffset = 0 yoffset = -speed self.orientation = 180 elif dx == 0 and ym < yp: xoffset = 0 yoffset = speed self.orientation = 0 elif dy == 0 and xm > xp: xoffset = 0 yoffset = -speed self.orientation = 90 elif dy == 0 and xm < xp: xoffset = 0 yoffset = speed self.orientation = 270 else: xoffset, yoffset = 0,0 self.orientation = 180 elif xm > xp and ym > yp: angle_rad = np.arctan((abs(dy)/abs(dx))) xoffset = -np.cos(angle_rad)*speed yoffset = -np.sin(angle_rad)*speed self.orientation = angle_rad*(180.0/np.pi)+90 elif xm < xp and ym > yp: angle_rad = np.arctan((abs(dx)/abs(dy))) xoffset = np.sin(angle_rad)*speed yoffset = -np.cos(angle_rad)*speed self.orientation = angle_rad*(180.0/np.pi)+180 elif xm < xp and ym < yp: angle_rad = np.arctan((abs(dy)/abs(dx))) xoffset = np.cos(angle_rad)*speed yoffset = np.sin(angle_rad)*speed self.orientation = angle_rad*(180.0/np.pi)+270 else:# xm > xp and ym < yp: angle_rad = np.arctan((abs(dx)/abs(dy))) xoffset = -np.sin(angle_rad)*speed yoffset = np.cos(angle_rad)*speed self.orientation = angle_rad*(180.0/np.pi) self.image = pygame.transform.rotate(var.arrow_img, -self.orientation) self.rect = self.rect.move(-xoffset,-yoffset) self.dest = (self.dest[0]-xoffset+var.xoffset,self.dest[1]-yoffset+var.yoffset) class Level_Change(Building): def __init__(self, name, image, x, y, image_list, pair): self.hp = 1000 self.value = 1000 self.image_list = image_list self.pair = pair super(Level_Change, self).__init__(name, self.value, image, x, y, self.hp) '''anim timer''' self.anim_time = pygame.time.Clock() self.anim_time_left = 0 self.anim_speed = 1000/len(self.image_list) self.anim_counter = 0 def anim(self): #updates anim timer self.anim_time.tick() self.anim_time_left += self.anim_time.get_time() #checks which anim to display based on the direction and if sprite is moving and alive if self.anim_time_left >= self.anim_speed: #checks time to animate if self.anim_counter >= len(self.image_list): self.anim_counter = 0 self.image = self.image_list[self.anim_counter] self.anim_time_left = 0 self.anim_counter += 1 def activate(self,char,new_level): self.anim() if char.rect.collidepoint(self.rect.midbottom): self.level.go_to(new_level, self.pair) class Portal(Level_Change): def __init__(self, x, y, pair): self.name = 'Portal' self.image_list = var.portal_images self.image = self.image_list[0] super(Portal,self).__init__(self.name,self.image,x,y, self.image_list, pair) class Night_Mask(object): def __init__(self): self.surf_lighting = pygame.Surface((var.screenWIDTH,var.screenHEIGHT)) #Screenwidth and height self.light_sources = [] '''setting initial alpha and colorkey''' #self.surf_lighting.set_colorkey((255,255,255)) #self.surf_lighting.set_alpha(0) self.alpha = 0 '''Day time timer''' self.day_timer = pygame.time.Clock() self.day_time = 0 self.day_end = 2*60000#1440000 self.day_switch = self.day_end/2 #12 minutes '''Shadow timer''' self.Shadow_timer = pygame.time.Clock() self.Shadow_time = 0 self.Shadow_end = 25 @property def alpha(self): return self._alpha @alpha.setter def alpha(self, alpha): self.surf_lighting.set_alpha(int(alpha)) self._alpha = alpha def day_update(self,a_max): alfa = float(a_max) self.day_timer.tick() self.day_time += self.day_timer.get_time() if self.day_time <= self.day_switch: # checks if the time of day has been reached self.alpha = (alfa/self.day_switch)*self.day_time elif self.day_time >= self.day_end: self.day_time = 0 else: self.alpha = alfa+(alfa/self.day_switch)*(self.day_switch-self.day_time) def apply_shadows(self, lights_ls, building_list, character): self.Shadow_timer.tick() self.Shadow_time += self.Shadow_timer.get_time() if self.Shadow_time >= self.Shadow_end: self.Shadow_time = 0 # Ambient light self.surf_lighting.fill((self.alpha,self.alpha,self.alpha)) #import blursurf, and tulpescale locally for speed blursurf = fn.blurSurf ts = fn.tulpe_scale if self.alpha <= 120: #get occluders in view# visible_occluders = [x for x in building_list if var.screen.get_rect().colliderect(x.rect)] for build in visible_occluders: temp_rect = pygame.Rect(0,0,build.rect.width/2,build.rect.height/2) temp_rect.center = build.rect.center build.occlude = occluder.Occluder([temp_rect.topleft, ts(temp_rect.midtop,(0,-5)), temp_rect.topright, ts(temp_rect.midright,(5,0)), temp_rect.bottomright, ts(temp_rect.midbottom,(0,-5)), temp_rect.bottomleft, ts(temp_rect.midleft,(-5,0))]) for light in itertools.chain((x for x in lights_ls if var.screen.get_rect().collidepoint(x.rect.center) and x.is_lit == True)\ ,(y for y in character.inventory.contents if isinstance(y, Illuminator) and y.is_lit == True)): light.source.set_occluders((z.occlude for z in visible_occluders)) #needed to set the light position from the game position to the #library needs if light.carrier != None: light.rect.center = light.carrier.rect.center light.source.set_light_position(light.rect.center) light.mask, light.pos = light.source.get_mask_and_position(False) # resizes the falloff to match the mask dimensions light.falloff = pygame.transform.scale(var.surf_falloff, (light.mask.get_width(), light.mask.get_height())) #blits falloff to mask light.mask.blit(light.falloff,(0,0),special_flags=BLEND_MULT) #Add the contribution from the shadowed light source self.surf_lighting.blit(light.mask,light.pos,special_flags=BLEND_MAX) self.surf_lighting = blursurf(self.surf_lighting,4) class Skill(object): def __init__(self,name,has,pre_req,icon,description): self.name = name self.has = has self.pre_req = pre_req self.icon = icon self.description = description def tooltip(self,pos): if pos[1] > var.screenHEIGHT-var.screenHEIGHT/3: pos = fn.tulpe_scale(pos,(10,-var.screenHEIGHT/3+5)) else: pos = fn.tulpe_scale(pos,(10,5)) txtrect = pygame.Rect(pos, (35*6,int(len(self.description)/35.0*20))) #35 is number of character per line and 10 estimated char height and 5 estimated char width '''drawing bg''' bg = pygame.transform.smoothscale(var.but_bg, (txtrect.width+5, txtrect.height+self.icon.get_rect().height+15)) var.screen.blit(bg, fn.tulpe_scale((txtrect.left, txtrect.top),(-5,-5))) '''drawing icon''' var.screen.blit(self.icon, fn.tulpe_scale(txtrect.topleft,(0,txtrect.height+5))) '''drawing text''' fontobject = pygame.font.SysFont('initial', 15, bold=True, italic=False) fn.drawText(var.screen, self.description, (50,40,10), txtrect, fontobject, aa=False, bkg=None) class Sniper(Skill): def __init__(self): self.description = '-1 to target armor when shooting' super(Sniper, self).__init__('Sniper',False,None,var.skill_icons.image_at(pygame.Rect(57,485,56,56)),self.description) self.icon.set_colorkey(None) class Fast_shooter(Skill): def __init__(self): self.description = 'Shooting frequency +1/3' super(Fast_shooter, self).__init__('Fast Shooter',False,[Sniper()],var.skill_icons.image_at(pygame.Rect(340,542,56,56)),self.description) self.icon.set_colorkey(None) class Power_shot(Skill): def __init__(self): self.description = '+1 to damage when shooting' super(Power_shot, self).__init__('Power Shot',False,[Sniper(),Fast_shooter()],var.skill_icons.image_at(pygame.Rect(57,541,56,56)),self.description) self.icon.set_colorkey(None) class Power_blow(Skill): def __init__(self): self.description = '+1 to damage in close quarter combat' super(Power_blow, self).__init__('Power Blow',False,None,var.skill_icons.image_at(pygame.Rect(114,706,56,56)),self.description) self.icon.set_colorkey(None) class Ambidextrous(Skill): def __init__(self): self.description = 'Adds the damage of two single hand weapons' super(Ambidextrous, self).__init__('Ambidextrous',False,None,var.skill_icons.image_at(pygame.Rect(340,705,56,56)),self.description) self.icon.set_colorkey(None) class Duelist(Skill): def __init__(self): self.description = 'Damage x2 when attacking a single ennemy in close combat' super(Duelist, self).__init__('Duelist',False,[Ambidextrous()],var.skill_icons.image_at(pygame.Rect(340,649,56,56)),self.description) self.icon.set_colorkey(None) class Chain_attack(Skill): def __init__(self): self.description = 'Close combat attack frequency +1/3' super(Chain_attack, self).__init__('Chain attack',False,[Ambidextrous(), Duelist()],var.skill_icons.image_at(pygame.Rect(542,2,56,56)),self.description) self.icon.set_colorkey(None)
true
0b84b7629762e05900e859f4543d9030adbdc17e
Python
ryan0583/AOC-2019
/Day 19/day19.py
UTF-8
2,936
3.578125
4
[]
no_license
from Utils.graphics_panel import GraphicsPanel from Utils.intcode_computer import IntcodeComputer from Utils.point import Point def part1(): panel = GraphicsPanel.create_empty_panel(50, 50) panel.init_canvas() count = 0 computer = IntcodeComputer([], None, False) filename = "input.txt" ints = list(map(int, open(filename, "r").read().split(","))) for x in range(0, 50): for y in range(0, 50): computer.reset(ints) computer.inputs = [x, y] computer.process() computer.append_input(x) computer.append_input(y) output = computer.process() if output == 1: count += 1 panel.update_canvas(Point(x, y), "red") panel.paint_canvas() panel.paint_canvas() print(count) input("press any key") def print_stuff(start_x, start_y): dim = 100 panel = GraphicsPanel.create_empty_panel(dim, dim) panel.init_canvas() computer = IntcodeComputer([], None, False) filename = "input.txt" ints = list(map(int, open(filename, "r").read().split(","))) panel.reset() for x in range(start_x, start_x + dim): print("col " + str(x - start_x)) for y in range(start_y, start_y + dim): computer.reset(ints) computer.inputs = [x, y] output = computer.process() if output == 1: panel.update_canvas_with_offset(Point(x, y), "red", -start_x, -start_y) panel.paint_canvas() else: print("Output not 1 for point " + str(x) + ", " + str(y)) input("press any key") def part2(): def count_beam_squares(_x, _y_start, _y_end): _count = 0 y = _y_start _first_y = None _last_y = None found_beam = False while True: computer.reset(ints) computer.inputs = [_x, y] output = computer.process() if output == 1: _count += 1 found_beam = True _first_y = y elif found_beam: _last_y = y - 1 break y += 1 if _y_end is not None and y > _y_end: break return _count, _first_y, _last_y computer = IntcodeComputer([], None, False) filename = "input.txt" ints = list(map(int, open(filename, "r").read().split(","))) x = 1330 y_start = 400 while True: count1, first_y1, last_y1 = count_beam_squares(x, y_start, None) count2, first_y2, last_y2 = count_beam_squares(x + 99, last_y1 - 99, last_y1) print("col = " + str(x)) print(count1) print(last_y1 - 99) print(count2) print(first_y2) if count2 == 100: print("FOUND!!!") break x += 1 # part1() # part2() print_stuff(1353, 764)
true
4941a40661163242b46b72a90281b5561626b062
Python
dalaAM/month-01
/day08_all/day08/demo03.py
UTF-8
451
4.4375
4
[]
no_license
""" 将下列代码,定义为函数. for r in range(2): # 行数 0 1 for c in range(5): # 列数 01234 01234 print("老王", end=" ") print() # 换行 """ def print_table(data, r_count, c_count): for r in range(r_count): # 行数 for c in range(c_count): # 列数 print(data, end=" ") print() # 换行 print_table("老王", 2, 5) print_table("老崔", 6, 3)
true
69d7097a364b14a4a72eb9c5f70b5a2579c12d4f
Python
arnoldvc/Leccion1
/Leccion05/Set.py
UTF-8
565
3.546875
4
[]
no_license
# set planetas = {'Marte', 'Júpiter', 'Venus'} print(planetas) #largo print(len(planetas)) # revisar si un elemento está presente print('Marte' in planetas) # agregar un elemento planetas.add('Tierra') print( planetas) #no se pueden duplicar elementos planetas.add('Tierra') print(planetas) # eliminar elemento posiblemente arrojando un error planetas.remove('Tierra') print(planetas) # eliminar elemento sin arrojar error planetas.discard('Júpiters') print(planetas) # limpiar set planetas.clear() print(planetas) # eliminar el set #del planetas print(planetas)
true
a83fef96227c6603600885b11a88c2834283c00f
Python
SHDeseo/SHDeseo.github.io
/python/dss.py
UTF-8
169
3.53125
4
[ "MIT" ]
permissive
for i in range (1, 30+1): if i % 15 == 0 : print("Fizzbuzz") elif i % 3 == 0 : print("Fizz") elif i % 5 --0 : print("Buzz") else: print(i) print("Done!")
true
16ed911423db22c35eaa0e2fdbf82b2c8972395b
Python
timparkin/timparkingallery
/share/pollen/pyport/relation.py
UTF-8
659
2.8125
3
[]
no_license
''' Relation types ''' class Relation(object): def __init__(self, entity_class_name, join_attrs): self.entity_class_name = entity_class_name if not isinstance(join_attrs, (list, tuple)): join_attrs = (join_attrs,) self.join_attrs = join_attrs class ToOneRelation(Relation): pass class OneToOne(ToOneRelation): pass class ToManyRelation(Relation): def __init__(self, entity_class_name, join_attrs, order=None): Relation.__init__(self, entity_class_name, join_attrs) self.order = order class OneToMany(ToManyRelation): pass class ManyToMany(ToManyRelation): pass
true
a2c0f85b06650894db8bf75b1b2a64ed08f3f813
Python
hhaggan/python-azure-datalake-gen2-api
/pyadlgen2/azuredatalakegen2.py
UTF-8
9,126
3.171875
3
[ "MIT" ]
permissive
"""TODO Fill in the module description """ # --------------------------------------------------------------------- # LIBRARIES # External Libraries import pathlib from requests.exceptions import HTTPError # Internal Libraries from pyadlgen2.helpers.adlgen2restapiwrapper import ADLGen2RestApiWrapper # --------------------------------------------------------------------- class AzureDataLakeGen2(): """TODO Fill in the class description.""" def __init__(self, storage_account_name, storage_account_key): self.__storage_account_name = storage_account_name self.__storage_account_key = storage_account_key self.__azure_datalake_rest_api_wrapper = ADLGen2RestApiWrapper(storage_account_name, storage_account_key) def path_exists(self, path): """Checks if a given path exists in the datalake. Parameters ---------- path : str Absolute path that has to be checked. The first element represents the filesystem (a.k.a container) where the file is stored. We can thus see the path as: /{filesystem}/{path} *{path}* is optional. `path` can point to either a folder or a file, it doesn't matter. Returns ------- bool True if `path` exists, False otherwise. Raises ------ HTTPError If the call to the REST API fails for some reasons. """ path = pathlib.PurePosixPath(path) if not path.is_absolute(): raise ValueError('The param [path] must be an absolute path. Value passed:\n{}'.format(path)) datalake_filesystem = path.parts[1] datalake_path = path.relative_to(path.parts[0]+path.parts[1]) \ if path.relative_to(path.parts[0]+path.parts[1]) != pathlib.PurePosixPath('.') \ else None try: self.__azure_datalake_rest_api_wrapper.path_list( filesystem = datalake_filesystem , recursive = False , directory = datalake_path ) return True except HTTPError as e: if str(e).startswith('404 Client Error: The specified path does not exist.'): return False else: raise e def path_get_properties(self, path): r"""Get the properties of the specified path. Parameters ---------- path : str Absolute path of which we want the properties. The first element represents the filesystem (a.k.a container) where files are stored. We can thus see the path as: /{filesystem}/{folder1}/.../{folderN}[/{filename}] Returns ------- dict Returns a dict containing the properties of the specified path. Raises ------ ValueError If the specified `path` is not an absolute path. FileNotFoundError If the specified `path` does not exist. """ path = pathlib.PurePosixPath(path) if not path.is_absolute(): raise ValueError('The param [path] must be an absolute path. Value passed:\n{}'.format(path)) datalake_filesystem = path.parts[1] datalake_path = path.relative_to(path.parts[0]+path.parts[1]) \ if path.relative_to(path.parts[0]+path.parts[1]) != pathlib.PurePosixPath('.') \ else None if not self.path_exists(path): raise FileNotFoundError('The specified path does not exist.\n{}'.format(path)) response = self.__azure_datalake_rest_api_wrapper.path_get_properties( filesystem = datalake_filesystem , path = datalake_path , upn = True , action = 'getStatus' ) return response def path_is_directory(self, path): r"""Checks if `path` exists and is a directory. Parameters ---------- path : str Absolute path which we want to check. The first element represents the filesystem (a.k.a container) where files are stored. We can thus see the path as: /{filesystem}/{folder1}/.../{folderN}[/{filename}] Returns ------- bool Returns True if `path` exists and is a directory, False otherwise. Raises ------ ValueError If the specified `path` is not an absolute path. """ path = pathlib.PurePosixPath(path) if not path.is_absolute(): raise ValueError('The param [path] must be an absolute path. Value passed:\n{}'.format(path)) datalake_filesystem = path.parts[1] datalake_path = path.relative_to(path.parts[0]+path.parts[1]) \ if path.relative_to(path.parts[0]+path.parts[1]) != pathlib.PurePosixPath('.') \ else None if not self.path_exists(path): return False if self.path_get_properties(path)['x-ms-resource-type'] == 'directory': return True else: return False def path_is_file(self, path): r"""Checks if `path` exists and is a file. Parameters ---------- path : str Absolute path which we want to check. The first element represents the filesystem (a.k.a container) where files are stored. We can thus see the path as: /{filesystem}/{folder1}/.../{folderN}[/{filename}] Returns ------- bool Returns True if `path` exists and is a file, False otherwise. Raises ------ ValueError If the specified `path` is not an absolute path. """ path = pathlib.PurePosixPath(path) if not path.is_absolute(): raise ValueError('The param [path] must be an absolute path. Value passed:\n{}'.format(path)) datalake_filesystem = path.parts[1] datalake_path = path.relative_to(path.parts[0]+path.parts[1]) \ if path.relative_to(path.parts[0]+path.parts[1]) != pathlib.PurePosixPath('.') \ else None if not self.path_exists(path): return False if self.path_get_properties(path)['x-ms-resource-type'] == 'file': return True else: return False def file_create(self, file_path, file_data, file_properties, overwrite_if_exists = False): r"""Create a file at the specified path with the specified data. Parameters ---------- file_path : str Absolute path where the file has to be created. The first element represents the filesystem (a.k.a container) where the file is stored. The last part of the path represents the name of the file. We can thus see the path as: /{filesystem}/{folder1}/.../{folderN}/{filename} file_data : The data that will be written inside the file. file_properties : dict, OrderedDict The properties that will be set for the new file. overwrite_if_exists: bool, optional If True and the specified `file_path` already exists, will overwrite the existing data and properties. Returns ------- bool Returns True if execution succeed, raises an exception otherwise. Raises ------ FileExistsError If the specified `file_path` already exists and `overwrite_if_exists` is False. """ file_path = pathlib.PurePosixPath(file_path) if not file_path.is_absolute(): raise ValueError('The param [file_path] must be an absolute path. Value passed:\n{}'.format(file_path)) if self.path_exists(file_path): if not overwrite_if_exists: raise FileExistsError('The specified file_path already exists and the param [overwrite_if_exists] is set to False.\n{}'.format(file_path)) if not self.path_is_file(file_path): raise ValueError('The specified file_path already exists and is not a file.\n{}'.format(file_path)) # The creation of a file with the specified properties requires different # calls of the API. The steps are: # * create an empty file # * update the created with the actual data # * flush the data # * set the properties datalake_filesystem = file_path.parts[1] datalake_file_path = file_path.relative_to(file_path.parts[0]+file_path.parts[1]) \ if file_path.relative_to(file_path.parts[0]+file_path.parts[1]) != pathlib.PurePosixPath('.') \ else None response = self.__azure_datalake_rest_api_wrapper.path_create( filesystem = datalake_filesystem , path = datalake_file_path , resource = 'file' , request_headers={ 'Content-Encoding' : 'utf-8' , 'x-ms-content-type' : 'text/plain' } ) response = self.__azure_datalake_rest_api_wrapper.path_update( filesystem = datalake_filesystem , path = datalake_file_path , action = 'append' , position = str(0) , request_headers = { 'Content-Type' : 'text/plain' , 'x-ms-content-type' : 'text/plain' , 'Content-Length' : str(len(file_data.encode('utf-8'))) } , data_to_append = file_data ) print(response) response = self.__azure_datalake_rest_api_wrapper.path_update( filesystem = datalake_filesystem , path = datalake_file_path , action = 'flush' , close = 'true' , position = str(len(file_data.encode('utf-8'))) , request_headers = { 'Content-Length' : str(0) , 'x-ms-content-type' : 'text/plain' } ) # TODO Set Properties return response def file_delete(self): """TODO Fill in the method description""" raise NotImplementedError() def file_read(self): """TODO Fill in the method description""" raise NotImplementedError() def file_update(self): """TODO Fill in the method description""" raise NotImplementedError() def file_set_properties(self): """TODO Fill in the method description""" raise NotImplementedError() def read_file(self, filepath): response = self.__azure_datalake_rest_api_wrapper.path_read( filesystem = 'raw-temporary' , path = 'test.csv' ) return response
true
c1c75ec7c540c414aa3f0bdce45a3365f62e8719
Python
alabiansolution/python1901
/day3/class/constructor.py
UTF-8
168
3.359375
3
[]
no_license
class Fish: def __init__(self): print("This is a constructor") def swiming(self): print("This fish can swim") shark = Fish() shark.swiming()
true
b56a48ee23445b3204aebac6e958ae9ab1e53c4a
Python
yuyaxiong/interveiw_algorithm
/LeetCode/二叉堆/703.py
UTF-8
886
3.859375
4
[]
no_license
# 703. 数据流中的第 K 大元素 from typing import List import heapq class KthLargest: def __init__(self, k: int, nums: List[int]): class SmallHeap: def __init__(self, k): self.k = k self.small_heap = [] def add(self, val): if len(self.small_heap) == k: top_val = heapq.heappop(self.small_heap) heapq.heappush(self.small_heap, max(val, top_val)) else: heapq.heappush(self.small_heap, val) return self.small_heap[0] self.s_heap = SmallHeap(k) for n in nums: self.s_heap.add(n) def add(self, val: int) -> int: return self.s_heap.add(val) # Your KthLargest object will be instantiated and called as such: # obj = KthLargest(k, nums) # param_1 = obj.add(val)
true
7c282ff812a40ea9ca89b1d484965d62ec380ed1
Python
erigler-usgs/pyLTR
/pyLTR/math/integrate_test.py
UTF-8
1,517
2.671875
3
[]
no_license
from . import integrate import pyLTR.Models.MIX import datetime import numpy import unittest class TestIntegrate(unittest.TestCase): def setUp(self): # Test runner (nosetests) may fail without this silly try/except block: try: data = pyLTR.Models.MIX('examples/data/models', 'LMs_UTIO') except TypeError: data = pyLTR.Models.MIX.MIX('examples/data/models', 'LMs_UTIO') self.x=data.read('Grid X', datetime.datetime(year=2008, month=1, day=1, hour=4, minute=0, second=0)) self.y=data.read('Grid Y', datetime.datetime(year=2008, month=1, day=1, hour=4, minute=0, second=0)) # Remove singularity self.x[:,0] = 0.0 self.y[:,0] = 0.0 def testAreaCircle(self): """ Compute area of a circle in a 2d plane. """ analyticArea = numpy.pi * (self.y.max()**2) areaCircle = integrate.calcFaceAreas(self.x, self.y, numpy.zeros(self.x.shape)) self.assertAlmostEqual(analyticArea, areaCircle.sum(), delta=1e-4) def testAreaDisk(self): """ Compute area of a disk on the surface of a sphere. """ analyticArea=2.0*numpy.pi*(1.0-numpy.cos(44.0*numpy.pi/180.0)) # Assume we're working with a unit sphere z = numpy.sqrt(1.0-(self.x**2)-(self.y**2)) areaSphere = integrate.calcFaceAreas(self.x,self.y,z) self.assertAlmostEqual(analyticArea, areaSphere.sum(), delta=1e-3) if __name__ == "__main__": unittest.main()
true
a66cf8964e5a94decbaa8704a09a2970f4a6e35f
Python
TheSiggs/Automation-Scripts
/starbound auto clicker.py
UTF-8
621
3.234375
3
[]
no_license
import pyautogui as gui import time from random import randint # Basic Commands def click(x, y): gui.click(x, y) def wait(t): time.sleep(t) def find_location(): while True: time.sleep(1) x, y = gui.position() print("X:", x, "Y:", y, "RGB:", gui.screenshot().getpixel(gui.position())) if x == 0 and y == 0: break def main(): while True: wait(1) gui.rightClick(698, 217) wait(0.1) gui.rightClick(698, 217) wait(1) gui.press('1') wait(1) gui.press('esc') # X: 698 Y: 217 main() # find_location()
true
68e5be4e83ddf4e9fac588c320be4f34cbf03dc9
Python
chirag-parmar/Cryptopals
/Set 1/hex2base64.py
UTF-8
147
2.671875
3
[]
no_license
import sys argv = sys.argv[1:] for hexStrings in argv: print(hexStrings.decode("hex") + '\n' + hexStrings.decode("hex").encode("base64") + '\n')
true
3332e1aa34530af16fb3e93e4f18e1d7557eb589
Python
ZoltanSzeman/jumpup
/settings.py
UTF-8
661
2.8125
3
[]
no_license
# Created by Zoltan Szeman # 2020-05-28 import pygame class Settings(): """An object for the basic game settings.""" def __init__(self): # screen settings self.size = (700, 600) self.color = 0, 0, 0 # ball movement settings self.jump_speed = 1200.0 self.gravity = 2000.0 self.x_speed = 3 self.fps = 120 self.bounc_factor = 0.3 #platform size, movement and color settings self.plat_w_min = 30 self.plat_w_max = 150 self.plat_h = 10 self.plat_no = 10 self.plat_vel = 1.0 self.brown = (255, 255, 0)
true
86083e9f48b3e38cd54efffa124d7e17bfe17cb3
Python
Yavor16/Space-Shooter-Game
/src/Enemy.py
UTF-8
3,669
3.359375
3
[]
no_license
import math import pygame import random from EnemyBullet import EnemyBullet as EnemyBull class EnemyShip(pygame.sprite.Sprite): def __init__(self, screen, player, damage): super().__init__() self.screen = screen self.x = random.randint(1, 765) self.y = -30 self.player = player self.direction = random.randint(0, 1) self.updirection = random.randint(0,1) self.image = pygame.image.load("./images/enemy.png") self.image = pygame.transform.scale(self.image, ((32, 32))) self.startLocation = (self.x, self.y) self.rect = self.image.get_rect(center = (self.x, self.y)) self.enemyBullet = EnemyBull(screen=self.screen, player=player, location=(self.rect.x, self.rect.y), damage=10) self.damage = damage self.maxHealth = 30 self.health = 30 self.score = 1 def __del__(self): self.screen = None self.image = None def LeftandRightEnemyMovement(self): if self.x > 30 and self.x < 765: self.x = (self.x + 0.1, self.x - 0.1)[self.direction == 1] else: if self.x <= 30: self.x += 0.1 elif self.x >= 765: self.x -= 0.1 self.direction = (0, 1)[self.direction == 0] def UpandDownEnemyMovement(self): if self.y > 30 and self.y < 400: self.y = (self.y + 0.1, self.y - 0.1)[self.updirection == 0] else: if self.y <= 30: self.y += 0.1 elif self.y >= 400: self.y -= 0.1 self.updirection = (0, 1)[self.updirection == 0] def EnemyMovementAndRotation(self): randomDistanceForX = random.randint(300, 500) randomDistanceForY = random.randint(300, 700) if abs(self.startLocation[0] - self.x) >= randomDistanceForX: self.direction = (0, 1)[self.direction == 0] if abs(self.startLocation[1] - self.y) >= randomDistanceForY: self.updirection = (0, 1)[self.updirection == 0] self.UpandDownEnemyMovement() self.LeftandRightEnemyMovement() self.RotateEnemy() def RotateEnemy(self): enemy_rect = self.image.get_rect(center = (self.x, self.y)) mx, my = self.player.GetPosition() dx, dy = mx - enemy_rect.centerx, my - enemy_rect.centery angle = math.degrees(math.atan2(-dy, dx)) - 90 rot_image = pygame.transform.rotate(self.image, angle) rot_image_rect = rot_image.get_rect(center = enemy_rect.center) self.screen.blit(rot_image, rot_image_rect.center) def EnemyShoot(self): try: if self.enemyBullet.y <= 0 or self.enemyBullet.y >= 600 or self.enemyBullet.x >= 800 or self.enemyBullet.x <= 0: del self.enemyBullet else: self.enemyBullet.MoveBullet() distance = math.sqrt((math.pow(self.enemyBullet.x - self.player.x, 2)) + (math.pow(self.enemyBullet.y - self.player.y, 2))) if distance < 27: self.player.health-=self.damage del self.enemyBullet except: self.enemyBullet = EnemyBull(screen=self.screen, player=self.player, location=(self.x, self.y), damage=10) def HealthBar(self): pygame.draw.rect(self.screen, (255, 0, 0), (self.x , self.y - 15, self.maxHealth, 10)) pygame.draw.rect(self.screen, (0, 255, 0), (self.x , self.y - 15, self.health, 10)) def AllEnemyEvents(self): self.HealthBar() self.EnemyMovementAndRotation() self.EnemyShoot()
true
f4ec6b9da608e8b895c94d4ed35747fab7397a6e
Python
padelstein/ZolaPOM
/UnitTesting/zola_testing/homepage_links/bottom_twitter.py
UTF-8
917
2.5625
3
[]
no_license
''' Created on Jul 16, 2013 @author: emma ''' import unittest #imports unit test/ability to run as pyunit test from UnitTesting.page_objects.webdriver_wrapper import webdriver_wrapper from UnitTesting.page_objects.homepage import homepage class bottom_twitter_icon(unittest.TestCase): def bottom_twitter_icon_test(self, webd_wrap): page_homepage = homepage(webd_wrap) page_homepage.get_page() page_homepage.click_twitter_icon() webd_wrap.switch_window() webd_wrap.check_url('https://twitter.com/zolabooks') webd_wrap.close_the_browser() def test_bottom_twitter_icon(self): #running x as a unit test for browser in webdriver_wrapper._browsers: self.bottom_twitter_icon_test(webdriver_wrapper(browser)) print "Module Complete", __name__ if __name__ == "__main__": unittest.main()
true
dc934fb4f9f7664c06b73ab49ac842697f0316a8
Python
ealgera/challenges
/06/usertweet.py
UTF-8
307
3.046875
3
[]
no_license
class UserTweet: def __init__(self, n, sn, t): self.name = n self.screenname = sn self.tweet = t #self.tweet_parsed = [] def print_Tweet(self): print(f"Naam : {self.name}") print(f"Screen: {self.screenname}") print(f"Tweet : {self.tweet}")
true
2a816e766c0a8694856407ff9d675585c134b6e3
Python
mehanig/can-scrapers
/can_tools/scrapers/official/NM/nm_vaccine.py
UTF-8
3,977
2.765625
3
[ "MIT" ]
permissive
import pandas as pd import requests import us from can_tools.scrapers import variables from can_tools.scrapers.base import CMU from can_tools.scrapers.official.base import StateDashboard from can_tools.scrapers.util import requests_retry_session class NewMexicoBase(StateDashboard): state_fips = int(us.states.lookup("New Mexico").fips) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.session = requests_retry_session() class NewMexicoVaccineCounty(NewMexicoBase): """ Fetch county level Covid-19 vaccination data from official state of New Mexico REST APIs """ source = "https://cvvaccine.nmhealth.org/public-dashboard.html" source_name = "New Mexico Department of Health" has_location = False location_type = "county" def fetch(self) -> requests.Response: # Set url of downloadable dataset url = "https://cvvaccine.nmhealth.org/api/GetCounties" request = self.session.get(url) if not request.ok: message = f"Could not request data from {url}" raise ValueError(message) return request.json() def normalize(self, data) -> pd.DataFrame: # Read data into data frame key = "data" if key not in data: raise ValueError(f"Expected to find {key} in JSON response") df = pd.DataFrame(data[key]) # Determine what columns to keep cols_to_keep = [ "county", "date", "modernaShipped", "pfizerShipped", "dosesAdministered", "totalShipped", "partiallyVaccinated", "fullyVaccinated", "percentPartiallyVaccinated", "percentFullyVaccinated", ] # Drop extraneous columns df = df.loc[:, cols_to_keep] # Rename columns df = df.rename(columns={"date": "dt", "county": "location_name"}) # Convert date time column to a datetime df = df.assign(dt=lambda x: pd.to_datetime(x["dt"])) # Create dictionary for columns to map crename = { "modernaShipped": CMU( category="moderna_vaccine_distributed", measurement="cumulative", unit="doses", ), "pfizerShipped": CMU( category="pfizer_vaccine_distributed", measurement="cumulative", unit="doses", ), "dosesAdministered": CMU( category="total_vaccine_doses_administered", measurement="cumulative", unit="doses", ), "totalShipped": CMU( category="total_vaccine_distributed", measurement="cumulative", unit="doses", ), "partiallyVaccinated": variables.INITIATING_VACCINATIONS_ALL, "fullyVaccinated": variables.FULLY_VACCINATED_ALL, "percentPartiallyVaccinated": variables.PERCENTAGE_PEOPLE_INITIATING_VACCINE, "percentFullyVaccinated": variables.PERCENTAGE_PEOPLE_COMPLETING_VACCINE, } # Move things into long format df = df.melt( id_vars=["dt", "location_name"], value_vars=crename.keys() ).dropna() # Determine the category of each observation df = self.extract_CMU(df, crename) # Determine what columns to keep cols_to_keep = [ "dt", "location_name", "category", "measurement", "unit", "age", "race", "ethnicity", "sex", "value", ] # Drop extraneous columns out = df.loc[:, cols_to_keep] # Convert value columns out["value"] = out["value"].astype(int) # Add rows that don't change out["vintage"] = self._retrieve_vintage() return out
true
e7661bb06e8c128503c9539442a6541d5b4616b1
Python
GreatTwang/lccc_solution
/Python/Array(value)/Single Number.py
UTF-8
357
3.265625
3
[]
no_license
#Given a non-empty array of integers, every element appears twice except for one. Find that single one. class Solution: def singleNumber(self, nums: List[int]) -> int: a=0 for each in nums: a^=each return a class Solution: def singleNumber(self, nums: List[int]) -> int: return 2*sum(set(nums))-sum(nums)
true
5cb25eb90d21b5703b843116087acf1d3af36951
Python
canwhite/QCPySignInTest
/guest/sign/models.py
UTF-8
1,278
2.875
3
[]
no_license
from django.db import models # Create your models here. #发布会表 class Event(models.Model): """docstring for Event""" #发布会标题 name = models.CharField(max_length = 100) #参加人数 limit = models.IntegerField() #状态 status = models.BooleanField() #地址 address = models.CharField(max_length = 200) #发布会时间 start_time = models.DateTimeField('events time') #创建时间(自动获取当前时间) create_time = models.DateTimeField(auto_now = True) #__str__()方法告诉python如何将对象以str的方式显示出来 def __str__(self): return self.name #嘉宾表 class Guest(models.Model): """docstring for Guest""" #关联发布会id #创建一个外键,通过它可以获取发布会表 event = models.ForeignKey(Event) #姓名 realname = models.CharField(max_length = 64) #手机号 phone = models.CharField(max_length = 16) #邮箱 email = models.EmailField() #签到状态 sign = models.BooleanField() #创建时间(自动获取当前时间) create_time = models.DateTimeField(auto_now = True) class Meta: """docstring for Meta""" unique_together = ("event","phone") #用于告诉python如何将对象以str的形式显示出来 def __str__(self): return self.realname
true
607173b874cbab75cfee259b202ceec5b0d2571b
Python
kenie/myTest
/100/example_089.py
UTF-8
706
3.78125
4
[]
no_license
#!/usr/bin/env python #-*- coding:UTF-8 -*- '''题目:某个公司采用公用电话传递数据,数据是四位的整数,在传递过程中是加密的,加密规则如下: 每位数字都加上5,然后用和除以10的余数代替该数字,再将第一位和第四位交换,第二位和第三位交换。''' from sys import stdout if __name__ == "__main__": s = int(raw_input("Enter a 4 digit number:")) a = [] a.append(s%10) a.append(s%100/10) a.append(s%1000/100) a.append(s/1000) for i in range(4): a[i] += 5 a[i] %=10 for i in range(2): a[i],a[3 - i] = a[3 - i],a[i] for i in range(3,-1,-1): stdout.write(str(a[i]))
true