repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
sarojit2018/Deep-Edges
inference.py
<reponame>sarojit2018/Deep-Edges<filename>inference.py from dataloader import * from model import deepEdge import numpy as np import cv2 import tensorflow as tf from keras.models import * from keras.layers import * from keras.optimizers import * from keras.callbacks import ModelCheckpoint, LearningRateScheduler from keras import backend as keras import os import matplotlib.pyplot as plt from model import deepEdge DE = deepEdge() DE.load_weights('deepEdge_best_val_loss_v1.hdf5') print(DE.summary()) inference_edges_src = './BIPED/edges/imgs/test/rgbr/' inference_edges_dst = './DE_inference/' if not os.path.exists(inference_edges_dst): os.mkdir(inference_edges_dst) for filename in os.listdir(inference_edges_src): print(filename) try: #if 1: img = plt.imread(inference_edges_src + filename)[:,:,:3] #avoid 4 channel input except: #else: print("Error reading file! Continuing...") continue #make sure to normalise the img img_max = np.max(img) if img_max > 0: #To avoid division by zero error img = img/img_max img = cv2.resize(img, (512, 512), interpolation = cv2.INTER_CUBIC) #Note: matplotlib automatically takes in a normalised img while read #predict edges_pred = np.squeeze(DE(np.reshape(img, (1,) + img.shape))) plt.imsave(inference_edges_dst + filename, edges_pred)
sarojit2018/Deep-Edges
losses.py
<reponame>sarojit2018/Deep-Edges<filename>losses.py import numpy as np import os import skimage.io as io import skimage.transform as trans import numpy as np from keras.models import * from keras.layers import * from keras.optimizers import * from keras.callbacks import ModelCheckpoint, LearningRateScheduler from keras import backend as keras from keras import backend as K def dice_coef(y_true, y_pred, smooth=1): """ Dice = (2*|X & Y|)/ (|X|+ |Y|) = 2*sum(|A*B|)/(sum(A^2)+sum(B^2)) ref: https://arxiv.org/pdf/1606.04797v1.pdf """ intersection = K.sum(K.abs(y_true * y_pred), axis=-1) return (2. * intersection + smooth) / (K.sum(K.square(y_true),-1) + K.sum(K.square(y_pred),-1) + smooth) def dice_coef_loss(y_true, y_pred): return 1-dice_coef(y_true, y_pred)
sarojit2018/Deep-Edges
dataloader.py
import numpy as np import cv2 from random import random from random import shuffle from random import randint from random import uniform import os import matplotlib.pyplot as plt def datastreamer_BIPED(batch_size = 10 , target_shape = (512,512), mode = 'train', base_path = '/Users/sarojitauddya/edges_detect/BIPED/edges/', debug = False): #print(mode) #print("Entered") #print(debug) target_x, target_y = target_shape edge_base_path = base_path + 'edge_maps/' imgs_base_path = base_path + 'imgs/' edge_path = '' imgs_path = '' if mode=='train': edge_path = edge_base_path + 'train/rgbr/real/' imgs_path = imgs_base_path + 'train/rgbr/real/' elif mode=='test': edge_path = edge_base_path + 'test/rgbr/' imgs_path = imgs_base_path + 'test/rgbr/' list_edge = os.listdir(edge_path) list_imgs = os.listdir(imgs_path) #print(list_edge) #print(list_imgs) num_images = 0 while 1: shuffle(list_edge) imgs_batch = [] edge_batch = [] for filename in list_edge: if filename[-3:]!='png' and filename[-3:]!='jpg': continue if num_images == batch_size: num_images = 0 imgs_batch = np.array(imgs_batch) #print(type(edge_batch)) edge_batch = np.array(edge_batch) if imgs_batch.shape[0] == 0: pass else: yield imgs_batch, edge_batch imgs_batch = [] edge_batch = [] image_path = imgs_path + filename[:-3] + 'jpg' edges_path = edge_path + filename image = plt.imread(image_path) edges = plt.imread(edges_path) if debug: print("Max Image pixel: "+str(np.max(image))) print("Min Image pixel: "+str(np.min(image))) patch_image = np.zeros((target_x,target_y,3)) patch_edges = np.zeros((target_x,target_y,1)) size_x, size_y,_ = image.shape edges = np.reshape(edges, (size_x, size_y, 1)) if size_x <= target_x or size_y <= target_y: #May not be the case for BIPED dataset print("Oddity in the BIPED dataset") patch_image = cv2.resize(image, (target_x, target_y), interpolation = cv2.INTER_CUBIC) patch_edges = cv2.resize(edges, (target_x, target_y), interpolation = cv2.INTER_CUBIC) #Generally the size of images in BIPED dataset is 720 by 1280 #Random patch based training start_x, start_y = randint(0, size_x - target_x), randint(0, size_y - target_y) patch_image = image[start_x:start_x + target_x, start_y:start_y + target_y,:] patch_edges = edges[start_x:start_x + target_x, start_y:start_y + target_y,:] #Random rotations (0,90,180,270) #Randomly rotate/flip rn_un = uniform(0,1) cv2_object = None if rn_un <= 0.25: cv2_object = cv2.ROTATE_90_COUNTERCLOCKWISE #counterclockwise 90 elif rn_un > 0.25 and rn_un<=0.5: cv2_object = cv2.ROTATE_90_CLOCKWISE #clockwise 90 elif rn_un >0.5 and rn_un<=0.75: cv2_object = cv2.ROTATE_180 #flip else: cv2_object = None if False: patch_image = cv2.rotate(patch_image, cv2_object) patch_edges = cv2.rotate(patch_edges, cv2_object) #Colour based augmentation #Randomly choose channels ch1 = randint(0,2) ch2 = randint(0,2) ch3 = randint(0,2) if debug: print("*****Chosen channels*****") print(ch1, ch2, ch3) print("*************************") patch_image_colour_aug = np.zeros(patch_image.shape) patch_image_colour_aug[:,:,0] = patch_image[:,:,ch1] patch_image_colour_aug[:,:,1] = patch_image[:,:,ch2] patch_image_colour_aug[:,:,2] = patch_image[:,:,ch3] patch_image = np.uint8(patch_image_colour_aug) #Thicken edges kernel = np.ones((2,2)) patch_edges = cv2.dilate(patch_edges, kernel, iterations = 2) if debug: plt.imshow(patch_image) plt.title("Patch Image") plt.show() plt.imshow(patch_edges) plt.title("Patch Edge") plt.show() patch_image = np.float32(patch_image) patch_edges = np.float32(patch_edges) imgs_batch.append(patch_image/255) edge_batch.append(patch_edges/np.max(patch_edges)) num_images += 1
Arkellus/Fugu14_onlinebuild
wait_login.py
from os.path import exists import time while not exists('./DONE'): print("not done") time.sleep(5)
Arkellus/Fugu14_onlinebuild
cdhash_patch.py
<filename>cdhash_patch.py<gh_stars>1-10 #!/usr/bin/env python3 import sys cdhash = sys.argv[1] print(f"CDHash of jailbreakd: {cdhash}") print("Patching arm/iOS/Fugu14App/Fugu14App/closures.swift...") with open("./arm/iOS/Fugu14App/Fugu14App/closures.swift", "r") as f: closure_swift = f.read() lines = [] for line in closure_swift.split("\n"): if line.startswith(' try simpleSetenv("JAILBREAKD_CDHASH", '): lines.append (f' try simpleSetenv("JAILBREAKD_CDHASH", "{cdhash}")') else: lines.append(line) with open("./arm/iOS/Fugu14App/Fugu14App/closures.swift", "w") as f: f.write("\n".join(lines)) print("Patched")
hdjang/SSD-variants
train.py
import os import time import argparse import random import numpy as np from numpy.random import RandomState import cv2 import torch import torch.optim as optim import torch.backends.cudnn as cudnn from torch.autograd import Variable from torch.utils.data import DataLoader from pascal_voc import VOCDetection, VOC, Viz from transforms import * from evaluation import eval_voc_detection import sys sys.path.append('./models') from SSD import SSD300 from loss import MultiBoxLoss from multibox import MultiBox from tensorboardX import SummaryWriter summary = SummaryWriter() # Setup parser = argparse.ArgumentParser(description='PyTorch SSD variants implementation') parser.add_argument('--checkpoint', help='resume from checkpoint', default='') parser.add_argument('--voc_root', help='PASCAL VOC dataset root path', default='') parser.add_argument('--batch_size', type=int, help='input data batch size', default=32) parser.add_argument('--lr', '--learning_rate', type=float, help='initial learning rate', default=1e-3) parser.add_argument('--start_iter', type=int, help='start iteration', default=0) parser.add_argument('--backbone', help='pretrained backbone net weights file', default='vgg16_reducedfc.pth') parser.add_argument('--cuda', action='store_true', help='enable cuda') parser.add_argument('--test', action='store_true', help='test mode') parser.add_argument('--demo', action='store_true', help='show detection result') parser.add_argument('--seed', type=int, help='random seed', default=233) parser.add_argument('--threads', type=int, help='number of data loader workers.', default=4) opt = parser.parse_args() print('argparser:', opt) # random seed random.seed(opt.seed) np.random.seed(opt.seed) torch.manual_seed(opt.seed) if opt.cuda: assert torch.cuda.is_available(), 'No GPU found, please run without --cuda' torch.cuda.manual_seed_all(opt.seed) # model model = SSD300(VOC.N_CLASSES) cfg = model.config if opt.checkpoint: model.load_state_dict(torch.load(opt.checkpoint)) else: model.init_parameters(opt.backbone) encoder = MultiBox(cfg) criterion = MultiBoxLoss() # cuda if opt.cuda: model.cuda() criterion.cuda() cudnn.benchmark = True # optimizer optimizer = optim.SGD(model.parameters(), lr=opt.lr, momentum=0.9, weight_decay=5e-4) # learning rate / iterations init_lr = cfg.get('init_lr', 1e-3) stepvalues = cfg.get('stepvalues', (80000, 100000)) max_iter = cfg.get('max_iter', 120000) def adjust_learning_rate(optimizer, stage): lr = init_lr * (0.1 ** stage) for param_group in optimizer.param_groups: param_group['lr'] = lr # def warm_up(iteration): # warmup_steps = [0, 300, 600, 1000] # if iteration in warmup_steps: # i = warmup_steps.index(iteration) # lr = 10 ** np.linspace(-6, np.log10(init_lr), len(warmup_steps))[i] # for param_group in optimizer.param_groups: # param_group['lr'] = lr def learning_rate_schedule(iteration): if iteration in stepvalues: adjust_learning_rate(optimizer, stepvalues.index(iteration) + 1) def train(): model.train() PRNG = RandomState(opt.seed) # augmentation / transforms transform = Compose([ [ColorJitter(prob=0.5)], # or write [ColorJitter(), None] BoxesToCoords(), Expand((1, 4), prob=0.5), ObjectRandomCrop(), HorizontalFlip(), Resize(300), CoordsToBoxes(), [SubtractMean(mean=VOC.MEAN)], [RGB2BGR()], [ToTensor()], ], PRNG, mode=None, fillval=VOC.MEAN) target_transform = encoder.encode dataset = VOCDetection( root=opt.voc_root, image_set=[('2007', 'trainval'), ('2012', 'trainval'),], keep_difficult=True, transform=transform, target_transform=target_transform) dataloader = DataLoader(dataset=dataset, batch_size=opt.batch_size, shuffle=True, num_workers=opt.threads, pin_memory=True) iteration = opt.start_iter while True: for input, loc, label in dataloader: learning_rate_schedule(iteration) input, loc, label = Variable(input), Variable(loc), Variable(label) if opt.cuda: input, loc, label = input.cuda(), loc.cuda(), label.cuda() xloc, xconf = model(input) loc_loss, conf_loss = criterion(xloc, xconf, loc, label) loss = loc_loss + conf_loss optimizer.zero_grad() loss.backward() optimizer.step() if iteration % 10 == 0: summary.add_scalar('loss/loc_loss', loc_loss.data[0], iteration) summary.add_scalar('loss/conf_loss', conf_loss.data[0], iteration) summary.add_scalars('loss/loss', {"loc_loss": loc_loss.data[0], "conf_loss": conf_loss.data[0], "loss": loss.data[0]}, iteration) if iteration % 5000 == 0 and iteration != opt.start_iter: print('Save state, iter: {}, Loss:{}'.format(iteration, loss.data[0])) if not os.path.isdir('weights'): os.mkdir('weights') torch.save(model.state_dict(), 'weights/{}_0712_{}.pth'.format(cfg.get('name', 'SSD'), iteration)) iteration += 1 if iteration > max_iter: return 0 def test(): PRNG = RandomState() dataset = VOCDetection( root=opt.voc_root, image_set=[('2007', 'test')], transform=Compose([ BoxesToCoords(), Resize(300), CoordsToBoxes(), [SubtractMean(mean=VOC.MEAN)], [RGB2BGR()], [ToTensor()]]), target_transform=None) print(len(dataset)) pred_bboxes, pred_labels, pred_scores, gt_bboxes, gt_labels = [], [], [], [], [] for i in range(len(dataset)): img, loc, label = dataset[i] gt_bboxes.append(loc) gt_labels.append(label) input = Variable(img.unsqueeze(0), volatile=True) if opt.cuda: input = input.cuda() xloc, xconf = model(input) xloc = xloc.data.cpu().numpy()[0] xconf = xconf.data.cpu().numpy()[0] boxes, labels, scores = encoder.decode(xloc, xconf, nms_thresh=0.5, conf_thresh=0.01) pred_bboxes.append(boxes) pred_labels.append(labels) pred_scores.append(scores) print(eval_voc_detection(pred_bboxes, pred_labels, pred_scores, gt_bboxes, gt_labels, iou_thresh=0.5, use_07_metric=True)) def demo(): PRNG = RandomState() voc_vis = Viz() dataset = VOCDetection( root=opt.voc_root, image_set=[('2007', 'test')], transform=Compose([ BoxesToCoords(), Resize(300), CoordsToBoxes(), [SubtractMean(mean=VOC.MEAN)], [RGB2BGR()], [ToTensor()]]), target_transform=None) print(len(dataset)) i = PRNG.choice(len(dataset)) for _ in range(1000): img, _, _ = dataset[i] input = Variable(img.unsqueeze(0), volatile=True) if opt.cuda: input = input.cuda() xloc, xconf = model(input) imgs = input.data.cpu().numpy().transpose(0, 2, 3, 1) xloc = xloc.data.cpu().numpy() xconf = xconf.data.cpu().numpy() for img, loc, conf in zip(imgs, xloc, xconf): #print(img.mean(axis=(0,1))) img = ((img[:, :, ::-1] + VOC.MEAN)).astype('uint8') boxes, labels, scores = encoder.decode(loc, conf, conf_thresh=0.5) img = voc_vis.draw_bbox(img, boxes, labels, True) cv2.imshow('0', img[:, :, ::-1]) c = cv2.waitKey(0) if c == 27 or c == ord('q'): # ESC / 'q' return else: i = PRNG.choice(len(dataset)) if __name__ == '__main__': if opt.test: test() elif opt.demo: demo() else: train()
hdjang/SSD-variants
models/SSD.py
# "SSD: Single Shot MultiBox Detector" <NAME> et al. ECCV16 import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import numpy as np import os import itertools from collections import OrderedDict from vgg import VGG16 # VGG16 as backbone class L2Norm(nn.Module): def __init__(self,n_channels, scale=20): super(L2Norm,self).__init__() self.weight = nn.Parameter(torch.Tensor(n_channels)) nn.init.constant(self.weight, scale) def forward(self, x): x /= (x.pow(2).sum(dim=1, keepdim=True).sqrt() + 1e-10) out = self.weight.unsqueeze(0).unsqueeze(2).unsqueeze(3).expand_as(x) * x return out class SSD300(nn.Module): config = { 'name': 'SSD300-VGG16', 'image_size': 300, 'grids': (38, 19, 10, 5, 3, 1), # feature map size 'aspect_ratios': ((1/2., 1, 2), (1/3., 1/2., 1, 2, 3), (1/3., 1/2., 1, 2, 3), (1/3., 1/2., 1, 2, 3), (1/2., 1, 2), (1/2., 1, 2)), 'steps': [s / 300. for s in [8, 16, 32, 64, 100, 300]], 'sizes': [s / 300. for s in [30, 60, 111, 162, 213, 264, 315]], 'prior_variance': [0.1, 0.1, 0.2, 0.2], # prior_variance imply relative weights of position offset, } # width/height and class confidence def __init__(self, n_classes): super(SSD300, self).__init__() self.n_classes = n_classes self.Base = VGG16() self.Extra = nn.Sequential(OrderedDict([ ('extra1_1', nn.Conv2d(1024, 256, 1)), ('extra1_2', nn.Conv2d(256, 512, 3, padding=1, stride=2)), ('extra2_1', nn.Conv2d(512, 128, 1)), ('extra2_2', nn.Conv2d(128, 256, 3, padding=1, stride=2)), ('extra3_1', nn.Conv2d(256, 128, 1)), ('extra3_2', nn.Conv2d(128, 256, 3)), ('extra4_1', nn.Conv2d(256, 128, 1)), ('extra4_2', nn.Conv2d(128, 256, 3)), ])) self.pred_layers = ['conv4_3', 'conv7', 'extra1_2', 'extra2_2', 'extra3_2', 'extra4_2'] n_channels = [512, 1024, 512, 256, 256, 256] self.L2Norm = nn.ModuleList([L2Norm(512, 20)]) self.norm_layers = ['conv4_3'] # decrease prediction layers' influence on backbone self.Loc = nn.ModuleList([]) self.Conf = nn.ModuleList([]) for i, ar in enumerate(self.config['aspect_ratios']): n = len(ar) + 1 self.Loc.append(nn.Conv2d(n_channels[i], n * 4, 3, padding=1)) self.Conf.append(nn.Conv2d(n_channels[i], n * (self.n_classes + 1), 3, padding=1)) def forward(self, x): xs = [] for name, m in itertools.chain(self.Base._modules.items(), self.Extra._modules.items()): if isinstance(m, nn.Conv2d): x = F.relu(m(x), inplace=True) else: x = m(x) if name in self.pred_layers: if name in self.norm_layers: i = self.norm_layers.index(name) xs.append(self.L2Norm[i](x)) else: xs.append(x) return self._prediction(xs) def _prediction(self, xs): locs = [] confs = [] for i, x in enumerate(xs): loc = self.Loc[i](x) loc = loc.permute(0, 2, 3, 1).contiguous().view(loc.size(0), -1, 4) locs.append(loc) conf = self.Conf[i](x) conf = conf.permute(0, 2, 3, 1).contiguous().view(conf.size(0), -1, self.n_classes + 1) confs.append(conf) return torch.cat(locs, dim=1), torch.cat(confs, dim=1) def init_parameters(self, backbone=None): def weights_init(m): if isinstance(m, nn.Conv2d): nn.init.xavier_uniform(m.weight.data) m.bias.data.zero_() self.apply(weights_init) if backbone is not None and os.path.isfile(backbone): self.Base.load_pretrained(backbone) print('Backbone loaded!') else: print('No backbone file!') class SSD512(SSD300): config = { 'name': 'SSD512-VGG16', 'image_size': 512, 'grids': (64, 32, 16, 8, 4, 2, 1), 'aspect_ratios': ((1/2., 1, 2), (1/3., 1/2., 1, 2, 3), (1/3., 1/2., 1, 2, 3), (1/3., 1/2., 1, 2, 3), (1/3., 1/2., 1, 2, 3), (1/2., 1, 2), (1/2., 1, 2)), 'sizes': [s / 512. for s in (20.48, 61.2, 133.12, 215.04, 296.96, 378.88, 460.8, 542.72)], 'init_lr': 0.001, 'stepvalues': (45000, 60000), 'max_iter': 75000, } def __init__(self, n_classes): super(SSD300, self).__init__() self.n_classes = n_classes self.Base = VGG16() self.Extra = nn.Sequential(OrderedDict([ ('extra1_1', nn.Conv2d(1024, 256, 1)), ('extra1_2', nn.Conv2d(256, 512, 3, padding=1, stride=2)), ('extra2_1', nn.Conv2d(512, 128, 1)), ('extra2_2', nn.Conv2d(128, 256, 3, padding=1, stride=2)), ('extra3_1', nn.Conv2d(256, 128, 1)), ('extra3_2', nn.Conv2d(128, 256, 3, padding=1, stride=2)), ('extra4_1', nn.Conv2d(256, 128, 1)), ('extra4_2', nn.Conv2d(128, 256, 3, padding=1, stride=2)), ('extra5_1', nn.Conv2d(256, 128, 1)), ('extra5_2', nn.Conv2d(128, 256, 3)), ])) self.pred_layers = ['conv4_3', 'conv7', 'extra1_2', 'extra2_2', 'extra3_2', 'extra4_2', 'extra5_2'] n_channels = [512, 1024, 512, 256, 256, 256, 256] self.L2Norm = nn.ModuleList([L2Norm(512, 20)]) self.l2norm_layers = ['conv4_3'] self.Loc = nn.ModuleList([]) self.Conf = nn.ModuleList([]) for i, ar in enumerate(self.config['aspect_ratios']): n = len(ar) + 1 self.Loc.append(nn.Conv2d(n_channels[i], n * 4, 3, padding=1)) self.Conf.append(nn.Conv2d(n_channels[i], n * (self.n_classes + 1), 3, padding=1)) # TODO #class SSDResNet #class SSDKITTI
lpninja/ELCCpv1
ELCCpv1.py
#!/usr/bin/env python """ELCCpv1.py: Sets the ElectriCChain standard syntax for the TXID space in the blockchain comments for connecting Solar PV inverters and data-loggers to the blockchain. Works with any blockchain running a daemon and having space to add a text comment only limited by the number of text characters. """ __author__ = "lpninja <EMAIL>" __copyright__ = "Copyright 2017, <NAME>" __license__ = "The Unlicense" __version__ = "2.0" __comment__= "無" """This is the TXID standard. Comment Component cert in JSON: sysv1{ """'sys' denotes the following JSON string contains details about the system logging the data, 'v1' allows for version control and changes to future datalogging syntax""" "UID":"SolarCoin affiliate website, or blockpass User ID", """The UserID is linked to the appropriate solarcoin affiliate websites UserID, or a third-party service protocol such as blockpass.org, any third party can implement their ID system up to 40 Characters.""" "SigAddr":"a new random address selected from the SolarCoin wallet used solely to sign and verify tx-messages" "tilt":"tilt angle of the solar panels in degrees to the surface horizontal of the mounting plane, or 'tracked' for systems with tracking.", "azimuth":"azimuth angle of the solar panels in degrees (0-359), with 0 be magnetic North in the Northern hemisphere, 180 degrees is magnetic South and 'tracked' for systems with tracking.", "module":"manufacturer modelcode", "inverter":"maufacturer modelcode", "data-logger":"maufacturer modelcode", "pyranometer":"manufacturer modelcode", """ If there is no pyranometer used, then leave it blank.""" "windsensor":"manufacturer modelcode", """ If there is no windsensor used, then leave it blank.""" "rainsensor":"manufacturer modelcode", """ If there is no rainsensor used, then leave it blank.""" "Web layer API":"off chain name weblink login", "Size kW":X.XXX, "lat":"00.000N/S", """For on-chain privacy, your can leave it to less decimals places for Lat/Long""" "long":"000.000E/W", """For on-chain privacy, your can leave it to less decimals places for Lat/Long""" "Comment":"anything up to 40 characters, The type of IoT running this py script e.g. RPi3b, RPi2, OdroidXU4 etc.", } "Sig": "digital signature based on SigAddr, and using the concatenation of sysv1 message {.....} + SHA1 checksum of the datalogger.py program" """ """Example: text:sysv1{"UID":"14dac6fffd768ee96250acd8bd0ff55eae03eae5","SigAddr":"8HZUxJZb2dBmhiMtXhBzNETqBj9NWotxUv","module":"Solarworld Sunmodule Plus SW 265 mono black SW-01-6023US","tilt":"50","azimuth":"210","inverter":"Enphase M250 Microinverter 800-00181-r06","data-logger":"Raspberry Pi2b","pyranometer":"","windsensor":"","rainsensor":"","Web layer API":"","Size_kW":"3.975","lat":"51.678N","long":"0.301E","Comment":"I am the first Raspberry Pi Node"}Sig:IDRMXcpAgHzoVSHFINS0YLx73wtrfMA0AatpbPqdKilQ9kbJM9eAfN3wDpctXpmsewrgGOA2efvpi5fT7gq8h7w=""" Generation cert in JSON: genv1 """'gen' denotes the following JSON string contains details of energy generated, 'v1' allows for version control and changes to future datalogging syntax""" {"UID":"7859bc519a67977e06d5e9d58860ab0546f65a29", """The UserID is linked to the appropriate solarcoin affiliate websites UserID, or a third-party service protocol such as blockpass.org, any third party can implement their ID system up to 40 Characters.""" "t0":"XXXX-XX-XX XX:XX:XX","MWh0":XXXX.XXXXXX, "t1":"XXXX-XX-XX XX:XX:XX","MWh1":XXXX.XXXXXX, "t2":"XXXX-XX-XX XX:XX:XX","MWh2":XXXX.XXXXXX, "t3":"XXXX-XX-XX XX:XX:XX","MWh3":XXXX.XXXXXX, "t4":"XXXX-XX-XX XX:XX:XX","MWh4":XXXX.XXXXXX, "t5":"XXXX-XX-XX XX:XX:XX","MWh5":XXXX.XXXXXX, "t6":"XXXX-XX-XX XX:XX:XX","MWh6":XXXX.XXXXXX, "t7":"XXXX-XX-XX XX:XX:XX","MWh7":XXXX.XXXXXX, }"Sig":"digital signature based on SigAddr from sysv1 and using the contatenation of genv1 message {.....} + SHA1 checksum of datalogger.py program" """'tX' denotes this is a time period, all dates and times in Gregorian calendar, 'MWhX' denotes the system total amount of energy logged at the timestamp, to 11 characters""" """Example: genv1{"UID":"14dac6fffd768ee96250acd8bd0ff55eae03eae5","t0":"2017-10-09 15:00:30","MWh0":11.490584,"t1":"2017-10-09 15:15:34","MWh1":11.490653,"t2":"2017-10-09 15:31:07","MWh2":11.490673,"t3":"2017-10-09 15:45:40","MWh3":11.490693,"t4":"2017-10-09 16:00:14","MWh4":11.49071,"t5":"2017-10-09 16:15:48","MWh5":11.490718,"t6":"2017-10-09 16:30:50","MWh6":11.490725,"t7":"2017-10-09 16:45:23","MWh7":11.490731}Sig:IGLDDNxi/GEljzT1xyf6+6Y8kuQAwEcllWZkaUBeNfWSgaM8E7OYs4uZBXbDsJysCQY98Ik1fSSpexPpKAwaLTI="""
dailab/roomba-python
game.py
# # game.py # # Simple tester for the Roomba Interface # from create.py # # Adjust your ROOMBA_PORT if necessary. # python game.py # starts a pygame window from which the # Roomba can be controlled with w/a/s/d. # Use this file to play with the sensors. import os, sys import pygame import create import time # Change the roomba port to whatever is on your # machine. On a Mac it's something like this. # On Linux it's usually tty.USB0 and on Win # its to serial port. #ROOMBA_PORT = "/dev/tty.usbserial-DA017V6X" ROOMBA_PORT = "/dev/rfcomm0" robot = create.Create(ROOMBA_PORT, BAUD_RATE=115200) robot.toSafeMode() #robot.printSensors() pygame.init() size = width, height = 800, 600 screen = pygame.display.set_mode(size) pygame.display.set_caption('Roomba Test') img_roomba_top = pygame.image.load(os.path.join('img', 'roomba.png')) # Fill background background = pygame.Surface(screen.get_size()) background = background.convert() background.fill((250, 250, 250)) # Display some text #font = pygame.font.Font(None, 18) font = pygame.font.SysFont("calibri",16) # Blit everything to the screen # screen.blit(background, (0, 0)) # pygame.display.flip() MAX_FORWARD = 50 # in cm per second MAX_ROTATION = 200 # in cm per second SPEED_INC = 10 # increment in percent # start 50% speed lb_left = robot.senseFunc(create.LIGHTBUMP_LEFT) lb_front_left = robot.senseFunc(create.LIGHTBUMP_FRONT_LEFT) lb_center_left = robot.senseFunc(create.LIGHTBUMP_CENTER_LEFT) lb_center_right = robot.senseFunc(create.LIGHTBUMP_CENTER_RIGHT) lb_front_right = robot.senseFunc(create.LIGHTBUMP_FRONT_RIGHT) lb_right = robot.senseFunc(create.LIGHTBUMP_RIGHT) #dist_fun = robot.senseFunc(create.DISTANCE) def main(): FWD_SPEED = MAX_FORWARD/2 ROT_SPEED = MAX_ROTATION/2 robot_dir = 0 robot_rot = 0 robot.resetPose() px, py, th = robot.getPose() while True: senses = robot.sensors([create.WALL_SIGNAL, create.WALL_IR_SENSOR, create.LEFT_BUMP, create.RIGHT_BUMP, create.ENCODER_LEFT, create.ENCODER_RIGHT, create.CLIFF_LEFT_SIGNAL, create.CLIFF_FRONT_LEFT_SIGNAL, create.CLIFF_FRONT_RIGHT_SIGNAL, create.CLIFF_RIGHT_SIGNAL, create.DIRT_DETECTED]) update_roomba = False for event in pygame.event.get(): if event.type == pygame.QUIT: return if event.type == pygame.KEYDOWN: if event.key == pygame.K_w: robot_dir+=1 update_roomba = True if event.key == pygame.K_s: robot_dir-=1 update_roomba = True if event.key == pygame.K_a: robot_rot+=1 update_roomba = True if event.key == pygame.K_d: robot_rot-=1 update_roomba = True if event.key == pygame.K_ESCAPE: pygame.quit() return if event.key == pygame.K_SPACE: robot.resetPose() px, py, th = robot.getPose() if event.key == pygame.K_UP: update_roomba = True FWD_SPEED += MAX_FORWARD*SPEED_INC/100 if FWD_SPEED>MAX_FORWARD: FWD_SPEED = MAX_FORWARD ROT_SPEED += MAX_ROTATION*SPEED_INC/100 if ROT_SPEED > MAX_ROTATION: ROT_SPEED = MAX_ROTATION if event.key == pygame.K_DOWN: update_roomba = True FWD_SPEED -= MAX_FORWARD*SPEED_INC/100 if FWD_SPEED<0: FWD_SPEED = 0 ROT_SPEED -= MAX_ROTATION*SPEED_INC/100 if ROT_SPEED<0: ROT_SPEED = 0 if event.type == pygame.KEYUP: if event.key == pygame.K_w or event.key == pygame.K_s: robot_dir=0 update_roomba = True if event.key == pygame.K_a or event.key == pygame.K_d: robot_rot=0 update_roomba = True if update_roomba == True: #robot.sensors([create.POSE]) robot.go(robot_dir*FWD_SPEED,robot_rot*ROT_SPEED) time.sleep(0.1) # done with the actual roomba stuff # now print. screen.blit(background, (0, 0)) screen.blit(img_roomba_top, (0,0)) #Light Bump screen.blit(font.render("{}".format(lb_left()), 1, (10, 10, 10)), (112, 136)) screen.blit(font.render("{}".format(lb_front_left()), 1, (10, 10, 10)), (159, 62)) screen.blit(font.render("{}".format(lb_center_left()), 1, (10, 10, 10)), (228, 19)) screen.blit(font.render("{}".format(lb_center_right()), 1, (10, 10, 10)), (457, 19)) screen.blit(font.render("{}".format(lb_front_right()), 1, (10, 10, 10)), (484, 54)) screen.blit(font.render("{}".format(lb_right()), 1, (10, 10, 10)), (469, 115)) #Wall Sensors screen.blit(font.render("{}".format(senses[create.WALL_IR_SENSOR]), 1, (10, 10, 10)), (376, 396)) screen.blit(font.render("{}".format(senses[create.WALL_SIGNAL]), 1, (10, 10, 10)), (376, 416)) #Bumpers screen.blit(font.render("{}".format(senses[create.LEFT_BUMP]), 1, (10, 10, 10)), (142, 396)) screen.blit(font.render("{}".format(senses[create.RIGHT_BUMP]), 1, (10, 10, 10)), (142, 416)) #Encoders screen.blit(font.render("{}".format(senses[create.ENCODER_LEFT]), 1, (10, 10, 10)), (635, 396)) screen.blit(font.render("{}".format(senses[create.ENCODER_RIGHT]), 1, (10, 10, 10)), (635, 416)) #Cliff Sensors screen.blit(font.render("{}".format(senses[create.CLIFF_LEFT_SIGNAL]), 1, (10, 10, 10)), (635, 16)) screen.blit(font.render("{}".format(senses[create.CLIFF_FRONT_LEFT_SIGNAL]), 1, (10, 10, 10)), (635, 35)) screen.blit(font.render("{}".format(senses[create.CLIFF_FRONT_RIGHT_SIGNAL]), 1, (10, 10, 10)), (635, 54)) screen.blit(font.render("{}".format(senses[create.CLIFF_RIGHT_SIGNAL]), 1, (10, 10, 10)), (635, 73)) screen.blit(font.render(" Fwd speed: {:04.2f} cm/sec (change with Up/Down)".format(FWD_SPEED), 1, (10, 10, 10)), (50, 450)) screen.blit(font.render(" Rot speed: {:04.2f} cm/sec".format(ROT_SPEED), 1, (10, 10, 10)), (50, 470)) px, py, th = robot.getPose() screen.blit(font.render("Estimated X-Position: {:04.2f} (cm from start)".format(px), 1, (10, 10, 10)), (450, 450)) screen.blit(font.render("Estimated Y-Position: {:04.2f} (cm from start)".format(py), 1, (10, 10, 10)), (450, 470)) screen.blit(font.render(" Estimated Rotation: {:03.2f} (in degree)".format(th), 1, (10, 10, 10)), (450, 490)) screen.blit(font.render(" Dirt Detected: {}".format(senses[create.DIRT_DETECTED]), 1, (10, 10, 10)), (450, 510)) screen.blit(font.render("Move Roomba with w/a/s/d, adjust speed with UP/DOWN, reset pos with SPACE, and ESC to quit.", 1, (10, 10, 10)), (10, 570)) pygame.display.flip() if __name__ == '__main__': try: main() except Exception as err: print ("Caught exception") print (err) robot.go(0,0) robot.close()
dailab/roomba-python
starwars.py
<reponame>dailab/roomba-python<filename>starwars.py # Taken from # https://gist.github.com/thenoviceoof/5465084 # but modified to work on my Roomba 770 import time import create #ROOMBA_PORT = "/dev/tty.usbserial-DA017V6X" ROOMBA_PORT = "/dev/rfcomm0" # define silence r = 30 # map note names in the lilypad notation to irobot commands c4 = 60 cis4 = des4 = 61 d4 = 62 dis4 = ees4 = 63 e4 = 64 f4 = 65 fis4 = ges4 = 66 g4 = 67 gis4 = aes4 = 68 a4 = 69 ais4 = bes4 = 70 b4 = 71 c5 = 72 cis5 = des5 = 73 d5 = 74 dis5 = ees5 = 75 e5 = 76 f5 = 77 fis5 = ges5 = 78 g5 = 79 gis5 = aes5 = 80 a5 = 81 ais5 = bes5 = 82 b5 = 83 c6 = 84 cis6 = des6 = 85 d6 = 86 dis6 = ees6 = 87 e6 = 88 f6 = 89 fis6 = ges6 = 90 # define some note lengths # change the top MEASURE (4/4 time) to get faster/slower speeds MEASURE = 160 HALF = MEASURE/2 Q = MEASURE/4 E = MEASURE/8 Ed = MEASURE*3/16 S = MEASURE/16 MEASURE_TIME = MEASURE/64. def play_starwars(robot): starwars1 = [(a4,Q), (a4,Q), (a4,Q), (f4,Ed), (c5,S), (a4,Q), (f4,Ed), (c5,S), (a4,HALF)] starwars2 = [(e5,Q), (e5,Q), (e5,Q), (f5,Ed), (c5,S),(aes4,Q), (f4,Ed), (c5,S), (a4,HALF)] starwars3 = [(a5,Q), (a4,Ed), (a4,S), (a5,Q), (aes5,E), (g5,E),(ges5,S), (f5,S), (ges5,S)] starwars4 = [(r,E), (bes4,E), (ees5,Q), (d5,E), (des5,E),(c5,S), (b4,S), (c5,E), (c5,E)] starwars5 = [(r,E), (f4,E), (aes4,Q), (f4,Ed), (aes4,S),(c5,Q), (a4,Ed), (c5,S), (e5,HALF)] starwars6 = [(r,E), (f4,E), (aes4,Q), (f4,Ed), (c5,S),(a4,Q), (f4,Ed), (c5,S), (a4,HALF)] telekom = [(c4,S), (c4,S), (c4,S), (e4,S), (c4,Q)] print("uploading songs") robot.setSong( 1, starwars1 ) robot.setSong( 2, starwars2 ) robot.setSong( 3, starwars3 ) time.sleep(2.0) print("playing part 1") robot.playSongNumber(1) time.sleep(MEASURE_TIME*2.01) print("playing part 2") robot.playSongNumber(2) time.sleep(MEASURE_TIME*2.01) print("playing part 3") robot.playSongNumber(3) robot.setSong( 1, starwars4 ) time.sleep(MEASURE_TIME*1.26) print("playing part 4") robot.playSongNumber(1) robot.setSong( 2, starwars5 ) time.sleep(MEASURE_TIME*1.15) print("playing part 5") robot.playSongNumber(2) robot.setSong( 3, starwars3 ) time.sleep(MEASURE_TIME*1.76) print("playing part 3 again") robot.playSongNumber(3) robot.setSong( 2, starwars6 ) time.sleep(MEASURE_TIME*1.26) print("playing part 4 again") robot.playSongNumber(1) time.sleep(MEASURE_TIME*1.15) print("playing part 6") robot.playSongNumber(2) robot.setSong( 1, telekom ) time.sleep(MEASURE_TIME*1.76) robot.playSongNumber(1) print("done") robot.setSong( 2, telekom ) time.sleep(5) robot.playSongNumber(2) """ robot = create.Create(ROOMBA_PORT) robot.toSafeMode() play_starwars(robot) robot.close() """
dailab/roomba-python
demo.py
<gh_stars>0 import create import time import io import os import sys import argparse # define silence r = 30 # map note names in the lilypad notation to irobot commands c4 = 60 cis4 = des4 = 61 d4 = 62 dis4 = ees4 = 63 e4 = 64 f4 = 65 fis4 = ges4 = 66 g4 = 67 gis4 = aes4 = 68 a4 = 69 ais4 = bes4 = 70 b4 = 71 c5 = 72 cis5 = des5 = 73 d5 = 74 dis5 = ees5 = 75 e5 = 76 f5 = 77 fis5 = ges5 = 78 g5 = 79 gis5 = aes5 = 80 a5 = 81 ais5 = bes5 = 82 b5 = 83 c6 = 84 cis6 = des6 = 85 d6 = 86 dis6 = ees6 = 87 e6 = 88 f6 = 89 fis6 = ges6 = 90 # define some note lengths # change the top MEASURE (4/4 time) to get faster/slower speeds MEASURE = 160 HALF = MEASURE/2 Q = MEASURE/4 E = MEASURE/8 Ed = MEASURE*3/16 S = MEASURE/16 MEASURE_TIME = MEASURE/64. ROOMBA_PORT = "/dev/rfcomm0" FIFO_PATH = "/tmp/roombaCommands" #parser parser = argparse.ArgumentParser(description="Roomba Voice Command Control Software") parser.add_argument("-k", dest="keyword", help="Keyword for addressing the roomba", default="") parser.add_argument("-p", dest="path", help="path where creating the FIFO", default=FIFO_PATH) parser.add_argument("-r", dest="roomba", help="serial port to the roomba", default=ROOMBA_PORT) #parsing args args = parser.parse_args() keyword = args.keyword.lower() print("keyword is " + keyword) FIFO_PATH = args.path print("created fifo in "+ FIFO_PATH) ROOMBA_PORT = args.roomba print("roomba port set to "+ ROOMBA_PORT) #telekom jingle telekom = [(c4,S), (c4,S), (c4,S), (e4,S), (c4,Q)] #fifo init try: os.mkfifo(FIFO_PATH, 0766) except: os.unlink(FIFO_PATH) os.mkfifo(FIFO_PATH, 0766) #robot init robot = create.Create(ROOMBA_PORT, create.SAFE_MODE) robot.setSong(1, telekom) def clean_up(): print("clean up and exit") os.unlink(FIFO_PATH) robot.close() sys.exit(0) def main(): exit_loop = False fifo = open(FIFO_PATH, "r") while exit_loop == False: line = fifo.readline() if line != "": #line = keyword_ignore.sub("", line).strip(" ").strip("\n") line = line.lower().replace(keyword, "").strip(" ").strip("\n") print(line) if line == "clean": robot.toSafeMode() time.sleep(.5) print("starting to clean") robot._write(create.CLEAN) if line == "spot": robot.toSafeMode() time.sleep(.5) print("starting to spot clean") robot._write(create.SPOT) if line == "stop": print("stopping") robot.toSafeMode() time.sleep(.5) if line == "dock": robot.toSafeMode() time.sleep(.5) print("seeking dock") robot._write(create.FORCESEEKINGDOCK) if line == "jingle": robot.toSafeMode() time.sleep(.5) robot.playSongNumber(1) if line == "close": exit_loop = True try: main() except: print("\nexception -> ") clean_up()
pvaneck/tfjs-core
scripts/process_images_for_training.py
<filename>scripts/process_images_for_training.py # Copyright 2017 Smesh LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ====================================================================== # This program converts input images into a format suitable for use with the model builder demo. # Contributed by <NAME>, Smesh Labs (http://smesh.net/labs) # # Before running this program: # - Put all images under <yourImageDir> # - Each image must be prefixed with its class label, followed by '_'. # For example, cat_image00005.jpg # To run: # 1. python process_images_for_training.py --inimgs <absolutePathToImages> # Example: python process_images_for_training.py --inimgs "/mnt/data/myBirdImages/*.jpg" # # Results: find in the current directoty an image file 'images.png' (extension '.png' added automatically), # and a labels file 'labels' (or per command line options) # # Note: # - Make sure that the model-builder-datasets-configuration's data.labels.shape # matches the number of classes found in data # - Make sure that the NN model's output layer matches the number of classes # To-do: # - This code is not suitable for processing large number of images. # - Tested with python v2.7 and v3.5 #====================================================================== from __future__ import absolute_import from __future__ import division from __future__ import print_function import glob import numpy as np from PIL import Image from PIL import ImageOps import ntpath import argparse import os import re import sys # for images targetW = 32 targetH = 32 outImageFile = 'images.png' ## for labels outLabels = 'labels' delimiter = '_' def preprocessImages(FLAGS): path = FLAGS.inimgs targetW = FLAGS.size targetH = FLAGS.size outImageFile = FLAGS.outimgs outLabels = FLAGS.outlabels delimiter = FLAGS.delimiter cwd = os.getcwd() print('...Current working directory =', cwd) print(len(sys.argv)) if path: inputImages = path else: inputImages = cwd print('...Input imagefiles =', inputImages) fileList = [] newFiles = glob.glob(path) if newFiles is not None: print('...', len(newFiles), 'image files found') fileList.extend(newFiles) print('...Found a total of', len(fileList), 'images') if FLAGS.replicate > 1: fileList = np.tile(fileList, FLAGS.replicate) print('...Dataset has been replicated', FLAGS.replicate, 'times') thumbList = [] for n in fileList: img = Image.open(n) thumb = ImageOps.fit(img, (targetW,targetH), Image.ANTIALIAS) thumbList.append(thumb) img.close() imageList = [np.array(im) for im in thumbList] imageList = np.array(imageList, dtype='uint8') a = imageList b = a.reshape([a.shape[0], -1, 3]).squeeze() im = Image.fromarray(b) im.save(outImageFile+'.png') print('...single output image size (width/height) =', FLAGS.size) print('...Saved composed image to:', outImageFile+'.png') # Process class labels pattern = '([a-zA-Z_]*)' + delimiter + '.*$' labels = [re.search(pattern, ntpath.basename(s)).group(1) for s in fileList] classesClearText = np.unique(np.asarray(labels)) print('...', len(classesClearText), 'classes found:', classesClearText) FLAGS.nClassesIn = len(classesClearText) labels5 = pack(classesClearText.tolist(), labels, FLAGS) np.asarray(labels5).astype('uint8').tofile(outLabels) print('...Saved composed labels to:', outLabels) def pack(classes, labels, FLAGS): i = 0 nClassesIn = FLAGS.nClasses if nClassesIn: nClasses = nClassesIn print('...#classes forcibly set to', nClassesIn) else: nClasses = len(classes) length = len(labels) result = [ np.NaN ] * length * nClasses lumpedClass = None while i < length: oneLabel = labels[i] try: if FLAGS.vsOthers: matched = re.search(FLAGS.vsOthers, oneLabel) if matched: index = classes.index(oneLabel) else: index = classes.index(oneLabel) if lumpedClass is None: lumpedClass = index else: index = lumpedClass print('...class altered from', oneLabel, 'to', index) else: index = classes.index(oneLabel) result[i*nClasses+index] = 1 except: e = sys.exc_info()[0] print('!!! unknown class found, or invalid regex:', oneLabel) print( "<p>Error: %s</p>" % e ) i += 1 return result if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument( '--inimgs', type=str, default='train/*.*', help='File path to the input images, default=./train/*.*') parser.add_argument( '--outimgs', type=str, default='images', help='Output file name (without extension) for the composed image') parser.add_argument( '--delimiter', type=str, default='_', help='Delimiter used for parsing class name out of file name. E.g., a file name of "ABC_butterflies.jpg" will yield a class a class name of ABC') parser.add_argument( '--outlabels', type=str, default='labels', help='Output file name for the composed labels') parser.add_argument( '--size', type=int, default=32, help='Width/Height of each image, default=32') parser.add_argument( '--num_channels', type=int, default=3, help='Number of channels') parser.add_argument( '--replicate', type=int, default=1, help='Replicate this dataset this many times, default=1') parser.add_argument( '--nClasses', type=int, help='Set the number of classes. If absent then compute based on data') parser.add_argument( '--vsOthers', type=str, help='When specified this regular expression causes all unmatched sample classes to be lumped into one single class') FLAGS, unparsed = parser.parse_known_args() if unparsed: print('Error, unrecognized flags:', unparsed) exit(-1) preprocessImages(FLAGS)
pvaneck/tfjs-core
scripts/convert_uint8_tensor_to_png.py
<gh_stars>10-100 # Copyright 2017 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Converts an array of 3D tensors to pngs.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import os import numpy as np from PIL import Image FLAGS = None def main(): fpath = os.path.expanduser(FLAGS.uint8_tensor_file) with open(fpath, 'rb') as f: # a has shape N x Width x Height x Channels a = np.frombuffer(f.read(), np.uint8).reshape( [-1, FLAGS.size, FLAGS.size, FLAGS.num_channels]) print('Read', a.shape[0], 'images') print('min/max pixel values: ', a.min(), '/', a.max()) # Make each image take a single row in the big batch image by flattening the # width (2nd) and height (3rd) dimension. # a has shape N x (Width*Height) x Channels. a = a.reshape([a.shape[0], -1, FLAGS.num_channels]).squeeze() im = Image.fromarray(a) im.save(fpath + '.png') print('Saved image with width/height', im.size, 'at', fpath + '.png') if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument( '--uint8_tensor_file', type=str, required=True, help='File path to the binary uint8 tensor to convert to png') parser.add_argument( '--size', type=int, required=True, help='Width/Height of each image') parser.add_argument( '--num_channels', type=int, required=True, help='Number of channelse') FLAGS, unparsed = parser.parse_known_args() if unparsed: print('Error, unrecognized flags:', unparsed) exit(-1) main()
andrelikesdogs/sm64-randomizer
sm64r/Area.py
<filename>sm64r/Area.py from typing import Dict class Area: def __init__(self, area_id : int, name : str, properties : Dict): self.id = area_id self.name = name self.properties = properties def __str__(self): return f'<Area {hex(self.id)}: {self.name}>: {repr(self.properties)}'
andrelikesdogs/sm64-randomizer
sm64r/RandomModules/Objects/Whitelist.py
<gh_stars>10-100 from pathlib import Path import json import os from sm64r.Constants import application_path from sm64r.Entities import Object3D DEBUG_HIT_INDICES = {} class RandomizeObjectsWhitelist: def __init__(self, whitelist): self.object_whitelist = whitelist def matches_with(self, matching, object3d): matches = 0 # don't match empty sets if not len(matching.keys()): return (matches, False) if "behaviours" in matching: if object3d.behaviour is None: return (matches, False) elif object3d.behaviour not in matching["behaviours"]: return (matches, False) else: matches += 1 if "model_id" in matching: if object3d.model_id is None: return (matches, False) elif matching["model_id"] != object3d.model_id: return (matches, False) else: matches += 1 if "source" in matching: if matching["source"] != object3d.source: return (matches, False) else: matches += 1 if "course_id" in matching: if object3d.level is None or object3d.level.course_id is None: return (matches, False) elif matching["course_id"] != object3d.level.course_id: return (matches, False) else: matches += 1 if "course_property" in matching: # course property check for current area and for current level found_in_level_or_area = False matching_property = matching["course_property"] # areas if object3d.area_id in object3d.level.areas: if matching_property in object3d.level.areas[object3d.area_id].properties: found_in_level_or_area = True # level if matching_property in object3d.level.properties: found_in_level_or_area = True if not found_in_level_or_area: return (matches, False) else: matches += 1 if "bparam1" in matching: if len(object3d.bparams) < 1 or object3d.bparams[0] != matching["bparam1"]: return (matches, False) else: matches += 1 if "bparam2" in matching: if len(object3d.bparams) < 2 or object3d.bparams[1] != matching["bparam2"]: return (matches, False) else: matches += 1 if "bparam3" in matching: if len(object3d.bparams) < 3 or object3d.bparams[2] != matching["bparam3"]: return (matches, False) else: matches += 1 if "bparam4" in matching: if len(object3d.bparams) < 4 or object3d.bparams[3] != matching["bparam4"]: return (matches, False) else: matches += 1 if "area_id" in matching: if matching["area_id"] != object3d.area_id: return (matches, False) else: matches += 1 return (matches, True) def get_shuffle_properties(self, object3d : Object3D): best_match = None best_match_count = 0 # check against all matching/whitelist entries for whitelist_entry in self.object_whitelist: if whitelist_entry["match"] is None: continue # if whitelist entry has an exclude property, see if we can skip this entry if whitelist_entry["exclude"] is not None: _, match_exclude = self.matches_with(whitelist_entry["exclude"], object3d) if match_exclude: continue # the more precise the matching, the more priority it will have matches, did_match = self.matches_with(whitelist_entry["match"], object3d) # increase priority for matches from "for" rules if "from_for" in whitelist_entry and whitelist_entry["from_for"]: matches += 1 if did_match and matches > best_match_count: best_match = whitelist_entry best_match_count = matches return best_match
andrelikesdogs/sm64-randomizer
sm64r/RandomModules/Text.py
<filename>sm64r/RandomModules/Text.py import sys import string from random import shuffle from typing import NamedTuple from sm64r.Randoutils import format_binary from sm64r.Entities.TextEntryDialog import TextEntryDialog DATA_DIALOG_START = 0x803156 TBL_DIALOG_START = 0x81311E TBL_DIALOG_END = TBL_DIALOG_START + 170 * 16 TBL_LEVEL_NAMES = 0x8140BE TBL_ACT_NAMES = 0x814A82 TEXT_TO_IGNORE = [25, 26, 27, 28, 29] SM64_ENCODING_CHARS = { 0x50: '[UP]', 0x51: '[DOWN]', 0x52: '[LEFT]', 0x53: '[RIGHT]', 0x54: '[A]', 0x55: '[B]', 0x56: '[C]', 0x57: '[Z]', 0x58: '[R]', 0x6F: ',', 0xD0: ' ', 0xD1: "[THE]", 0xD2: "[YOU]", 0x9E: ' ', 0x9F: '-', 0xE1: '(', 0xE2: ')(', 0xE3: ')', 0xE4: '+', 0xE5: '&', 0xE6: ':', 0xF2: '!', 0xF4: '?', 0xF5: '"', 0xF6: '"', 0xF7: '~', 0xF9: '$', 0xFA: '[STAR]', 0xFB: '[X]', 0xFC: '[.]', 0xFD: '[STAR_UNOBTAINED]', 0xFE: '\n', 0xFF: '[END]' } idx = 0 for i in range(10): SM64_ENCODING_CHARS[idx] = str(i) idx += 1 for char in string.ascii_uppercase: SM64_ENCODING_CHARS[idx] = char idx += 1 for char in string.ascii_lowercase + '\'.': SM64_ENCODING_CHARS[idx] = char idx += 1 keys = list(sorted(SM64_ENCODING_CHARS.keys())) for key in keys: pass # print(hex(key), SM64_ENCODING_CHARS[key]) class TextRandomizer: def __init__(self, rom : 'ROM'): self.rom = rom def read_text_at_offset(self, offset): # 0x111A13 0x7D34 cursor = DATA_DIALOG_START + offset char = None text = [] charcodes = [] while char != '[END]': charcode = self.rom.read_integer(cursor) #print(charcode) if charcode not in SM64_ENCODING_CHARS: charcode = 0x9E charcodes.append(charcode) char = SM64_ENCODING_CHARS[charcode] text.append(char) cursor += 1 return ''.join(text) def read_dialog_table_entries(self): cursor = TBL_DIALOG_START entry_id = 0 entries = [] while cursor < TBL_DIALOG_END: table_entry = self.rom.read_bytes(cursor, 14) offset = self.rom.read_integer(cursor + 14, 2) text_at_entry = self.read_text_at_offset(offset) entries.append(TextEntryDialog(entry_id, text_at_entry, offset, mem_address_pointer=cursor, mem_address_text=DATA_DIALOG_START+offset)) entry_id += 1 cursor += 16 return entries def shuffle_dialog_pointers(self): self.dialog_entries = self.read_dialog_table_entries() shuffled_entries = self.dialog_entries.copy() shuffle(shuffled_entries) for entry_index, entry in enumerate(self.dialog_entries): new_entry = shuffled_entries[entry_index] entry.set(self.rom, "offset", new_entry.offset) ''' def read_entries(self): entries = [] cursor = DIALOG_START while cursor < DIALOG_END: char = None entry = [] while char != SM64_ENCODING_CHARS[0xFF]: char_int = self.rom.read_integer(cursor) if char_int in SM64_ENCODING_CHARS: char = SM64_ENCODING_CHARS[char_int] #print(char) entry.append(char) cursor += 1 print(''.join(entry)) entries.append(entry)'''
andrelikesdogs/sm64-randomizer
sm64r/RandomModules/Music.py
from random import shuffle from typing import List import logging from sm64r.Parsers.Level import Level from sm64r.Constants import SONG_NAMES class MusicRandomizer: def __init__(self, rom : 'ROM'): self.rom = rom def find_music_seqs(self, levels: List[Level]): music_seq_ids = [] music_seq_pos = [] # TODO: use levelscript parser system for this for level in levels: for (cmd, data, pos) in self.rom.read_cmds_from_level_block(level, filter=[0x36, 0x37]): sequence_id = None offset = 3 if cmd == 0x36 else 1 sequence_id = data[offset] # only consider music that are in range 1 to 0x22 valid = sequence_id > 0x0 and sequence_id <= 0x22 #print(level.name + ' has song ' + (SONG_NAMES[sequence_id] if sequence_id < len(SONG_NAMES) else str(sequence_id))) if valid: music_seq_ids.append(sequence_id) music_seq_pos.append((pos + offset, level)) return (music_seq_ids, music_seq_pos) def shuffle_music(self, levels : List[Level]): logging.info("Randomizing Level Music") (ids, pos) = self.find_music_seqs(levels) shuffle(ids) shuffle(pos) for seq_index in range(len(ids) - 1): (position, level) = pos[seq_index] seq_id = ids[seq_index] #print(f'{level.name} is now using music from {SONG_NAMES[seq_id]}') # write new music self.rom.target.seek(position, 0) self.rom.target.write(seq_id.to_bytes(1, 'little'))
andrelikesdogs/sm64-randomizer
sm64r/Level.py
from typing import List, Dict from .Area import Area class Level: def __init__(self, course_id : int, name : str, properties : Dict = None, areas : List[Area] = None, offset : int = None): self.course_id = course_id self.name = name self.properties = properties or {} self.offset = offset self.areas = areas or [] def __str__(self): return f'<Level {hex(self.course_id)}: {self.name}>' #: {repr(self.properties)}, {[str(area) for area in self.areas]}'
andrelikesdogs/sm64-randomizer
sm64r/Randoutils.py
import io import math from random import random def hexlify(l): if type(l) == list or type(l) == tuple: return [(hexlify(v)) for v in l] else: if l == None: return 'None' else: return hex(l) def format_binary(bin_data): if bin_data is None: return 'NO DATA' return ' '.join(hex(b)[2:].upper().rjust(2, '0') for b in bin_data) def round_up_at_half(n): if n % 1 >= 0.5: return math.ceil(n) return math.floor(n) def align_address(address, alignment=1): aligned_count = float(address) / float(alignment) alignment_corrected = round_up_at_half(address) return int(alignment_corrected) * alignment def pretty_print_table(title, data): print(title.center(73, "-")) longest_line = max([len(label) for label in data.keys()]) for (label, value ) in data.items(): print(f' {str(label).ljust(longest_line + 2, " ")} {str(value).ljust(longest_line + 2, " ")}', end='\n') print("-" * 73) #print() def format_float(f): return f"{f:.5f}" def clamp(v, mi, ma): return max(mi, min(v, ma)) # From stackoverflow: https://stackoverflow.com/a/34325723 def print_progress_bar (iteration, total, prefix = '', suffix = '', decimals = 1, length = 100, fill = '█'): """ Call in a loop to create terminal progress bar @params: iteration - Required : current iteration (Int) total - Required : total iterations (Int) prefix - Optional : prefix string (Str) suffix - Optional : suffix string (Str) decimals - Optional : positive number of decimals in percent complete (Int) length - Optional : character length of bar (Int) fill - Optional : bar fill character (Str) """ percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total))) filledLength = int(length * iteration // total) bar = fill * filledLength + '-' * (length - filledLength) print('\r%s |%s| %s%% %s' % (prefix, bar, percent, suffix), end = '\r') # Print New Line on Complete if iteration == total: print() def generate_obj_for_level_geometry(level_geometry : "LevelGeometry"): print(f'generating .obj for {level_geometry.level.name}') output = "" output += f"# Collision Data for {level_geometry.level.name}\n" output += f"mtllib ./debug.mtl\n" vertex_total = 0 #print(f'{len(level_geometry.area_geometries.keys())} areas') for (area_id, geometry) in level_geometry.area_geometries.items(): output += f"g level_area_{area_id}\n" #print(collision_entry) for vertex in geometry.vertices: output += "v " + " ".join(list(map(str, map(format_float, vertex)))) + "\n" # dont output triangles on layer 0, origin layer for (index, triangle) in enumerate(geometry.faces): #normal = round(clamp(abs(geometry.face_normals[index][1]), 0, 1000) / 1000) collision_type = level_geometry.get_collision_type_for_triangle(area_id, index) output += f"# Collision Type: {hex(collision_type)}\n" output += f"usemtl debug_{collision_type}\n" #output += f"usemtl debug_gradient_{normal}\n" output += "f " + " ".join(list(map(lambda x: str(vertex_total + x), triangle))) + "\n" return output distinguishable_colors = [(25, 25, 112), (0, 100, 0), (255, 0, 0), (255, 215, 0), (0, 255, 0), (0, 255, 255), (255, 0, 255), (255, 182, 193)] def generate_debug_materials(): lines = [] for index in range(2**16): r = random() g = random() b = random() lines.append(f'newmtl debug_{index}') lines.append(f'Ka {r} {g} {b}') lines.append(f'Kd {r} {g} {b}') lines.append('Ks 0.000 0.000 0.000') lines.append('Ns 10.000') for index in range(1000): c = index / 1000 lines.append(f'newmtl debug_gradient_{index}') lines.append(f'Ka {c} {c} {c}') lines.append(f'Kd {c} {c} {c}') lines.append('Ks 0.000 0.000 0.000') lines.append('Ns 10.000') return "\n".join(lines)
andrelikesdogs/sm64-randomizer
sm64r/RandomModules/Colors.py
from random import randint import colorsys import logging class ColorRandomizer: def __init__(self, rom : 'ROM'): self.rom = rom (start_segment_0x2, _) = self.rom.segments_sequentially[2] self.coin_addresses = { 'YELLOW': start_segment_0x2 + 0x56cc, 'BLUE': start_segment_0x2 + 0x570c, 'RED': start_segment_0x2 + 0x574c } def randomize_coin_colors(self): logging.info("Randomizing Coin Colors") hsl_offset = randint(0, 360) hsl_dist = 120 hsl_index = 0 coin_colors = [] for coin_type in self.coin_addresses.keys(): # hue shift for coin colors, to ensure difference in color hue = (hsl_offset + (hsl_dist * hsl_index)) % 360 hsl_index += 1 saturation = 50.0 luminence = 50.0 (r, g, b) = colorsys.hls_to_rgb(hue / 360.0, luminence / 100.0, saturation / 100.0) #randint(120, 255), randint(120, 255), randint(120, 255) logging.info(f'Coin Type: {coin_type} color: rgb({int(r * 255)}, {int(g * 255)}, {int(b * 255)})') coin_colors.append((coin_type, (int(r * 255), int(g * 255), int(b * 255)))) for (coin_type, color) in coin_colors: (r, g, b) = color cursor = self.coin_addresses[coin_type] for _ in range(4): self.rom.write_integer(cursor, r) self.rom.write_integer(cursor + 1, g) self.rom.write_integer(cursor + 2, b) cursor += 0x10 # 0xE padding between entries
andrelikesdogs/sm64-randomizer
sm64r/RandomModules/Instruments.py
<reponame>andrelikesdogs/sm64-randomizer from random import shuffle, choice from sm64r.Randoutils import format_binary INSTRUMENT_SET_LENGTHS = [ 6, # NLST 0 - SFX - 8000hz 9, # NLST 1 - SFX, Footsteps - 8000hz 3, # NLST 2 - SFX, Water - 8000hz 10, # NLST 3 - SFX, Sand (?) - 8000hz 16, # NLST 4 - SFX - 8000hz 16, # NLST 5 - SFX 16, # NLST 6 - SFX 15, # NLST 7 - SFX, Misc 27, # NLST 8 - Mario 7, # NLST 9 - SFX 24, # NLST 10 - SFX, Voices 12, # NLST 11 - Music, Snow Theme 16, # NLST 12 - Music, Unusued 13, # NLST 13 - Music, Race Theme (Slides, KtQ) 7, # NLST 14 - Music, Inside Castle 4, # NLST 15 - Music, SSL, LLL 10, # NLST 16 - Music, Haunted House Theme 14, # NLST 17 - Music, Title Theme 12, # NLST 18 - Music, Bowser Battle Theme 16, # NLST 19 - Music, Water (JRB, DDD) Theme 5, # NLST 20 - Music, Piranha Plant Sleeping 10, # NLST 21 - Music, HMC 2, # NLST 22 - Star Select 13, # NLST 23 - Music, Wing Cap 15, # NLST 24 - Music, Metal Cap 13, # NLST 25 - Music, Bowser Course Theme 13, # NLST 26 - Music, Fanfares 12, # NLST 27 - Music, Boss Fight 7, # NLST 28 - Music, Looping Stairs 6, # NLST 29 - Music, Final Boss Fight, Church Organs 4, # NLST 30 - Music, Unused 13, # NLST 31 - Music, Star Catch (?) 9, # NLST 32 - Music, Toad 4, # NLST 33 - Music, Ghost Merry-Go-Round 12, # NLST 34 - Music, Bob-Omb Battleifeld 8, # NLST 35 - Music, Unusued 10, # NLST 36 - Music, File Select 16, # NLST 37 - Music, Credits ] class InstrumentRandomizer: def __init__(self, rom : 'ROM'): self.rom = rom def shuffle_instruments(self): ''' # Lookup Table Method instrument_table = self.rom.read_bytes(0x7cc620, 0x23 * 2) # 0x25 instrument sets (half bytes) instrument_table = list(map(lambda x: [0xf0 & x, 0x0f & x], list(instrument_table))) print(instrument_table) print(format_binary(instrument_table)) ''' # Instrument Table Method sequence_instrument_table = list(self.rom.read_bytes(0x7cc674, 37)) instruments_tuples = [(seq_pair & 0xf0, seq_pair & 0x0f) for seq_pair in sequence_instrument_table] current_idx = 0 tries = 0 while current_idx < len(instruments_tuples): if tries > 1000: #print(f'couldnt find new inst set for seq index ${hex(current_idx)}') break new_inst_set = choice(instruments_tuples) # pick one at a time, allowing duplicates old_inst_set = instruments_tuples[current_idx] # check if it chose the default identical = new_inst_set[1] == old_inst_set[1] # are both from music or are both from sfx sfx_type_match = (new_inst_set[1] > 10 and old_inst_set[1] > 10) or (new_inst_set[1] < 10 and old_inst_set[1] < 10) # correct instrument lengths inst_lengths_gte = INSTRUMENT_SET_LENGTHS[new_inst_set[1]] >= INSTRUMENT_SET_LENGTHS[old_inst_set[1]] #is_short_instrument_set = INSTRUMENT_SET_LENGTHS[new_inst_set[1]] < 5 if not identical and sfx_type_match and inst_lengths_gte: # use old inst for #0 and new one for #1 because #0 is not really changing much #print(f'instrument change: [{hex(old_inst_set[0])} {hex(old_inst_set[1])}] to [{hex(new_inst_set[0])} {hex(new_inst_set[1])}]') self.rom.write_byte(0x7cc674 + current_idx, bytes([new_inst_set[0] | new_inst_set[1]])) current_idx = current_idx + 1 tries = 0 tries = tries + 1
andrelikesdogs/sm64-randomizer
sm64r/Entities/BaseMemoryRecord.py
from typing import NamedTuple, Union import math class MemoryMapping(NamedTuple): address_start: int address_end : int data_type: Union[str, tuple] # uint, int, @property def size(self): return self.address_end - self.address_start class BaseMemoryRecord: memory_address = None memory_mapping = None def __init__(self): # if this is not done, all memory mappings share one dict instance self.memory_mapping = {} def set(self, rom : 'ROM', key, value): if key not in self.memory_mapping: raise ValueError(f'"{key}" has no memory mapping') memory_information = self.memory_mapping[key] if memory_information.data_type == 'uint': rom.write_integer(memory_information.address_start, value, memory_information.size, False) setattr(self, key, value) elif memory_information.data_type == 'int': rom.write_integer(memory_information.address_start, value, memory_information.size, True) setattr(self, key, value) elif type(memory_information.data_type) == tuple: size = math.floor(memory_information.size / len(memory_information.data_type)) setattr(self, key, value) for index, value_type in enumerate(list(memory_information.data_type)): rom.write_integer(memory_information.address_start + index * size, value[index], size, value_type == 'int') else: raise TypeError(f'Datatype unknown, can\'t format this data for writing') def add_mapping(self, variable_key : str, data_type :str, start : int, end : int = None): if not end: end = start + 1 self.memory_mapping[variable_key] = MemoryMapping(start, end, data_type)
andrelikesdogs/sm64-randomizer
sm64r/Parsers/Imaging.py
<reponame>andrelikesdogs/sm64-randomizer<gh_stars>10-100 from PIL import Image import numpy as np class N64Image: def __init__(self, img : Image): self.img = img self.bytes_original = self.img.tobytes() @staticmethod def scale_8_to_5(val): return int(((((val) + 4) * 0x1F) / 0xFF)) @staticmethod def scale_5_to_8(val): return int(int(val * 0xFF) / 0x1F) def read_rgba16(self): """ Returns the loaded image as a bytearray of the RGBA16 format present on the N64 Returns: bytes -- A bytes object with the current image in RGBA16 format """ (width, height) = self.img.size px = self.img.load() n64_img_bytes = bytearray(len(self.bytes_original)) for y in range(0, height): for x in range(0, width): idx = (y * width + x) * 2 (r, g, b, a) = px[x, y] r_5 = N64Image.scale_8_to_5(r) g_5 = N64Image.scale_8_to_5(g) b_5 = N64Image.scale_8_to_5(b) n64_img_bytes[idx] = int((r_5 << 3) | (g_5 >> 2)) n64_img_bytes[idx+1] = int(((g & 0x03) << 6) | (b_5 << 1) | (1 if a > 0 else 0)) return bytes(n64_img_bytes) class Imaging: @staticmethod def parse_image(path): with open(path, "rb") as file: loaded_img = Image.open(file) return N64Image(loaded_img) @staticmethod def from_ingame(rom, texture): ingame_bytes = rom.read_bytes(texture.position, texture.size) width = texture.width height = texture.height img_bytes = np.zeros((width, height, 4), dtype="uint8") for y in range(0, height): for x in range(0, width): img_idx = (y * width + x) idx = img_idx * 2 px1 = ingame_bytes[idx] px2 = ingame_bytes[idx+1] r = N64Image.scale_5_to_8((px1 & 0xF8) >> 3) g = N64Image.scale_5_to_8((px1 & 0x07) << 2 | ((px2 & 0xC0) >> 6)) b = N64Image.scale_5_to_8((px1 & 0x3E) >> 1) a = 255 if (px2 & 0x1) > 0 else 0 img_bytes[y,x,0] = r img_bytes[y,x,1] = g img_bytes[y,x,2] = b img_bytes[y,x,3] = a img = Image.fromarray(img_bytes) #img.show() return N64Image(img)
andrelikesdogs/sm64-randomizer
sm64r/Scripts/find_star_locations.py
<filename>sm64r/Scripts/find_star_locations.py import struct import re from Rom import ROM rom_path = "Super Mario 64.z64" rom_out = "Super Mario 64.ext.out.z64" behaviour_locations = [ (0xF0000, 0x1FFFFF) ] known_star_locations = { 'BOB: Koopa the Quick': (3030, 4500, -4600), # short 'THI: Koopa the Quick': (7100, -1300, -6000), # short 'BOB: King Bob-Omb': (2000.0,4500.0,-4500.0), 'WF: Whomp Boss': (180.0, 3880.0, 340.0), 'SSL: Eyerok': (0.0, -900.0, -3700.0), 'LLL: Big Bully': (0.0, 950.0, -6800.0), 'SL: Ice Bully': (130.0, 1600.0, -4335.0), 'THI: Pirana Plants': (-6300.0, -1850.0, -6300.0), 'CCM: Racing Penguin': (-7339.0, -5700.0, -6774.0), 'THI: Wiggler': (0.0, 2048.0, 0.0), 'PSS: Peach Slide': (-6358.0, -4300.0, 4700.0), 'CCM: Penguin Baby': (3500.0, -4300.0, 4650.0), 'JRB: 4 Treasure Chests': (-1800.0, -2500.0, -1700.0), 'BBH: Hallway/Staircase Big Boo': (980.0, 1100.0, 250.0), 'SSL: Klepto': (-5550.0, 300.0, -930.0), 'BBH: Merry-Go-Round Big Boo': (-1600.0, -2100.0, 205.0), 'BBH: Mr. I': (1370.0, 2000.0, -320.0), 'BBH: Roof Balcony Big Boo': (700.0, 3200.0, 1900.0), 'LLL: Big Bully with Minions': (3700.0, 600.0, -5500.0), 'TTM: Cage Star': (2500.0, -1200.0, 1300.0), 'DDD: Manta Ray': (-3180.0, -3600.0, 120.0), 'CCM: Snowman Assembly': (-4700.0, -1024.0, 1890.0), 'CCM: Leave Slide': (2500.0, -4350.0, 5750.0), 'DDD: Water Rings': (3400.0, -3200.0, -500.0), } # 00 00 00 07 D0 # 00 00 00 7D 00 with ROM(rom_path, rom_out) as rom_orig: rom_orig.verify_header() new_rom_path = rom_orig.try_extend() with ROM(new_rom_path, rom_out) as rom: rom.verify_header() rom.read_configuration() rom.print_info() for (bstart, bend) in behaviour_locations: raw_bhv = rom.read_bytes(bstart, bend - bstart) str_bhv = raw_bhv.hex() print(f"Read {len(raw_bhv)} bytes from behaviour script location") for star_name, star_location in known_star_locations.items(): print(star_name) print(star_location) pos_bytes = [] for pos_comp in star_location: if type(pos_comp) is float: pos_bytes.append(struct.pack('>f', pos_comp)) if type(pos_comp) is int: pos_bytes.append(struct.pack('>h', pos_comp)) re_bytes = list(map(lambda x: re.compile(x.hex().lstrip('0'), re.I), pos_bytes)) found_locations = [[], [], []] for comp_idx, re_byte in enumerate(re_bytes): for m in re_byte.finditer(str_bhv): found_locations[comp_idx].append(bstart + m.start()) print('Matches:', len(found_locations[0]), len(found_locations[1]), len(found_locations[2])) #print(found_locations)
andrelikesdogs/sm64-randomizer
tests/test_config.py
import pytest from Config import Config def test_vanilla_rom(): config = Config.find_configuration(0x635a42c5) # Vanilla US ROM assert config is not None, "Configuration not found for Vanilla US ROM Checksum" assert config.name, "Missing Name" assert len(config.checksums) > 0, "Missing Checksums" assert len(config.levels) > 0, "Missing Levels" assert len(config.object_entries) > 0, "Missing Objects" assert not config.validation_errors assert not config.validation_warnings for entry in config.object_entries: print(entry) if entry["name"] != 'Default': assert entry["match"] is None or len(entry["match"]) > 0, "Empty matchings are only allowed for the 'Default' object definition" simple_config_rom = ''' name: "Testing Suite Simple" rom: - checksum: 0x123456 name: "Testing Shit" macro_table_address: 0x0 special_macro_table_address: 0x0 defined_segments: - segment: 0x0 start: 0x0 end: 0x0 ''' simple_config_level = ''' levels: - name: "A Test Level" course_id: 0x12 properties: - overworld ''' # configuration with only one object simple_config = \ simple_config_rom + \ simple_config_level + \ ''' object_randomization: objects: - name: "Test" match: 0x1234 rules: - max_slope: 0.0 ''' def test_simple_config(): config = Config.load_configuration_from_str(simple_config) assert config.name == 'Testing Suite Simple', "Invalid Name" assert config.checksums[0].get('checksum') == 0x123456, "Invalid Checksum" assert len(config.object_entries) == 2, "Invalid Object amount" assert config.object_entries[0].get('name') == 'Default', "No default object root" assert config.object_entries[1].get('name') == 'Test', "Invalid Order or no Test Object loaded" assert 0x12 in list(config.levels_by_course_id.keys()), "Level not loaded" # configuration that nests objects with rules, checking if inheritance works object_nesting_config = \ simple_config_rom + \ simple_config_level + \ ''' object_randomization: objects: - name: "Test" rules: - max_slope: 0.0 objects: - name: "A" match: 0x1 rules: - max_slope: 0.1 ''' def test_object_nesting(): config = Config.load_configuration_from_str(object_nesting_config) assert len(config.object_entries) == 3, "Invalid Object amount" assert "Test" in list(map(lambda x: x["name"], config.object_entries)), "Name concatination invalid" assert len(config.object_entries[0].get('children')) == 1, "Invalid amount of children for root" object_match_for_config = \ simple_config_rom + \ simple_config_level + \ ''' object_randomization: rules: - max_slope: 0.1 - max_y: 1 - underwater: never objects: - name: "Level 1" match: 0x13001234 objects: - name: "Level 1 with [0x1]" match: - bparam1: 0x1 - name: "Level 1 with [0x2]" match: - bparam1: 0x2 - name: "Level 1 with 0x2" match: - bparam1: 0x3 - name: "Level 1 but underwater" match: - course_property: disable_water_check for: - 'Level 1' rules: - underwater: allowed ''' def test_object_match_for(): config = Config.load_configuration_from_str(object_match_for_config) assert "Level 1" in list(map(lambda x: x["name"], config.object_entries)), "Level 1 did not get included" # match for rules assert "Level 1 but underwater: Level 1 with [0x1]" in list(map(lambda x: x["name"], config.object_entries)), "Nested object definitions did not get included" # main node too, not just children assert "Level 1 but underwater: Level 1" in list(map(lambda x: x["name"], config.object_entries)), "Nested object definition did not include the root object definition" for entry in config.object_entries: print(entry) if entry["name"] != 'Default': assert entry["match"] is not None and len(entry["match"]) > 0, "Empty matchings are only allowed for the 'Default' object definition"
andrelikesdogs/sm64-randomizer
sm64r/Constants.py
from pathlib import Path import os import json import sys from .Parsers.Level import Level application_path = None if getattr(sys, 'frozen', False): #print("frozen") #print("exec: ", sys.executable) #print("argv:", sys.argv[0]) application_path = os.path.realpath(os.path.dirname(sys.executable)) else: #print("unfrozen") application_path = os.path.dirname(os.path.abspath(os.path.join(__file__, ".."))) LVL_MAIN=Level(0x108A10, 0x108A40, None, "Main Entry") LVL_GAME_OVER=Level(0x269EA0, 0x26A3A0, None, "Game Over") LVL_MAIN_MENU=Level(0x2A6120, 0x2A65B0, 0x26, "Main Menu") LVL_MAIN_SCR=Level(0x2ABCA0, 0x2AC6B0, None, "Main Scripts") LVL_CASTLE_GROUNDS=Level(0x4545E0, 0x454E00, 0x10, "Castle Grounds") # 0 LVL_CASTLE_INSIDE=Level(0x3CF0D0, 0x3D0DC0, 0x06, "Castle Inside") # 0 LVL_CASTLE_COURTYARD=Level(0x4AF670, 0x4AF930, 0x1A, "Castle Courtyard") # 0 LVL_BOB=Level(0x405A60, 0x405FB0, 0x09, "Bob-omb Battlefield") # 1 LVL_WF=Level(0x49DA50, 0x49E710, 0x18, "Whomp's Fortress") # 2 LVL_JRB=Level(0x423B20, 0x4246D0, 0x0C, "<NAME>") # 3 LVL_CCM=Level(0x395C90, 0x396340, 0x05, "Cool, Cool Mountain") # 4 LVL_BBH=Level(0x3828C0, 0x383950, 0x04, "Big Boo's Haunt") # 5 LVL_HMC=Level(0x3E6A00, 0x3E76B0, 0x07, "Hazy Maze Cave") # 6 LVL_LLL=Level(0x48C9B0, 0x48D930, 0x16, "Lethal Lava Land") # 7 LVL_SSL=Level(0x3FB990, 0x3FC2B0, 0x08, "Shifting Sand Land") # 8 LVL_DDD=Level(0x495A60, 0x496090, 0x17, "Dire, Dire Docks") # 9 LVL_SL=Level(0x40E840, 0x40ED70, 0x0A, "Snowman's Land") # 10 LVL_WDW=Level(0x419F90, 0x41A760, 0x0B, "Wet-Dry World") # 11 LVL_TTM=Level(0x4EB1F0, 0x4EC000, 0x24, "Tall, Tall Mountain") # 12 LVL_THI=Level(0x42C6E0, 0x42CF20, 0x0D, "Tiny-Huge Island") # 13 LVL_TTC=Level(0x437400, 0x437870, 0x0E, "Tick Tock Clock") # 14 LVL_RR=Level(0x44A140, 0x44ABC0, 0x0F, "Rainbow Ride") # 15 LVL_VANISH_CAP=Level(0x461220, 0x4614D0, 0x12, "Vanish Cap") # 22 LVL_METAL_CAP=Level(0x4BE9E0, 0x4BEC30, 0x1C, "Metal Cap") # 20 LVL_WING_CAP=Level(0x4C2700, 0x4C2920, 0x1D, "Wing Cap") # 21 LVL_BOWSER_1=Level(0x45BF60, 0x45C600, 0x11, "Bowser in the Dark World") # Bowser 1 "BIDW", # 16 LVL_BOWSER_1_BATTLE=Level(0x4C41C0, 0x4C4320, 0x1E, "Bowser in the Dark World Battle") LVL_BOWSER_2=Level(0x46A840, 0x46B090, 0x13, "Bowser in the Fire Sea") # Bowser 2 "BIFS", # 17 LVL_BOWSER_2_BATTLE=Level(0x4CE9F0, 0x4CEC00, 0x21, "Bowser in the Fire Sea Battle") LVL_BOWSER_3=Level(0x477D00, 0x4784A0, 0x15, "Bowser in the Sky") # Bowser 3 "BITS", # 18 LVL_BOWSER_3_BATTLE=Level(0x4D14F0, 0x4D1910, 0x22, "Bowser in the Sky Battle") LVL_SECRET_AQUARIUM=Level(0x46C1A0, 0x46C3A0, 0x14, "Secret Aquarium") # 24 LVL_SECRET_PEACH_SLIDE=Level(0x4B7F10, 0x4B80D0, 0x1B, "Secret Slide") # 19 LVL_SECRET_RAINBOW=Level(0x4CD930, 0x4CDBD0, 0x1F, "Rainbow Bonus") # 23 """ All courses, mostly in order """ ALL_LEVELS = [ # Special LVL_MAIN, LVL_GAME_OVER, LVL_MAIN_MENU, LVL_MAIN_SCR, # Castle LVL_CASTLE_GROUNDS, LVL_CASTLE_INSIDE, LVL_CASTLE_COURTYARD, # Main Levels LVL_BOB, LVL_WF, LVL_JRB, LVL_CCM, LVL_BBH, LVL_HMC, LVL_LLL, LVL_SSL, LVL_DDD, LVL_SL, LVL_WDW, LVL_TTM, LVL_THI, LVL_TTC, LVL_RR, # Cap Levels LVL_VANISH_CAP, LVL_METAL_CAP, LVL_WING_CAP, # Bowser Levels LVL_BOWSER_1, LVL_BOWSER_1_BATTLE, LVL_BOWSER_2, LVL_BOWSER_2_BATTLE, LVL_BOWSER_3, LVL_BOWSER_3_BATTLE, # Secrets LVL_SECRET_AQUARIUM, LVL_SECRET_PEACH_SLIDE, LVL_SECRET_RAINBOW, ] LEVEL_SHORT_CODES = { LVL_BOB: 'BOB', LVL_WF: 'WF', LVL_JRB: 'JRB', LVL_CCM: 'CCM', LVL_BBH: 'BBH', LVL_HMC: 'HMC', LVL_LLL: 'LLL', LVL_SSL: 'SSL', LVL_DDD: 'DDD', LVL_SL: 'SL', LVL_WDW: 'WDW', LVL_TTM: 'TTM', LVL_THI: 'THI', LVL_TTC: 'TTC', LVL_RR: 'RR', LVL_BOWSER_1: 'BIDW', LVL_BOWSER_2: 'BIFS', LVL_BOWSER_3: 'BITS', LVL_SECRET_AQUARIUM: 'AQUARIUM', LVL_SECRET_PEACH_SLIDE: 'SLIDE', LVL_SECRET_RAINBOW: 'OTR', LVL_VANISH_CAP: 'VC', LVL_METAL_CAP: 'MC', LVL_WING_CAP: 'WC' } """ Castle Levels, inside, outside and courtyard """ CASTLE_LEVELS=[LVL_CASTLE_GROUNDS, LVL_CASTLE_INSIDE, LVL_CASTLE_COURTYARD] """ Mission Levels from BOB to TTC + RR """ MISSION_LEVELS=[LVL_BOB, LVL_WF, LVL_JRB, LVL_CCM, LVL_BBH, LVL_HMC, LVL_LLL, LVL_SSL, LVL_DDD, LVL_SL, LVL_WDW, LVL_TTM, LVL_THI, LVL_TTC, LVL_RR] """ Levels to obtain certain caps """ CAP_LEVELS=[LVL_WING_CAP, LVL_METAL_CAP, LVL_VANISH_CAP] """ Bowser levels (before fight) """ BOWSER_STAGES=[LVL_BOWSER_1, LVL_BOWSER_2, LVL_BOWSER_3] """ Special Levels that are not "really" playable """ SPECIAL_LEVELS=[LVL_MAIN, LVL_MAIN_MENU, LVL_GAME_OVER, LVL_MAIN_SCR] """ Mapping LEVEL-ID -> LEVEL """ LEVEL_ID_MAPPING={level.course_id: level for level in ALL_LEVELS} """ This is to ensure playability with key-doors """ GROUND_FLOOR_LEVELS = [ LVL_BBH, LVL_BOB, LVL_CCM, LVL_WF, LVL_JRB, LVL_SECRET_AQUARIUM, LVL_SECRET_PEACH_SLIDE, LVL_WING_CAP, LVL_BOWSER_1 ] BASEMENT_LEVELS = [ LVL_SSL, LVL_DDD, LVL_BOWSER_2, LVL_HMC, LVL_LLL, LVL_VANISH_CAP ] FIRST_FLOOR_LEVELS = [ LVL_SL, LVL_THI, LVL_WDW, LVL_TTM ] SECOND_FLOOR_LEVELS = [ LVL_TTC, LVL_SECRET_RAINBOW, LVL_RR, LVL_BOWSER_3 ] LEVEL_ORDER = [ *GROUND_FLOOR_LEVELS, *BASEMENT_LEVELS, *FIRST_FLOOR_LEVELS, *SECOND_FLOOR_LEVELS ] GEO_SCRIPT_FUNCS = { 0x00: "BRANCH_AND_STORE", 0x01: "TERMINATE_GEO_LAYOUT", 0x02: "BRANCH_GEO_LAYOUT", 0x03: "RETURN_FROM_BRANCH", 0x04: "OPEN_NODE", 0x05: "CLOSE_NODE", 0x06: "STORE_CURRENT_NODE_POINTER_TO_TABLE", # unused 0x07: "SET_OR_AND_NODE_FLAGS", # unused 0x08: "SET_SCREEN_RENDER_AREA", 0x09: "SET_BACKGROUND_FRUSTUM_MATRIX", 0x0A: "SET_CAMERA_FRUSTUM", 0x0B: "START_GEO_LAYOUT", 0x0C: "TOGGLE_Z_BUFFER", 0x0D: "SET_RENDER_RANGE", 0x0E: "SWITCH", 0x0F: "UNKNOWN_0x0F", 0x10: "TRANSLATE_AND_ROTATE", 0x11: "TRANSLATE_NODE_AND_LOAD_DL_OR_START_GEO_LAYOUT", 0x12: "ROTATE_NODE_AND_LOAD_DL_OR_START_GEO_LAYOUT", 0x13: "LOAD_DL_WITH_OFFSET", 0x14: "BILLBOARD_MODEL_AND_TRANSLATE_AND_LOAD_DL_OR_START_GEO_LAYOUT", 0x15: "LOAD_DL", 0x16: "START_GEO_LAYOUT_WITH_SHADOW", 0x17: "SETUP_OBJ_RENDER", 0x18: "LOAD_POLYGON_ASM", 0x19: "SET_BACKGROUND_IMAGE", 0x1A: "NO_OP", # unused 0x1D: "SCALE_MODEL", 0x1E: "NO_OP", # unused 0x1F: "NO_OP", # unused 0x20: "START_GEO_LAYOUT_WITH_RENDER_AREA" } PAINTING_IDS = { LVL_BOB: 0x00, LVL_CCM: 0x01, LVL_WF: 0x02, LVL_JRB: 0x03, LVL_LLL: 0x04, LVL_SSL: 0x05, LVL_HMC: 0x06, LVL_DDD: 0x07, LVL_WDW: 0x08, LVL_THI: 0x0D, # Huge Version LVL_TTM: 0x0A, LVL_TTC: 0x0B, LVL_SL: 0x0C } SONG_NAMES = [ "No Music", "End Level", "SMB music title", "Bob-omb's Battlefield", "Inside Castle walls", "Dire Dire Docks", "Lethal Laval land", "Bowser battle", "Snow", "Slide", "Crash", "Piranha plant lullaby", "Hazy Maze", "Star select", "Wing cap", "Metal cap", "Bowser Message", "Bowser course", "Star catch", "Ghost Merry-go-round", "Start and End Race with Koopa the Quick", "Star appears", "Boss fight", "Take a Key", "Looping stairs", "Crashes", "Credits song", "Crashes", "Toad", "Peach message", "Intro Castle sequence", "End fanfare", "End music", "Menu", "Lakitu", ] WARP_ID_WIN=0xf0 WARP_ID_LOSE=0xf1 WARP_ID_RECOVER=0xf3 SPECIAL_WARP_IDS = [WARP_ID_WIN, WARP_ID_LOSE, WARP_ID_RECOVER] BEHAVIOUR_NAMES = {} application_path with open(os.path.join(application_path, "Data", "behaviorNames.json"), "r") as behavior_file: BEHAVIOUR_NAMES = json.loads(behavior_file.read()) BEHAVIOUR_NAMES = dict({ hex(int(key, 16)): name for (key, name) in BEHAVIOUR_NAMES.items()})
andrelikesdogs/sm64-randomizer
sm64r/RandomModules/Mario.py
from random import randint, choice from sm64r.Randoutils import clamp import logging import math # SM64 USA (BE) ROM Position # 0x823B64 MEM_COLOR_ADDRESSES = { 'OVERALLS': 0x0, 'HAT_AND_SHIRT': 0x20, 'GLOVES': 0x38, 'SHOES': 0x48, 'SKIN': 0x60, 'HAIR': 0x80 } CLOTH_COLORS = [(255, 255, 255), (173, 36, 36), (9, 96, 168), (10, 193, 3), (99, 27, 98), (211, 155, 20), (204, 0, 91), (10, 160, 149), (105, 158, 0), (158, 60, 0), (82, 12, 206), (81, 81, 81), (193, 193, 0), (98, 63, 193)] # white, red, blue, lime, purple, gold, pink, turquoise, green, orange, smashluigitrousers, grey, yellow and lilac SENSIBLE_COLORS = { 'OVERALLS': CLOTH_COLORS, 'HAT_AND_SHIRT': CLOTH_COLORS, 'GLOVES': CLOTH_COLORS, 'SHOES': [(119, 95, 6), (0, 0, 0), (120, 120, 120), (255, 255, 255), (112, 29, 0), (0, 112, 28), (22, 92, 112), (68, 57, 112), (112, 39, 89)], # brown, black, gray, white, redbrown, green, turquoise, purple and pink 'SKIN': [(45, 34, 30), (60, 46, 40), (75, 57, 50), (90, 69, 60), (105, 80, 70), (120, 92, 80), (135, 103, 90), (150, 114, 100), (165, 126, 110), (180, 138, 120), (195, 149, 130), (210, 161, 140), (225, 172, 150), (240, 184, 160), (255, 195, 170), (255, 206, 108), (255, 174, 117), (255, 191, 135), (255, 220, 177)], 'HAIR': [(9, 6, 9), (44, 34, 43), (58, 48, 38), (78, 67, 63), (80, 68, 69), (106, 78, 86), (85, 72, 56), (167, 133, 106), (184, 151, 120), (220, 208, 186), (222, 168, 153), (151, 121, 97), (233, 206, 168), (228, 220, 168), (165, 137, 70), (145, 85, 61), (83, 61, 53), (113, 99, 90), (182, 166, 158), (214, 196, 194), (183, 18, 164), (202, 191, 177), (141, 74, 67), (181, 82, 57), (229, 0, 7), (0, 229, 26), (0, 110, 229), (229, 160, 0), (0, 143, 175)], } class MarioRandomizer: def __init__(self, rom : 'ROM'): self.rom = rom (segment_0x1_start, _) = self.rom.segments_sequentially[1] self.bank_start = segment_0x1_start def randomize_color(self, enable_dumb_colors=False): logging.info("Randomizing Mario\'s Colors") if self.rom.rom_type != 'EXTENDED': logging.error('Can not modify Mario\'s color on a non-extended ROM. Please load an extended ROM') return for (part, mem_address) in MEM_COLOR_ADDRESSES.items(): # read existing colors """ (r, g, b) = tuple([self.rom.read_integer(mem_address + i) for i in range(3)]) print(part, (r, g, b)) (r2, g2, b2) = tuple([self.rom.read_integer(mem_address + 0x8 + i) for i in range(3)]) print(part + " dark", (r2, g2, b2)) """ color_light = choice(SENSIBLE_COLORS[part]) color_dark = tuple([clamp(v + 20, 0, 255) for v in color_light]) # print(color_dark) # print(f'{part} is now {color}') self.rom.write_bytes(self.bank_start + mem_address, bytes([*color_light, 255])) # light self.rom.write_bytes(self.bank_start + mem_address + 0x8, bytes([*color_dark, 255])) # dark pass #self.rom.file.seek(0x114750) #read_range = 0x1279B0 - 0x114750 #mario_dl = self.rom.file.read(read_range) #print([hex(b) for b in mario_dl[0:10]]) #print([hex(b) for b in mario_dl]) # extended rom pos: 823b64, 12a78b #self.rom.target.seek(0x127F28) # hp torso #self.rom.target.write(bytes([0x13, 0x01, 0x00, 0x99, 0x00, 0x00, 0x00, 0x00, 0x04, 0x01, 0x03, 0x90])) #self.rom.target.write(bytes([0x13, 0x01, 0x00, 0x44, 0x00, 0x00, 0x00, 0x00, 0x04, 0x01, 0x03, 0x90])) #self.rom.target.seek(0x127EFC) #self.rom.target.write(bytes([0x13, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0xCC, 0x98])) #self.rom.target.write(bytes([0x13, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0xCC, 0x30])) #self.rom.target.seek(0x128A34) #self.rom.target.write(bytes([0x13, 0x01, 0x00, 0x44, 0x00, 0x00, 0x00, 0x00, 0x04, 0x01, 0x03, 0x70])) #self.rom.target.write(bytes([0x13, 0x01, 0x00, 0x44, 0x00, 0x00, 0x00, 0x00, 0x04, 0x01, 0x03, 0x70])) #while self.rom.file.tell() < MARIO_GEO_ADDRESS_END:
andrelikesdogs/sm64-randomizer
sm64r/Parsers/GeoLayoutParser.py
<reponame>andrelikesdogs/sm64-randomizer from sm64r.Randoutils import format_binary COMMAND_LENGTHS = { 0x00: 8, 0x01: 4, 0x02: 8, 0x03: 4, 0x04: 4, 0x05: 4, 0x06: 4, 0x07: 4, 0x08: 12, 0x09: 4, 0x0A: None, # min 8 0x0B: 4, 0x0C: 4, 0x0D: 8, 0x0E: 8, 0x0F: 20, # 0x14 0x10: 16, # 0x10 0x11: None, # min 8 0x12: None, # min 8 0x13: 12, 0x14: None, # min 8 0x15: 8, 0x16: 8, 0x17: 4, 0x18: 8, 0x19: 8, 0x1A: 8, 0x1D: None, # min 8 0x1E: 8, 0x1F: 16, # 0x10 0x20: 4 } class GeoLayoutParser: def __init__(self, rom, addr_id, addr_start, addr_end, area_id, source = "Unknown"): self.rom = rom self.addr_id = addr_id self.addr_start = addr_start self.addr_end = addr_end self.source = source self.area_id = area_id #print(f'Parsing GeoLayout ID: {(self.addr_id)}: {hex(self.addr_start)} - {hex(self.addr_end)}') self.commands_by_id = {} self.cursor = self.addr_start self.depth = 0 self.process() def process(self): while True: cmd_byte = self.rom.read_integer(self.cursor) if cmd_byte in COMMAND_LENGTHS: cmd_length = COMMAND_LENGTHS[cmd_byte] if cmd_length is None: # dynamic length if cmd_byte == 0x0A: use_asm = self.rom.read_integer(self.cursor + 1) cmd_length = 12 if use_asm > 0 else 8 if cmd_byte == 0x11 or cmd_byte == 0x12 or cmd_byte == 0x14: has_segment_addr = (self.rom.read_integer(self.cursor + 1) & 0xF0) == 8 cmd_length = 12 if has_segment_addr else 8 if cmd_byte == 0x1D: ms_bit = self.rom.read_integer(self.cursor + 1) & 0x1 cmd_length = 12 if ms_bit else 8 else: # static length pass if cmd_length is None: raise ValueError(f"Could not determine dynamic length for geolayout cmd {hex(cmd_byte)}") #print(format_binary(self.rom.read_bytes(self.cursor, cmd_length))) if cmd_byte not in self.commands_by_id: self.commands_by_id[cmd_byte] = [] self.commands_by_id[cmd_byte].append((self.cursor, self.rom.read_bytes(self.cursor, cmd_length))) #print(" " * self.depth, format_binary(self.rom.read_bytes(self.cursor, cmd_length))) self.cursor += cmd_length if cmd_byte == 0x00: all_zero = self.rom.read_integer(self.cursor, 4) == 0 if all_zero: ''' 0x00: Branch and Store ''' segmented_addr = self.rom.read_integer(self.cursor + 4, 4) target_addr = self.rom.read_segment_addr(segmented_addr) if target_addr: self.cursor_prev = self.cursor self.cursor = target_addr #print(self.cursor) self.depth += 1 #print("branching...") self.process() self.cursor = self.cursor_prev self.depth -= 1 else: print(format_binary(self.rom.read_bytes(self.cursor, 8))) raise ValueError(f"Geometry Layout Command 0x00 segment is unresolved at {hex(self.cursor)}. Probably reading garbage") else: print(format_binary(self.rom.read_bytes(self.cursor, 8))) raise ValueError(f"Geometry Layout Command 0x00 is unlinked at {hex(self.cursor)}. Probably reading garbage") if cmd_byte == 0x01: break else: print(format_binary(self.rom.read_bytes(self.cursor, 8))) raise ValueError("Entered invalid geometry layout. Probably reading garbage") if self.addr_end and self.cursor >= self.addr_end: break
andrelikesdogs/sm64-randomizer
sm64r/Entities/TextEntryDialog.py
from typing import NamedTuple from sm64r.Entities.BaseMemoryRecord import BaseMemoryRecord, MemoryMapping class TextEntryDialog(BaseMemoryRecord): memory_address_text: int = None memory_address_pointer: int = None text: str = None entry_id: int = None def __init__(self, entry_id, text, offset, mem_address_pointer : int = None, mem_address_text : int = None): super().__init__() self.entry_id = entry_id self.text = text self.memory_address_pointer = mem_address_pointer self.memory_address_text = mem_address_text self.offset = offset self.add_mapping("offset", "uint", mem_address_pointer + 14, mem_address_pointer + 16)
andrelikesdogs/sm64-randomizer
sm64r/Parsers/Level.py
from typing import NamedTuple from sm64r.Randoutils import format_binary LVL_CMD_LOAD_RAW_DATA_AND_JUMP = "LOAD_RAW_DATA_AND_JUMP" LVL_CMD_LOAD_RAW_DATA_AND_JUMP_PLUS_CALL = "LOAD_RAW_DATA_AND_JUMP_PLUS_CALL" LVL_CMD_END_LEVEL_DATA = "END_LEVEL_DATA" LVL_CMD_DELAY_FRAMES = "DELAY_FRAMES" LVL_CMD_DELAY_FRAMES_2 = "DELAY_FRAMES_2" LVL_CMD_JUMP_TO_ADDRESS = "JUMP_TO_ADDRESS" LVL_CMD_PUSH = "PUSH" LVL_CMD_POP = "POP" LVL_CMD_PUSH_SCRIPT_0X = "PUSH_SCRIPT_0X" LVL_CMD_CONDITIONAL_POP = "CONDITIONAL_POP" LVL_CMD_CONDITIONAL_JUMP = "CONDITIONAL_JUMP" LVL_CMD_CONDITIONAL_PUSH = "CONDITIONAL_PUSH" LVL_CMD_CONDITIONAL_SKIP = "CONDITIONAL_SKIP" LVL_CMD_SKIP_NEXT = "SKIP_NEXT" LVL_CMD_NOP = "NOP" LVL_CMD_SET_ACCU_FROM_ASM = "SET_ACCU_FROM_ASM" LVL_CMD_SET_ACCU_FROM_ROUTINE = "SET_ACCU_FROM_ROUTINE" LVL_CMD_SET_ACCU = "SET_ACCU" LVL_CMD_PUSH_POOL = "PUSH_POOL" LVL_CMD_POP_POOL = "POP_POOL" LVL_CMD_ROM_TO_RAM = "ROM_TO_RAM" LVL_CMD_ROM_TO_SEGMENT = "ROM_TO_SEGMENT" LVL_CMD_MIO0_DECOMPRESS = "MIO0_DECOMPRESS" LVL_CMD_CREATE_DEMO = "CREATE_DEMO" LVL_CMD_MIO0_DECOMPRESS_TEXTURES = "MIO0_DECOMPRESS_TEXTURES" LVL_CMD_START_LOAD_SEQ = "START_LOAD_SEQ" LVL_CMD_LEVEL_AND_MEMORY_CLEANUP = "LEVEL_AND_MEMORY_CLEANUP" LVL_CMD_END_LOAD_SEQ = "END_LOAD_SEQ" LVL_CMD_ALLOCATE_LEVEL_DATA_FROM_POOL = "ALLOCATE_LEVEL_DATA_FROM_POOL" LVL_CMD_START_AREA = "START_AREA" LVL_CMD_END_AREA = "END_AREA" LVL_CMD_LOAD_POLY_WITHOUT_GEO = "LOAD_POLY_WITHOUT_GEO" LVL_CMD_LOAD_POLY_WITH_GEO = "LOAD_POLY_WITH_GEO" LVL_CMD_PLACE_OBJECT = "PLACE_OBJECT" LVL_CMD_LOAD_MARIO = "LOAD_MARIO" LVL_CMD_CONNECT_WARPS = "CONNECT_WARPS" LVL_CMD_CONNECT_PAINTING = "CONNECT_PAINTING" LVL_CMD_CONNECT_INSTANT_WARP = "CONNECT_INSTANT_WARP" LVL_CMD_LOAD_COLLISION = "LOAD_COLLISION" LVL_CMD_SETUP_RENDER_ROOM = "SETUP_RENDER_ROOM" LVL_CMD_SHOW_DIALOG = "SHOW_DIALOG" LVL_CMD_SET_DEFAULT_TERRAIN = "SET_DEFAULT_TERRAIN" LVL_CMD_FADE_COLOR = "FADE_COLOR" LVL_CMD_SET_MUSIC = "SET_MUSIC" LVL_CMD_SET_MUSIC_SPECIAL = "SET_MUSIC_SPECIAL" LVL_CMD_PLACE_MACRO_OBJECTS = "PLACE_MACRO_OBJECTS" LVL_CMD_PLACE_JET_STREAM = "PLACE_JET_STREAM" """ Names for all LEVEL segment functions in SM64 """ LVL_CMD_IDS = { 0x00: LVL_CMD_LOAD_RAW_DATA_AND_JUMP, 0x01: LVL_CMD_LOAD_RAW_DATA_AND_JUMP_PLUS_CALL, 0x02: LVL_CMD_END_LEVEL_DATA, 0x03: LVL_CMD_DELAY_FRAMES, 0x04: LVL_CMD_DELAY_FRAMES_2, 0x05: LVL_CMD_JUMP_TO_ADDRESS, 0x06: LVL_CMD_PUSH, 0x07: LVL_CMD_POP, 0x0A: LVL_CMD_PUSH_SCRIPT_0X, 0x0B: LVL_CMD_CONDITIONAL_POP, 0x0C: LVL_CMD_CONDITIONAL_JUMP, 0x0D: LVL_CMD_CONDITIONAL_PUSH, 0x0E: LVL_CMD_CONDITIONAL_SKIP, 0x0F: LVL_CMD_SKIP_NEXT, 0x10: LVL_CMD_NOP, 0x11: LVL_CMD_SET_ACCU_FROM_ASM, 0x12: LVL_CMD_SET_ACCU_FROM_ROUTINE, 0x13: LVL_CMD_SET_ACCU, 0x14: LVL_CMD_PUSH_POOL, 0x15: LVL_CMD_POP_POOL, 0x16: LVL_CMD_ROM_TO_RAM, 0x17: LVL_CMD_ROM_TO_SEGMENT, 0x18: LVL_CMD_MIO0_DECOMPRESS, 0x19: LVL_CMD_CREATE_DEMO, 0x1A: LVL_CMD_MIO0_DECOMPRESS_TEXTURES, 0x1B: LVL_CMD_START_LOAD_SEQ, 0x1C: LVL_CMD_LEVEL_AND_MEMORY_CLEANUP, 0x1D: LVL_CMD_END_LOAD_SEQ, 0x1E: LVL_CMD_ALLOCATE_LEVEL_DATA_FROM_POOL, 0x1F: LVL_CMD_START_AREA, 0x20: LVL_CMD_END_AREA, 0x21: LVL_CMD_LOAD_POLY_WITHOUT_GEO, 0x22: LVL_CMD_LOAD_POLY_WITH_GEO, 0x24: LVL_CMD_PLACE_OBJECT, 0x25: LVL_CMD_LOAD_MARIO, 0x26: LVL_CMD_CONNECT_WARPS, 0x27: LVL_CMD_CONNECT_PAINTING, 0x28: LVL_CMD_CONNECT_INSTANT_WARP, 0x2E: LVL_CMD_LOAD_COLLISION, 0x2F: LVL_CMD_SETUP_RENDER_ROOM, 0x30: LVL_CMD_SHOW_DIALOG, 0x31: LVL_CMD_SET_DEFAULT_TERRAIN, 0x33: LVL_CMD_FADE_COLOR, 0x36: LVL_CMD_SET_MUSIC, 0x37: LVL_CMD_SET_MUSIC_SPECIAL, 0x39: LVL_CMD_PLACE_MACRO_OBJECTS, 0x3B: LVL_CMD_PLACE_JET_STREAM, } class Level(NamedTuple): address_start: int # start of level command area on ROM address_end: int # end of level command area on ROM course_id: int # not course-id name: str # human readable name level_area: int = 0 # area this levels painting is in @property def address(self): return (self.address_start, self.address_end) class LevelCommand(NamedTuple): identifier: int # int identifying the command name: str = None # name for command length: int = 0 data: bytes = None # command specific data bytes position: int = None # memory position highlight: bool = False @staticmethod def from_id(cmd_id, *args, **kwargs): if cmd_id in LVL_CMD_IDS: return LevelCommand(cmd_id, LVL_CMD_IDS[cmd_id], *args, **kwargs) else: return LevelCommand(cmd_id) def __str__(self): prefix = "[ UNKNOWN POSITION ]" if self.position is not None: prefix = f"[{hex(self.position-2)} / {self.position}]" ident = self.name or f'UNKNOWN ({hex(self.identifier)})' length = f'({self.length + 2})' data = "NO DATA" highlight = "****" if self.highlight else "" if self.data is not None: data = format_binary( bytes([self.identifier, self.length + 2]) + self.data ) output = " ".join([highlight, prefix, ident, length, data]) return output
andrelikesdogs/sm64-randomizer
sm64r/RandomModules/Stardoors.py
import sm64r.Constants as Constants from sm64r.Parsers.CollisionPresets import CollisionPresetParser CASTLE_DOORS_TO_REPLACE = [ (0x22, 0x13000B0C), # 0 Star Door (0x23, 0x13000B0C), # 1 Star Door (0x24, 0x13000B0C), # 3 Star Door ] KEY_DOORS = [ (0x25, 0x13000AFC), # Keyhole Door ] CASTLE_DOOR_LEVEL_MAPPING = { # Ground Floor 0xe79e35: [Constants.LVL_BOB], 0xe79e5d: [Constants.LVL_CCM], 0xe79e53: [Constants.LVL_JRB, Constants.LVL_SECRET_AQUARIUM], 0xe79e3f: [Constants.LVL_SECRET_PEACH_SLIDE], 0xe79e49: [Constants.LVL_WF], # First Floor 0xe7f59b: [Constants.LVL_SL], 0xe7f587: [Constants.LVL_THI], 0xe7f591: [], # SL Mirror # Basement 0xe8307b: [Constants.LVL_HMC], # Second Floor } # 3rd Star Door: # The third and final star door leading to BITS does not conform with the others. It is always open # but instead shows a text-box before opening when under the selected amount of stars (bparam1). # The stairs will be unpassable as long as the star count is below 70. # This limit is hardcoded in the game, here: # # | ROM | RAM | # ---------------------------------------- # Address | 0x8024A3A8 | 0x0053AB | # ---------------------------------------- STAR_DOOR_LEVEL_MAPPING = { (0x3CF0E8, 0x3CF100): [Constants.LVL_BOWSER_1], # 8 Star Door (0x3CF51C, 0x3CF504): [Constants.LVL_RR, Constants.LVL_TTC, Constants.LVL_SECRET_RAINBOW], # 50 Star Door (0x3CF534, 0x3CF54C): [Constants.LVL_BOWSER_3], # 70 Star Door } STARS_PER_LEVEL = { Constants.LVL_BOB: 7, Constants.LVL_WF: 7, Constants.LVL_JRB: 7, Constants.LVL_CCM: 7, Constants.LVL_BBH: 7, Constants.LVL_HMC: 7, Constants.LVL_LLL: 7, Constants.LVL_SSL: 7, Constants.LVL_DDD: 7, Constants.LVL_SL: 7, Constants.LVL_WDW: 7, Constants.LVL_TTM: 7, Constants.LVL_THI: 7, Constants.LVL_TTC: 7, Constants.LVL_RR: 7, Constants.LVL_SECRET_PEACH_SLIDE: 2, Constants.LVL_SECRET_AQUARIUM: 1, Constants.LVL_BOWSER_1: 1, Constants.LVL_BOWSER_2 : 1, Constants.LVL_BOWSER_3: 1, Constants.LVL_METAL_CAP: 1, Constants.LVL_VANISH_CAP: 1, Constants.LVL_WING_CAP: 1, # 3 Toads # 2 MIPS } class StardoorRandomizer: def __init__(self, rom : 'ROM'): self.rom = rom def replace_all_doors(self): # Replace all castle doors with macro object doors, in order to be able to change bparams # Delete all doors in castle and keep track of properties castle_levelscript = self.rom.levelscripts[Constants.LVL_CASTLE_INSIDE] needs_replacing = [] for object3d in castle_levelscript.objects: for (target_model_id, target_behaviour_script) in CASTLE_DOORS_TO_REPLACE: if (target_model_id is None or object3d.model_id == target_model_id) and (target_behaviour_script is None or object3d.behaviour == target_behaviour_script): object3d.remove(self.rom) needs_replacing.append(object3d) #object3d.remove(self.rom) # In order to inject new objects into a level, we first need to implement an additional "PUSH" # for this we have to find a spot. We will be removing the first entry for 0x24 for each area, # replacing it with a push that will contain the removed objects, as well as many more that # will be added by the randomizer. """ first_objs_in_area = {} for object3d in castle_levelscript.objects: if object3d.source == "PLACE_OBJ" and object3d.area_id not in first_objs_in_area: first_objs_in_area[object3d.area_id] = object3d SEGMENT_ID = 19 SEGMENT_SIZE = 2048 level_script_pos = 0x01900030 level_script_length = 0 created_segments = [] segment_offset = 0 for area_id, first_obj in first_objs_in_area.items(): new_segment_start = (SEGMENT_ID << 24) | (segment_offset * SEGMENT_SIZE) created_segments.append(new_segment_start) print(first_obj.mem_address) # write objects in new position self.rom.write_bytes(level_script_pos, prev_object_bytes) level_script_length += len(prev_object_bytes) self.rom.write_bytes(level_script_pos + 18, bytes([0x07, 0x04, 0x00, 0x00])) # POP level_script_length += 0x04 # replace our target object with 0x06 prev_object_bytes = self.rom.read_bytes(first_obj.mem_address - 2, 18) jump_cmd = bytes([0x06, 0x08, 0x00, 0x00, *new_segment_start.to_bytes(4, self.rom.endianess)]) load_cmd = bytes([0x17, 0x0C, 0x00, SEGMENT_ID, *level_script_pos.to_bytes(4, self.rom.endianess), *(level_script_pos + level_script_length).to_bytes(4, self.rom.endianess)]) self.rom.write_bytes(first_obj.mem_address - 2, jump_cmd + load_cmd) self.rom.write_bytes(new_segment_start, prev_object_bytes) segment_offset += 1 break #### Macro Approach (Doesn't work - no bparams available???) for object3d in needs_replacing: macro_table_address = macro_table_area_mapping[object3d.area_id] castle_levelscript.add_macro_object( macro_table_address, 0x47, # new door preset object3d.rotation[1], # rot y object3d.position[0], # x object3d.position[1], # y object3d.position[2], # z 10, # required stars 10, ) break # Add new macro entries to Castle Inside # ROM Address Hex Address # Area 1 15217259 0xE8326B # Area 2 15217383 0xE832E7 # Area 3 15217395 0xE832F3 # JRB Door #castle_levelscript.add_macro_object(0xE8326B, 0x47, 225, 1075, 205, -229, 10, 0) #castle_levelscript.add_macro_object(0xE8326B, 0x47, 0, -1050, -50, 750, 10, 0) #castle_levelscript.add_macro_object(0xE8326B, 0x47, 90, -950, -50, 750, 10, 0) #castle_levelscript.add_macro_object(0xE8326B, 0x47, 180, -1050, -50, 700, 10, 0) #castle_levelscript.add_macro_object(0xE8326B, 0x47, 270, -950, -50, 700, 10, 0) #area_1_macro_table = castle_levelscript.macro_tables[0xE8326B] #area_2_macro_table = castle_levelscript.macro_tables[0xE832E7] #area_3_macro_table = castle_levelscript.macro_tables[0xE832F3] pass """ def open_keydoors(self): castle_levelscript = self.rom.levelscripts[Constants.LVL_CASTLE_INSIDE] for object3d in castle_levelscript.objects: for (target_model_id, target_behaviour_script) in KEY_DOORS: if (target_model_id is None or object3d.model_id == target_model_id) and (target_behaviour_script is None or object3d.behaviour == target_behaviour_script): object3d.set(self.rom, 'bparams', (0, object3d.bparams[1], 0, 0)) def open_level_stardoors(self): self.replace_all_doors() pass def shuffle_level_stardoors(self): self.replace_all_doors() pass def shuffle_area_star_requirements(self): pass
andrelikesdogs/sm64-randomizer
sm64r/Entities/Warp.py
from typing import NamedTuple from sm64r.Entities.BaseMemoryRecord import BaseMemoryRecord, MemoryMapping class Warp(BaseMemoryRecord): to_area_id: int to_course_id: int to_warp_id: int warp_id: int type: str = "NORMAL" # INSTANT, NORMAL, PAINTING anim_type: str = None area_id: int has_checkpoint: bool = False memory_address: int = None def __init__(self, warp_type : str, warp_id : int, to_area_id : int, to_course_id : int, to_warp_id : int, course_id : int, area_id : int, has_checkpoint : bool = False, mem_address : int = None): super().__init__() self.warp_id = warp_id self.to_course_id = to_course_id self.to_area_id = to_area_id self.to_warp_id = to_warp_id self.type = warp_type self.has_checkpoint = has_checkpoint self.memory_address = mem_address self.course_id = course_id self.area_id = area_id self.add_mapping('warp_id', 'uint', mem_address) self.add_mapping('to_course_id', 'uint', mem_address + 1) self.add_mapping('to_area_id', 'uint', mem_address + 2) self.add_mapping('to_warp_id', 'uint', mem_address + 3) def __str__(self): return f"<Warp address: {hex(self.memory_address)} ID: {hex(self.warp_id)} found in {hex(self.course_id)} (Area {hex(self.area_id)}), to course {hex(self.to_course_id)} (Area {hex(self.to_area_id)}) to warp {hex(self.to_warp_id)}>"
andrelikesdogs/sm64-randomizer
sm64r/RandomModules/Textures.py
<reponame>andrelikesdogs/sm64-randomizer from typing import List, Union, NamedTuple import numpy as np from PIL import Image from pathlib import Path import os from sm64r.Parsers.Imaging import Imaging, N64Image from sm64r.Constants import application_path class Texture(NamedTuple): position: int size: int width: int height: int name: str class InMemoryTexture(NamedTuple): position: int size: int width: int height: int name: str data: bytes class MultiTexture(NamedTuple): name: str textures: List[Texture] ''' paintings = [ ('bob', 0xA800, 0xB800), ('ccm', 0xC800, 0xD800), ('wf', 0xE800, 0xF800), ('jrb', 0x10800, 0x11800), ('lll', 0x13800, 0x12800), ('ssl', 0x14800, 0x15800), ('wdw', 0x17800, 0x18800), ('thi', 0x19800, 0x1A800), ('ttm', 0x1B800, 0x1C800), ('ttc', 0x1D800, 0x1E800), ('sl', 0x1F800, 0x20800) ] ''' class TextureAtlas: definitions : dict = {} def __init__(self, rom : 'ROM'): self.rom = rom def add_level_paintings(self): """ Adds all in-game paintings from the configuration to the TextureAtlas """ for level in self.rom.config.levels: # load paintings if "shuffle_painting" in level.properties: for painting_shuffle in level.properties["shuffle_painting"]: # custom paintings get loaded on rom read # game paintings get loaded here if "game_painting" in painting_shuffle.keys(): #print(f"added {level.name} painting") self.add_segmented_position_texture(painting_shuffle["game_painting"], painting_shuffle["sections"]) def add_vanilla_portrait_custom_paintings(self): """ Loads the custom-made painting for levels that don't have a painting in the original game. """ opts = self.rom.config # read custom paintings if opts.custom_paintings: for author in opts.custom_paintings.keys(): for painting_definition in opts.custom_paintings[author]: TextureAtlas.import_texture(painting_definition['name'], painting_definition['file'], painting_definition['transform']) @staticmethod def get_byte_size_for_format(texture_format, size): if texture_format == 'rgba16': return int(size[0] * size[1] * 16 / 8) else: raise ValueError(f'unknown format or not implemented: {texture_format}') def add_segmented_position_texture(self, name : str, sections): textures = [] for section in sections: segment_start = self.rom.segments_sequentially[section["segment_index"]][0] position = segment_start + section["segment_offset"] textures.append(Texture( position, TextureAtlas.get_byte_size_for_format(section["format"] if "format" in section else "rgba16", section["size"]), section["size"][0], section["size"][1], section["name"] )) if not len(textures): raise ValueError("no sections parsed") if len(sections) > 1: mt = MultiTexture(name, textures) TextureAtlas.add_texture_definition(name, mt) return mt else: TextureAtlas.add_texture_definition(name, textures[0]) return textures[0] @staticmethod def import_texture(name, filepath, transforms = dict()): full_path = os.path.join(application_path, filepath) if not os.path.exists(full_path): raise ValueError(f'custom texture {name} could not be found: {filepath}') parsed_img = Imaging.parse_image(full_path) rgba_img = parsed_img.read_rgba16() sections = [InMemoryTexture( None, TextureAtlas.get_byte_size_for_format('rgba16', parsed_img.img.size), parsed_img.img.size[0], parsed_img.img.size[1], name, rgba_img, )] if transforms: for transform in transforms: if transform["type"] == "split-horizontal": full_size = int(parsed_img.img.size[0] * parsed_img.img.size[1] * 2) half_size = int(full_size / 2) #print(full_size, half_size) part_a = rgba_img[0:half_size] part_b = rgba_img[half_size:full_size] sections = [ InMemoryTexture( None, TextureAtlas.get_byte_size_for_format('rgba16', parsed_img.img.size)/2, parsed_img.img.size[0], parsed_img.img.size[1]/2, f'{name}_a', part_a ), InMemoryTexture( None, TextureAtlas.get_byte_size_for_format('rgba16', parsed_img.img.size)/2, parsed_img.img.size[0], parsed_img.img.size[1]/2, f'{name}_b', part_b ) ] if len(sections) > 1: TextureAtlas.add_texture_definition(name, MultiTexture(name, sections)) else: TextureAtlas.add_texture_definition(name, sections[0]) def load_default_unknown_texture(self): # load questionmark as segmented position texture = self.add_segmented_position_texture( 'question_mark', [ dict( segment_index = 42, segment_offset = 0x49B8, size = [32, 32], name = 'question_mark' ) ] ) n64img = Imaging.from_ingame(self.rom, texture) resized = N64Image(n64img.img.resize((64, 64), Image.LANCZOS)) rgba_img = resized.read_rgba16() full_size = int(len(rgba_img) / 2) half_size = int(full_size / 2) #print(half_size, full_size) part_a = rgba_img[0:half_size] part_b = rgba_img[half_size:full_size] sections = [ InMemoryTexture( None, half_size, 64, 32, f'painting_unknown_upper', part_a ), InMemoryTexture( None, half_size, 64, 32, f'painting_unknown_lower', part_b ) ] TextureAtlas.add_texture_definition("painting_unknown", MultiTexture("painting_unknown", sections)) def add_dynamic_positions(self): self.add_segmented_position_texture( 'castle_grounds_tree_shadow', [ dict( segment_index = 37, segment_offset = 0xD494, size = [32, 32], name = 'castle_grounds_tree_shadow' ) ] ) @staticmethod def hide_texture(rom : "ROM", name): if name not in TextureAtlas.definitions: raise ValueError(f"{name} is not defined as a texture") definition = TextureAtlas.definitions[name] empty_data = bytes([0x0 for i in range(definition.size)]) #print(f"deleting texture {name}: {len(empty_data)} bytes") rom.write_bytes(definition.position + 0x13, empty_data) # 0x13: header @staticmethod def add_texture_definition(name, texture : Union[Texture, MultiTexture]): TextureAtlas.definitions[name] = texture @staticmethod def has_texture(name): return name in TextureAtlas.definitions @staticmethod def is_replacable(name): if name not in TextureAtlas.definitions: return False if type(TextureAtlas.definitions[name]) is MultiTexture: for defintion in TextureAtlas.definitions[name].textures: if type(defintion) is InMemoryTexture: return False if type(TextureAtlas.definitions[name]) is InMemoryTexture: return False return True @staticmethod def copy_texture_from_to(rom : "ROM", name_from : str, name_to : str): if name_from not in TextureAtlas.definitions: raise ValueError(f'{name_from} not found as a defined texture') if name_to not in TextureAtlas.definitions: raise ValueError(f'{name_to} not found as a defined texture') if rom.rom_type != 'EXTENDED': raise ValueError(f'This ROM file is not extended, and thus can\'t modify textures (atleast right now)') texture_from = TextureAtlas.definitions[name_from] texture_to = TextureAtlas.definitions[name_to] if len(texture_from.textures) != len(texture_to.textures): raise ValueError('Can only swap textures between two texture groups with the same length right now') if type(texture_to.textures[0]) is InMemoryTexture: raise ValueError(f'{name_to} is an in memory texture and can not be replaced') texs_from = [] texs_to = [] for texture in texture_from.textures: if type(texture) is InMemoryTexture: # read from var texs_from.append(texture.data) elif type(texture) is Texture: # read from rom texs_from.append(rom.read_bytes(texture.position, texture.size)) for texture in texture_to.textures: if type(texture) is InMemoryTexture: # read from var texs_to.append(texture.data) elif type(texture) is Texture: # read from rom texs_to.append(rom.read_bytes(texture.position, texture.size)) for idx in range(len(texs_from)): bytes_from = texs_from[idx] tex_to = texture_to.textures[idx] rom.write_byte(tex_to.position, bytes_from)
andrelikesdogs/sm64-randomizer
sm64r/RandomModules/Warps.py
<reponame>andrelikesdogs/sm64-randomizer from random import shuffle, choice import logging import os from sm64r.Constants import LVL_CASTLE_COURTYARD, LVL_CASTLE_INSIDE, LVL_CASTLE_GROUNDS, LVL_THI, ALL_LEVELS, LEVEL_ID_MAPPING, LEVEL_SHORT_CODES, LVL_BOWSER_1, LVL_BOWSER_1_BATTLE, LVL_BOWSER_2, LVL_BOWSER_2_BATTLE, LVL_BOWSER_3, LVL_BOWSER_3_BATTLE from sm64r.Spoiler import SpoilerLog from sm64r.RandomModules.Textures import TextureAtlas if "SM64R" in os.environ and "WARPS" in os.environ["SM64R"]: import networkx as nx import plotly.offline as py import plotly.graph_objs as go WARP_ID_MAPPING = { 0xf0: 'SUCCESS', 0xf1: 'FAILURE', 0xf3: 'RECOVERY' } class WarpRandomizer: def __init__(self, rom : 'ROM'): self.rom = rom self.warps = [] self.applied_change_list = [] def _pick_best_fitting_warp(self, target_group_name, warp, warps_available): if target_group_name in list(warps_available.keys()): return choice(warps_available[target_group_name]) target_key = choice(list(warps_available.keys())) return choice(warps_available[target_key]) def shuffle_level_entries(self, settings : dict): # For different levels of SM64, we can assume there are 4 different types of warps we need to consider # these are not coded any differently, but they are important to find, to get a complete set of warps for any given "target level" # "entrances_src" - Found in Overworlds - Paintings, Holes in the floor # "entrances_dst" - Found in Target lvl - Entry positions into levels, mostly '0xa' for the beginning, marios spawn # "exits_dst" - Found in Overworlds - Lead to themselves handle animations somehow. Level exit_srcs (0xf0, 0xf1, 0xf3) also lead to them # "exits_src" - Found in Target lvl - `0xf0`, `0xf1` and `0xf3` (Win, Lose, Recovery/Pause-Exit) # self.warps = [] for level in self.rom.config.levels: for warp in self.rom.levelscripts[level].warps: self.warps.append(warp) # levels that contain entries to levels overworld_levels = list(filter(lambda level: "overworld" in level.properties, self.rom.config.levels)) shuffle_warp_levels = list(filter(lambda level: "shuffle_warps" in level.properties, self.rom.config.levels)) # both lists combined shuffleable_warp_levels = [*overworld_levels, *shuffle_warp_levels] target_levels = [] # list of warps that are used for handling animations in ow levels all_exit_dst_warps = [] # entrances for levels entrance_src_for_levels = {} # found in ow entrance_dst_for_levels = {} # found in level exit_dst_for_levels = {} # found in ow exit_src_for_levels = {} # found in level # find warps *TO* levels # all levels that may contain entrance warps, this will find, e.g. overworld and HMC (to Metal Cap): # - entrance_srcs to levels # - exit_dsts from levels, not matched yet # for level in shuffleable_warp_levels: for warp in self.rom.levelscripts[level].warps: target_level = self.rom.config.levels_by_course_id[warp.to_course_id] # Levels with disabled entry_shuffle if "disabled" in target_level.properties: if target_level.properties["disabled"] is True or "entry_shuffle" in target_level.properties["disabled"]: continue # Warps that lead to themselves if warp.to_warp_id == warp.warp_id and warp.to_area_id == warp.area_id and warp.to_course_id == warp.course_id: all_exit_dst_warps.append(warp) # we can't know where it's from until we check the levels continue # Levels that are overworlds if target_level in overworld_levels: continue if target_level not in entrance_src_for_levels: entrance_src_for_levels[target_level] = [] if warp not in entrance_src_for_levels[target_level]: entrance_src_for_levels[target_level].append(warp) if target_level not in target_levels: target_levels.append(target_level) # find exits in levels we found entrances to # - exit_dsts in ow from levels, now matched # - exit_srcs in levels # - entrance_dsts in ow for level in entrance_src_for_levels.keys(): # first, find all warps in the levels our entrance sources lead to for warp in self.rom.levelscripts[level].warps: # match with one of the exits we found in the overworlds/hub levels for exit_dst in all_exit_dst_warps: # matched warp must match area, course and warp-id if exit_dst.warp_id == warp.to_warp_id and exit_dst.course_id == warp.to_course_id and exit_dst.area_id == warp.to_area_id: if level not in exit_dst_for_levels: exit_dst_for_levels[level] = [] if exit_dst not in exit_dst_for_levels[level]: # save anim type (success, failure or recovery) on exit_dst exit_dst.anim_type = WARP_ID_MAPPING[warp.warp_id] if warp.warp_id in WARP_ID_MAPPING else None exit_dst_for_levels[level].append(exit_dst) # this was previously not matched to a level if level not in exit_src_for_levels: exit_src_for_levels[level] = [] if warp not in exit_src_for_levels[level]: exit_src_for_levels[level].append(warp) # match entrance destinations with level warps for entrance_src in entrance_src_for_levels[level]: # (course_id will always match, because we're checking the warps from and to this level) # must match warp_id <-> to_warp_id, area_id (in which area) <-> to_area_id if entrance_src.to_warp_id == warp.warp_id and entrance_src.to_area_id == warp.area_id and entrance_src.to_course_id == warp.course_id: if level not in entrance_dst_for_levels: entrance_dst_for_levels[level] = [] if warp not in entrance_dst_for_levels[level]: entrance_dst_for_levels[level].append(warp) # add exit warps from continued levels, i.e. from the fight stages in bowser levels if "continues_level" in level.properties: course_ids = level.properties["continues_level"] if type(level.properties["continues_level"]) is list else [level.properties["continues_level"]] continued_levels = list(map(lambda x: self.rom.config.levels_by_course_id[x], course_ids)) if level not in exit_dst_for_levels or level not in exit_src_for_levels: print(f"WARNING: continued level for \"{level.name}\" without any warps of itself - how is this even possible") else: for continued_level in continued_levels: for warp in self.rom.levelscripts[continued_level].warps: for exit_dst in all_exit_dst_warps: if exit_dst.warp_id == warp.to_warp_id and exit_dst.course_id == warp.to_course_id and exit_dst.area_id == warp.to_area_id: # NOTE: we're adding the warp exits to the LEVELs exit destination warps, not to the continued levels destination warps # as it won't have one seperately. this means during shuffling, the exits in this continued level will behave the same way # as if the warps were simply in the original stage. exit_dst.anim_type = WARP_ID_MAPPING[warp.warp_id] if warp.warp_id in WARP_ID_MAPPING else None exit_dst_for_levels[level].append(exit_dst) exit_src_for_levels[level].append(warp) # pool of warps that can be shuffled between warp_pools = {} # all warp sets all_warp_sets = [] # Create "warp sets" that lead from ow to level and from level to ow for target_level in target_levels: #print(target_level.name) source_level = None warp_set = dict( source_level=None, target_level=target_level, allowed=[], entrance_srcs=[], entrance_dsts=[], exit_srcs=[], exit_dsts=[] ) if target_level in entrance_src_for_levels: warp_set["entrance_srcs"] = entrance_src_for_levels[target_level] # use an entry from entrance sources to get the source level first_entrance = entrance_src_for_levels[target_level][0] source_level = self.rom.config.levels_by_course_id[first_entrance.course_id] warp_set["source_level"] = source_level if target_level in entrance_dst_for_levels: warp_set["entrance_dsts"] = entrance_dst_for_levels[target_level] if target_level in exit_src_for_levels: warp_set["exit_srcs"] = exit_src_for_levels[target_level] if target_level in exit_dst_for_levels: warp_set["exit_dsts"] = exit_dst_for_levels[target_level] if "shuffle_warps" in source_level.properties: # create whitelist for allowed shuffles satisfies_all_rules = None matching_ruleset = [] for rules in source_level.properties["shuffle_warps"]: satisfies_all_rules = None for rule in rules["to"]: satisfies_all_rules = True if "course_id" in rule and rule["course_id"] != target_level.course_id: satisfies_all_rules = False if satisfies_all_rules: break if satisfies_all_rules: matching_ruleset = rules["with"] warp_set["allowed"] = matching_ruleset pool = frozenset([frozenset(rule.items()) for rule in warp_set["allowed"]]) if pool not in warp_pools: warp_pools[pool] = [] warp_pools[pool].append(warp_set) all_warp_sets.append(warp_set) #print("Appending", warp_set["target_level"].name, pool) # Existing level paintings lvl_painting_names = {} new_level_warps = [] # This part will generate new warp connections until one is "valid" aka in logic while len(new_level_warps) == 0 or not self.validate_path_for_keys(new_level_warps): # because warps are grouped by the connections that are allowed, shuffling inside # these groups will always follow the rules # FIXME: one-way connections (i.e. wing-cap could be vanish cap but not the other way around) # will not work and always result in unshuffled levels new_level_warps = [] # go through pools, shuffle within those pools and assign warps for ruleset, warpsets in warp_pools.items(): ### Debug Warpsets """ print('-' * 30) print(ruleset) for warpset in warpsets: print(f"Warps from {warpset['source_level'].name} to {warpset['target_level'].name}") print(f" Entrances: SRC: {len(warpset['entrance_srcs'])} DEST: {len(warpset['entrance_dsts'])}") print(f" Exits: SRC: {len(warpset['exit_srcs'])} DEST: {len(warpset['exit_dsts'])}") """ ### Split into Overworld and Levels for each pool pool_warpset_ow = [] # from pool_warpset_lvl = [] # to for warpset in warpsets: # add painting to shuffle-able list of paintings if "shuffle_painting" in warpset["target_level"].properties: shuffle_painting_properties = warpset["target_level"].properties["shuffle_painting"] if len(shuffle_painting_properties) > 1: print(f'Warning: Only one painting shuffle is allowed per level. Please check properties of "{warpset["target_level"]}".') else: shuffle_painting_definiton = shuffle_painting_properties[0] # add in-game painting to shuffle-able list if "game_painting" in shuffle_painting_definiton.keys(): lvl_painting_names[warpset["target_level"]] = shuffle_painting_definiton["game_painting"] # add custom painting to shuffle-able list if "custom_painting" in shuffle_painting_definiton.keys(): lvl_painting_names[warpset["target_level"]] = shuffle_painting_definiton["custom_painting"] pool_warpset_ow.append(dict( level=warpset["target_level"], entrances=warpset["entrance_srcs"], exits=warpset["exit_dsts"] )) pool_warpset_lvl.append(dict( level=warpset["target_level"], entrances=warpset["entrance_dsts"], exits=warpset["exit_srcs"] )) # Perform the shuffle shuffle(pool_warpset_ow) shuffle(pool_warpset_lvl) # Link them back together for group_idx in range(len(pool_warpset_ow)): ow_set = pool_warpset_ow[group_idx] lvl_set = pool_warpset_lvl[group_idx] new_level_warps.append( (ow_set, lvl_set) ) #for (ow_set, lvl_set) in new_level_warps: #print(f'{ow_set["level"].name} now goes to {lvl_set["level"].name}') #print('-' * 20) # If random paintings enabled, shuffle the key:value pairs in lvl_paintings if "shuffle_paintings" in settings: if settings["shuffle_paintings"] == "random": keys = list(lvl_painting_names.keys()) shuffled_keys = [*keys] shuffle(shuffled_keys) for level_key_index, level_key in enumerate(keys): lvl_painting_names[level_key] = lvl_painting_names[shuffled_keys[level_key_index]] # list of changes that will be done change_list = [] # actually link together warps for (ow_set, lvl_set) in new_level_warps: SpoilerLog.add_entry('warps', f'{ow_set["level"].name} leads to {lvl_set["level"].name}') #print(f'{ow_set["level"].name} now goes to {lvl_set["level"].name}') # link overworld entrances to new level for idx in range(len(ow_set["entrances"])): src = ow_set["entrances"][idx] dst = choice(lvl_set["entrances"]) change_list.append((src, dst.course_id, dst.area_id, dst.warp_id)) # relink exits for idx in range(len(lvl_set["exits"])): src = lvl_set["exits"][idx] src.anim_type = WARP_ID_MAPPING[src.warp_id] if src.warp_id in WARP_ID_MAPPING else None targets = [] target = choice(ow_set["exits"]) # fallback: pick random if no fitting targets if not src.anim_type: # if an exit warp inside a level is not one of the success, defeat or recovery warp types # it means this level can link to another level. like HMC to MC continue for dst in ow_set["exits"]: if dst.anim_type == src.anim_type: targets.append(dst) if len(targets): target = choice(targets) change_list.append((src, target.course_id, target.area_id, target.warp_id)) if "shuffle_paintings" in settings and settings["shuffle_paintings"] != "off": if "shuffle_painting" in ow_set["level"].properties: if len(ow_set["level"].properties["shuffle_painting"]) > 1: print(f'Warning: Only one painting shuffle is allowed per level. Please check properties of "{warpset["target_level"]}".') else: source_painting_definition = ow_set["level"].properties["shuffle_painting"][0] # replace this source_painting_name = source_painting_definition["game_painting"] if "game_painting" in source_painting_definition else source_painting_definition["custom_painting"] # with this target_painting_name = lvl_painting_names[lvl_set["level"]] #print("setting painting from ", source_painting_name, " to ", target_painting_name) # don't copy if it's the same if source_painting_name != target_painting_name: # ensure we have a copy-able texture if not TextureAtlas.has_texture(target_painting_name): target_painting_name = "painting_unknown" # use replacement texture # ensure target is replaceable, textures loaded externally are not if TextureAtlas.is_replacable(source_painting_name): TextureAtlas.copy_texture_from_to(self.rom, target_painting_name, source_painting_name) self.applied_change_list = change_list for (target, course_id, area_id, warp_id) in change_list: target.set(self.rom, "to_course_id", course_id) target.set(self.rom, "to_area_id", area_id) target.set(self.rom, "to_warp_id", warp_id) ### Debug View ''' for target_level in target_levels: print(f" Warps found for {target_level.name}") if target_level in entrance_src_for_levels: print(f" Entry Sources: {len(entrance_src_for_levels[target_level])}") for w in entrance_src_for_levels[target_level]: print(w) else: print(" No Entry Sources") if target_level in entrance_dst_for_levels: print(f" Entry Destinations: {len(entrance_dst_for_levels[target_level])}") for w in entrance_dst_for_levels[target_level]: print(w) else: print(" No Entry Destinations") if target_level in exit_src_for_levels: print(f" Exit Sources: {len(exit_src_for_levels[target_level])}") for w in exit_src_for_levels[target_level]: print(w) else: print(" No Exit Sources") if target_level in exit_dst_for_levels: print(f" Exit Destinations: {len(exit_dst_for_levels[target_level])}") for w in exit_dst_for_levels[target_level]: print(w) else: print(" No Exit Destinations") print("-" * 30) ''' def validate_path_for_keys(self, changelist): indiv_key_requirements_per_level = {} total_key_requirements_per_level = {} key_sources = {} # from = original entry position # to = new entry position # collect requires_key and key_receive groups for (from_warps, to_warps) in changelist: key_requirements = [] if "requires_key" in from_warps["level"].properties: requires_key = from_warps["level"].properties["requires_key"] key_requirements = [requires_key] if type(requires_key) is not list else requires_key if "key_receive" in to_warps["level"].properties: key_sources[to_warps["level"].properties["key_receive"]] = to_warps["level"] #print(to_warps["level"].name, " awards ", to_warps["level"].properties["key_receive"]) #awards_text = "" if "key_receive" not in to_warps["level"].properties else f' and rewards \"{to_warps["level"].properties["key_receive"]}\"' #print(to_warps["level"].name, " now requires ", key_requirements, awards_text) indiv_key_requirements_per_level[to_warps["level"]] = key_requirements # define function to recursively gather all keys required per level def recurse_find_keys_needed(level, keys, acc): for key in keys: if key not in acc: acc.add(key) level_req = key_sources[key] #print("key ", key, " found in ", level_req) level_req_keys = indiv_key_requirements_per_level[level_req] recurse_find_keys_needed(level_req, level_req_keys, acc) return acc # define total keys per level via above recursive func for level, keys in indiv_key_requirements_per_level.items(): total_key_requirements_per_level[level] = recurse_find_keys_needed(level, keys, set()) #print(level, indiv_key_requirements_per_level[level], total_key_requirements_per_level[level]) if "key_receive" in level.properties and level.properties["key_receive"] in total_key_requirements_per_level[level]: #print(f"{level.name} requires {total_key_requirements_per_level[level]} but rewards {level.properties['key_receive']} - invalid") return False return True def plot_network(self): G = nx.DiGraph() def key_from_warp(warp): return f'{hex(warp.course_id)} ({hex(warp.area_id)}): {hex(warp.warp_id)}' warp_by_key = {} all_connections = {} for warp in self.warps: warp_key = key_from_warp(warp) warp_by_key[warp_key] = warp for warp in self.warps: target_key = f'{hex(warp.to_course_id)} ({hex(warp.to_area_id)}): {hex(warp.to_warp_id)}' target_warp = warp_by_key[target_key] all_connections[warp] = target_warp for (src_warp, target_course_id, target_area_id, target_warp_id) in self.applied_change_list: target_key = f'{hex(target_course_id)} ({hex(target_area_id)}): {hex(target_warp_id)}' target_warp = warp_by_key[target_key] all_connections[src_warp] = target_warp for src_warp, target_warp in all_connections.items(): G.add_edge(key_from_warp(src_warp), key_from_warp(target_warp)) pos = nx.spring_layout(G) #plt.subplot() #nx.draw(G, with_labels=True) #plt.show() edge_x = [] edge_y = [] for edge in G.edges(): x0, y0 = pos[edge[0]] x1, y1 = pos[edge[1]] edge_x.append(x0) edge_x.append(x1) edge_x.append(None) edge_y.append(y0) edge_y.append(y1) edge_y.append(None) edge_trace = go.Scatter( x=edge_x, y=edge_y, line=dict(width=0.5, color='#888'), hoverinfo='none', mode='lines') node_x = [] node_y = [] node_text = [] node_colors = [] for node in G.nodes(): x, y = pos[node] node_x.append(x) node_y.append(y) warp = warp_by_key[node] target_level = self.rom.config.levels_by_course_id[warp.to_course_id] #print(warp_by_key[node]) node_text.append(f'{target_level.name} (Area: {hex(warp.area_id)}): {hex(warp.warp_id)}') if warp.warp_id in WARP_ID_MAPPING.values(): node_colors.append('#ff0000') elif warp.warp_id == 0xa: node_colors.append('#0000ff') else: node_colors.append('#aeaeae') node_trace = go.Scatter( x=node_x, y=node_y, mode='markers', hoverinfo='text', marker=dict( color=[], colorscale='YlGnBu', line_width=2)) node_trace.text = node_text #node_trace.color = node_colors fig = go.Figure(data=[edge_trace, node_trace], layout=go.Layout( showlegend=False, hovermode='closest', annotations=[ dict( showarrow=False, xref="paper", yref="paper", x=0.005, y=-0.002 ) ], xaxis=dict(showgrid=False, zeroline=False, showticklabels=False), yaxis=dict(showgrid=False, zeroline=False, showticklabels=False)) ) py.plot(fig, filename=f'dumps/warp_graph/Warps.html', auto_open=True) ''' def shuffle_level_entries_old(self, painting_mode : str): # levels that contain entries to levels entry_levels = [LVL_CASTLE_COURTYARD, LVL_CASTLE_GROUNDS, LVL_CASTLE_INSIDE] entry_level_course_ids = [level.level_id for level in entry_levels] # anim warps are warps in the overworld that simply connect to themselves. # they confuse me but i suspect they only handle animation stuff anim_warps = [] # Warp, Warp, Warp ow_warps = {} # { (Level, Area): ([Entry Warp, Entry Warp], (Anim Exit, Anim Exit)), (Entry, Anim Exits), (Entry, Anim Exits) lvl_warps = {} # { (Level, Area): FAIL: [ Warp, Warp ], SUCCESS: Warp, Warp } # go through all levels that contain entries (all castle levels) for level in entry_levels: # go through all warps, take note of the special animated warps # they can be identified by their warp_id leading to their target_warp_id for warp in self.rom.levelscripts[level].warps: # painting warps and warp-ids that match levels without a painting a grouped by # target-level and target-area-id to ensure we don't break THI if warp.type == 'PAINTING' or warp.to_course_id in COURSES_WITH_NO_PAINTING: target_level = LEVEL_ID_MAPPING[warp.to_course_id] key = (target_level, warp.to_area_id) ow_warps.setdefault(key, ([], {})) # level entries (paintings, holes, etc), anim exits (lead to themselves) ow_warps[key][0].append(warp) else: # special target == dest warps if warp.warp_id == warp.to_warp_id: anim_warps.append(warp) anim_warp_ids = [warp.warp_id for warp in anim_warps] # now collects all exits from the levels we have the entries of warp_types = { 0xf0: "SUCCESS", 0xf1: "FAILURE", #0xf3: "RECOVER", # ye let's not shuffle this for now } for key in ow_warps.keys(): (level, area_id) = key lvl_warps[key] = {} # get all warps inside the level that target this level and this area_id search_targets = [level] if level in LEVEL_CONNECTED_WARPS: search_targets.extend(LEVEL_CONNECTED_WARPS[level]) for search_level in search_targets: for warp in self.rom.levelscripts[search_level].warps: # 1. warp must lead to one of the anim exits from the overworld # 2. warp must lead to one of the OW levels # 3. warp must be of one of the warp types if warp.to_warp_id in anim_warp_ids and warp.to_course_id in entry_level_course_ids and warp.warp_id in warp_types: if level not in MUST_MATCH_AREA_LEVELS or warp.area_id == area_id: warp_type = warp_types[warp.warp_id] # add a specific warp-type to the exits list lvl_warps[key].setdefault(warp_type, []).append(warp) # add all the anim warps that this warp refers to ow_warps[key][1].setdefault(warp_type, []).extend([anim_warp for anim_warp in anim_warps if anim_warp.warp_id == warp.to_warp_id]) # Debug View of all Warps found for ((level, area), (entry_warps, anim_warp_groups)) in ow_warps.items(): logging.debug(f'Level: {level.name} Area: {hex(area)}') logging.debug(" Exits") for (warp_group, exit_warps) in lvl_warps[(level, area)].items(): logging.debug(" " * 2 + str(warp_group)) logging.debug(" " * 4 + repr([(hex(warp.to_warp_id), hex(warp.memory_address)) for warp in exit_warps])) logging.debug('') logging.debug(" Entries:") logging.debug(repr([(hex(warp.warp_id), hex(warp.memory_address)) for warp in entry_warps])) logging.debug('') logging.debug(" Anim Warps:") for (anim_warp_group, entry_anim_warps) in anim_warp_groups.items(): logging.debug(" " * 2 + str(anim_warp_group)) logging.debug(" " * 4 + repr([(hex(warp.to_warp_id), hex(warp.memory_address)) for warp in entry_anim_warps])) logging.debug('-' * 50) valid_warps = False target_warp_levels = list(lvl_warps.keys()) #shuffle(target_warp_levels) while not valid_warps: shuffle(target_warp_levels) idx = 0 valid_warps = True for ((original_level, original_area), ow_entry_exit_sets) in ow_warps.items(): (target_level, target_area) = target_warp_levels[idx] # ensure correct order if target_level in ENFORCE_ORDER.keys(): logging.info(f'ensuring validity with level {target_level.name}') # bowser in the fire sea for example can't be on the first floor, because that's the boss that gives you the key for the first floor if original_level in ENFORCE_ORDER[target_level]: logging.info(f'{target_level.name} cant be in {original_level}, because it cant be reached without it') valid_warps = False break idx += 1 idx = 0 for (original_level_area, (entries, anim_exits)) in ow_warps.items(): level_area_target = target_warp_levels[idx] SpoilerLog.add_entry('warps', f'{original_level_area[0].name} leads to {level_area_target[0].name}') #print(f'{original_level_area[0].name} now leads to {level_area_target[0].name} ({len(entries)} entries updating)') for entry_warp in entries: #print(hex(level_area_target[0].level_id)) entry_warp.set(self.rom, "to_course_id", level_area_target[0].level_id) entry_warp.set(self.rom, "to_area_id", level_area_target[1]) orig_exits = lvl_warps[original_level_area] level_exits = lvl_warps[level_area_target] # replace all exit warps in the target level with ones leading to the original entry for (group_name, warps) in level_exits.items(): logging.info(f'{level_area_target[0].name.ljust(40, " ")} (Area {hex(level_area_target[1])}): {group_name}: Animation Warps replacing {len(warps)} entries') for warp in warps: target_warp = self._pick_best_fitting_warp(group_name, warp, orig_exits) warp.set(self.rom, "to_course_id", target_warp.to_course_id) warp.set(self.rom, "to_warp_id", target_warp.to_warp_id) warp.set(self.rom, "to_area_id", target_warp.to_area_id) idx += 1 if painting_mode == 'random': shuffle(target_warp_levels) # set paintings idx = 0 for (original_level_area, (entries, anim_exits)) in ow_warps.items(): if painting_mode != 'vanilla': level_area_target = target_warp_levels[idx] if original_level_area[0] in LEVEL_SHORT_CODES and level_area_target[0] in LEVEL_SHORT_CODES: from_code = f'painting_{LEVEL_SHORT_CODES[original_level_area[0]].lower()}' to_code = f'painting_{LEVEL_SHORT_CODES[level_area_target[0]].lower()}' if TextureAtlas.has_texture(from_code): if TextureAtlas.has_texture(to_code): TextureAtlas.copy_texture_from_to(self.rom, from_code, to_code) else: TextureAtlas.copy_texture_from_to(self.rom, from_code, 'painting_unknown') idx += 1 original_warps = list(warp_connections.items()) target_warps = list(warp_connections.items()) shuffle(target_warps) for idx, (level, area) in enumerate(target_warps): original_warp = original_warps[idx] print(f'{original_warp[0][0].name} now leads to {level[0].name}') pass for level_exits in lvl_warps: for level_exit in level_exits: pass print(len(lvl_warps)) print(len(ow_warps_by_level_by_area.keys())) #print('\n'.join([str(item) for item in ow_warps_cleaned_dict.items()]))'''
andrelikesdogs/sm64-randomizer
sm64r/RandomModules/Skybox.py
<filename>sm64r/RandomModules/Skybox.py from random import choice from sm64r.Randoutils import format_binary import math # Skyboxes SKYBOX_IDS = [ 0x00, # Bob-Omb's Battlefield 0x01, # Lethal Lava Land 0x02, # Wet Dry World 0x03, # Rainbow Ride 0x04, # Cool, Cool Mountain 0x05, # Shifting Sand Land 0x06, # Big Boo's Haunt 0x07, # Bowser 1 Course 0x08, # Jolly Roger Bay 0x09, # Bowser 3 Course ] SKYBOX_POSITIONS = { 0x00: 0xB35715, 0x01: 0xBA22D5, 0x02: 0xBC2C15, 0x03: 0xBEAD55, 0x04: 0xB5D855, 0x05: 0xC12E95, 0x06: 0xC3AFD5, 0x07: 0xC57915, 0x08: 0xB85995, 0x09: 0xC7FA55 } SKYBOX_INDICES = { 0x00: 36, 0x01: 282, 0x02: 170, 0x03: 236, 0x04: 87, 0x05: 119, 0x06: 68, 0x07: 250, 0x08: 188, 0x09: 315, } class SkyboxRandomizer: def __init__(self, rom : 'ROM'): self.rom = rom def randomize_skyboxes(self): sky_positions = {} # match via bank indices for (sky_index, bank_index) in SKYBOX_INDICES.items(): sky_positions[sky_index] = self.rom.segments_sequentially[bank_index] for level in self.rom.config.levels: random_texture_id = choice(SKYBOX_IDS) segments_loaded = self.rom.levelscripts[level].commands_by_id[0x17] for segment_cmd in segments_loaded: bank = segment_cmd.data[1] #print(hex(bank)) if bank == 0xa: (start, end) = sky_positions[random_texture_id] ''' # output changes changelist = list(segment_cmd.data) changelist[2:6] = start.to_bytes(4, self.rom.endianess) changelist[6:12] = end.to_bytes(4, self.rom.endianess) print(format_binary(segment_cmd.data), " to ", format_binary(bytes(changelist))) ''' self.rom.write_integer(segment_cmd.position + 2, start, 4) self.rom.write_integer(segment_cmd.position + 6, end, 4) geo_layouts = self.rom.levelscripts[level].geometry_layouts for geo_layout in geo_layouts: if 0x19 in geo_layout.commands_by_id: for (position, prev_command) in geo_layout.commands_by_id[0x19]: if prev_command[4:8] == bytes([0x80, 0x27, 0x63, 0xD4]): ''' # output changes changelist = list(prev_command) changelist[3] = random_texture_id print(format_binary(prev_command), " to ", format_binary(bytes(changelist))) ''' self.rom.write_integer(position + 3, random_texture_id)
andrelikesdogs/sm64-randomizer
sm64r/Enhancements/TextureChanges.py
from sm64r.RandomModules.Textures import TextureAtlas class TextureChanges: def __init__(self, rom): self.rom = rom def remove_tree_shadows(self): TextureAtlas.hide_texture(self.rom, "castle_grounds_tree_shadow")
rohanb1985/PerforceHandler
P4VMergeSpecificCLCustomTool.py
from perforce.PerforceUtils import PerforceUtils from perforce.PerforceMerge import PerforceMerge import datetime import yaml import os import sys import pprint print ("Starting Merge at: " +str(datetime.datetime.now())) #fetchConfig userConfigurationMap = list() configFile ="config\config.yml" if not os.path.isfile(configFile) : exit("No Config file found") #load config with open(configFile) as file: userConfigurationMap = yaml.safe_load(file) print ("Configuration: " + str(userConfigurationMap)) p4user = sys.argv[1] p4host = sys.argv[2] #print ("Connecting to perforce...") pu = PerforceUtils(p4host = p4host, p4user = p4user, ipIsLogOn = userConfigurationMap['logging']) p4 = pu.connectToPerforce() #print ("Connected to perforce.") ipChangeList = sys.argv[3] #print ("Fetch details of Change list: " + ipChangeList) changeListDetails = pu.fetchDetailsOfChangeList(ipChangeList) submittedChangeLists = list() submittedChangeLists.append(changeListDetails) #print ("Calling Merge...") p4Merge = PerforceMerge(p4, submittedChangeLists, userConfigurationMap) newlyCreatedChangeLists = p4Merge.mergeAndResolveChangeLists() if newlyCreatedChangeLists is not None and len(newlyCreatedChangeLists) > 0: print("~~~~~~~~~~~~~~Following are the Newly Created Change Lists...~~~~~~~~~~~~~") pprint.pprint(newlyCreatedChangeLists) else: print("Nothing to Merge!!") print ("Completed at: "+str(datetime.datetime.now())) pu.disconnectFromPerforce()
rohanb1985/PerforceHandler
perforce/PerforceMerge.py
from perforce.PerforceUtils import PerforceUtils from utils.MyLogger import MyLogger import yaml import pprint import re class PerforceMerge: def __init__(self, ipP4, ipSubmittedChangeLists, ipUserConfigurationMap): self.p4 = ipP4 self.submittedChangeLists = ipSubmittedChangeLists self.userConfigurationMap = ipUserConfigurationMap self.log = MyLogger(self.userConfigurationMap['logging']) def getBranchesConfig(self): branchesConfig = list() self.log.myPrint ("User Configuration: " + str(self.userConfigurationMap)) branchesFile = self.userConfigurationMap['BranchesFile'] if branchesFile is None: exit ("Branches File missing! Please check configuration") with open(branchesFile) as file: branchesConfig = yaml.safe_load(file) self.log.myPrint ("Branches Config: " + str(branchesConfig)) if len(branchesConfig) <= 0 : exit("Branches configuration not properly defined!") return branchesConfig; def mergeAndResolveChangeLists(self): mergeAndResolveResults = list() targetBranchClNoDict = dict() branchesConfig = self.getBranchesConfig() for changeList in self.submittedChangeLists: clNumber = changeList['change'] originalCLBranch = changeList['path'].split(self.userConfigurationMap['p4DepotHead'])[1].split("/")[0] print ("Changelist:" + clNumber + "-------- Branch: "+originalCLBranch) targetBranches = branchesConfig['BranchDetails'][originalCLBranch] if targetBranches is None: continue for targetBranch in targetBranches: if targetBranch in targetBranchClNoDict: targetBranchClNoDict[targetBranch].append(clNumber) else: targetBranchClNoDict[targetBranch] = list() targetBranchClNoDict[targetBranch].append(clNumber) self.log.myPrint ("targetBranchClNoDict - " )#+ str(targetBranchClNoDict)) self.log.myPrint (targetBranchClNoDict, True) pu = PerforceUtils(ipP4 = self.p4, ipIsLogOn = self.userConfigurationMap['logging']) for targetBranchName in targetBranchClNoDict.keys(): targetBranch = self.userConfigurationMap['p4DepotHead'] + targetBranchName self.log.myPrint ("Fetching user's client for input branch - "+targetBranch) client = pu.fetchUserClientForBranch(targetBranch) if client is None: userRoot = self.userConfigurationMap['userRoot'] client = pu.createNewClient(targetBranchName, targetBranch, userRoot) if client is None: continue self.log.myPrint ("Connecting to perforce with client: "+client) pu.connectToClient(client) newlyCreatedCLList = list() for parentChangeList in targetBranchClNoDict[targetBranchName]: parentCLDetails = pu.fetchDetailsOfChangeList(parentChangeList) self.log.myPrint ("~~~~~~~~~Change Details:~~~~~~~~~~~") self.log.myPrint (parentCLDetails, True) parentCLDesc = parentCLDetails['desc'] self.log.myPrint ("Creating a new changelist...") createdCLNumber = pu.createChangelist("Merging "+originalCLBranch+" CL "+parentCLDetails['change']+" to "+targetBranchName+" - "+parentCLDesc) parentCLBranch = re.match(r'%s([^/]+)' % self.userConfigurationMap['p4DepotHead'], parentCLDetails['path']).group(0) self.log.myPrint ("Parent Branch" + str(parentCLBranch)) self.log.myPrint ("Merging files...") mergeResults = pu.mergeChangelist(parentChangeList, createdCLNumber, parentCLBranch, targetBranch) newCLDetails = pu.fetchDetailsOfChangeList(createdCLNumber) self.log.myPrint ("New CL Details: "+str(newCLDetails)) if 'depotFile' not in newCLDetails.keys(): pu.deleteChangelist(createdCLNumber) else: newlyCreatedCLList.append(createdCLNumber) if len(newlyCreatedCLList) <= 0: continue newlyCreatedCLDict = {"Changelist created for "+client : newlyCreatedCLList} mergeAndResolveResults.append(newlyCreatedCLDict) self.log.myPrint ("Resolving changelists...") resolveResults = pu.resolveChangelists(client) if resolveResults is not None and len(resolveResults) > 0: unresolvedFilesList = list() for resolveResult in resolveResults: if "resolve skipped" in resolveResult: unresolvedFilesList.append(resolveResult) if len(unresolvedFilesList) > 0: unresolvedFilesDict = {"UnResolved files for "+client : unresolvedFilesList} mergeAndResolveResults.append(unresolvedFilesDict) return mergeAndResolveResults
rohanb1985/PerforceHandler
perforce/PerforceUtils.py
from P4 import P4,P4Exception from utils.MyLogger import MyLogger import os import pprint import datetime class PerforceUtils: def __init__(self, **args): if args.get('p4host') is None and args.get('ipP4') is None: exit ("Either of P4 Host or the P4 object should be sent!") if args.get("p4host") is not None: self.p4 = P4() self.p4.port = args.get("p4host") self.p4.user = args.get("p4user") elif args.get("ipP4") is not None: self.p4 = args.get("ipP4") if args.get("ipIsLogOn") is not None: self.log = MyLogger(args.get("ipIsLogOn")) else: self.log = MyLogger("N") def connectToPerforce(self): self.log.myPrint ("---> connectToPerforce") try: self.p4.connect() self.log.myPrint ("<--- connectToPerforce") return self.p4 except P4Exception as p4exp: self.log.myPrint ("Some P4 exception while logging into to Perforce!") exit (p4exp) except Exception as exp: self.log.myPrint ("Some exception while connecting to Perforce!") exit (exp) def connectToClient(self, client = ""): self.log.myPrint ("--->connectToClient "+client) self.p4.client = client def fetchSubmittedChangeListsFromIpDateToNow(self, startDate): try: self.log.myPrint ("---> fetchSubmittedChangeListsFromIpDateToNow") submittedChangeLists = self.p4.run("changes", "-s", "submitted", "-u", self.p4.user, "@"+startDate+",@now") self.log.myPrint ("Changelists fetched: ") self.log.myPrint(submittedChangeLists, True) self.log.myPrint ("<--- fetchSubmittedChangeListsFromIpDateToNow") return submittedChangeLists except P4Exception as err: self.log.myPrint (err) def fetchSubmittedChangeListsForBranch(self, ipBranch, startDate, endDate): try: submittedChangeLists = self.p4.run("changes", "-s", "submitted", "-l", ipBranch+"...@"+startDate+",@"+endDate) return submittedChangeLists except P4Exception as err: self.log.myPrint (err) def createChangelist(self, desc = "Merge files"): try: self.log.myPrint ("--->createChangelist") changeList = self.p4.fetch_change() changeList[ "Description" ] = desc createdCLNumber = self.p4.save_change( changeList )[0].split()[1] self.log.myPrint ("<---createChangelist. Changelist created - "+createdCLNumber) return createdCLNumber except P4Exception as err: self.log.myPrint (err) def mergeChangelist(self, parentCL, createdCL, fromBranch, toBranch): try: self.log.myPrint ("--->mergeChangelist parentCL %s, createdCl %s, fromBranch %s, toBranch %s" % (parentCL, createdCL, fromBranch, toBranch)) mergeResults = self.p4.run("merge", "-c", createdCL, "-S", fromBranch, "-P", toBranch, "-s", fromBranch +"/...@"+parentCL+",@"+parentCL) self.log.myPrint ("~~~~~~~~~~Merge Results: ~~~~~~~~~~~~" ) self.log.myPrint(mergeResults, True) self.log.myPrint ("<---mergeChangelist") except P4Exception as err: self.log.myPrint (err) def deleteChangelist(self, changeListNumber): try: self.log.myPrint ("---> deleteChangelist") deleteResult = self.p4.run("change", "-d", changeListNumber) self.log.myPrint ("DeleteResult: "+str(deleteResult)) except P4Exception as err: self.log.myPrint (err) def resolveChangelists(self, client): self.log.myPrint ("--->resolveChangelists") try: resolveResults = self.p4.run_resolve ( "-am" ) self.log.myPrint ("~~~~~~~~~~Resolve Results:~~~~~~~~~~~ ") self.log.myPrint(resolveResults) self.log.myPrint ("<---resolveChangelists") return resolveResults except P4Exception as err: self.log.myPrint (err) def fetchUserClientForBranch(self, ipBranch): try: self.log.myPrint ("--->fetchUserClientForBranch for Branch " + ipBranch) allClients = self.p4.run("clients", "-u", self.p4.user, "-S", ipBranch) self.log.myPrint(allClients, True) if allClients is None or len(allClients) <= 0: return None; systemHost = os.environ['COMPUTERNAME'] for client in allClients: clientHost = client['Host'] if clientHost == systemHost: selectedClientName = client['client'] self.log.myPrint ("<---fetchUserClientForBranch with Client " + selectedClientName) return selectedClientName return None; except P4Exception as err: self.log.myPrint (err) def fetchDetailsOfChangeList(self, changeListNumber): try: changeListDetails = self.p4.run("describe","-s", changeListNumber) changeListDesc = changeListDetails[0] return changeListDesc except P4Exception as err: self.log.myPrint (err) def disconnectFromPerforce(self): try: self.p4.disconnect() self.log.myPrint ("Disconnected.") except P4Exception as err: self.log.myPrint (err) def logoutFromPerforce(self): try: self.p4.run_logout() self.log.myPrint ("Logged Out.") except P4Exception as err: self.log.myPrint (err) def createNewClient(self, ipBranch, ipStream, ipRoot): self.log.myPrint ("--->Creating client for Branch %s, Stream %s, and Root %s" % (ipBranch, ipStream, ipRoot)) try: clientName = os.environ['COMPUTERNAME'] + "_" + ipBranch client = self.p4.fetch_client(clientName) client["Root"] = ipRoot + ipBranch client['Stream'] = ipStream client["View"] = [ipStream + "/... //%s/... " % client['Client']] client['LineEnd'] = "unix" self.p4.save_client(client) self.log.myPrint(client, True) self.log.myPrint ("<--- Created above Client.") return client['Client'] except P4Exception as err: self.log.myPrint (err) return None def fetchClientDetails(self, ipClient): try: self.log.myPrint ("--->fetchClientDetails for Client " + ipClient) clientDetails = self.p4.run("client", "-o", ipClient) self.log.myPrint(clientDetails, True) self.log.myPrint ("<---fetchClientDetails") return clientDetails except P4Exception as err: self.log.myPrint (err)
rohanb1985/PerforceHandler
P4VMergeCLCustomTool.py
<filename>P4VMergeCLCustomTool.py from perforce.PerforceUtils import PerforceUtils from perforce.PerforceMerge import PerforceMerge import datetime import yaml import os import sys import pprint print ("Starting Merge at: " +str(datetime.datetime.now())) #fetchConfig userConfigurationMap = list() home = os.path.expanduser("~") configFile ="config\config.yml" if not os.path.isfile(configFile) : exit("No Config file found") #load config with open(configFile) as file: userConfigurationMap = yaml.safe_load(file) print ("Configuration: " + str(userConfigurationMap)) startDate = datetime.datetime.now().strftime("%Y/%m/%d") if 'StartDate' in userConfigurationMap.keys(): startDate = userConfigurationMap['StartDate'] print ("Start Date %s date found in config" % startDate) else: print ("No config found for start date. Taking current date - %s - as start date" % startDate) p4user = sys.argv[1] p4host = sys.argv[2] pu = PerforceUtils(p4host = p4host, p4user = p4user) p4 = pu.connectToPerforce() submittedChangeLists = pu.fetchSubmittedChangeListsFromIpDateToNow(startDate) p4Merge = PerforceMerge(p4, submittedChangeLists, userConfigurationMap) newlyCreatedChangeLists = p4Merge.mergeAndResolveChangeLists() if newlyCreatedChangeLists is not None and len(newlyCreatedChangeLists) > 0: print("~~~~~~~~~~~~~~Following are the Newly Created Change Lists...~~~~~~~~~~~~~") pprint.pprint(newlyCreatedChangeLists) else: print("Nothing to Merge!!") print ("Completed at: "+str(datetime.datetime.now())) pu.disconnectFromPerforce()
josephlewis42/personal_codebase
python/least_subset_solver.py
#!/usr/bin/env python # Apache License 2011-11 <NAME> <<EMAIL>> import re while True: f_name = raw_input("Enter the name of the file or q to quit: ") if f_name == 'q': exit() with open(f_name) as f: tmp = map(float, re.sub('[^0-9 -.]','',f.read()).split(' ')) # Read the file (removing garbage), split it, and turn it to a list of floats. n distance = tmp[0] nums = sorted(tmp[1:]) # nlg(n) running time, as per Python Documentation sets = [] for i in nums: if not sets: sets.append([i]) else: for s in sets: if s[len(s) - 1] + distance < i: s.append(i) break else: # The for-else loop only runs if the for loop falls off the end rather than being broken. sets.append([i]) print "%s sets returned with distance %s\n" % (len(sets), distance) for s in range(len(sets)): print "\n== Set %s ==\n%s" % (s+1, sets[s])
josephlewis42/personal_codebase
python/randall/alife_randall_checkout/ai_webserver/login.py
# login.py # # Copyright 2011 <NAME> <<EMAIL>> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. #Check password user_pass = {"admin":"<PASSWORD>"} if SESSION and 'login' in SESSION.keys() and SESSION['login']: #Redirect to the index page if already logged in. self.redirect('index.py') elif POST_DICT: try: #If the user validated correctly redirect. if POST_DICT['password'] == user_pass[POST_DICT['username']]: #Send headder SESSION['login'] = True SESSION['username'] = POST_DICT['username'] self.redirect('index.py') else: POST_DICT = [] except: POST_DICT = [] if not POST_DICT: self.send_200() page = ''' <!-- login.py Copyright 2010 <NAME> <<EMAIL>> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. --> <html lang="en"> <head> <title>AI Webserver Login</title> <meta http-equiv="content-type" content="text/html;charset=utf-8" /> <LINK REL=StyleSheet HREF="assets/login.css" TYPE="text/css"> </LINK> <script type="text/javascript" src="assets/jquery.js"></script> <script type="text/javascript" src="assets/md5.js"></script> <script type="text/javascript"> function start() { $('#login').hide(); $('#login_text').hide(); $('#login').delay(1000).fadeIn(2000, function() {}); $('#login_text').fadeIn(2000, function() {}); } function hash() { //Hash the password before submission, not secure against //things like wireshark, but will at least hide plaintext. :) document.getElementById('pass').value = MD5(document.getElementById('pass').value); $('#bg').fadeOut(1000, function() {}); $('#login').fadeOut(2000, function() {}); $('#login_text').fadeOut(2000, function() {}); } </script> </head> <body id="login_page" onLoad="start()"> <!--Stretched background--> <img src="assets/earthrise.jpg" alt="background image" id="bg" /> <h1 id="login_text">AI Webserver Login</h1> <!--Login form--> <div id="login"> <form method="post"> <input type="text" name="username" placeholder="Username"/> <br /> <input type="password" id="pass" name="password" placeholder="Password"/> <br /> <input type="submit" value="Submit" onClick="hash()"/> </form> </div> </html> </body> ''' #Send body self.wfile.write(page)
josephlewis42/personal_codebase
python/OpenCalc/Lib/Code/Functions/Standard.py
<gh_stars>1-10 ''' Description Of Module @Author = <NAME><<EMAIL>> @Date = 2010-2-24 @License = GPL ==Changelog== 2010-2-24 - First version made by <NAME> 2010-03-04 - Abs fixed so it will not return a string, and print an error Joseph Lewis 2010-03-17 - Abs fixed from a prior error, in which it didn't work (abs used instead of fabs) ''' #Import Statements import math import OpenCalc #Define Constants #Define Functions def abs(num): return math.fabs(num)
josephlewis42/personal_codebase
python/auto_summary/AutoSummary.py
<reponame>josephlewis42/personal_codebase #!/usr/bin/env python # -*- coding: utf-8 -*- '''Provides An Automated Summary of a document. Copyright 2011 <NAME> <joehms22 [at] gmail com> Originally Made: 2011-09-21 Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ''' import sys import re import argparse __author__ = "<NAME>" __copyright__ = "Copyright 2011, <NAME>" __license__ = "BSD" TOP_HUNDRED_SCORE = 0 EN_TOP = '''the be to of and a in that have i it for not on with he as you do at this but his by from they we say her she or an will my one all would there their what so up out if about who get which go me when make can like time no just him know take person into year your good some could them see other than then now look only come its over think also back after use two how our work first well way even new want because any these give day most us''' def chars_per_word(sentence): '''Returns the average characters per word.''' return float(len(sentence)) / float(len(sentence.split(' '))) def clean_text(text,leavepunct=False): # Strip to a-z A-Z (TODO: I18N). text = text.replace("\n", " ") if leavepunct: return re.sub("[^a-z.!\? ]", " ", text.strip().lower()) return re.sub("[^a-z ]", " ", text.strip().lower()) def word_frequency(text): '''Counts the frequenc of words in the piece of text, and returns a dict for each word (a-z) lowercased where the key represents the word and the number of times the word is found the value. ''' words = {} tmp = clean_text(text) # Cut to words. for word in tmp.split(): if word in words: words[word] += 1 else: words[word] = 1 return words def set_words_to_value(word_dict, top=EN_TOP, value=TOP_HUNDRED_SCORE): '''Sets the given words to the given value in the given word_dict. The default is to set the top hundred words in english to the TOP_HUNDRED_SCORE. ''' j = word_frequency(top).keys() # get the words in the top hundred text. # remove the top 100 words for w in j: words[w] = value def sentences_in(text): '''Returns a list of sentences in the text. ''' text = text.replace("\n", " ") return re.split('[\?.!]', text) def score_sentence(sentence, words): '''The scoring function, given a dictoinary of word:value pairs, creates a score for each sentence. ''' # Score value based upon words and frequencies of those words. tmp = clean_text(sentence) total = 0 for word in tmp.split(): if word in words: total += words[word] # Make the total in to a percentage. try: total /= float(len(tmp.split())) # Secret ingredient, higher characters per word generally means # more important sentence. total *= chars_per_word(tmp) return total except ZeroDivisionError: return -100 def top_sentences(text, word_freq_dict): '''Returns a sorted list with the top rated sentences first, that contains the tuples (score, sentence_location, sentence_text) For example, the sentence "Call me Ishmael" would come back: (1.8304283, 0, "Call me Ishmael.") 0 would mean it was the first sentence in the text, and it had a score of 1.83... ''' sentences = [] # array of tuples (total score, sentence num, sentence text) known_sentences = set() currs = 0 for s in sentences_in(text): currs += 1 # Increment the current sentence. total = score_sentence(s, words) # Don't add duplicate sentences. s = s.strip() if s not in known_sentences: sentences.append((total, currs, s+".")) known_sentences.add(s) # Sort highest rated sentences to lowest. sentences = sorted(sentences) sentences.reverse() return sentences def __combine_summary(summary): '''Combines a summary in to a meaningful paragraph. A summary is an array of tuples with values of (position of sentence, text). This creates better summary paragraphs by ordering important sentences in the order they were originally. ''' summary = sorted(summary) paragraph = "" for l, s in summary: paragraph += s + " " return paragraph def percentage_top(percentage, sorted_sentences): '''Returns the top rated percentage of the given sentences, in paragraph form. i.e. to get the top 25 percent of a text, call with: percentage_top(25, <list from top_sentences>) ''' percentage = percentage / 100.0 num_sentences = int(len(sorted_sentences)*percentage) + 1 if num_sentences >= len(sorted_sentences): num_sentences = len(sorted_sentences) # Create summary (top x sentences) summary = [] for j in range(num_sentences): t,l,s = sorted_sentences[j] summary.append((l,s)) return __combine_summary(summary) def top_words(num_words, sorted_sentences): '''Returns x number of words from the top sentences.''' summary = [] words = 0 try: for t,l,s in sorted_sentences: if words >= num_words: break words += len(s.split()) summary.append((l,s)) except IndexError: pass return __combine_summary(summary) if __name__ == "__main__": parser = argparse.ArgumentParser(description='Creates summaries from documents by magic.') parser.add_argument('-p','--percent', type=int, default=None, help='the percent of the original document to give as a summary') parser.add_argument('-w', '--words', type=int, default=None, help='the number of words to output as a summary') parser.add_argument('PATH', help='the path of the textfile to read from') args = parser.parse_args() try: if args.PATH: text = open(args.PATH).read() words = word_frequency(text) set_words_to_value(words) sentences = top_sentences(text, words) if args.words: print top_words(args.words, sentences) if args.percent: if args.words: print "\n\n" print percentage_top(args.percent, sentences) except IOError: print "File given can't be found."
josephlewis42/personal_codebase
python/py_basic_ide/pyBASIC/runner.py
import time debug = False def error_fx(text): '''The default error handling, print the text to the console. replace with your own function if you want, have it print to your wx application or whatever.''' sys.stderr.write(text) def output_fx(text): '''The default output handling, print text to the console. replace with your own function if you want, like have it print to a text control in your wx application.''' print text def input_fx(text): '''The default user input handler, use raw_input, if you like you can replace this with your own function, like have it read from a text control.''' return raw_input(text) def check_killed(): '''Checks if the program was killed during execution implemented by pyBASIC ide to kill runaway threads.''' return False def var_replace(string, var_dict): ''' Replaces variables the user is using ($asdf) with python understood ones ( %(asdf)s ) ''' terminators = [" ", ",", "\'", "\"", ".", ";", ":", "!", "?"] #string = string.replace("\\$", "|DOLLAR SIGN|") newstring = "" in_var = False curr_var = "" for char in string: #If we are in a var add the current char to the curr var if in_var and char not in terminators: curr_var += char #The start of a variable if char == '$': in_var = True newstring += "%(" #The end of a var elif in_var == True and char in terminators: #Give the appropriate ending based on type if type(var_dict[curr_var.strip()]) == type(0.0): newstring+=")d" if type(var_dict[curr_var.strip()]) == type(0): newstring += ")i" if type(var_dict[curr_var.strip()]) == type(""): newstring += ")s" newstring += char curr_var = "" in_var = False else: newstring += char #if closed without finishing variable if in_var == True: #Give the appropriate ending based on type if type(var_dict[curr_var.strip()]) == type(0.0): newstring+=")d" if type(var_dict[curr_var.strip()]) == type(0): newstring += ")i" if type(var_dict[curr_var.strip()]) == type(""): newstring += ")s" return newstring.replace("|DOLLAR SIGN|", "$") def get_labels(td): labeldict = {"START": 0} index = 0; for line in td: if line[0] in ["LBL", "LABEL"]: labeldict[line[1]] = index index += 1 return labeldict def error(str,line): error_fx("Error Line %d: %s" % (line, str)) def debug_msg(str): if debug: output_fx(str) def process_line(index, line, label_list, var_dict): ''' Processes a line of basic to run. Returns the new index along with the new variable list. ''' if line[0] in ["STOP"]: #Force out of bounds = program stops index = -100 #Print statment if line[0] in ["PRINT"]: try: output_fx( eval(var_replace(line[1], var_dict)%(var_dict)) ) except KeyError: error("No such variable", index) except ValueError: error("Value Error",index) except TypeError: error("Type Error", index) #Clear Statment if line[0] in ["CLEAR", "CLS"]: for i in range(0,100): output_fx("") #If statment if line[0] in ["IF"]: #debug_msg(var_replace(line[1], var_dict) %(var_dict)) #debug_msg(eval(var_replace(line[1], var_dict)%(var_dict)))) if eval(var_replace(line[1], var_dict)%(var_dict)): index, var_dict = process_line(index, line[2], label_list, var_dict) else: index, var_dict = process_line(index, line[3], label_list, var_dict) index -= 1 #Goto Statment if line[0] in ["GOTO"]: index = label_list[line[1]] -1 #Define Let Statment if line[0] in ["LET"]: try: mystr = var_replace(line[2], var_dict) x = eval(mystr %(var_dict)) var_dict[line[1]] = x except ValueError: error("ValueError", index) except TypeError: error("Type Error", index) #Define Input Statment if line[0] in ["INPUT"]: x = input_fx(line[1] + "\n") try: x = float(x) except ValueError: x = str(x) var_dict[line[2]] = x debug_msg(var_dict) index += 1 return index, var_dict def run(td): ''' Runs a BASIC program given a token document. ''' debug_msg("Lines List:\n"+str(td)+"\n") start_time=time.time() index = 0 #Current line in file. running = True label_list = get_labels(td) var_dict = {} while running: try: line = td[index] index, var_dict = process_line(index, line, label_list, var_dict) if check_killed(): #Stop by making a long line print "Killed" index = len(td) except IndexError: running = False end_time=time.time() output_fx("\n\n") output_fx("--------------------------------") output_fx("Program exited normally.") debug_msg("Debug Mode ON:") debug_msg("Variables: " + str(var_dict)) debug_msg("Labels: " + str(label_list)) debug_msg("Uptime: " + str(end_time - start_time) + " seconds")
josephlewis42/personal_codebase
python/pyWebserver/webserver.py
<gh_stars>1-10 ''' Copyright 2009 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ''' #Imports from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer from os import curdir, sep, path import mimetypes import time import sys import os import socket #Data port_number = 8000 indexpath = "/index.html" _404 = "/404.html" webdir = curdir + "/siteroot" errordir = "/errors" host_name = "" class RequestHandler(BaseHTTPRequestHandler): global webdir global indexpath def do_HEAD(self): ''' Sends the headders for the content, by guessing the mime based on the extention ''' mime = mimetypes.guess_type(self.path) #Guess MIME self.send_response(200) #Send Client OK Response self.send_header('Content-type', mime) self.end_headers() def do_GET(self): ''' Sends the client the web page/file that they requested. This also takes care of the index file. ''' #Show The Headder mime = mimetypes.guess_type(self.path) #Guess MIME self.send_response(200) #Send Client OK Response self.send_header('Content-type', mime) self.end_headers() try: #If the path is blank show the index if self.path == "/": self.path = indexpath #Send the user the web file f = open(webdir + self.path) self.wfile.write(f.read()) f.close() except(IOError): ''' Show the 404 error for pages that are unknown. ''' f = open(webdir + errordir + _404) self.wfile.write(f.read()) f.close() def start(): ''' Sets up and starts the webserver. ''' #Imports global host_name global port_number #Tell the admin when the server started print "Started HTTPServer, press Control + C to quit." print time.asctime(), "Server Starts - Host:%s Port:%s" % (host_name, port_number) #Start the server server = HTTPServer((host_name,port_number), RequestHandler) try: server.serve_forever() except KeyboardInterrupt: print time.asctime(), "Server Stops" server.server_close() def read_config(): import ConfigParser global port_number global indexpath global _404 global webdir global errordir global host_name global password config = ConfigParser.ConfigParser() config.read(curdir + '/Configuration/configure.cfg') #Set all vars from the file _404 = config.get('Pages', '_404') webdir = curdir + config.get('Pages', 'siteroot') errordir = config.get('Pages', 'error_dir') indexpath = config.get('Pages', 'index') config.get('Server', 'host_name') # The commented section gets the hostname from the file #host_name = socket.gethostname() port_number = int(config.get('Server', 'port')) def main(): read_config() start() if __name__ == '__main__': main()
josephlewis42/personal_codebase
python/Genetic Programming/Finished Programs/2010-08-25 GP Test One.py
#!/usr/bin/python from pyevolve import * import math error_accum = Util.ErrorAccumulator() def gp_add(a, b): return a+b def gp_sub(a,b): return a-b def gp_mul(a, b): return a*b def gp_div(a,b): ''' "Safe" division, if divide by 0, return 1. ''' if b == 0: return 1.0 else: return a/(b*1.0) def rangef(min, max, step): result = [] while 1: result.append(min) min = min+step if min>=max: break return result def eval_func(chromosome): global error_accum error_accum.reset() code_comp = chromosome.getCompiledCode() for x in rangef(-1, 1, .1): evaluated = eval(code_comp) target = x**2 + x + 1 error_accum += (target, evaluated) return error_accum.getRMSE() def main_run(): genome = GTree.GTreeGP() genome.setParams(max_depth=5, method="ramped") genome.evaluator.set(eval_func) ga = GSimpleGA.GSimpleGA(genome) ga.setParams(gp_terminals = ['x', '1'], gp_function_prefix = "gp") ga.setMinimax(Consts.minimaxType["minimize"]) ga.setGenerations(100) ga.setMutationRate(0.08) ga.setCrossoverRate(1.0) ga.setPopulationSize(100) ga.evolve(freq_stats=5) print ga.bestIndividual() if __name__ == "__main__": main_run()
josephlewis42/personal_codebase
Euler/001.py
#!/usr/bin/env python ''' If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. ''' threes = [i for i in range(0,1000,3)] fives = [i for i in range(0,1000,5)] print sum(set(threes + fives))
josephlewis42/personal_codebase
python/randall/alife_randall_checkout/ai_webserver/emotions.py
<gh_stars>1-10 # emotions.py # # Copyright 2011 <NAME> <<EMAIL>> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. self.send_200() if not SESSION or 'login' not in SESSION.keys() or not SESSION['login']: self.wfile.write("You are not logged in...<script type='text/javascript'>window.location = 'login.py'</script>") else: #Handle AJAX query. if 'reload' in QUERY_DICT.keys(): zero_emotions = "" page = '''<h3>Emotions:</h3> <div id="progresscontainer">''' try: w = SESSION['world'] a = SESSION['actor'] #Make bars for used emotions for item in w[a].emotions: iv = int(item.value) if iv > 0: page += item.name + ":<br />" page += '''<div class='progressbar'> <div class='progressbartext'>%i%%</div> <div class='progressbarinner' style='width:%i%%;'></div> </div>'''%(iv, iv) else: zero_emotions += "<li>%s</li>"%(item.name) #Alert the user for emotions not used. if zero_emotions != "": page += "<h4>Emotions Not Currently Felt:</h4><ul class='sidebyside'>%s</ul>"%(zero_emotions) page += "</div>" self.wfile.write(page) except KeyError, e: self.wfile.write("Error: Couldn't find the key specified: %s" %(e)) except Exception, e: self.wfile.write("Error: %s" %(e)) #Handle page query. else: page = ''' <html> <head> <script type="text/javascript" src="assets/jquery.js"></script> <script type="text/javascript" src="assets/reloader.js"></script> <link rel="StyleSheet" href="assets/login.css" type="text/css" /> </head> <body onLoad="javascript:Update(2000, 'emotions', 'emotions.py?reload=true');" class="widget"> Loading... </body> </html> ''' self.wfile.write(page)
josephlewis42/personal_codebase
python/exe_reader.py
<reponame>josephlewis42/personal_codebase<filename>python/exe_reader.py #!/usr/bin/env python ''' A program that extracts strings from binary files. Usage: reader.py path/to/file Apache License <NAME> <<EMAIL>> 2011 ''' import sys numstrs = 0 with open(sys.argv[1]) as j: j = j.read() mystr = "" for i in range(0,len(j)): if 31 < ord(j[i]) < 127: mystr += j[i] else: if len(mystr) > 4: # If the string isn't that long, then discard it, we don't care. uniqs = set() for char in mystr: uniqs.add(char) if len(uniqs) > .5 * len(mystr): # If duplicate chars are less than half the string print mystr numstrs += 1 mystr = "" print "==========\n\nOutput: %s strings" % numstrs
josephlewis42/personal_codebase
wheel_of_fortune_ai/wordgraph.py
<reponame>josephlewis42/personal_codebase<filename>wheel_of_fortune_ai/wordgraph.py import collections class NgramGraph: graph = None def __init__(self): self.graph = collections.defaultdict(list) def add_edge(from_node, to_node, score): graph[from_node].append((score, to_node)) graph[from_node] = sorted(graph[from_node], reverse=True) def dfs(self, start_node, depth, match_function):
josephlewis42/personal_codebase
python/chat/server.py
# Server program from socket import * # Set the socket parameters host = gethostname() print host port = 21567 buf = 1024 addr = (host,port) # Check what port to open print "What port, the usual is 21567?" port = raw_input('Port >> ') if not port: port = 21567 addr = (host,int(port)) # Create socket and bind to address UDPSock = socket(AF_INET,SOCK_DGRAM) UDPSock.bind(addr) # Receive messages while 1: data,addr = UDPSock.recvfrom(buf) if not data: print "Client has exited!" break else: print "\n" + data # Close socket UDPSock.close()
josephlewis42/personal_codebase
python/distributed_hash_table.py
#!/usr/bin/env python3 import SocketServer, subprocess, sys from threading import Thread HASH_LENGTH = 32 NUM_HASHES = 2**HASH_LENGTH START_HASH = 0 END_HASH = 0 port = 8000 next_host = "" next_port = "" prev_host = "" prev_port = "" hashed_items = {} def recv_all(socket): total_data=[] while True: data = socket.recv(1024) if not data: break total_data.append(data) return "".join(total_data) def pipe_command(request, host, port): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((host, port)) sock.send(request) response = recv_all(sock) sock.close() return response class SingleTCPHandler(SocketServer.BaseRequestHandler): "One instance per connection. Override handle(self) to customize action." def handle(self): # self.request is the client connection cmd = self.read_token() # read the command cmd = cmd.upper() if cmd == "SEARCH": self.search() elif cmd == "SET_LEFT": self.set_left() elif cmd == "SET_RIGHT": self.set_right() elif cmd == "STORE": self.store() elif cmd == "DELETE": self.delete() self.request.close() def read_token(self): """Reads a token from the input, discarding beginning whitespace and consuming a single whitepsace character after the token """ WHITESPACE = " \t\r\n" data = "" char = self.request.recv(1) while char in WHITESPACE: char = self.request.recv(1) while char not in WHITESPACE and char is not None: data += char char = self.request.recv(1) return data def hash_in_range(self, hashvalue): return hashvalue >= START_HASH and hashvalue < END_HASH def search(self): hashvalue = int(self.read_token()) if self.hash_in_range(hashvalue): if hashvalue in hashed_items: self.request.send(hashed_items[hashvalue]) else: self.request.send(pipe_command("SEARCH " + str(hashvalue), next_host, next_port)) def set_left(self): prev_host = self.read_token() prev_port = int(self.read_token()) def set_right(self): next_host = self.read_token() next_port = int(self.read_token()) def store(self): hashvalue = int(self.read_token()) data = recv_all(self.request) if self.hash_in_range(hashvalue): hashed_items[hashvalue] = data print("stored: {}".format(hashvalue)) else: self.request.send(pipe_command("STORE " + str(hashvalue) + " " + data, next_host, next_port)) def delete(self): hashvalue = int(self.read_token()) if self.hash_in_range(hashvalue): hashed_items[hashvalue] = None print("deleted: {}".format(hashvalue)) else: self.request.send(pipe_command("DELETE " + str(hashvalue) + " ", next_host, next_port)) class SimpleServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer): # Ctrl-C will cleanly kill all spawned threads daemon_threads = True # much faster rebinding allow_reuse_address = True def __init__(self, server_address, RequestHandlerClass): SocketServer.TCPServer.__init__(self, server_address, RequestHandlerClass) if __name__ == "__main__": nodeid = int(sys.argv[1]) maxnodes = int(sys.argv[2]) port = int(sys.argv[3]) keyspace = NUM_HASHES / maxnodes START_HASH = nodeid * keyspace END_HASH = (nodeid + 1) * keyspace print("taking hashes between: {} and {} on port {}".format(START_HASH, END_HASH, port)) server = SimpleServer(("", port), SingleTCPHandler) server.serve_forever()
josephlewis42/personal_codebase
python/randall/alife_randall_checkout/ai_webserver/stats.py
# stats.py # # Copyright 2011 <NAME> <<EMAIL>> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. self.send_200() if not SESSION or 'login' not in SESSION.keys() or not SESSION['login']: self.wfile.write("You are not logged in...<script type='text/javascript'>window.location = 'login.py'</script>") #Handle AJAX query. elif 'reload' in QUERY_DICT.keys(): import time global last_news_time global current_news try: #Check for new news every ten seconds if last_news_time + 5 < time.time(): last_news_time = time.time() current_news = SESSION['world'].item_event_interface.fetch_news() except NameError: #Globals not defined yet. last_news_time = time.time() current_news = SESSION['world'].item_event_interface.fetch_news() page = '''<h3>Recent News:</h3><p>''' for item in current_news: page += item + "<br />" page += "</p>" self.wfile.write(page) #Handle page query. else: page = ''' <html> <head> <script type="text/javascript" src="assets/jquery.js"></script> <script type="text/javascript" src="assets/reloader.js"></script> <link rel="StyleSheet" href="assets/login.css" type="text/css" /> </head> <body onLoad="javascript:Update(10000, 'body', 'stats.py?reload=true');" class="widget"> Loading... </body> </html> ''' self.wfile.write(page)
josephlewis42/personal_codebase
blog/dns_message.py
<reponame>josephlewis42/personal_codebase<gh_stars>1-10 #!/usr/bin/env python3 ''' A program to send messages via DNS queries. Copyright 2013 <NAME> <<EMAIL>> | <<EMAIL>> MIT License ''' import subprocess DNS_SERVER = '8.8.8.8' DOMAIN_NAME = "www.testdnsflagsetting{}.com" NORECURSE_OPT = "+norecurse" msg = raw_input("Enter a message, or blank to receive: ") def read_byte(byteno): byte = "0b" for i in range(byteno * 8, (byteno + 1) * 8): output = subprocess.check_output(['dig','@{}'.format(DNS_SERVER), DOMAIN_NAME.format(i), NORECURSE_OPT]) if ";; AUTHORITY SECTION:" in output: byte += '1' else: byte += '0' return int(byte, 2) # converts binary to an int def write_byte(byteno, byte): to_write = bin(byte)[2:].zfill(8) # gets binary representation of a byte for loc, b in enumerate(to_write): if b == '1': i = (byteno * 8) + loc subprocess.check_output(['dig','@{}'.format(DNS_SERVER), DOMAIN_NAME.format(i)]) print "Wrote 1 at: {}".format(i) if len(msg) == 0: message = "" for byte in range(1,read_byte(0) + 1): # first byte is length of message message += chr(read_byte(byte)) if len(message) > 0: print message else: print "[No Message]" else: total = len(msg) write_byte(0, total) for loc, char in enumerate(msg): write_byte(loc + 1, ord(char)) print "Message written"
josephlewis42/personal_codebase
python/randall/alife_randall_checkout/ai_webserver/chat.py
# chat.py -- A simple chat mechanism. # # Copyright 2011 <NAME> <<EMAIL>> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. self.send_200() if not SESSION or 'login' not in SESSION.keys() or not SESSION['login']: self.wfile.write("You are not logged in...<script type='text/javascript'>window.location = 'login.py'</script>") else: import time #If there is a global chat use it, if not init it. global chat try: c = chat except NameError: #Not defined yet. chat = [] #Handle chat text entry. if POST_DICT != None: try: text = POST_DICT['text'] usr = SESSION['username'] t = time.strftime("%b %d %H:%M:%S %Z") chat.insert(0, "<span style='color:#7F7F7F;'>%s</span> <b>%s &gt;</b> %s" % (t, usr, text)) if len(chat) > 10: chat = chat[:10] except KeyError: #The text entered must have been None. pass #Handle AJAX chat refresh query. if 'reload' in QUERY_DICT.keys(): text = "" for i in chat: text += i + "<br />\n" page = '''<h3>Chat</h3> <p style="height:80px;overflow:auto;">%s</p> ''' % (text) self.wfile.write(page) #Handle page query. else: self.wfile.write(''' <html> <head> <script type="text/javascript" src="assets/jquery.js"></script> <script type="text/javascript" src="assets/reloader.js"></script> <link rel="StyleSheet" href="assets/login.css" type="text/css" /> </head> <body onLoad="javascript:Update(1500, '#chatarea', 'chat.py?reload=true');" class="widget"> <div id="chatarea"></div> <form method="post" width='100%' style='background-color:#FFF;'> <input type="text" name="text" placeholder="Enter message..."/> <input type="submit" value="Submit"/> </form> </body> </html> ''')
josephlewis42/personal_codebase
python/py_basic_ide/MAIN.pyw
<filename>python/py_basic_ide/MAIN.pyw #!/usr/bin/env python # -*- coding: utf-8 -*- # generated by wxGlade 0.6.3 on Tue May 18 15:24:52 2010 import wx #YYYYMMDD.HHMMSS of this release. __version__ = 20100528 human_version = "2010-05-28" # begin wxGlade: extracode import pyBASIC import threading import time thread_is_on = False kill_thread = False file_location = "" debug_mode = False input_queue = "" OUTPUT_EVENT_ID = wx.NewId() OPEN_ID = wx.NewId() SAVE_AS_ID = wx.NewId() SAVE_ID = wx.NewId() RUN_ID = wx.NewId() DEBUG_ID = wx.NewId() ABOUT_ID = wx.NewId() UPDATES_ID = wx.NewId() class OutputEvent ( wx.PyEvent ): '''An event that handles output from the parser.''' def __init__(self, standard_output, error_output): wx.PyEvent.__init__(self) self.SetEventType(OUTPUT_EVENT_ID) self.stdout = standard_output self.stderr = error_output def OUTPUT_EVENT(win, func): """Define Result Event.""" win.Connect(-1, -1, OUTPUT_EVENT_ID, func) class BASICThread ( threading.Thread ): '''This thread runs the BASIC program and manages messages to and from it.''' def __init__(self, program_text, notify_window): self.program_text = program_text threading.Thread.__init__( self ) self._notify_window = notify_window def stdout(self, text): '''Handles the stdout questioning for the thread.''' wx.PostEvent(self._notify_window, OutputEvent(text, "")) def stderr(self, text): '''Handles the stderr for the thread.''' wx.PostEvent(self._notify_window, OutputEvent("", text)) def input(self, text): '''Handles input for the thread.''' global input_queue self.stdout(text) while input_queue == "": time.sleep(.1) iq = input_queue input_queue = "" return iq def kill( self ): '''Gives the thread a suicide mission.''' return kill_thread def run ( self ): import pyBASIC global program_text global thread_is_on, kill_thread thread_is_on = True #Replace handlers with our own. pyBASIC.parser.error_fx = self.stderr pyBASIC.runner.error_fx = self.stderr pyBASIC.runner.input_fx = self.input pyBASIC.runner.output_fx = self.stdout pyBASIC.runner.check_killed = self.kill pyBASIC.set_debug( debug_mode ) print "Compileing" doc = pyBASIC.tokenize_document(self.program_text) print "Running" try: pyBASIC.run(doc) except: self.stderr("FATAL ERROR, Quitting") self.stdout("-------------\nABNORMAL EXIT") print "Quitting" kill_thread = False thread_is_on = False # end wxGlade class main_frame(wx.Frame): def __init__(self, *args, **kwds): # begin wxGlade: main_frame.__init__ kwds["style"] = wx.CAPTION|wx.CLOSE_BOX|wx.MINIMIZE_BOX|wx.MAXIMIZE_BOX|wx.SYSTEM_MENU|wx.RESIZE_BORDER|wx.TAB_TRAVERSAL|wx.CLIP_CHILDREN wx.Frame.__init__(self, *args, **kwds) self.window_1 = wx.SplitterWindow(self, -1, style=wx.SP_3D|wx.SP_BORDER) self.window_1_pane_2 = wx.Panel(self.window_1, -1) self.window_1_pane_1 = wx.Panel(self.window_1, -1) # Menu Bar self.frame_1_menubar = wx.MenuBar() self.file_menu = wx.Menu() self.open_document_item = wx.MenuItem(self.file_menu, OPEN_ID, "Open\tCtrl+o", "Opens an existing document.", wx.ITEM_NORMAL) self.file_menu.AppendItem(self.open_document_item) self.file_menu.AppendSeparator() self.save_document_item = wx.MenuItem(self.file_menu, SAVE_ID, "Save\tCtrl+s", "Saves the current document you are working on.", wx.ITEM_NORMAL) self.file_menu.AppendItem(self.save_document_item) self.save_document_as_item = wx.MenuItem(self.file_menu, SAVE_AS_ID, "Save As\tCtrl+Shift+s", "Saves the document you are working with in a new location.", wx.ITEM_NORMAL) self.file_menu.AppendItem(self.save_document_as_item) self.frame_1_menubar.Append(self.file_menu, "File") wxglade_tmp_menu = wx.Menu() self.run_document_item = wx.MenuItem(wxglade_tmp_menu, RUN_ID, "Run\tCtrl+r", "Runs the currently open document.", wx.ITEM_NORMAL) wxglade_tmp_menu.AppendItem(self.run_document_item) self.debug_button = wx.MenuItem(wxglade_tmp_menu, DEBUG_ID, "Debug\tCtrl+d", "Shows debug statments to help you figure out whats going wrong.", wx.ITEM_CHECK) wxglade_tmp_menu.AppendItem(self.debug_button) self.frame_1_menubar.Append(wxglade_tmp_menu, "Program") wxglade_tmp_menu = wx.Menu() self.about_button = wx.MenuItem(wxglade_tmp_menu, ABOUT_ID, "About", "About pyBASIC IDE", wx.ITEM_NORMAL) wxglade_tmp_menu.AppendItem(self.about_button) self.check_updates_menuitem = wx.MenuItem(wxglade_tmp_menu, UPDATES_ID, "Check For Updates", "Checks for updates.", wx.ITEM_NORMAL) wxglade_tmp_menu.AppendItem(self.check_updates_menuitem) self.frame_1_menubar.Append(wxglade_tmp_menu, "Help") self.SetMenuBar(self.frame_1_menubar) # Menu Bar end self.editor_text_ctrl = wx.TextCtrl(self.window_1_pane_1, -1, "PRINT \"Hello World\"", style=wx.TE_MULTILINE) self.output_text_ctrl = wx.TextCtrl(self.window_1_pane_2, -1, "", style=wx.TE_MULTILINE) self.input_text_ctrl = wx.TextCtrl(self.window_1_pane_2, -1, "") self.submit_button = wx.Button(self.window_1_pane_2, -1, "Submit") self.error_text_ctrl = wx.TextCtrl(self.window_1_pane_2, -1, "", style=wx.TE_MULTILINE) self.__set_properties() self.__do_layout() wx.EVT_MENU(self, OPEN_ID, self.open_document) wx.EVT_MENU(self, SAVE_ID, self.save_document) wx.EVT_MENU(self, SAVE_AS_ID, self.save_document_as) wx.EVT_MENU(self, RUN_ID, self.run_basic) wx.EVT_MENU(self, DEBUG_ID, self.debug_activate) wx.EVT_MENU(self, ABOUT_ID, self.about_program) wx.EVT_MENU(self, UPDATES_ID, self.check_updates) wx.EVT_BUTTON(self, self.submit_button.GetId(), self.submit_text) # end wxGlade # Set up event handler for any worker thread results OUTPUT_EVENT(self,self.OnOutput) #Bind the input control with the enter key self.input_text_ctrl.Bind(wx.EVT_KEY_DOWN, self.input_key_press) def input_key_press(self, event): ''' Checks for the enter key, if it has been pressed then the program will submit the value that is in the pad input box ''' keycode = event.GetKeyCode() #If user pressed enter or return spawn the submit input event if keycode == wx.WXK_RETURN or keycode == wx.WXK_NUMPAD_ENTER: self.submit_text(event) event.Skip() def OnOutput(self, event): '''Handles changing the display when an event is post.''' if event.stderr != "": self.error_text_ctrl.AppendText( str(event.stderr) + "\n") if event.stdout != "": if event.stdout.endswith("\n"): self.output_text_ctrl.AppendText( str(event.stdout)) else: self.output_text_ctrl.AppendText( str(event.stdout) + "\n") def __set_properties(self): # begin wxGlade: main_frame.__set_properties self.SetTitle("pyBASIC - Integrated Development Enviornment") self.SetSize((700, 500)) self.editor_text_ctrl.SetToolTipString("Write your code here.") self.output_text_ctrl.SetBackgroundColour(wx.Colour(0, 0, 0)) self.output_text_ctrl.SetForegroundColour(wx.Colour(255, 255, 255)) self.output_text_ctrl.SetToolTipString("Output will appear here") self.input_text_ctrl.SetToolTipString("Input your text here.") self.error_text_ctrl.SetForegroundColour(wx.Colour(255, 0, 0)) self.error_text_ctrl.SetToolTipString("Errors will appear here") # end wxGlade def __do_layout(self): # begin wxGlade: main_frame.__do_layout sizer_1 = wx.BoxSizer(wx.VERTICAL) sizer_3 = wx.BoxSizer(wx.VERTICAL) sizer_4 = wx.BoxSizer(wx.HORIZONTAL) sizer_2 = wx.BoxSizer(wx.HORIZONTAL) sizer_2.Add(self.editor_text_ctrl, 1, wx.ALL|wx.EXPAND, 4) self.window_1_pane_1.SetSizer(sizer_2) sizer_3.Add(self.output_text_ctrl, 2, wx.ALL|wx.EXPAND, 4) sizer_4.Add(self.input_text_ctrl, 1, wx.ALL, 4) sizer_4.Add(self.submit_button, 0, wx.ALL, 3) sizer_3.Add(sizer_4, 0, wx.EXPAND, 0) sizer_3.Add(self.error_text_ctrl, 1, wx.ALL|wx.EXPAND, 4) self.window_1_pane_2.SetSizer(sizer_3) self.window_1.SplitVertically(self.window_1_pane_1, self.window_1_pane_2) sizer_1.Add(self.window_1, 1, wx.EXPAND, 0) self.SetSizer(sizer_1) self.Layout() self.Centre() self.SetSize((700, 500)) # end wxGlade def submit_text(self, event): # wxGlade: main_frame.<event_handler> global input_queue input_queue = self.input_text_ctrl.GetValue() #Set even if 0 if input_queue != "": self.output_text_ctrl.AppendText(">" + str(input_queue) + "\n") else: self.error_text_ctrl.AppendText( "INPUT ERROR: Please input some real text or a number.\n") self.input_text_ctrl.Clear() event.Skip() def open_document(self, event): # wxGlade: main_frame.<event_handler> import os global file_location dlg = wx.FileDialog(self, "Open a file", os.getcwd(), "", "BASIC Files (*.bas)|*.bas|All Files|*.*", wx.OPEN) if dlg.ShowModal() == wx.ID_OK: path = dlg.GetPath() print "Opening at: %s" % (path) file = open(path, 'r') self.editor_text_ctrl.Clear() self.editor_text_ctrl.AppendText( file.read() ) file.close() file_location = path dlg.Destroy() def save_document(self, event, quiet=False): # wxGlade: main_frame.<event_handler> global file_location if file_location == "": import os dlg = wx.FileDialog(self, "Save a file", os.getcwd(), "", "BASIC Files (*.bas)|*.bas|All Files|*.*", wx.SAVE) if dlg.ShowModal() == wx.ID_OK: file_location = dlg.GetPath() if dlg.GetFilterIndex() == 0 and not file_location.endswith(".bas"): file_location = file_location+".bas" dlg.Destroy() print "Saving at: %s" % (file_location) file = open(file_location, 'w') file.write(self.editor_text_ctrl.GetValue()) file.close() event.Skip() def run_basic(self, event): # wxGlade: main_frame.<event_handler> '''Run the BASIC program the user has.''' global kill_thread global thread_is_on if thread_is_on: '''If thread is running''' print "Thread is on" kill_thread = True time.sleep(1) print "Starting another thread..." #Clear the inputs self.input_text_ctrl.Clear() self.error_text_ctrl.Clear() self.output_text_ctrl.Clear() program_text = self.editor_text_ctrl.GetValue() compiler_thread = BASICThread( program_text, self ) compiler_thread.start() #event.skip() def about_program(self, event): # wxGlade: main_frame.<event_handler> description = """pyBASIC IDE is a cross between TIBASIC, and CLASSIC BASIC, allowing new programmers to experience the excitement of the classical home programming language.\n\n Special thanks to <NAME>.""" licence = """pyBASIC is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. Ubuntu Remote is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Ubuntu Remote; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA""" info = wx.AboutDialogInfo() info.SetName( 'pyBASIC IDE' ) info.SetVersion( human_version ) info.SetDescription( description ) info.SetCopyright( '© 2010 <NAME> <<EMAIL>>' ) info.SetWebSite( 'http://code.google.com/p/pybasic/' ) info.SetLicence( licence ) info.AddDeveloper( '<NAME> <<EMAIL>>' ) wx.AboutBox(info) def save_document_as(self, event): # wxGlade: main_frame.<event_handler> global file_location file_location = "" self.save_document(event) def debug_activate(self, event): # wxGlade: main_frame.<event_handler> global debug_mode debug_mode = not debug_mode print debug_mode def check_updates(self, event, silent=False): # wxGlade: main_frame.<event_handler> print "Checking for updates please wait..." import urllib import webbrowser try: version_on_site = urllib.urlopen("http://pybasic.googlecode.com/svn/trunk/current_version.txt").read() print "Version On Site: " + str(float(version_on_site)) + " This Version " + str(__version__) if float(version_on_site) > __version__: dial = wx.MessageDialog(None, 'Updates Avalable!\nhttp://code.google.com/p/pybasic/', 'Info', wx.OK) dial.ShowModal() webbrowser.open("http://code.google.com/p/pybasic") elif silent == False: dial = wx.MessageDialog(None, 'You are up to date!', 'Info', wx.OK) dial.ShowModal() elif float(version_on_site) < __version__: dial = wx.MessageDialog(None, 'You are using BETA, Thanks!', 'Info', wx.OK) dial.ShowModal() except: if silent == False: dial = wx.MessageDialog(None, 'Unable to reach server.', 'Info', wx.OK) dial.ShowModal() # end of class main_frame def startup(): app = wx.PySimpleApp(0) wx.InitAllImageHandlers() frame_1 = main_frame(None, -1, "") app.SetTopWindow(frame_1) frame_1.Show() frame_1.check_updates("", silent=True) app.MainLoop() if __name__ == "__main__": startup()
josephlewis42/personal_codebase
python/image_generator.py
#!/usr/bin/env python import os import random def write_pgm(filename, content, width): '''Writes a pgm image file from the given content, with width being given. The contnet written is the value at the content at the position, if contnet was [1,0,1,0] and width was 2 the pixels would end up being 10 10 1 being on and 0 being off (black and white). content can be any iteratable object. ''' #Create folders if necessary if os.sep in filename: filepath = filename[:filename.rfind("/")] if not os.path.exists(filepath): os.makedirs(filepath) #Set up variables height = int(len(content) / width) j = 0 line = "" #Open up the new file. with open(filename, 'w') as f: #File header based on pgm standard: f.write("P1\n%i %i\n" % (width, height)) for i in content: if j < width: line += str(i) + " " j += 1 else: f.write(line + "\n") line = "" j = 0 #Append the last line. f.write(line) def add_one(array): add = True for i in range(len(array)): if add: if array[i] == 1: array[i] = 0 else: array[i] = 1 add = False def main_straight_through(): a = [0]*100 i = 0 while a[99] != 1: add_one(a) i += 1 print i write_pgm("%i/%i/%i.pgm"%(i/1000, i/100, i), a, 10) def main_random(height=10, width=10, num_to_gen=10000): length = height * width num_so_far = 0 try: while num_so_far < num_to_gen: my_rand = random.randint(0, 2**length) a = bin(my_rand)[2:] to_add = "0" * (length - len(a)) #Padding front with zeros. a = to_add + a write_pgm("randout_%s.pgm" % (hex(my_rand)[2:-1]), a, width) num_so_far += 1 except KeyboardInterrupt: print("Control + C pressed.") print("Generated %i random images." % (i)) if __name__ == "__main__": a = raw_input("[R]andom or [S]equential Image Generation?") if a.lower() == 'r': h = input("Height in pixels? ") w = input("Width in pixels? ") n = input("How many random images do you want to generate? ") print("The images will be generated in the present working directory") print("Their respective ids will be the hex value of their binary represenation.") main_random(h,w,n) else: print("Generating sequential images, warning, this happens very fast.") print("Press Control + C to stop generation...") main_straight_through()
josephlewis42/personal_codebase
python/gamebot/game_searcher.py
import codescraper DEBUGGING = True class NoResultsException(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) class GameSearcher: '''The game searcher class provides a framework for searching Google for swfs.''' _page_list = [] _list_loc = 0 _next_page = 0 _game_query = "" _current_url = "" #The current swf's url. max_recursion = 30 #Number of pages to search until saying there is no game current_recursion = 0 def _clear_current_search(self): '''Clears the current game search.''' self._page_list = [] self._list_loc = 0 self._next_page = 0 self._game_query = "" def _get_more_games(self): #Get google page, and get potential paths query = self._game_query + "&start=" + str(self._next_page) page_text = codescraper.fetch_page(query) #There are 10 results per page, so the next page should be 10 results further along. self._next_page += 10 #This gets all the text between the tags given on the page. url_list = codescraper.return_between("<cite>", "</cite>", page_text) if url_list == []: raise NoResultsException, "No results found!" for a in url_list: #Google sometimes puts html tags in their cite tags like <b> #since these will become messy when you try to create urls from it #we need to remove them. a = codescraper.remove_HTML_tags(a) self._page_list.append(a) def _get_next_game_url(self): '''Creates a url for the next game on the list.''' try: url = 'http://' + self._page_list[self._list_loc] except IndexError: #Index out of bounds. self._get_more_games() return self._get_next_game_url() self._list_loc += 1 return url def get_next_game(self): self.current_recursion += 1 #Get the next game url url = self._get_next_game_url() if url == None: return None #Get the content type as told by the webserver. ct = codescraper.url_content_type(url) if ct in ["application/x-shockwave-flash", "text/html; charset=iso-8859-1"]: self._current_url = url #Remember the current url. return url return self.get_next_game() def get_current_game(self): return self._current_url def search_for_games(self, query): '''Searches for games with the current query''' #Clean the current search self._clear_current_search() #Build google query query = query.replace("%20", "+") self._game_query = "http://www.google.com/search?q=" + query + "+filetype%3Aswf&hl=en&num=10" #Populate the list so the first request will be faster. self._get_more_games() if __name__ == "__main__": print("Running breaking tests.") g = GameSearcher() g.search_for_games("blah blah all good things happen to great people hannah") while(g._list_loc < 1): print g.get_next_game() print("Running bubble tanks tests.") g.search_for_games("bubble%20tanks") while(g._list_loc < 1): print g.get_next_game()
josephlewis42/personal_codebase
python/OpenCalc/Lib/Code/Functions/Template.py
<reponame>josephlewis42/personal_codebase ''' Description Of Module @Author = Author @Date = Date @License = GPL ==Changelog== Date - Change Date2 - Change2 ''' #Import Statements #Define Constants #Define Functions
josephlewis42/personal_codebase
python/randall/alife_randall_checkout/randallai/AI/pavlov.py
#!/usr/bin/env python ''' Copyright (c) 2011 <NAME> <<EMAIL>> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. The pavlov module provides a condition response mechanism. Events can be registered with pavlov, pavlov will then create associations with events that are closely spaced. NOTE: This was the original class built for the project, and is therefore the most primitive. It has bad built-in constants, messy comments, non-elegant code, etc. and could me made many times better with a little work. ''' import threading import time import sys #Turn the variable DEBUGGING to True if you want to see debugging #messages for this module. DEBUGGING = False __version__ = 1.1 __author__ = "<NAME> <<EMAIL>>" ASSOCIATION_TO_EVENT = 1.0 #The amount of association neededed before one event triggers another ASSOCIATION_PER_SECOND = 0.2 #The amount to raise association per second that is left in the amount of time since the last neuron call to this one. DISASSOCIATION_PER_CALL = 0.05 #The amount of association to remove per disassoc call. MAX_ASSOCIATION_TIME = 3.0 #The number of seconds until two events get no association added when they are fired. class Neuron: _evt_a = None _evt_b = None _evt_a_time = 0 _evt_b_time = 0 assoc = 0.0 def __init__(self, event_a, event_b): '''Create a new Neuron that "remembers" how often two events are registered in proximity to one another. Paramaters: event_a -- The first event. event_b -- The second event. WARNING: Do not use this class directly unless you are absoloutly sure you know what you are doing, it is better to instantiate a ResponseNetwork, which will build and manage Neurons for you. ''' self._evt_a = event_a self._evt_b = event_b if DEBUGGING: print("Neuron created between %s, %s" % (event_a, event_b)) def _evt_time_diff(self): '''The difference in the times each event was last called. Always positive. ''' return abs(self._evt_a_time - self._evt_b_time) def _closeness_to_perfect(self): '''The measure of how close the events were to being in sync, closer events mean more related events. ''' return (MAX_ASSOCIATION_TIME - self._evt_time_diff()) / MAX_ASSOCIATION_TIME def send_event(self, e): '''If the association is above the threshold return the event that was not put in as a paramater, else return None. ''' if self.assoc >= ASSOCIATION_TO_EVENT: if DEBUGGING: print("Response between %s, %s " % (self._evt_a, self._evt_b)) if e == self._evt_b: return self._evt_a return self._evt_b return None def register_event(self, e): '''If the event given is one of those that this Neuron registers and it is in a close enough proximity to the other event this Neuron registers, add association between the two relative to how close they are (closer = more association). If the association is higher than the threshold return the event that was not called. Paramaters: e -- The event that might be in this Neuron that is needed to be updated. ''' if e in (self._evt_a, self._evt_b): #Update time for appropriate event if e == self._evt_a: self._evt_a_time = time.time() else: self._evt_b_time = time.time() #If times close enough together add association. if self._evt_time_diff() < MAX_ASSOCIATION_TIME: self.assoc += self._closeness_to_perfect() * ASSOCIATION_PER_SECOND #Notify of updated association if DEBUGGING: print("%s, %s Association: %.2f%%" % (self._evt_a, self._evt_b, self.percent_associated())) #If assoc high enough, return the event not yet sent. return self.send_event(e) def decrement_assoc(self, multiplier=1): '''Decrements the association, based off the DISASSOCIATION_PER_CALL variable. The optional paramater multiplier can make up for _very_ large neural nets by multiplying the disassoc time. Paramaters: multiplier -- DEFAULT:1 Multiplies the disassoc call by a this number. (int/float) ''' self.assoc -= DISASSOCIATION_PER_CALL * multiplier if self.assoc < 0: self.assoc = 0 def percent_associated(self): '''Returns the association of the two events as a percent, useful for user output, but should not be used anywhere else. (float) ''' return (float(self.assoc)/float(ASSOCIATION_TO_EVENT)) * 100 class ResponseNetwork(threading.Thread): '''A rudimentary condition response "brain". Conditions are registered, then the brain is started. Any time the class is notified with a condition it judges the closeness of that condition with others, if they commonly occur together then an association is built. When an association meets a supplied threshhold both events are triggered, in this fashion rudimentary behavior may be observed. WARNING: The response network is not meant to be shut down and turned back on at will, once off returning to an on state may cause bizarre crashes. Instead use a function that halts updates for a variable amount of time. ''' _neurons = [] #A list of created neurons. _cr = {} #A dictionary of condition > response pairs. _awake = True #Set to false to have the thread kill itself. def __init__(self, update_time=1, autostart=False): '''Sets up the response-network. Paramaters: update_time -- A function that returns a float as the number of seconds until the organs update and fire events, or just a float. DEFAULT: 1 (function, float) autostart -- Should pavlov bootstrap it's own thread (true) or are you going to call start() manually (false)? (bool) Default: False Note: Why use a function for update_time? Well, what if your device wanted to go to sleep but still retain all of it's conditions and responses? What about suspending condition response memory loss while in a state of panic? Maybe the charging station is a long way away for your robot, and you don't want it to forget while it is making the trip. ''' self._update_time = update_time threading.Thread.__init__ ( self ) if autostart: self.start() def __getitem__(self, key): '''Emulates a list or dictionary, called with a tuple of the emotion cross, or an index. Raises IndexError if not found. Example: >>> ResponseNetwork[('one','two')] <class Neuron at 0x0000007b> >>> ResponseNetwork[0] <class Neuron at 0x0000002a> >>> ResponseNetwork[None] IndexError ''' #Check for strings try: for n in self._neurons: if n._evt_a in key and n._evt_b in key: return n except TypeError: pass #Check for indexes try: return self._neurons[key] except TypeError: pass #else raise error raise IndexError def __len__(self): '''Returns the number of neurons.''' return len(self._neurons) def register_con_res(self, condition, response=None): '''Registers a condition with a response. Paramaters: condition -- Any object, usually a string, used to identify a condition. (any) response -- A function, or None. The response will be run any time the condition is created. DEFAULT:None (__call__ or None) Note: If no response is created then a lambda is generated that performs the operation "1+1"; in very large systems this could be a problem with speed or memory storage. Warning: If the response does not have the __call__ attribute (is a function) then the default lambda is generated, no warning will be given. It is assumed you know what you are doing! ''' #If thread alive, we must add them to the active list right now. if self.is_alive(): for cond2 in self._cr.keys(): self._neurons.append(Neuron(cond2, condition)) #Add to the dictionary now. if hasattr(response, '__call__'): self._cr[condition] = response else: self._cr[condition] = (lambda : 1+1) def change_response(self, condition, response): '''Changes the response for a given condition that is allready registered. ''' self._cr[condition] = response def _setup_net(self): '''Sets up the neural net with the current conditions and responses in the dictionary. ''' self._neurons = [] #Get a list of all the conditions tmp = self._cr.keys() #Add a neuron bridging all possible keys for i in range(0, len(tmp)): for j in range(i + 1, len(tmp)): self._neurons.append(Neuron(tmp[i], tmp[j])) if DEBUGGING: print('-' * 30) print("Total Neurons: %i" % (len(self._neurons))) def run(self): '''A pretty simple run method, decrements all of the associations in the neurons on a schedule. ''' #Set up neurons self._setup_net() #Allow starting self._awake = True #Decrement from here on in until the network is killed. while self._awake: #Get the time until the next decrement. if hasattr(self._update_time, '__call__'): ut = float(self._update_time()) else: ut = self._update_time time.sleep(ut) for n in self._neurons: n.decrement_assoc() def condition(self, c, autoappend=True): '''Sends a condition through the neural network creating responses and association between the neurons. Paramaters: c -- The condition to begin registering events from. autoappend -- If the condition is not known about yet, should it be added to the neural net? Yes makes the creature more resiliant and able to learn, but harder to debug. (boolean) Default: True ''' if autoappend: if c not in self._cr.keys(): self.register_con_res(c) #Holds conditions already fired so there are no infinite loops. done_conditions = set() fired = set() #Holds the conditions that have yet to be processed new_conditions = [c] if DEBUGGING: print("=" * 80) while new_conditions: c = new_conditions.pop() done_conditions.add(c) if DEBUGGING: print("Condition raised: %s" % (str(c))) for n in self._neurons: #Only fire neurons once if n not in fired: resp = n.register_event(c) #Not null and not called before if resp and resp not in done_conditions: if resp not in new_conditions: new_conditions.append(resp) fired.add(n) #Call all of the responses now. for c in done_conditions: r = self._cr[c] if hasattr(r, '__call__'): r() def lookup_association(self, c): '''Returns a list of all the things associated with the given condition. A complete reverse-lookup. If a and b are associated, and b and c, and c and d, and c and f, then a reverse lookup for a would return [b,c,d,f]. Note: This does not raise association between Neurons. Paramaters: c -- The condition to lookup events from. ''' #Hold conditions already fired so there are no infinite loops. done_conditions = set() #Conditions already checked. fired = set() #Neurons already fired. #Holds the conditions that have yet to be processed, but have #been fired by a neuron. new_conditions = [c] if DEBUGGING: print("=" * 80) print("Reverse lookup on condition: %s" % (str(c))) while new_conditions: c = new_conditions.pop() done_conditions.add(c) if DEBUGGING: print("Condition checked: %s" % (str(c))) for n in self._neurons: #Only fire neurons once if n not in fired: resp = n.send_event(c) #If the Neuron was fired, and the condition hasn't #allready been sent. if resp and resp not in done_conditions: if resp not in new_conditions: new_conditions.append(resp) fired.add(n) return list(done_conditions) def get_neuron(self, evt1, evt2): '''Returns the Neuron that bridges the two events, returns None if the Neuron doesn't exist. ''' try: return self.__getitem__((evt1, evt2)) except IndexError: return None def get_association(self, evt1, evt2): '''Returns a tuple (association, assoc_to_event) for the Neuron bridging the given two events, Returns (None, None) if Neuron doesn't exist. ''' n = self.get_neuron(evt1, evt2) if n != None: return (n.assoc, n.assoc_to_evt) return (None, None) def sleep(self): '''Kills the thread.''' self._awake = False def export_csv(self): '''Returns a string representation of a csv file. This can be written to a file later. The columns and rows are the neuron names, and in the cells between are the percentages of association between the two. The csv is comma delimited and single quotes designate cell contents. Neurons that don't exist will be blank, neurons with 0 association will be 0.0000. ''' output = "" tmp = self._cr.keys() #Get all the conditions now so it doesn't change. tmp.sort() #Get a list of every neuron and it's value for quick lookup #later on. neuron_snapshot = {} for n in self._neurons: neuron_snapshot[(n._evt_a, n._evt_b)] = n.percent_associated() #Write column header. output += "''," #Blank for first col (row headers). for k in tmp: output += "'%s'," % (str(k)) output += "\n" #Write rows for i in tmp: #Row header output += "'%s'," % (i) #Row contents for j in tmp: #Try fetching the percent forward and backward, if not #found that means we are comparing a key to itself, #which has no value, for sanity purposes. try: percent = neuron_snapshot[(i,j)] except: try: percent = neuron_snapshot[(j,i)] except: percent = "" output += "'%s'," % (str(percent)) #End this line. output += "\n" return output def export_HTML_table(self, hidezeros=True): '''Returns a string representation of an HTML table. This can be written to a file later. The columns and rows are the neuron names, and in the cells between are the percentages of association between the two. Neurons that don't exist will be blank. Paramaters: hidezeros - If the neuron is zero hide the value. (bool) DEFAULT: True ''' output = "" tmp = self._cr.keys() #Get all the conditions now so it doesn't change. tmp.sort() #Get a list of every neuron and it's value for quick lookup #later on. neuron_snapshot = {} for n in self._neurons: neuron_snapshot[(n._evt_a, n._evt_b)] = n.percent_associated() #Write column header. output += "<table>\n<tr><th></th>" #Blank for first col (row headers). for k in tmp: output += "<th>%s</th>" % (str(k)) output += "</tr>\n" #Write rows for i in tmp: #Row header output += "<tr><th>%s</th>" % (i) #Row contents for j in tmp: #Try fetching the percent forward and backward, if not #found that means we are comparing a key to itself, #which has no value, for sanity purposes. try: percent = neuron_snapshot[(i,j)] except: try: percent = neuron_snapshot[(j,i)] except: percent = None if not percent or hidezeros and int(percent) == 0: output += "<td></td>" else: output += "<td>%.2f</td>" % (percent) #End this line. output += "</tr>\n" output += "</table>" return output if __name__ == "__main__": DEBUGGING = True r = ResponseNetwork() r.register_con_res('a') r.register_con_res('b') r.register_con_res('c') r.register_con_res('d') r.start() time.sleep(1) print r[1] r.condition('a') r.condition('b') r.condition('a') r.condition('b') r.condition('a') r.condition('b') r.condition('a') r.condition('b') r.condition('a') r.condition('b') r.condition('a') time.sleep(5) r.condition('a') r.condition('c') r.condition('a') r.condition('c') r.condition('a') r.condition('c') r.condition('a') print r.lookup_association('a') r.sleep()
josephlewis42/personal_codebase
python/py_basic_ide/pyBASIC/parser.py
<gh_stars>1-10 #!/usr/bin/python SHOW_ERRORS = True import sys def error_fx(text): '''The default error handling, print the text to the console. replace with your own function if you want, have it print to your wx application or whatever.''' sys.stderr.write(text) def show_error(text): ''' Send an error if SHOW_ERRORS = True ''' if SHOW_ERRORS: error_fx(text) def split_text(text, seperator=" "): return get_word(text, seperator) def get_word(text, seperator=" "): ''' Returns the beginning and end of text seperated around seperator. If seperator is not found, the tail will be a blank string. ''' try: head = text[0:text.index(seperator)] tail = text[text.index(seperator) + len(seperator) : len(text)] except ValueError: return text, "" return head.strip(), tail.strip() def remove_between(text, char="\""): ''' Returns a string from between the next two characters from the input string, returns the head, thorax, and tail. Example: remove_between("TEST \"Hello Jane!\" said Dick.") ("TEST ", "Hello Jane!", "said Dick.") ''' head, tail = get_word(text, char) thorax, abdomen = get_word(tail,char) return head.strip(), thorax.strip(), abdomen.strip() def has_another(text, substring): ''' Tests if the text has another substring, if it does returns true, if else it returns false. ''' try: text.index(substring) return True except: return False def tokenize(line, linenumber): ''' Tokenize so the runner can work and check for errors in the syntax. ''' word_list = [] #Is returned with each token in a proper area. #Get the keyword first_word, rest_line = split_text(line) first_word = first_word.upper() #Add the first word to the list for identification in runner. word_list.append(first_word) #Check for first keyword acceptable_words_list = ["PRINT", "CLS", "IF", "GOTO", \ "LABEL", "INPUT", "LET", "REM", \ "END", "STOP", "", "CLEAR", "LBL"] if first_word not in acceptable_words_list: show_error("Token error line %d, %s is not a valid token." %(linenumber, first_word)) #Tokenize the rest of the line based off of first keyword. """ If statment: ["IF", "EXPRESSION", "THEN STATMENT", "ELSE STATMENT"] Example IF y=='' THEN PRINT 'Hello' Is formatted as. ["IF", "%(y)s == ''", "PRINT 'Hello'", "PRINT 'Goodbye'"] The else is optional. """ if first_word in ["IF"]: #Check for syntax errors if not has_another(rest_line, "THEN"): show_error("IF error line %d, no THEN statment."%(linenumber)) expression, tail = get_word(rest_line, "THEN") word_list.append(expression) if not has_another(rest_line, "ELSE"): #if no else word_list.append( tokenize(tail, linenumber) ) word_list.append( tokenize("REM Nothing", linenumber) ) else: #If there is an else still. then, rest = get_word(tail, "ELSE") word_list.append( tokenize(then, linenumber) ) word_list.append( tokenize(rest, linenumber) ) #Let if first_word in ["LET"]: if not has_another(rest_line, "="): show_error("LET error line %d, no assignment operator after variable." %(linenumber)) else: head, tail = get_word(rest_line, "=") word_list.append(head) word_list.append(tail) #Input if first_word in ["INPUT"]: a,b,c = remove_between(rest_line, "\"") if a != "": show_error("INPUT error line %d, too many tokens before String." %(linenumber)) if has_another(c, " "): show_error("INPUT error line %d, extra tokens found after variable." %(linenumber)) if c == "": show_error("INPUT error line %d, no assignment variable." %(linenumber)) word_list.append(b) #User Display Text word_list.append(c) #Variable #Rem if first_word in ["REM"]: word_list.append(rest_line) #End if first_word in ["END"]: if rest_line != "": show_error("END error line %d, too many tokens after END." %(linenumber)) #Stop if first_word in ["STOP"]: if rest_line != "": show_error("STOP error line %d, too many tokens after STOP." %(linenumber)) #gosub #Goto Statment if first_word in ["GOTO"]: if has_another(rest_line, " "): show_error("GOTO error line %d, too many tokens after GOTO" %(linenumber)) else: word_list.append(rest_line) #PRINT Statment if first_word in ["PRINT"]: word_list.append(rest_line) #Clear statment if first_word in ["CLS", "CLEAR"]: if rest_line != "": show_error("CLEAR/CLS error line %d, too many tokens after CLEAR/CLS." %(linenumber)) #LABEL statment if first_word in ["LABEL", "LBL"]: if has_another(rest_line, " "): show_error("LABEL/LBL error line %d, too many tokens after LABEL/LBL." %(linenumber)) else: word_list.append(rest_line) #Return the list of tokenized words return word_list def tokenize_document(text): ''' Create a token list of a document with newline characters. ''' tokens = [] tokenlines = text.split("\n") index = 1 for line in tokenlines: t = tokenize(line, index) if t != [""]: tokens.append(t) index += 1 return tokens def tokenize_from_file(path): ''' Create a basic token list from a document. ''' text = "" a = file(path) for line in a: text += line return tokenize_document(text)
josephlewis42/personal_codebase
python/dns.py
<filename>python/dns.py #!/usr/bin/env python ''' Copyright (c) 2010 <NAME> <<EMAIL>> SIMPLE DNS TEST SERVER This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ''' import socket import time UDP_IP = 'localhost' UDP_PORT = 53 #53 is the standard for DNS. BUFFER_SIZE = 1024 LOG_FILENAME = "DNS.log" qdb = {'google.p2p':'172.16.17.32','home.p2p':'192.168.127.12','localhost.p2p':'127.0.0.1'} class DNS(): ''' This class is for creating a simple DNS server.''' def start(self): '''Starts the DNS and gets it listening.''' try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.bind( (UDP_IP, UDP_PORT) ) print("Server starts at: %s:%d" % (UDP_IP, UDP_PORT)) self.log_time() except socket.error,e: print("Error connecting to socket: %s" % (e)) exit() while True: #Accept Unlimited Connections try: #If the connection closes before ready it will cause an error. #Receive data data, addr = s.recvfrom(BUFFER_SIZE) #If there is garbage notify the admin. if not data: break #Get a response. query, ip, packet = self.proc_data(data) #Send the packet back. self.log(str(addr) + " : " + query + " <--> " + ip) s.sendto(packet, addr) except KeyboardInterrupt: print("Control + c pressed exit() called...") self.log_time() exit() except: self.log("Connection error, possibly a portscan.") self.log_time() def log_time(self): '''Logs the current time.''' self.log('Time UTC: ' + str(time.asctime(time.gmtime())) + "\n") self.log('Time Local: ' + str(time.asctime(time.localtime())) + "\n") def log(self, data): '''Logs any data sent to the file specified by LOG_FILENAME.''' print( str( data.replace("\n", "") ) ) #Give visual feedback. log_file = open(LOG_FILENAME, 'a') log_file.write( str(data) ) log_file.close() def proc_data(self, data): ''' Processes the data. Return the return packet as a string. and the query site. This is what the original packet looks like (taken from the rfc). http://www.faqs.org/rfcs/rfc1035.html 1 1 1 1 1 1 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ID | char 0,1 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ |QR| Opcode |AA|TC|RD|RA| Z | RCODE | char 2,3 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | QDCOUNT | char 4,5 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ANCOUNT | char 6,7 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | NSCOUNT | char 8,9 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ARCOUNT | char 10,11 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ ''' #First 16 bits are query ID qid = data[0:2] #Next sixteen bits are query info (changes to strings of bits) first = bin(ord(data[2]))[2:] second = bin(ord(data[3]))[2:] #Query or response? qr = bool(int(first[0])) #Opcode (0,1 or 2) remove all but first four bits #opcode = eval('0b'+first[1:5]) opcode = (ord(data[2]) >> 3) & 15 #QDCOUNT an unsigned 16 bit integer specifying the number of # entries in the question section. qdcount = data[4:6] #ANCOUNT an unsigned 16 bit integer specifying the number of # resource records in the answer section. ancount = data[6:8] #NSCOUNT an unsigned 16 bit integer specifying the number of name # server resource records in the authority records # section. nscount = data[8:10] #ARCOUNT an unsigned 16 bit integer specifying the number of # resource records in the additional records section. arcount = data[10:12] #Query (for now assume that there is only one) #Query starts with a number of characters, then prints that #number of chars, then another number, then prints that, etc #until we get a 0 query = '' pos=12 length=ord(data[pos]) while length: query += data[pos+1 : pos+length+1] + '.' pos += length + 1 length = ord(data[pos]) #Remove trailing dot. query = query[:-1] #Only look up our domains if query.endswith('.p2p') and not query.endswith('.icann.p2p'): try: if query.startswith('www.'): #Save db space by not storing wwws query = query[4:] ip = qdb[query] except: self.log("Query not in DB: %s" % (query)) ip = '0.0.0.0' else: try: ip = socket.gethostbyname(query) except: #Can't reach dns, just send back nothing. ip = '0.0.0.0' #CONSTRUCT RESPONSE: response = '' #Add the query id response += qid #Add response header. # 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 #|QR| Opcode |AA|TC|RD|RA| Z | RCODE | response += chr(0b10000000) + chr(0b0000000) #Add qd count response += qdcount #Add answer count (same as qd count) FIXME Will fail with more than one msg. response += qdcount #Add aanswer coundt response += chr(0b0) + chr(0b0) + chr(0b0) + chr(0b0) #Add original question response += data[12:] #Add pointer for message compression: #See RFC Section 4.1.4. Message compression response += chr(0b11000000) + chr(0b1100) #TYPE two octets containing one of the RR type codes. This # field specifies the meaning of the data in the RDATA # field. response += chr(0b00000000) + chr(0b00000001) #CLASS two octets which specify the class of the data in the # RDATA field. response += chr(0b00000000) + chr(0b00000001) #TTL a 32 bit unsigned integer that specifies the time # interval (in seconds) that the resource record may be # cached before it should be discarded. Zero values are # interpreted to mean that the RR can only be used for the # transaction in progress, and should not be cached. # #This should be the same length of time until next DNS cache update, for #now don't cache. response += chr(0b00000000) + chr(0b00000000) + chr(0b00000000) + chr(0b00000000) #RDLENGTH an unsigned 16 bit integer that specifies the length in # octets of the RDATA field. # #For now this is 4 bytes (size of an ip address) response += chr(0b00000000) + chr(0b00000100) #RDATA a variable length string of octets that describes the # resource. The format of this information varies # according to the TYPE and CLASS of the resource record. # For example, the if the TYPE is A and the CLASS is IN, # the RDATA field is a 4 octet ARPA Internet address. response += socket.inet_aton(ip) return (query, ip, response) if __name__ == "__main__": print("Simple DNS server written by <NAME> <<EMAIL>>") value = "" while value != 'y' and value != 'n': value = raw_input("Do you want to bind externally y/n?") if value == 'y': #Find our external ip s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(('google.com', 80)) UDP_IP = s.getsockname()[0] else: UDP_IP = 'localhost' DNS().start()
josephlewis42/personal_codebase
python/gamebot/games_db.py
#!/usr/bin/env python ''' Provides a database for games Copyright (c) 2011 <NAME> <<EMAIL>> 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, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 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. ''' import sqlite3 import time import re conn = None # Connection to the games db. cursor = None #The cursor for games def setup(): '''Sets up the games database (connects, etc.)''' global conn global cursor conn = sqlite3.connect('games_db.sqlite') conn.row_factory = sqlite3.Row #Produce dicts of data rather than tuples cursor = conn.cursor() #If the database isn't set up, create the new tables. try: #Is this database set up? cursor.execute("select * from Games") except sqlite3.OperationalError: ''' ==Database Layout== TABLE: Games name (name of the game) date (date last accessed) file (blob of this file) ''' cursor.execute('''create table Games (name text, date numeric, file blob)''') setup() def cleanup(t): '''Removes games older than the given time (UNIX time).''' #Remove all deleted nodes cursor.execute("DELETE FROM Games WHERE date<?",(t,)) # Clean up the database. cursor.execute("VACUUM") conn.commit() def empty(): '''Completely cleans the database.''' cleanup(time.time()) def __clean_name(name): return re.sub('[^a-z1-9]', '', name.lower().strip()) def add(name, blob): '''Adds a game to the database.''' b = sqlite3.Binary(blob) #Convert the input to a blob. #Clean up the name to be very simple (for easier searching) name = __clean_name(name) cursor.execute("INSERT INTO Games (name, date, file) VALUES (?, ?, ?)", (name, int(time.time()), b)) conn.commit() def find(name): '''Finds the game with the given name, returns the binary if possible, if not returns None. ''' name = __clean_name(name) cursor.execute("SELECT * FROM Games WHERE Name=?",(name,)) row = cursor.fetchone() if row != None: return row['file'] return None def random_names(): '''Returns a list of the names of 10 random games.''' cursor.execute("SELECT name FROM Games ORDER BY RANDOM() LIMIT 10") names = [] for n in cursor.fetchall(): names.append(n['name']) return names
josephlewis42/personal_codebase
python/gamebot/games_server.py
#!/usr/bin/env python ''' Provides a database for games Copyright (c) 2011 <NAME> <<EMAIL>> 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, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 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. ''' import games_db import game_searcher import codescraper import re import email_fetch gs = game_searcher.GameSearcher() ef = None sofar = 0 #served so far inst = ''' <span style="text-align: center;"><h1>Game Bot</h1></span> <p>Thank you for using GAME BOT, the best (and probably only) automated game fetching service in the world. The game you requested has been attached, if nothing attached, GAME BOT couldn't find the game you requested.</p> <p><i>Sharing is caring!</i> Please forward these games to your allies, rather than having them download from GAME BOT so we can keep bandwidth costs down.</p> <p>Better yet, just start an email account (we suggest Gmail) which you and your friends share the password to, then use it to fetch and store games you all like, creating a private, secure, game collection.</p> <hr> <h3> FAQs </h3> <p> Q: This isn't the game I asked for, what happened?<br> A: GAME BOT is after all a computer, and sometimes it gets fooled.<br> <br> Q: How do I use GAME BOT?<br> A: Send GAME BOT an email message where the subject is the game you want to play, GAME BOT will find it on the Internet and send it back to you soon.<br> <br> Q: Who actually owns these games?<br> A: All games are Copyright their respective creators, GAME BOT simply passes what is already available on the Internet on to you.<br> <br> Q: How do I contribute?<br> A: In the future GAME BOT may ask you to complete a survey, that will pay the maker of GAME BOT to keep it running and updated, but for now, just enjoy it :)<br> <br> Q: How do I play these games?<br> A: Download the file attached, then open it up in Firefox, Internet Explorer, Chrome, or any other Flash enabled web browser.<br> <br> Q: The game attached does not work, why?<br> A: Some game authors only allow their games to be played on the sites they put them on, there is nothing GAME BOT can do about this.<br> </p> ''' def __clean_name(name): return re.sub('[^a-z1-9\w+]', '', name.lower().strip()) def fetch_game(name): print "Looking for: %s" % (name) bin = games_db.find(name) if bin: print " > Found in database." return bin else: try: name = __clean_name(name) gs.search_for_games(name) game_loc = gs.get_next_game() print " > Finding online at: %s" % (game_loc) games_db.add(name, codescraper.fetch_page(game_loc)) return games_db.find(name) except game_searcher.NoResultsException: return None def build_body(): '''Builds the body of the message.''' body = inst + ''' <hr> <h3> Random Games You Might Like </h3> <ul> ''' for i in games_db.random_names(): body += " <li> "+ i + "</li>" body += "</ul>" return body def mail_caller(msg): global sofar j = email_fetch.SimpleMessage(msg) sofar += 1 print ("%s : %s is searching for: %s" % (sofar, j.personfrom, j.subject)) game = fetch_game(j.subject) attach = {} if game != None: attach['%s.swf' % (__clean_name(j.subject))] = game ef.send_mail(j.personfrom, j.subject, build_body(), full_attachments=attach) if __name__ == "__main__": #while 1: # fetch_game(raw_input("What game do you want? ")) email_fetch.DEBUG = True #turn on debugging for email fetch (verbose mode) print "If this is your first time running the server, please configure" print "it using config_file.ini, config_file.ini is already set up for" print "gmail (just change your email and password!)" ef = email_fetch.EmailInterface(time=3, callback=mail_caller) #Have the email fetcher set up by the ini file. import ini_reader ini_reader.setup_fetcher(ef) try: ef.run() except KeyboardInterrupt: print "Server terminated, bye."
josephlewis42/personal_codebase
Euler/009.py
#!/usr/bin/env python ''' A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a2 + b2 = c2 For example, 32 + 42 = 9 + 16 = 25 = 52. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc. ''' import pymath trip = pymath.primitive_pythagorean_triples(1000)[0] print trip[0] * trip[1] * trip[2]
josephlewis42/personal_codebase
python/Genetic Programming/Examples/pyevolve_ex17_gtree.py
from pyevolve import GSimpleGA from pyevolve import GTree from pyevolve import Crossovers from pyevolve import Mutators import time import random def eval_func(chromosome): score = 0.0 # If you want to add score values based # in the height of the Tree, the extra # code is commented. #height = chromosome.getHeight() for node in chromosome: score += (100 - node.getData())*0.1 #if height <= chromosome.getParam("max_depth"): # score += (score*0.8) return score def run_main(): genome = GTree.GTree() root = GTree.GTreeNode(2) genome.setRoot(root) genome.processNodes() genome.setParams(max_depth=3, max_siblings=2, method="grow") genome.evaluator.set(eval_func) genome.crossover.set(Crossovers.GTreeCrossoverSinglePointStrict) ga = GSimpleGA.GSimpleGA(genome) ga.setGenerations(100) ga.setMutationRate(0.05) ga.evolve(freq_stats=10) print ga.bestIndividual() if __name__ == "__main__": run_main()
josephlewis42/personal_codebase
python/reprap-franklin/firmware/__init__.py
<reponame>josephlewis42/personal_codebase import full #Full firmware implementation. #Individual Firmwares Here import repman import gen5
josephlewis42/personal_codebase
python/pretty_diff.py
''' Generates a diff when given two arguments, and opens the web browser to display it. Copyright (c) 2013, <NAME> <<EMAIL>> | <<EMAIL>> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ''' import difflib import sys import webbrowser import sys import tempfile def generate_diff(lines1, lines2): '''Generates a pretty diff and opens the system web browser to show it. lines1 - a list of strings for the first file's lines. lines2 - a list of strings for the second file's lines. ''' diff = difflib.HtmlDiff().make_file(fromlines, tolines, "Original", "New") with tempfile.NamedTemporaryFile(suffix='.html', delete=False) as tmp: tmp.writelines(diff) webbrowser.open(tmp.name) if __name__ == "__main__": if len(sys.argv) < 3: print("usage: {} original_file new_file".format(sys.argv[0])) exit(2) fromlines = open(sys.argv[1], 'U').readlines() tolines = open(sys.argv[2], 'U').readlines() generate_diff(fromlines, tolines)
josephlewis42/personal_codebase
python/reprap-franklin/inputs/unix_socket.py
<reponame>josephlewis42/personal_codebase #!/usr/bin/env python '''Provides an interface between the RepRap Franklin and a UNIX socket. VirtualBox can be configured to use a UNIX socket as an interface to the virtual machine's serial port, this class opens up that file and communicates with the RepRap software running on the given machine. Copyright 2011 <NAME> <<EMAIL>> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. ''' import threading import time import socket class UNIXSocketInput( threading.Thread ): def __init__(self, reprap, source, delay=None): self.reprap = reprap self.source = source self.delay = delay threading.Thread.__init__(self) self.daemon = True def run(self): #try: s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) s.connect(self.source) s.send("start\n") #Supposedly needed (the RepRap wiki) buf = "" #Buffer for commands. while 1: buf += s.recv(2048) if "\n" in buf: #Break up commands. line, buf = buf.split("\n", 1) retcode = self.reprap.current_firmware.execute_gcode(line) s.send(retcode) if callable(self.delay): self.delay() else: time.sleep( float(self.delay) ) #except Exception, exc: # print("Exception: %s" % (exc)) print("Done reading from file.")
josephlewis42/personal_codebase
Euler/014.py
''' Collatz sequence The following iterative sequence is defined for the set of positive integers: n -> n/2 (n is even) n -> 3n + 1 (n is odd) Using the rule above and starting with 13, we generate the following sequence: 13 -> 40 -> 20 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1 It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1. Which starting number, under one million, produces the longest chain? NOTE: Once the chain starts the terms are allowed to go above one million. ''' import pymath sequences = {} def find_next_number(n): if n % 2 == 0: return n / 2 else: return 3 * n + 1 def get_collatz_sequence(n): ''' Use some dynamic programming here to speed things up! ''' if n == 1: return [1] if n in sequences: return sequences[n] return [n] + get_collatz_sequence(find_next_number(n)) for i in range(1,1000000): seq = get_collatz_sequence(i) sequences[i] = seq largestValue = 0 largestKey = 0 for key, value in sequences.items(): if len(value) > largestValue: largestValue = len(value) largestKey = key print largestKey
josephlewis42/personal_codebase
python/Genetic Programming/Examples/pyevolve_ex20_gp_dotwrite.py
from pyevolve import * import math rmse_accum = Util.ErrorAccumulator() def gp_add(a, b): return a+b def gp_sub(a, b): return a-b def gp_mul(a, b): return a*b def gp_sqrt(a): return math.sqrt(abs(a)) def eval_func(chromosome): global rmse_accum rmse_accum.reset() code_comp = chromosome.getCompiledCode() for a in xrange(0, 5): for b in xrange(0, 5): evaluated = eval(code_comp) target = math.sqrt((a*a)+(b*b)) rmse_accum += (target, evaluated) return rmse_accum.getRMSE() def step_callback(engine): if engine.getCurrentGeneration() == 0: GTree.GTreeGP.writePopulationDotRaw(engine, "pop.dot", 0,1) return False def step_callback(gp_engine): print "Called \n\n\n\n\n\n\n\n\n\n" if gp_engine.getCurrentGeneration() == 23: GTree.GTreeGP.writePopulationDot(gp_engine, "trees.dot", start=0, end=3) def main_run(): genome = GTree.GTreeGP() genome.setParams(max_depth=6, method="ramped") genome.evaluator += eval_func genome.mutator.set(Mutators.GTreeGPMutatorSubtree) ga = GSimpleGA.GSimpleGA(genome, seed=666) ga.stepCallback.set(step_callback) ga.setParams(gp_terminals = ['a', 'b'], gp_function_prefix = "gp") ga.setMinimax(Consts.minimaxType["minimize"]) ga.setGenerations(30) ga.setCrossoverRate(1.0) ga.setMutationRate(0.08) ga.setPopulationSize(100) ga.setMultiProcessing(False) ga.stepCallback.set(step_callback) #genome.writePopulationDotRaw(ga, "pop.dot", 0, 1) ga(freq_stats=5) best = ga.bestIndividual() print ga.bestIndividual() if __name__ == "__main__": main_run()
josephlewis42/personal_codebase
python/monty_hall.py
<filename>python/monty_hall.py #!/usr/bin/env python #Monty Hall Problem # # switch = True : change doors # switch = False: don't change doors import random import time starttime = time.time() def choose_door_to_open(one, two): #If either of the doors is the one with the prize if one or two: if one: return 2 else: return 1 #If neither of the doors has a prize, return a random number else: return random.randint(1,2) wins = 0 losses = 0 rounds = 1000000 switch = True for i in range(1,rounds+1): #Set up doors door_one = False door_two = False door_three = False #Choose door that is to have door_with_prize = random.randint(1,3) if door_with_prize == 1: door_one = True if door_with_prize == 2: door_two = True if door_with_prize == 3: door_three = True #print "Doors:" #print "One: "+str(door_one) #print "Two: "+str(door_two) #print "Three: "+str(door_three) #Have the program randomly choose a start door chosen_door = random.randint(1,3) #print "Chosen door: "+str(chosen_door) #Have the program choose which door to open. if chosen_door == 1: opens = choose_door_to_open(door_two, door_three) if opens == 1: opens = 2 else: opens = 3 elif chosen_door == 2: opens = choose_door_to_open(door_one, door_three) if opens == 1: opens = 1 else: opens = 3 else: opens = choose_door_to_open(door_one, door_two) if opens == 1: opens = 1 else: opens = 2 #print "Door Opened: "+str(opens) #Have the program choose to switch or stay and report result. if switch: if opens == 1 and chosen_door == 2: chosen_door = 3 elif opens == 1 and chosen_door == 3: chosen_door = 2 elif opens == 2 and chosen_door == 1: chosen_door = 3 elif opens == 2 and chosen_door == 3: chosen_door = 1 elif opens == 3 and chosen_door == 1: chosen_door = 2 elif opens == 3 and chosen_door == 2: chosen_door = 1 #print "Change door to: "+str(chosen_door) #else: #print "Chosen door is same." if chosen_door == door_with_prize: #print "Win" wins = wins + 1 else: #print "Lose" losses = losses + 1 #print "===End of round: "+str(i)+" ===" print "===RESULTS===" print "Wins: "+str(wins) print str((wins / (rounds * 1.0))*100)+"%" print "Losses: "+str(losses) print str((losses / (rounds * 1.0))*100)+"%" print #print time.time() - starttime #raw_input("Press enter to exit...")
josephlewis42/personal_codebase
python/Genetic Programming/Examples/pyevolve_ex10_g1dbinstr.py
from pyevolve import G1DBinaryString from pyevolve import GSimpleGA from pyevolve import Selectors from pyevolve import Mutators # This function is the evaluation function, we want # to give high score to more zero'ed chromosomes def eval_func(chromosome): score = 0.0 # iterate over the chromosome for value in chromosome: if value == 0: score += 0.1 return score def run_main(): # Genome instance genome = G1DBinaryString.G1DBinaryString(50) # The evaluator function (objective function) genome.evaluator.set(eval_func) genome.mutator.set(Mutators.G1DBinaryStringMutatorFlip) # Genetic Algorithm Instance ga = GSimpleGA.GSimpleGA(genome) ga.selector.set(Selectors.GTournamentSelector) ga.setGenerations(70) # Do the evolution, with stats dump # frequency of 10 generations ga.evolve(freq_stats=20) # Best individual print ga.bestIndividual() if __name__ == "__main__": run_main()
josephlewis42/personal_codebase
python/archiver/archive.py
#!/usr/bin/env python ''' Generates an "archived" version of some text by converting it to text/qr codes in HTML. ''' import StringIO import urllib import qrcode import sys import os import hashlib import datetime CHARS_PER_SECTION = 500 def generate_file_info(filename, text): '''Generates file information about the file at the given path.''' output = "[fileinformation]\n\n" output += "name = {}\n".format(filename) output += "path = {}\n".format(os.path.abspath(filename)) stat = os.stat(filename) output += "size = {}\n".format(stat.st_size) output += "accessed = {}\n".format(stat.st_atime) output += "modified = {}\n".format(stat.st_mtime) output += "ctime = {}\n".format(stat.st_ctime) output += "md5 = {}\n".format(hashlib.md5(text).hexdigest()) output += "sha1 = {}\n".format(hashlib.sha1(text).hexdigest()) output += "current_time = {}\n".format(datetime.datetime.now().isoformat()) return output def to_data_uri(pil_image): '''Converts a pil image to a data: URI''' f = StringIO.StringIO() pil_image.save(f, "PNG") return 'data:image/png,' + urllib.quote(f.getvalue()) def split_text(text, length): ''' splits text in to sections of the given length ''' output = [] while text: output.append(text[:length]) text = text[length:] return output def bold_non_printing(text): replacedict = { "<":"&lt;", ">":"&gt;", "&":"&amp;", "\n":"<span class='nonprinting'>[LF]</span><br/>", " ":"<span class='nonprinting'>.</span><wbr>", "\t":"<span class='nonprinting'>[TAB]</span>", "\r":"<span class='nonprinting'>[CR]</span>" } outtext = "" for char in text: if char in replacedict: outtext += replacedict[char] else: outtext += char return outtext def generate_table_row(text): qr = qrcode.make(text) bolded = bold_non_printing(text) return '''<tr> <td><p style="font-family:monospace">{}</p></td> <td><img width="250px" src="{}"></td> </tr>'''.format(bolded, to_data_uri(qr)) def generate_table_header_row(text): return '''<tr><th colspan='2'>{}</th></tr>'''.format(text) def text_to_document(text, title): output = "<table border='1'><tbody>" output += generate_table_header_row("<h1>{}</h1>".format(title)) output += generate_table_header_row("File Information") output += generate_table_row(generate_file_info(title, text)) output += generate_table_header_row("Data") for section in split_text(text, CHARS_PER_SECTION): output += generate_table_row(section) #qr = qrcode.make(section) #bolded = bold_non_printing(section) #output += '''<tr style="page-break-inside: avoid;"><td><p style="font-family:monospace">{}</p></td><td><img width="250px" src="{}"></td></tr>'''.format(bolded, to_data_uri(qr)) output += "</tbody></table>" return output if __name__ == "__main__": print '''<html> <head> <style> img { display:block; page-break-inside: avoid; } tr { page-break-inside: avoid; } th { text-align:center; } .nonprinting { background-color:#ccc; } </style> </head> <body> ''' for arg in sys.argv[1:]: #try: with open(arg) as f: print text_to_document(f.read(), arg) #except Exception: # pass print '''</body></html>'''
josephlewis42/personal_codebase
python/reprap-franklin/toolheads/toolhead.py
<reponame>josephlewis42/personal_codebase #!/usr/bin/env python '''Provides an Extruder base class for the RepRap. All extruders extend this class, and can therefore be chosen by the user at runtime. Copyright 2011 <NAME> <<EMAIL>> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. ''' class Toolhead(object): color = "white" #Color to print in name = "" #Name of the extruder to show the user. width = 1 #Width of a line to print (1 is good for most purposes) #Actual attribues. extrude_rate = 0 temperature = 22.22 #Room temp (celsius) valve_open = False def open_valve(self): self.valve_open = True def close_valve(self): self.valve_open = False
josephlewis42/personal_codebase
python/randall/alife_randall_checkout/ai_webserver/index.py
# index.py # # Copyright 2011 <NAME> <<EMAIL>> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. if not SESSION or 'login' not in SESSION.keys() or not SESSION['login']: self.redirect("login.py") else: self.send_200() #Create a new world if needed. global world global shutdown_hook if not world: from randallai import Randall world = Randall.newrandall() #kill the world when the server is closing. def killworld(): world.kill() shutdown_hook.append(killworld) SESSION['world'] = world page = ''' <!-- index.py Copyright 2010 <NAME> <<EMAIL>> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. --> <html lang="en"> <head> <title>AI Webserver</title> <meta http-equiv="content-type" content="text/html;charset=utf-8" /> <LINK REL=StyleSheet HREF="assets/login.css" TYPE="text/css"> </LINK> <script type="text/javascript" src="assets/jquery.js"></script> <script type="text/javascript" src="assets/md5.js"></script> <script type="text/javascript" src="assets/reloader.js"></script> <script type="text/javascript"> function start() { $('#fg').show(); $('.widget_container').hide(); $('#fg').fadeOut(2000, function() {}); $('.widget_container').fadeIn(2000, function() {}); //Updates for the widgets. Update(10000, '#newswidget', 'stats.py?reload=true'); Update(2000, '#emotionswidget', 'emotions.py?reload=true'); Update(2000, '#needswidget', 'needs.py?reload=true'); Update(2000, '#organswidget', 'organs.py?reload=true'); Update(500, '#chatwidget', 'chat.py?reload=true'); //Load the map once. $('#mapswidget').load('map.py?load=true'); setInterval("$(\\"#commands\\").load(\\"map.py?update=true\\");show_mouse()", 1100); //Load the actor chooser widget once. $('#actorchooserwidget').load('actor_chooser.py?load=true'); } var orig = ""; var current = null; function show_mouse() { if(current != null) { $(current).html(orig); } current = $('#commands').html(); orig = $(current).html(); $(current).html("<span style='color:#640F9A'>&lt;:3)~</span>"); } </script> </head> <body onLoad="start()" id="main_panel"> <div id="fg"></div> <div class="large_widget_container"> <div id="mapswidget" class="widget"></div> <br /> <div id="newswidget" class="widget"></div> <div id='commands' style="display:none;"></div> <!--<div id="chatwidget" class="widget"></div>--> <iframe src="chat.py" width="100%"></iframe> <br /> </div> <div class="small_widget_container"> <div id="actorchooserwidget" class="widget"></div> <br /> <div id="needswidget" class="widget"></div> <br /> <div id="organswidget" class="widget"></div> <br /> <div id="emotionswidget" class="widget"></div> <br /> </div> </body> </html> ''' #Send body self.wfile.write(page)
josephlewis42/personal_codebase
python/codescraper.py
<gh_stars>1-10 #!/usr/bin/python '''Copyright 2010 <NAME> <<EMAIL>> BSD License Retrives Java code stored in an HTML page that is wrapped in <pre> tags. ''' import re import urllib2 import xml.sax.saxutils numnones = 0 def unescape(string): '''Unescape the & escapes in html, like &quot; returns a string ''' string = string.replace("&quot;", "\"") #Not done by xml lib string = xml.sax.saxutils.unescape(string) return string def remove_HTML_tags(text): '''Removes html tags from a supplied string. Warning: This is accomplished using regular expressions that simply cut out all text in between and including less than and greater than characters. ''' regex_html = re.compile(r'<.*?>') return regex_html.sub('', text) def fetch_page(url): '''Returns the html for the webpage at the supplied url.''' page = urllib2.urlopen(url) pagetext = "" for line in page: pagetext += line return pagetext def get_name(class_text): ''' Returns the name of the abstract, class, or interface, when given the text of a Java file. Returns None if the name can not be determined. Warning: Although Java classes may be named with unicode, this function will only return characters A-Z, a-z, and 0-9. ''' #Compile the regular expressions, they all ignore case and accept all chars. class_ = re.compile(r'public class (.*?) ', re.DOTALL | re.IGNORECASE) interface = re.compile(r'public interface (.*?) ', re.DOTALL | re.IGNORECASE) abstract = re.compile(r'public abstract class (.*?) ', re.DOTALL | re.IGNORECASE) #Find the name of the class/interface/abstract name = class_.findall(class_text) #Returns [] if none found if name == []: name = abstract.findall(class_text) if name == []: name = interface.findall(class_text) #If no name is found return None. if name == []: return None #Remove any remaining non a-z A-Z characters accepted_chars = re.compile(r'[^A-Za-z0-9]*') return accepted_chars.sub('', name[0]) def return_between(first_tag, second_tag, text): '''Returns an array of the text between the delimiters given. All text between the end and beginning delimiters will be discarded. Arguments: first_tag -- The tag to begin text harvesting. (string) second_tag -- The tag to end text harvesting. (string) text -- The string in which the tags are to be found. (string) ''' basic_split = text.split(first_tag) #select only the sections which contain the close tags, discard the rest. second_split = [] for i in basic_split: if second_tag in i: second_split.append(i) #Cut out the text before the close tag between = [] for line in second_split: value, end = line.split(second_tag, 1) between.append(value) return between def write_file(name, content, location, ext=".java"): '''Writes a file with the name given, with the content provided, to the location given, with the given extension. Arguments: name -- The name of the file to be written. content -- The content of the file to be written. location -- The folder where the file will be created/overwritten. Keyword Arguments: ext -- The extension for the file. (default ".java") Warning: This function will overwrite any pre-existing files without giving warnings. ''' if not location.endswith("/"): #FIXME This is not cross platform! location = location + "/" print("Location: "+location) f = open( location + name + ext, "w" ) f.write( content ) f.close() def main(url, output_folder): '''Fetches the text at the supplied url and outputs .java files of code between pre tags. Arguments: url -- The url of the page to scrape code from. (string) output_folder -- The directory that the java files will be created in. ''' global numnones page_text = fetch_page(url) #Get the text between the pre tags code_and_garbage = return_between("<pre>", "</pre>", page_text) #Walk through each entry clean it, and write the source file for i in code_and_garbage: print i i = remove_HTML_tags(i) i = unescape(i) name = get_name(i) if name == None: write_file("None"+str(numnones), i, output_folder) numnones += 1 else: write_file(name, i, output_folder) if __name__ == "__main__": location = raw_input("Enter the url: ") output_folder = raw_input("Enter the folder to write to: ") main( location, output_folder )
josephlewis42/personal_codebase
python/stemmer.py
<gh_stars>1-10 #!/usr/bin/env python ''' An implementation of the PORTER2 algorithm for English stemming in Python. Implemented from: http://snowball.tartarus.org/algorithms/english/stemmer.html Copyright 2012 <NAME> <<EMAIL>> | <<EMAIL>> Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ''' import re __author__ = "<NAME>" __copyright__ = "Copyright 2012, Joseph Lewis" __license__ = "BSD" __version__ = "" VOWELS = ['a','e','i','o','u','y'] WXY = VOWELS + ['w','x','Y'] DOUBLES = ['bb','dd','ff','gg','mm','nn','pp','rr','tt'] VALID_LI = ['c','d','e','g','h','k','m','n','r','t'] def short_syllable(word): '''Define a short syllable in a word as either (a) a vowel followed by a non-vowel other than w, x or Y and preceded by a non-vowel, or * (b) a vowel at the beginning of the word followed by a non-vowel. RETURNS: All short syllables in word. ''' regex = ur"([^aeiouy][aeiouy][^aeiouwxy])+?" shorts = re.findall(regex, word) if len(word) >= 2 and word[0] in VOWELS and word[1] not in VOWELS: shorts.append(word[:2]) return shorts def is_short(word, R1): '''A word is called short if it ends in a short syllable, and if R1 is null ''' for short in short_syllable(word): if word.endswith(short) and R1 == None: return True return False def replace_one_in_order(word, suffixes): for suffix, replacewith in suffixes.items(): if word.endswith(suffix): return word[:-len(suffix)] + replacewith return word def replace_if_in_order_and_in_r1(word, suffixes, r1): for suffix, replacewith in suffixes.items(): if word.endswith(suffix) and suffix in word[r1:]: return word[:-len(suffix)] + replacewith return word def delete_suffix(word, suffixes): for suffix in suffixes: if word.endswith(suffix): return word[:-len(suffix)] return word def _setYs(word): word = [char for char in word] for i in range(len(word)): if i == 0 and word[0] == "y": word[0] = 'Y' elif word[i] == 'y' and word[i - 1] in VOWELS: word[i] = 'Y' return "".join(word) def stem(word): ''' R1 is the region after the first non-vowel following a vowel, or the end of the word if there is no such non-vowel. ''' word = word.lower() # if a word has 2 letters or less, leave it as it is if len(word) < 3: return word # remove initial ', if present if word.startswith("'"): word = word[1:] # set initiial y or y after vowel to Y word = _setYs(word) R1 = None for i in range(1, len(word)): if word[i] not in VOWELS and word[i - 1] in VOWELS: R1 = i + 1 break R2 = None if R1: for i in range(R1, len(word)): if word[i] not in VOWELS and word[i - 1] in VOWELS: R2 = i + 1 break short = is_short(word, R1) # Step 0: + Search for the longest among the suffixes,','s,'s' and remove if found. word = replace_one_in_order(word, {"'s'":"","'s":'',"'":''}) ''' Step 1a: Search for the longest among the following suffixes, and perform the action indicated. ''' if word.endswith('sses'): word = word[:-4] + "ss" elif word.endswith('ied') or word.endswith('ies'): if len(word) > 4: word = word[:-3] + "i" else: word = word[:-3] + "ie" elif word.endswith('s') and word[-2] not in VOWELS: word = word[:-1] # Step 1b if word.endswith("eedly") and R1 and "eedly" in word[R1:]: word = word[:-5] + "ee" elif word.endswith("eed") and R1 and "eed" in word[R1:]: word = word[:-3] + "ee" elif len([x for x in ['ed','edly','ing','ingly'] if word.endswith(x)]) > 0: word2 = replace_one_in_order(word, {'edly':'','ed':'','ingly':'','ing':''}) for char in word2: # delete if the preceding word part contains a vowel, and after the deletion: if char in VOWELS: word = word2 #if the word ends at, bl or iz add e (so luxuriat -> luxuriate), or word2 = replace_one_in_order(word, {'at':'ate','bl':'ble','iz':'ize'}) if word2 is not word: word = word2 break #if the word ends with a double remove the last letter (so hopp -> hop), or for double in DOUBLES: if word.endswith(double): word = word[:-1] break #if the word is short, add e (so hop -> hope) if is_short(word, word[R1:]): word = word + 'e' #replace suffix y or Y by i if preceded by a non-vowel which is not the first letter of the word (so cry -> cri, by -> by, say -> say) elif len(word) > 2 and word[-1] in ['y','Y'] and word[-2] not in VOWELS: word = word[:-1] + 'i' # Step 2: Search for the longest among the following suffixes, and, if found and in R1, perform the action indicated. word2 = replace_if_in_order_and_in_r1(word, {"tional":"tion", "enci":"ence", "anci":"ance", "abli":"able", "entli":"ent", "ization":"ize", "izer":"ize", "ational":"ate", "ation":"ate", "ator":"ate", "alism":"al", "aliti":"al", "alli":"al", 'fulness':'ful', 'ousli':'ous', 'ousness':'ous', 'iveness':'ive', 'iviti':'ive', 'biliti':'ble', 'bli':'ble', 'fulli':'ful', 'lessi':'less', 'logi':'ogi'}, R1) if word2 is not word: word = word2 elif word.endswith('li') and word[-3] in VALID_LI and "li" in word[R1:]: word = word[:-2] # step 3 word2 = replace_if_in_order_and_in_r1(word, {"ational":"ate", "tional":"tion", "alize":"al", "icate":"ic", "iciti":"ic", "ical":"ic", "ful":"", "ness":""}, R1) if word2 is not word: word = word2 elif word.endswith('ative') and "ative" in word[R2:]: word = word[:-5] # Step 4 word2 = delete_suffix(word, ['al', 'ance', 'ence', 'er', 'ic', 'able', 'ible', 'ant', 'ement', 'ment', 'ent', 'ism', 'ate', 'iti', 'ous', 'ive', 'ize']) if word2 is not word: word = word2 else: if word.endswith('ion') and word[:-4] in ['s','t']: word = word[:-3] # Step 5 #Search for the the following suffixes, and, if found, perform the action indicated. #e - delete if in R2, or in R1 and not preceded by a short syllable if word.endswith("e") and ((R2 and word[R2:].endswith("e")) or (R1 and word[R1:].endswith("e") and is_short(word[:-1], None))): word = word[:-1] #l - delete if in R2 and preceded by l if word.endswith("l") and (R2 and word[-2] == 'l'): word = word[:-1] return word.lower()
josephlewis42/personal_codebase
Euler/005.py
#!/usr/bin/env python ''' 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? ''' import pymath # Know it must at least be a multiple of 20 print pymath.lcm_array(range(1,21))
josephlewis42/personal_codebase
python/OpenCalc/Lib/Code/Functions/__init__.py
<reponame>josephlewis42/personal_codebase ''' Initiates all functions use from MODULENAME import * that way when this is imported the functions you provide can be easily accessable ''' from Trig import * from Fractions import * from Standard import * from Log_Exp import * from Random import *
josephlewis42/personal_codebase
python/Genetic Programming/Examples/pyevolve_ex5_callback.py
<reponame>josephlewis42/personal_codebase from pyevolve import G1DList from pyevolve import GSimpleGA from pyevolve import Selectors # The step callback function, this function # will be called every step (generation) of the GA evolution def evolve_callback(ga_engine): generation = ga_engine.getCurrentGeneration() if generation % 100 == 0: print "Current generation: %d" % (generation,) print ga_engine.getStatistics() return False # This function is the evaluation function, we want # to give high score to more zero'ed chromosomes def eval_func(genome): score = 0.0 # iterate over the chromosome for value in genome: if value==0: score += 0.1 return score def run_main(): # Genome instance genome = G1DList.G1DList(200) genome.setParams(rangemin=0, rangemax=10) # The evaluator function (objective function) genome.evaluator.set(eval_func) # Genetic Algorithm Instance ga = GSimpleGA.GSimpleGA(genome) ga.selector.set(Selectors.GRouletteWheel) ga.setGenerations(800) ga.stepCallback.set(evolve_callback) # Do the evolution ga.evolve() # Best individual print ga.bestIndividual() if __name__ == "__main__": run_main()
josephlewis42/personal_codebase
python/OpenCalc/Lib/Code/Functions/Fractions.py
<gh_stars>1-10 ''' Works with fractions @Author = <NAME> @Date = 2/19/2010 @License = GPL ==Changelog== 2/19/2010 - Original Built by <NAME> <<EMAIL>> 2/23/2010 - Changed caps to lower case for ease of typing, added fareyLimit var, and added function simplify so it will be easier for users. ''' #Import Statements import math #Define Constants fareyLimit = 1000 # The number of times farey executes until it chooses the most correct answer #Define Functions def simplify(num): return farey(num,fareyLimit) def farey(v, lim): ''' Taken From http://code.activestate.com/recipes/52317/ PSF License <NAME> ''' if v < 0: n,d = FAREY(-v, lim) return -n,d z = lim-lim # get 0 of right type for denominator lower, upper = (z,z+1), (z+1,z) while 1: mediant = (lower[0] + upper[0]), (lower[1]+upper[1]) if v * mediant[1] > mediant[0]: if lim < mediant[1]: return upper lower = mediant elif v * mediant[1] == mediant[0]: if lim >= mediant[1]: return mediant if lower[1] < upper[1]: return lower return upper else: if lim < mediant[1]: return lower upper = mediant
josephlewis42/personal_codebase
python/pyportscanner.py
#!/usr/bin/env python from socket import * if __name__ == '__main__': target = raw_input('Enter host to scan: ') low = int(raw_input('Enter low port to scan:')) hi = int(raw_input('Enter high port to scan:')) targetIP = gethostbyname(target) print 'Starting scan on host ', targetIP #scan reserved ports for i in range(low, hi): print i s = socket(AF_INET, SOCK_STREAM) try: j = s.connect_ex((target, i)) print i if(result == 0): try: srv = getservbyport(i) except: srv = "" print 'Port %d OPEN - %s' % (i, srv) j.close() except: pass
josephlewis42/personal_codebase
python/Genetic Programming/Examples/pyevolve_ex14_ackley.py
from pyevolve import G1DList, GSimpleGA, Selectors from pyevolve import Initializators, Mutators, Consts, DBAdapters import math # This is the Rastringin Function, a deception function def ackley(xlist): sum1 = 0 score = 0 n = len(xlist) for i in xrange(n): sum1 += xlist[i]*xlist[i] t1 = math.exp(-0.2*(math.sqrt((1.0/5.0)*sum1))) sum1 = 0 for i in xrange(n): sum1 += math.cos(2.0*math.pi*xlist[i]); t2 = math.exp((1.0/5.0)*sum1); score = 20 + math.exp(1) - 20 * t1 - t2; return score def run_main(): # Genome instance genome = G1DList.G1DList(5) genome.setParams(rangemin=-8, rangemax=8, bestrawscore=0.00, rounddecimal=2) genome.initializator.set(Initializators.G1DListInitializatorReal) genome.mutator.set(Mutators.G1DListMutatorRealGaussian) # The evaluator function (objective function) genome.evaluator.set(ackley) # Genetic Algorithm Instance ga = GSimpleGA.GSimpleGA(genome) ga.setMinimax(Consts.minimaxType["minimize"]) ga.setGenerations(1000) ga.setMutationRate(0.04) ga.terminationCriteria.set(GSimpleGA.RawScoreCriteria) # Create DB Adapter and set as adapter # sqlite_adapter = DBAdapters.DBSQLite(identify="ackley") # ga.setDBAdapter(sqlite_adapter) # Do the evolution, with stats dump # frequency of 10 generations ga.evolve(freq_stats=50) # Best individual best = ga.bestIndividual() print "\nBest individual score: %.2f" % (best.getRawScore(),) print best if __name__ == "__main__": run_main()
josephlewis42/personal_codebase
python/Genetic Programming/Examples/pyevolve_ex7_rastrigin.py
<reponame>josephlewis42/personal_codebase from pyevolve import GSimpleGA from pyevolve import G1DList from pyevolve import Mutators, Initializators from pyevolve import Selectors from pyevolve import Consts import math # This is the Rastrigin Function, a deception function def rastrigin(genome): n = len(genome) total = 0 for i in xrange(n): total += genome[i]**2 - 10*math.cos(2*math.pi*genome[i]) return (10*n) + total def run_main(): # Genome instance genome = G1DList.G1DList(20) genome.setParams(rangemin=-5.2, rangemax=5.30, bestrawscore=0.00, rounddecimal=2) genome.initializator.set(Initializators.G1DListInitializatorReal) genome.mutator.set(Mutators.G1DListMutatorRealGaussian) genome.evaluator.set(rastrigin) # Genetic Algorithm Instance ga = GSimpleGA.GSimpleGA(genome) ga.terminationCriteria.set(GSimpleGA.RawScoreCriteria) ga.setMinimax(Consts.minimaxType["minimize"]) ga.setGenerations(3000) ga.setCrossoverRate(0.8) ga.setPopulationSize(100) ga.setMutationRate(0.06) ga.evolve(freq_stats=50) best = ga.bestIndividual() print best if __name__ == "__main__": run_main()
josephlewis42/personal_codebase
python/gamebot/email_fetch.py
<gh_stars>1-10 #!/usr/bin/env python '''Provides an ability to send and recieve emails. The EmailInterface class allows checking of an email box on demand, along with on a fixed interval. Copyright 2011 <NAME> <<EMAIL>> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. ''' import threading import time import smtplib from email.mime.multipart import MIMEMultipart from email.mime.multipart import MIMEBase from email.mime.text import MIMEText from email import encoders import email import os import poplib __author__ = "<NAME>" __copyright__ = "Copyright 2011, Joseph Lewis" __license__ = "GPL" __version__ = "" DEBUG = False class SimpleMessage: subject = "" to = "" personfrom = "" def __init__(self, raw_email): self.message = raw_email self.clean = raw_email.lower() lines = self.clean.split("\n") for line in lines: if line.startswith("from:"): self.personfrom = line[6:] if line.startswith("to:"): self.to = line[4:] if line.startswith("subject:"): self.subject = line[9:] class NotConfiguredException(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) class EmailInterface( threading.Thread ): _smtp_configured = False _pop_configured = False kill_me = False time = 0 def __init__(self, callback=None, time=None): ''' Connects every time seconds to check for new mail. If there is new mail, mail_callback will be called and passed the new message one message per call. ''' self.time = time self.callback = callback threading.Thread.__init__(self) def configure_smtp(self, username, password, host, port): self._smtp_configured = True self.smtp_url = host self.smtp_port = port self.smtp_username = username self.smtp_password = password if DEBUG: print("Setting up SMTP: %s@%s:%s" % (username, host, port)) def configure_pop(self, username, password, host, port=110, SSL=False): self._pop_configured = True self.pop_host = host self.pop_port = port self.pop_username = username self.pop_password = password self.pop_SSL = SSL if DEBUG: print("Setting up POP: %s@%s:%s" % (username, host, port)) def run(self): if not isinstance(self.time, (float,int,long)): return while not self.kill_me: time.sleep(self.time) try: if DEBUG: print ("%s - Checking mail" % (time.strftime("%Y-%m-%d %H:%M:%S"))) msgs = self.check_mail() except NotConfiguredException: print("POP not yet configured.") if DEBUG: print ("%s - %s messages." % (time.strftime("%Y-%m-%d %H:%M:%S"), len(msgs))) for i in msgs: if callable(self.callback): self.callback(i) def kill(): '''Kills the mail checking thread.''' self.kill_me = False def check_mail(self): '''Checks the mail for the given account, returns a list of messages in the Inbox. If POP is not configured a NotConfiguredException is raised. ''' if not self._pop_configured: raise NotConfiguredException msgs = [] if self.pop_SSL: pop = poplib.POP3_SSL(self.pop_host, self.pop_port) else: pop = poplib.POP3(self.pop_host, self.pop_port) try: pop.user(self.pop_username) pop.pass_(self.pop_password) numMessages = len(pop.list()[1]) for i in range(numMessages): message = "" for line in pop.retr(i+1)[1]: message += line+"\n" msgs.append(message) finally: pop.quit() return msgs def send_mail(self, to, subject, body, attachments=[], full_attachments={}): '''Sends a message to the given recipient, attachments is a list of file paths to attach, they will be attached with the given names, and if there is a problem they won't be attached and the message will still be sent. PARAMATERS: to - Email address to send the message to. (String) subject - Subject of the email (String) body - Body of the email (html allowed) (String) attachments - A list of attachments to the message. full_attachments - A dict of things to attach, name => data. each name should be unique. Raises a NotConfiguredException if smtp has not yet been set up. ''' if not self._smtp_configured: raise NotConfiguredException, "SMTP is not configured." # Setup the message msg = MIMEMultipart() msg['From'] = self.smtp_username msg['To'] = to msg['Subject'] = subject # Attach the body. msg.attach(MIMEText(body, 'html')) # Attach each attachment. for attach in attachments: with open(attach, 'rb') as o: part = MIMEBase('application', 'octet-stream') part.set_payload(o.read()) encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(attach)) msg.attach(part) # Attach everything from the full attachments dictionary. for name in full_attachments.keys(): part = MIMEBase('application', 'octet-stream') part.set_payload(full_attachments[name]) encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % (name)) msg.attach(part) # Beam me up Scotty! mailServer = smtplib.SMTP(self.smtp_url, self.smtp_port) mailServer.ehlo() mailServer.starttls() mailServer.ehlo() mailServer.login(self.smtp_username, self.smtp_password) mailServer.sendmail(self.smtp_username, to, msg.as_string()) mailServer.close() if DEBUG: print ("%s - Message sent to: %s" % (time.strftime("%Y-%m-%d %H:%M:%S"), to))
josephlewis42/personal_codebase
python/OpenCalc/Main.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # generated by wxGlade 0.6.3 on Sat Feb 27 13:35:04 2010 import wx # begin wxGlade: extracode import wx.html as html from Lib.Code import Parser import sys from Lib.Code import Frontend import wxmpl # end wxGlade class CalcWidget(wx.Frame,Frontend.events): def __init__(self, *args, **kwds): # begin wxGlade: CalcWidget.__init__ kwds["style"] = wx.CAPTION|wx.CLOSE_BOX|wx.MINIMIZE_BOX|wx.MAXIMIZE_BOX|wx.SYSTEM_MENU|wx.RESIZE_BORDER|wx.FULL_REPAINT_ON_RESIZE|wx.TAB_TRAVERSAL|wx.CLIP_CHILDREN wx.Frame.__init__(self, *args, **kwds) self.main_window = wx.SplitterWindow(self, -1, style=wx.SP_3DBORDER|wx.SP_BORDER|wx.SP_LIVE_UPDATE) self.help_browser_panel = wx.Panel(self.main_window, -1) self.main_panel = wx.Panel(self.main_window, -1) self.notebook_manager = wx.Notebook(self.main_panel, -1, style=0) self.graphs_panel = wx.Panel(self.notebook_manager, -1) self.functions_panel = wx.Panel(self.notebook_manager, -1) self.pad_panel = wx.Panel(self.notebook_manager, -1) # Menu Bar self.main_menubar = wx.MenuBar() wxglade_tmp_menu = wx.Menu() self.switch_to_pad_menu_item = wx.MenuItem(wxglade_tmp_menu, wx.NewId(), "&Switch To Pad\tCtrl+Shift+P", "Switch the view to the pad", wx.ITEM_NORMAL) wxglade_tmp_menu.AppendItem(self.switch_to_pad_menu_item) wxglade_tmp_menu.AppendSeparator() self.clear_pad_menu_item = wx.MenuItem(wxglade_tmp_menu, wx.NewId(), "&Clear\tCtrl+K", "Clear the pad.", wx.ITEM_NORMAL) wxglade_tmp_menu.AppendItem(self.clear_pad_menu_item) self.main_menubar.Append(wxglade_tmp_menu, "&Pad") self.functions_menu = wx.Menu() self.switch_to_function_menu_item = wx.MenuItem(self.functions_menu, wx.NewId(), "&Switch To Functions\tCtrl+Shift+F", "Switch the view to the function area.", wx.ITEM_NORMAL) self.functions_menu.AppendItem(self.switch_to_function_menu_item) self.functions_menu.AppendSeparator() self.functions_menu.Append(wx.NewId(), "&Clear All Functions", "", wx.ITEM_NORMAL) self.main_menubar.Append(self.functions_menu, "&Functions") self.graph_menu = wx.Menu() self.switch_to_graphs_menu_item = wx.MenuItem(self.graph_menu, wx.NewId(), "&Swith To Graphs\tCtrl+Shift+G", "Switch the view to graphs.", wx.ITEM_NORMAL) self.graph_menu.AppendItem(self.switch_to_graphs_menu_item) self.graph_menu.AppendSeparator() self.save_graph = wx.MenuItem(self.graph_menu, wx.NewId(), "Save As", "Save the current graph as an image.", wx.ITEM_NORMAL) self.graph_menu.AppendItem(self.save_graph) self.main_menubar.Append(self.graph_menu, "&Graphs") self.SetMenuBar(self.main_menubar) # Menu Bar end self.main_statusbar = self.CreateStatusBar(1, wx.ST_SIZEGRIP) self.output_text_ctrl = wx.TextCtrl(self.pad_panel, -1, "", style=wx.TE_MULTILINE|wx.TE_READONLY) self.input_text_ctrl = wx.TextCtrl(self.pad_panel, -1, "") self.button_3 = wx.Button(self.pad_panel, -1, "&Submit") self.functions_list_box = wx.ListBox(self.functions_panel, -1, choices=[]) self.label_2 = wx.StaticText(self.functions_panel, -1, "Y=") self.function_text_ctrl = wx.TextCtrl(self.functions_panel, -1, "") self.label_3 = wx.StaticText(self.functions_panel, -1, "Color:") self.function_color_combo_box = wx.ComboBox(self.functions_panel, -1, choices=["Blue", "Cyan", "Green", "Black", "Magenta", "Yellow"], style=wx.CB_DROPDOWN|wx.CB_READONLY) self.label_4 = wx.StaticText(self.functions_panel, -1, "Style:") self.function_style_combo_box = wx.ComboBox(self.functions_panel, -1, choices=["Solid Line", "Dashed Line", "Dash - Dot Line", "Dotted Line"], style=wx.CB_DROPDOWN) self.label_5 = wx.StaticText(self.functions_panel, -1, "Name:") self.function_name_text_ctrl = wx.TextCtrl(self.functions_panel, -1, "") self.function_show_checkbox = wx.CheckBox(self.functions_panel, -1, "Show") self.functions_ok_button = wx.Button(self.functions_panel, wx.ID_OK, "") self.function_cancel_button = wx.Button(self.functions_panel, wx.ID_CANCEL, "") self.graph_2d_plot_panel = wxmpl.PlotPanel(self.graphs_panel, -1) self.label_8_copy_3 = wx.StaticText(self.graphs_panel, -1, "Presets:") self.combo_box_1 = wx.ComboBox(self.graphs_panel, -1, choices=["Trig", "Standard"], style=wx.CB_DROPDOWN) self.label_6 = wx.StaticText(self.graphs_panel, -1, "X Min:") self.text_ctrl_1 = wx.TextCtrl(self.graphs_panel, -1, "-10") self.label_7 = wx.StaticText(self.graphs_panel, -1, "X Max:") self.text_ctrl_1_copy_2 = wx.TextCtrl(self.graphs_panel, -1, "10") self.label_8 = wx.StaticText(self.graphs_panel, -1, "Y Min:") self.text_ctrl_1_copy = wx.TextCtrl(self.graphs_panel, -1, "-10") self.label_8_copy = wx.StaticText(self.graphs_panel, -1, "Y Max:") self.text_ctrl_1_copy_3 = wx.TextCtrl(self.graphs_panel, -1, "10") self.checkbox_1 = wx.CheckBox(self.graphs_panel, -1, "3D Graph") self.label_8_copy_2 = wx.StaticText(self.graphs_panel, -1, "Z Min:") self.text_ctrl_1_copy_1 = wx.TextCtrl(self.graphs_panel, -1, "-10") self.label_8_copy_1 = wx.StaticText(self.graphs_panel, -1, "Z Max:") self.text_ctrl_1_copy_4 = wx.TextCtrl(self.graphs_panel, -1, "10") self.table_panel = wx.Panel(self.notebook_manager, -1) self.bitmap_button_1 = wx.BitmapButton(self.help_browser_panel, -1, wx.Bitmap("./Lib/Icons/go-home.png", wx.BITMAP_TYPE_ANY)) self.panel_2 = wx.Panel(self.help_browser_panel, -1) self.label_1 = wx.StaticText(self.help_browser_panel, -1, "Help Browser", style=wx.ALIGN_CENTRE) self.html_window = html.HtmlWindow(self.help_browser_panel, -1) self.__set_properties() self.__do_layout() self.Bind(wx.EVT_MENU, self.switch_to_pad, self.switch_to_pad_menu_item) self.Bind(wx.EVT_MENU, self.clear_pad, self.clear_pad_menu_item) self.Bind(wx.EVT_MENU, self.switch_to_functions, self.switch_to_function_menu_item) self.Bind(wx.EVT_MENU, self.switch_to_graphs, self.switch_to_graphs_menu_item) self.Bind(wx.EVT_MENU, self.save_graph_as, self.save_graph) self.Bind(wx.EVT_BUTTON, self.Submit_Input, self.button_3) self.Bind(wx.EVT_LISTBOX, self.update_function_editor, self.functions_list_box) self.Bind(wx.EVT_BUTTON, self.submit_function, self.functions_ok_button) self.Bind(wx.EVT_BUTTON, self.update_function_editor, self.function_cancel_button) self.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGED, self.notebook_page_changed, self.notebook_manager) self.Bind(wx.EVT_BUTTON, self.LoadPage, self.bitmap_button_1) # end wxGlade def __set_properties(self): # begin wxGlade: CalcWidget.__set_properties self.SetTitle("OpenCalc") _icon = wx.EmptyIcon() _icon.CopyFromBitmap(wx.Bitmap("./Lib/Icons/main_icon.png", wx.BITMAP_TYPE_ANY)) self.SetIcon(_icon) self.SetSize((640, 515)) self.main_statusbar.SetStatusWidths([-1]) # statusbar fields main_statusbar_fields = ["OpenCalc 10.0 Stable"] for i in range(len(main_statusbar_fields)): self.main_statusbar.SetStatusText(main_statusbar_fields[i], i) self.input_text_ctrl.SetFocus() self.function_color_combo_box.SetSelection(0) self.function_style_combo_box.SetSelection(0) self.function_name_text_ctrl.Enable(False) self.function_show_checkbox.SetValue(1) self.combo_box_1.SetSelection(1) self.text_ctrl_1_copy_1.Enable(False) self.text_ctrl_1_copy_4.Enable(False) self.bitmap_button_1.SetSize(self.bitmap_button_1.GetBestSize()) # end wxGlade def __do_layout(self): # begin wxGlade: CalcWidget.__do_layout main_sizer = wx.BoxSizer(wx.VERTICAL) help_browser_sizer = wx.BoxSizer(wx.VERTICAL) help_browser_title_sizer = wx.BoxSizer(wx.HORIZONTAL) sizer_2 = wx.BoxSizer(wx.HORIZONTAL) sizer_1 = wx.BoxSizer(wx.VERTICAL) sizer_9 = wx.BoxSizer(wx.VERTICAL) sizer_8_copy_1 = wx.BoxSizer(wx.HORIZONTAL) sizer_8_copy = wx.BoxSizer(wx.HORIZONTAL) sizer_8 = wx.BoxSizer(wx.HORIZONTAL) sizer_4 = wx.BoxSizer(wx.HORIZONTAL) sizer_5 = wx.BoxSizer(wx.VERTICAL) sizer_6 = wx.BoxSizer(wx.VERTICAL) sizer_7 = wx.BoxSizer(wx.HORIZONTAL) sizer_3 = wx.BoxSizer(wx.VERTICAL) sizer_3.Add(self.output_text_ctrl, 1, wx.ALL|wx.EXPAND, 5) sizer_3.Add(self.input_text_ctrl, 0, wx.ALL|wx.EXPAND, 5) sizer_3.Add(self.button_3, 0, wx.ALL|wx.ALIGN_RIGHT, 5) self.pad_panel.SetSizer(sizer_3) sizer_5.Add(self.functions_list_box, 2, wx.ALL|wx.EXPAND, 5) sizer_6.Add(self.label_2, 0, 0, 0) sizer_6.Add(self.function_text_ctrl, 0, wx.EXPAND, 0) sizer_6.Add(self.label_3, 0, 0, 0) sizer_6.Add(self.function_color_combo_box, 0, wx.EXPAND, 0) sizer_6.Add(self.label_4, 0, 0, 0) sizer_6.Add(self.function_style_combo_box, 0, wx.EXPAND, 0) sizer_6.Add(self.label_5, 0, 0, 0) sizer_6.Add(self.function_name_text_ctrl, 0, wx.EXPAND, 0) sizer_6.Add(self.function_show_checkbox, 0, 0, 0) sizer_7.Add(self.functions_ok_button, 0, wx.ALIGN_CENTER_VERTICAL, 0) sizer_7.Add(self.function_cancel_button, 0, wx.ALIGN_CENTER_VERTICAL, 0) sizer_6.Add(sizer_7, 0, wx.ALIGN_RIGHT|wx.ALIGN_BOTTOM|wx.ALIGN_CENTER_VERTICAL, 0) sizer_5.Add(sizer_6, 0, wx.ALL|wx.EXPAND, 5) self.functions_panel.SetSizer(sizer_5) sizer_1.Add(self.graph_2d_plot_panel, 1, wx.ALL|wx.EXPAND, 5) sizer_4.Add(self.label_8_copy_3, 0, 0, 0) sizer_4.Add(self.combo_box_1, 0, wx.EXPAND, 0) sizer_9.Add(sizer_4, 1, wx.EXPAND, 0) sizer_8.Add(self.label_6, 0, 0, 0) sizer_8.Add(self.text_ctrl_1, 0, 0, 0) sizer_8.Add(self.label_7, 0, 0, 0) sizer_8.Add(self.text_ctrl_1_copy_2, 0, 0, 0) sizer_9.Add(sizer_8, 1, wx.EXPAND, 0) sizer_8_copy.Add(self.label_8, 0, 0, 0) sizer_8_copy.Add(self.text_ctrl_1_copy, 0, 0, 0) sizer_8_copy.Add(self.label_8_copy, 0, 0, 0) sizer_8_copy.Add(self.text_ctrl_1_copy_3, 0, 0, 0) sizer_9.Add(sizer_8_copy, 1, wx.EXPAND, 0) sizer_9.Add(self.checkbox_1, 0, 0, 0) sizer_8_copy_1.Add(self.label_8_copy_2, 0, 0, 0) sizer_8_copy_1.Add(self.text_ctrl_1_copy_1, 0, 0, 0) sizer_8_copy_1.Add(self.label_8_copy_1, 0, 0, 0) sizer_8_copy_1.Add(self.text_ctrl_1_copy_4, 0, 0, 0) sizer_9.Add(sizer_8_copy_1, 1, wx.EXPAND, 0) sizer_1.Add(sizer_9, 0, wx.EXPAND, 0) self.graphs_panel.SetSizer(sizer_1) self.notebook_manager.AddPage(self.pad_panel, "Pad") self.notebook_manager.AddPage(self.functions_panel, "Functions") self.notebook_manager.AddPage(self.graphs_panel, "Graphs") self.notebook_manager.AddPage(self.table_panel, "Tables") sizer_2.Add(self.notebook_manager, 1, wx.EXPAND, 0) self.main_panel.SetSizer(sizer_2) help_browser_title_sizer.Add(self.bitmap_button_1, 0, 0, 0) help_browser_title_sizer.Add(self.panel_2, 1, wx.EXPAND, 0) help_browser_title_sizer.Add(self.label_1, 0, wx.ALL|wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 8) help_browser_sizer.Add(help_browser_title_sizer, 0, wx.EXPAND|wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 1) help_browser_sizer.Add(self.html_window, 1, wx.ALL|wx.EXPAND|wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 5) self.help_browser_panel.SetSizer(help_browser_sizer) self.main_window.SplitVertically(self.main_panel, self.help_browser_panel) main_sizer.Add(self.main_window, 1, wx.EXPAND, 0) self.SetSizer(main_sizer) self.Layout() self.Centre() # end wxGlade # end of class CalcWidget if __name__ == "__main__": app = wx.PySimpleApp(0) wx.InitAllImageHandlers() Main_Frame = CalcWidget(None, -1, "") app.SetTopWindow(Main_Frame) #Redirect stdout to the pad sys.stdout=Main_Frame #Make it setup my way Main_Frame.setup() Main_Frame.Show() app.MainLoop()
josephlewis42/personal_codebase
python/OpenCalc/Lib/Code/Functions/Random.py
''' Random makes random numbers. @Author = <NAME> <<EMAIL>> @Date = 2010-03-04 @License = GPL ==Changelog== 2010-03-04 - Module started. ''' #Import Statements import random as r import time as t #Define Constants #Define Functions def time(): ''' Return the current date. ''' return t.asctime() def seedrand(seed=time()): ''' Seeds the number generator, if no input is provided the current time will be used. ''' r.seed(seed) return "Seeded with %s." %(seed) def random(): ''' Returns a random float between 0, and 1 ''' return r.random() def randint(low = 0, high = 99): ''' Returns a random number between the two specified, if none specified returns between 0 and 99 ''' return r.randint(low, high)
josephlewis42/personal_codebase
wheel_of_fortune_ai/common.py
<filename>wheel_of_fortune_ai/common.py #!/usr/bin/env python3 ''' Provides common functions used through the similarity engines. Author: <NAME> <<EMAIL>> | <<EMAIL>> Copyright 2012, All Rights Reserved 2012-10-27 - Initial Work ''' import re import unittest def document_to_terms(doc): '''Parses a document in to a list of strings.''' doc = doc.lower() doc = re.sub(r"""[^\w\s]+""", '', doc) return doc.split() def map_item_frequency(initial_list): ''' Maps each item in the initial list to the number of times it occurs in that list. ''' output = {} for item in initial_list: try: output[item] += 1 except KeyError: output[item] = 1 return output class TestCommon(unittest.TestCase): def test_map_item_frequency(self): self.assertEqual(map_item_frequency([1,2,3]), {1:1,2:1,3:1}) self.assertEqual(map_item_frequency([1,2,1]), {1:2,2:1}) #self.assertEqual(" hello","world") #self.assertRaises(TypeError, random.shuffle, (1,2,3)) #self.assertTrue(element in self.seq) def test_document_to_terms(self): doc = "Hello, world! Quoth Joe." self.assertTrue(len(document_to_terms(doc)) == 4) self.assertEqual(document_to_terms(doc), ["hello","world","quoth","joe"]) if __name__ == '__main__': unittest.main()
josephlewis42/personal_codebase
Euler/007.py
<reponame>josephlewis42/personal_codebase<filename>Euler/007.py #!/usr/bin/env python ''' By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10001st prime number? ''' import pymath print max(pymath.n_primes(10001))
josephlewis42/personal_codebase
python/OpenCalc/Lib/Code/Parser.py
<reponame>josephlewis42/personal_codebase ''' This module takes care of doing math for the program. @Author = <NAME> @Date = Friday, Feb. 19, 2010 @License = GPL ==Changelog== 2/19/2010 - Original Built by <NAME> <<EMAIL>> 2/23/2010 - Added simple fixes for floating point errors, added ^ ** replace 2/25/2010 - Added a fix for division of two ints for versions before 3.0 2/28/2010 - Added support for variables a-z 2010-03-14 - Added another parse method, and cleaned up the original parse ''' from __future__ import division #Do division like humans do in old python versions import sys from numpy import array #Check what version python is: #If less than 2.2 will not work properly if sys.hexversion < 0x020200F0: print >> sys.stderr, "Your python is too old for division to work natrually. OPENCALC ERR:0001" #If 2.2 to 3 then will work with import statment elif sys.hexversion >= 0x020200F0 and sys.hexversion <0x030000F0: print >> sys.stderr, "Importing future so division will work right. OPENCALC NOT:0001" #If 3 or beyond remove the unneeded and possibly hazardous import elif sys.hexversion >= 0x030000F0: del division #Import all functions from the functions library, in their native form so eval can use them from Functions import * #Import Variables from Variables import * ans = 0 #The answer from the last problem (easy reference) def parse(user_input): ''' Parse user input, by first cleaning it up so the machine can read what the user put in, then run the input to set any vars it used, then execute it to use as the new ans variable, then fix it's type, and send it on it's way. ''' #Import all global variables the user has access to global ans,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z #Clean up user input user_input = user_input.replace("^", "**") #Execute code (if any) like y = 3*3, this will set y exec "%s" % (user_input) in globals() #Set the ans variable. ans = eval(user_input) #Solve rounding errors (Floating Point Arithmatic) if isinstance(ans, (int, long, float, complex)): ans = float("%.8f" % ans)# Change to float with 8 places, if a number return ans def clean_parse(machine_input, x = x): ''' This parse method is used for internal parsing, of things like arrays by modules like Graph, everything should be allready evaluated. If you want to replace the variable x with one of your own then do so, otherwise the global x will be used. ''' global ans,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,y,z return eval(machine_input)
josephlewis42/personal_codebase
python/randall/alife_randall_checkout/randallai/AI/logos.py
#!/usr/bin/env python ''' The logos module provides a kind of decision making process center. It has hints of imagination and logic. Copyright (c) 2011 <NAME> <<EMAIL>> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. ''' import threading import time import pavlov import maslow import copy __version__ = 1.0 __author__ = "<NAME> <<EMAIL>>" DEBUGGING = False class Mode: '''An interface for building modes for the mind to operate in. Each mode has a specific Need that triggers it i.e. Hunger mode would be triggered by the Need "Hunger". Modes are added to a Mind class. When the Mind updates it checks for the most pressing Need, then triggers the mode with the same name as the need. The mode then is called periodically by the brain until it sets its done value to True, the mind then moves to the next most pressing need. If the done flag is not set to True this need will continue to execute until another one becomes more pressing. If however a more pressing need comes up, like a Basic Need, while a higher one is being fufilled the higher need will be destroyed in favor of the lesser one. The variables available to you are: done -- Is this Mode done executing? Set to True to end. my_need -- An instance of the need that is associated with this mode. my_map -- An instance of the mapper.Grid that the Actor belonging to the Mind of this Need has. name -- The name of this mode, should be the same as a need, when the need with the same name arises this mode goes in to effect. ''' done = False my_need = None my_map = None my_actor = None name = "Override with the same name as a need so the two are\ associated" def __init__(self, need, my_map, my_actor): self.my_need = need self.my_map = my_map self.my_actor = my_actor def make_move(self): '''Override this function with one that will make a move for the Actor.''' raise NotImplementedError("make_move was not overriden for the mode: %s" % (self.name)) def get_closest(self, itemlist, quick=False): '''Gets the path to the closest item in itemlist. Returns none if none of the given items were in the known world.''' here = self.my_actor.view_terrain() closest = [] for i in itemlist: j = self.my_map.find_closest(i, here, quick) if j != (None, None): closestdict.append(j) try: return closest.sort()[0] except IndexError: return None def search_and_go_mode( mode_name ): '''Returns a simple mode class with the given mode_name that searches for an item and goes to it.''' class sag_mode( Mode ): path_to_resource = None done = False name = mode_name item = "" def make_move(self): #Get the path to item the first time. if self.path_to_resource == None: pr = self.my_actor.response_network.lookup_association(self.name) self.potential_resource = self.my_actor.world.item_event_interface.exists( pr ) dist, closest, item = self.my_actor.internal_map.find_closest_list(self.potential_resource, self.my_actor.view_terrain()) if closest: self.item = item self.path_to_resource = self.my_actor.internal_map.path_to(self.my_actor.view_terrain(), closest) else: self.done = True else: if self.my_actor.can_move: try: mc = self.path_to_resource.pop(0) self.my_actor.move_to_cell(mc) except AssertionError, e: #The path is obstructed, find a new one. self.path_to_resource = None except IndexError: #We are here, interact with the item that called this. self.my_actor.interact(self.item) self.done = True return sag_mode def quick_search_and_go( mode_names, mind_instance ): '''Fills the given mind with search_and_go style modes for the given mode_names. i.e. quick_search_and_go(['food','water'], <mindinstance>) would add basic food and water search capabilities to your mind. ''' for item in mode_names: mind_instance.append( search_and_go_mode( item ) ) class ExploreMode( Mode ): items_here = [] done = False #Continue forever name = "explore" lastcell = None def __init__(self, need, my_map, my_actor): #Explore all items here first. self.items_here = copy.deepcopy(my_actor.view_terrain().items) Mode.__init__(self, need, my_map, my_actor) def make_move(self): c = None #The current cell. #If we have played with all the items here just move on. if not self.items_here: while self.my_actor.can_move: try: thiscell = self.my_actor.view_terrain() c = self.my_actor.world.terrain.random_accessible_neighbor(thiscell,self.lastcell) self.my_actor.move_to_cell(c) self.lastcell = thiscell except AssertionError: continue #The cell given was not accessible, try again. except RuntimeWarning: pass #The actor just moved. self.items_here = copy.deepcopy(c.items) else: while self.items_here: self.my_actor.interact(self.items_here.pop()) class Mind( threading.Thread ): '''The Mind reads information from the given maslow.Needs class, decides the most important thing to do and acts on it using its owner's body. ''' _awake = True current_need = None modes = [ExploreMode] def __init__(self, needs, owner, update_time=0.1, autostart=True): '''Initializes the brain! Paramaters: needs -- An instance of maslow.Needs that the mind uses to decide what mode to enter. (maslow.Needs) owner -- The instance of world.Actor whose mind this is, used in moving around and such. (world.Actor) update_time -- The amount of time to wait between brain cycles can be a function or float or int. If it is a function the function should either wait for a certain amount of time then return 0 or return the number of seconds to wait. Default: 0.1 (Function, float, int) autostart -- Should the mind start as soon as it is instanciated? If not it will just sit there like a cold dead organ until its thread is started using the start() function. Default: True (boolean) ''' self.needs = needs self.owner = owner self.update_time = update_time threading.Thread.__init__(self) #Start the thread automagically if desired. if autostart: self.start() def append(self, item): '''Add a Mode to the Mind.''' self.modes.append(item) def __getitem__(self, key): '''Emulates a list or dictionary, called with the name of the Mode. Raises IndexError if not found.''' #Check for ints if isinstance(key, int): return self.modes[key] #Check for strings and other ojbects for e in self.modes: if e.name == key: return e #else raise error raise IndexError("%s is not a valid Mode!" % (str(key))) def __len__(self): '''Returns the number of modes.''' return len(self.modes) def run(self): #Make sure awake is true before we start lest the developer #tries to sleep then re-wake the thread for some reason. self._awake = True while self._awake: #Handle update times for functions and numbers. if hasattr(self.update_time, '__call__'): ut = float( self.update_time() ) else: ut = self.update_time #Wait so we don't hog the CPU. What are we coming to? A #world where AI doesn't rape your machine? time.sleep(ut) #Check for the current most pressing need. urgent = self.needs.most_urgent(40) if not urgent: urgent = maslow.Need("explore", maslow.OTHER) #If it is the same as the currently running one, go ahead. if self.current_need and urgent.name == self.current_need.name and not self.current_need.done: if DEBUGGING: print("Calling make_move for %s" % (self.current_need.name)) self.current_need.make_move() else: #Just make a new need and set it as current. #If the current need is the same as the last one, that probably means it couldn't be #reached, try exploring. if self.current_need and self.current_need.done and self.current_need.name == urgent.name: urgent = maslow.Need("explore", maslow.OTHER) if DEBUGGING: print("Creating new %s"%(urgent.name)) self.current_need = self[urgent.name](urgent, self.owner.internal_map, self.owner) self.current_need.make_move() def sleep(self): '''Kills the thread.''' self._awake = False
josephlewis42/personal_codebase
Euler/016.py
''' 215 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. What is the sum of the digits of the number 21000? ''' print(sum([int(i) for i in str(2 ** 1000)]))
josephlewis42/personal_codebase
Euler/004.py
<filename>Euler/004.py #!/usr/bin/env python ''' A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 99. Find the largest palindrome made from the product of two 3-digit numbers. ''' import pymath nums = [] for x in range(1000): for y in range(1000): nums.append(x * y) print max([x for x in nums if pymath.palindrome(x)])
josephlewis42/personal_codebase
python/reprap-franklin/toolheads/basic.py
<reponame>josephlewis42/personal_codebase #!/usr/bin/env python '''Provides a basic extruder base class for the RepRap. Copyright 2011 <NAME> <<EMAIL>> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. ''' import toolhead class BasicExtruder( toolhead.Toolhead ): color = "blue" #Color of the lines the extruder makes on the model. name = "Basic Extruder" #Name of the extruder.
josephlewis42/personal_codebase
python/randall/alife_randall_checkout/cgi_threaded_webserver.py
#!/usr/bin/env python '''Copyright 2010 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ''' #Imports from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer from os import curdir, sep, path from SocketServer import ThreadingMixIn import threading import mimetypes import time import sys import os import socket import cgi import uuid import urlparse #Data port_number = 8000 indexpath = "/index.py" webdir = curdir + "/ai_webserver" print "hi" try: #Find our external ip s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(('google.com', 80)) host_name = s.getsockname()[0] except: #Use internal ip. host_name = "localhost" authenticated = {} world = None shutdown_hook = [] #Upon shutdown of the server, each item here is called once, a good way to shut down threads. class RequestHandler(BaseHTTPRequestHandler): global webdir global indexpath global authenticated global world POST_DICT = None COOKIE = None def do_HEAD(self): ''' Sends the headders for the content, by guessing the mime based on the extention ''' mime = mimetypes.guess_type(self.path) #Guess MIME self.send_response(200) #Send Client OK Response self.send_header('Content-type', mime) self.end_headers() def authenticate(self): a = str(uuid.uuid4()) authenticated[a] = {'UUID':a} return 'sid = ' + a def deauthenticate(self): try: if self.COOKIE: authenticated.pop(self.COOKIE['sid']) except ValueError: print("Problem deauthenticating. %s") def redirect(self, url, cookie=True): '''Sends a redirect to the specified url. A SESSION will be started (if not already) if the cookie attribute is True. ''' self.send_response(302) #Send Client REDIRECT Response self.send_header('Location', url) if not self.SESSION and cookie: self.send_header('Set-Cookie', self.authenticate()) self.end_headers() def send_200(self, mime_type="text/html", cookie=True): '''Sends a 200 response.. Default mime and content are "text/html and blank respectively. A SESSION will be started (if not already) if the cookie attribute is True. ''' self.send_response(200) #Send Client OK Response self.send_header('Content-type', mime_type) if not self.SESSION and cookie: self.send_header('Set-cookie', self.authenticate()) self.end_headers() def get_file_contents(self, path): '''Returns the contents of the requested file. If no contents found returns a blank string.''' try: a = open(path, 'rb') tmp = a.read() a.close() return tmp except IOError: return "" def parse_cookie(self): try: cookie_dict = {} c = self.headers['Cookie'] c = c.split(';') for i in c: i = i.split('=') cookie_dict[i[0].strip()] = i[1].strip() self.COOKIE = cookie_dict return cookie_dict except: return None def do_GET(self): '''Sends the client the web page/file that they requested. This also takes care of the index file. Variables available to the client are POST_DICT, a dictionary of form_name and value attributes, None if no data was POSTed. The variable SESSION stores information about this particular session it is a dictionary. The variable QUERY_DICT stores information about the query string at the end of the url. ''' filepath = urlparse.urlparse(self.path).path COOKIE = self.parse_cookie() #Get session informaiton. try: self.SESSION = authenticated[COOKIE['sid']] except: #Bad or no cookie. self.SESSION = None #Get the query information #Get the query string and query dictionary so it becomes easier to tell #what arguments were passed along with the url. query_string = urlparse.urlparse(self.path).query #Create the dictionary from the query string and make it global. self.QUERY_DICT = urlparse.parse_qs(query_string) #Make things more accessable to scripts. SESSION = self.SESSION QUERY_DICT = self.QUERY_DICT POST_DICT = self.POST_DICT try: #If the path is blank show the index if filepath == "/": filepath = indexpath #Hide non-public files. myfile = filepath.split("/")[-1] if myfile and myfile.startswith(".") or myfile.startswith("noweb"): raise IOError #404 error, disguise the path. :) if filepath.endswith(".py") or filepath.endswith(".cgi"): with open(webdir + filepath) as f: exec(f.read()) return else: #Show The Headder mime = mimetypes.guess_type(filepath) #Guess MIME self.send_response(200) #Send Client OK Response self.send_header('Content-type', mime) self.end_headers() #Send the user the web file f = open(webdir + filepath) self.wfile.write(f.read()) f.close() except(IOError): '''Show the 404 error for pages that are unknown.''' self.send_response(404) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write("Error 404") def do_POST(self): # Parse the form data posted form = cgi.FieldStorage( fp=self.rfile, headers=self.headers, environ={'REQUEST_METHOD':'POST', 'CONTENT_TYPE':self.headers['Content-Type'], }) formdata = {} for k in form.keys(): formdata[k] = form[k].value self.POST_DICT = formdata #Do a standard get now. self.do_GET() class ThreadedHTTPServer(ThreadingMixIn, HTTPServer): '''Handles requests in a separate thread.''' def start(): '''Sets up and starts the webserver.''' print ("Started HTTPServer, press Control + C to quit.") print ("%s Server Starts at - http://%s:%s" % (time.asctime(), host_name, port_number) ) #Start the server server = ThreadedHTTPServer((host_name, port_number), RequestHandler) try: server.serve_forever() except KeyboardInterrupt: print ("\n"*2) print ("%s Server Stops" % (time.asctime())) print ("%s Calling shutdown_hook items, waiting for threads to finish:" % (time.asctime())) for item in shutdown_hook: item() while threading.active_count() > 1: time.sleep(1) print ("%s Done." % (time.asctime())) server.server_close() if __name__ == '__main__': start()
josephlewis42/personal_codebase
python/chat/client.py
<gh_stars>1-10 #!/usr/bin/python from socket import * #Define Variables host = "localhost" port = 21567 buf = 1024 addr = (host,port) username = "User" # Create socket UDPSock = socket(AF_INET,SOCK_DGRAM) def setup(): ''' Sets up the user profile, and the connection to the other computer ''' #Import Globals global host global port global addr global username print "Where do you want to connect to?" host = raw_input('Host >> ') if not host: host = "localhost" print "What port, the usual is 21567?" port = raw_input('Port >> ') if not port: port = 21567 addr = (host,int(port)) print ""; username = raw_input('Username >> ') if not username: username = "User" def startTalking(): print "===Enter message to send to server==="; # Send messages while (1): data = raw_input('>> ') if not data: #Close the port on the server so it can exit UDPSock.sendto(data,addr) break else: if(UDPSock.sendto(username + " : " + data,addr)): print "Sending message '",data,"'....." # Close socket UDPSock.close() def start(): setup() startTalking() if __name__ == '__main__': # This code runs when script is started from command line start() SystemExit() exit()
josephlewis42/personal_codebase
python/Genetic Programming/Examples/pyevolve_ex21_nqueens.py
<filename>python/Genetic Programming/Examples/pyevolve_ex21_nqueens.py<gh_stars>1-10 from pyevolve import G1DList from pyevolve import Mutators, Crossovers from pyevolve import Consts, GSimpleGA from pyevolve import DBAdapters from random import shuffle # The "n" in n-queens BOARD_SIZE = 64 # The n-queens fitness function def queens_eval(genome): collisions = 0 for i in xrange(0, BOARD_SIZE): if i not in genome: return 0 for i in xrange(0, BOARD_SIZE): col = False for j in xrange(0, BOARD_SIZE): if (i != j) and (abs(i-j) == abs(genome[j]-genome[i])): col = True if col == True: collisions +=1 return BOARD_SIZE-collisions def queens_init(genome, **args): genome.genomeList = range(0, BOARD_SIZE) shuffle(genome.genomeList) def run_main(): genome = G1DList.G1DList(BOARD_SIZE) genome.setParams(bestrawscore=BOARD_SIZE, rounddecimal=2) genome.initializator.set(queens_init) genome.mutator.set(Mutators.G1DListMutatorSwap) genome.crossover.set(Crossovers.G1DListCrossoverCutCrossfill) genome.evaluator.set(queens_eval) ga = GSimpleGA.GSimpleGA(genome) ga.terminationCriteria.set(GSimpleGA.RawScoreCriteria) ga.setMinimax(Consts.minimaxType["maximize"]) ga.setPopulationSize(100) ga.setGenerations(250) ga.setMutationRate(0.02) ga.setCrossoverRate(1.0) #sqlite_adapter = DBAdapters.DBSQLite(identify="queens") #ga.setDBAdapter(sqlite_adapter) vpython_adapter = DBAdapters.DBVPythonGraph(identify="queens", frequency=1) ga.setDBAdapter(vpython_adapter) ga.evolve(freq_stats=10) best = ga.bestIndividual() print best print "Best individual score: %.2f\n" % (best.getRawScore(),) if __name__ == "__main__": run_main()
josephlewis42/personal_codebase
python/python_webserver.py
#!/usr/bin/env python ''' A very simple Python webserver that isn't very good. ''' from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler sitedir = "." #could set to /var/www if your normal site is there, etc. class RequestHandler(BaseHTTPRequestHandler): def _writeheaders(self): self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() def do_HEAD(self): self._writeheaders() def do_GET(self): self._writeheaders() if self.path == "/": self.path = "index.html" try: f = open(sitedir + self.path) self.wfile.write(f.read()) f.close() except IOError, e: # probably means we tried fetching a directory self.wfile.write("Couldn't find file") print e serveraddr = ('', 8080) srvr = HTTPServer(serveraddr, RequestHandler) print("Server online and active") srvr.serve_forever()