text stringlengths 38 1.54M |
|---|
#! /usr/bin/python
import sys
f = open('July20/random_med_mote6.log','r')
g = open('July20/random_med_mote6.out','w')
lines = f.readlines()
for line in lines:
line = line.strip()
if line != '':
nums = line.split()
output = ''
source = int(nums[8],16)
if source == 0:
output = output + "Infrastructure message "
elif source == 1:
output = output + "Ping message " + str(int(nums[9],16)) # No_Pings
elif source == 2:
output = output + "Advertisement message "
elif source == 3:
output = output + "Request message "
elif source == 4:
output = output + "Data message "
elif source == 8:
output = output + "NEW Data status update: "
elif source == 9:
output = output + "Current data status: "
output = output + " from " + str(int(nums[10]+nums[11],16)) # source address
if source == 1: # PING
if nums[12][0] < '8': # positive ping value
output = output + " with ping value " + str(int(nums[12]+nums[13],16))
else: # negative ping value
output = output + " with ping value " + str(int(nums[12]+nums[13],16)-2**16)
else: # data ID / data type concatenation
output = output + " with data ID " + nums[12] + " and data type " + nums[13]
output = output + " vNum: " + str(int(nums[14],16)) # version number
output = output + " and pNum: " + str(int(nums[15],16)) + '\n' # packet number
output = output + " --- Current time: " + str(int(nums[16]+nums[17]+nums[18]+nums[19],16))
output = output + ", have sent " + str(int(nums[22]+nums[23],16)) + " packets"
output = output + " and have ver " + str(int(nums[20],16)) + ", packets up to " + str(int(nums[21],16)) + '\n'
g.write(output)
|
# space scramble
# ludwig game jam 2021
# written and designed by capnsquishy
import os
import pygame
from pygame import Rect
from pygame.math import Vector2
from views import title_screen, resource_screen
class Interface:
def __init__(self):
pygame.init()
self.cell_size = Vector2(64, 64)
self.world_size = Vector2(16, 10)
self.views = { # decides which view we are rendering and updating for
'title': None,
'menu': None,
'resource_overview': None,
'options': None,
'ship': None
}
self.view = 'title'
# initialize window settings
window_size = self.world_size.elementwise() * self.cell_size
self.window = pygame.display.set_mode((int(window_size.x), int(window_size.y)))
pygame.display.set_caption('space scramble')
# game loop settings
self.clock = pygame.time.Clock()
self.running = True
# initialize title view
self.views['title'] = title_screen.TitleScreenView(self.window, self.cell_size)
# keep track of events for views to process
self.event_list = None
# collect events for processing, and ensure that we quit the program if needed
def process_input(self):
self.event_list = pygame.event.get()
for event in self.event_list:
if event.type == pygame.QUIT:
self.running = False
break
# send events to view for processing and rendering, and check for change in view
def update(self):
# update view
self.views[self.view].update(self.event_list)
# check for change in view
self.view = self.views[self.view].view_change()
# initialize new view if changed
if not self.views[self.view]:
if self.view == 'resource_overview':
self.views[self.view] = resource_screen.ResourceScreenView(self.window, self.cell_size)
# exit if needed
if self.view == 'exit':
self.running = False
# main game loop to process inputs, update game state, and render screen
def run(self):
while self.running:
self.process_input()
self.update()
self.clock.tick(60)
# initializes the game interface and begins the main game loop
interface = Interface()
interface.run()
# exits the game
pygame.quit()
|
from abc import ABC, abstractmethod
class TurnsManager(ABC):
@abstractmethod
def add_unit(self, unit):
raise NotImplemented
@abstractmethod
def remove_unit(self, unit):
raise NotImplemented
@abstractmethod
def get_next(self):
raise NotImplemented
|
from sys import stdin,stdout
def dsum(n):
if n//10==0:return n*(n+1)//2
count,temp=0,n
while not temp//10==0:count,temp=count+1,temp//10
p=10**count
mod=n%p
return (dsum(mod)+temp*(mod+1)+p*temp*(temp-1)//2+(p*count*temp*45//10))
def main():
out=""
a,b=map(int,stdin.readline().split())
while a!=-1 and b!=-1:
out+="%d\n"%(dsum(b)-dsum(a-1))
a,b=map(int,stdin.readline().split())
print(out)
if __name__=="__main__":main()
|
from django.views.generic import ListView
from models import TriggerLog
class CaseFirstBookChangesView(ListView):
template_name = "triggerlog/case_first_book_changes.html"
paginate_by = 12
table = 'bookcaseidinfo'
context_object_name = 'logs'
def get_queryset(self):
logs = TriggerLog.objects.filter(
tablename=self.table).order_by('-time')
return logs
|
import boto3
connection = boto3.client(
'emr',
aws_access_key_id="ASIAWAQG777R7GVHCPFI",
aws_secret_access_key = "******",
aws_session_token = "*******"
)
lst = connection.list_clusters(ClusterStates=['TERMINATED'])
print(lst)
|
import random
def main():
resp = input("Would you like to play a game?[y/n]")
if resp.lower() == 'y':
play_game()
def play_game():
number = random.randint(1, 100)
guess = -1
while guess != number:
guess = int(input("Pick a number between 1 - 100. "))
if guess > number:
print("Too high!")
elif guess < number:
print("Too low!")
print("You got it!")
if __name__ == '__main__':
main()
|
import matplotlib
import matplotlib.pyplot as pyplot
import csv
import sys
import os
from operator import itemgetter
def createPlot(xList, xLabel, yLabel, title):
pyplot.hist(xList, bins=50)
pyplot.title(title)
pyplot.xlabel(xLabel)
pyplot.ylabel(yLabel)
def sortByNumberOfLines(fileList):
l = []
for fName in fileList:
dic = {}
dic["file name"] = fName
dic["line count"] = countLines(fName)
l.append(dic)
sortedList = sorted(l, key=itemgetter('line count'), reverse=True)
return [dic["file name"] for dic in sortedList]
def countLines(fName):
with open(fName) as f:
for i, l in enumerate(f):
pass
return i + 1
if __name__ == "__main__":
legendNames = []
sortedFilenames = sortByNumberOfLines(sys.argv[1:])
for inFileName in sortedFilenames:
fileName, fileExtension = os.path.splitext(inFileName)
with open(inFileName, 'rb') as csvFile:
legendNames.append(fileName)
lines = csvFile.readlines()
xLabel = lines[0].split("\t")[0]
yLabel = lines[0].split("\t")[1]
lines = lines[1:]
xList = [float(line.split("\t")[0]) for line in lines]
createPlot(xList, xLabel, yLabel, fileName)
pyplot.legend(legendNames, loc='upper right')
pyplot.savefig("chart.png")
pyplot.show()
|
#!/usr/bin/python3
# for pruning parabank 2, takes only the first unique target line, fifthing the data
# optionally take the most different one
import sys
def dice(sent1, sent2):
set1 = set(sent1.split())
set2 = set(sent2.split())
return 2 * len(set1.intersection(set2)) / (len(set1) + len(set2))
def main(args):
last_trg = None
choice = [1, None]
for line in sys.stdin:
src, trg = line.rstrip().split('\t')
if trg != last_trg:
if last_trg != None:
print(choice[1], last_trg, sep='\t')
choice = [1, None]
if args.method == 'diff':
score = dice(src, trg)
if score < choice[0]:
choice = [score, src]
else:
if choice[1] == None:
choice = [1, src]
last_trg = trg
print(choice[1], last_trg, sep='\t')
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--method', choices=['first', 'diff'], default='first')
args = parser.parse_args()
main(args)
|
import numpy as np
from scipy import sparse
from scipy.sparse.linalg import spsolve
import matplotlib.pyplot as plt
# --------------------------------------------------------------------
# basic parameters
dt = 0.2*60*60 # delta t [s]
tn = 10000 # number of time steps
t = np.arange(0, dt*tn, dt)
L = 5.0e6 # length of basin [m]
l = 1. # basin unit length [bd]
xi = int(5e3+1) # number of horizontal grids
dx = l/(xi-1.) # grid length in terms of bd [bd]
beta = 1.0e-4 # Rossby parameter [bd-1s-1]
gamma = 1.0e-6 # friction coefficient [s-1]
wb_width = gamma/beta # west boundary layer width [bd]
wc = -1e-4 # wind curl [s-2]
vbar = wc/beta # average v-velocity without friction at steady state (beta*v=wc) [bd s-1]
# methodology switchs
bc = 'noslip' # noslip or freeslip
dmethod = 'leapfrog' # forward, leapfrog, trape, or AB
# --------------------------------------------------------------------
# initiate variables
# horizontal location
# add 2 imaginary points, one at each end to deal with boundary condition
x = np.linspace(-dx/l, 1+dx/l, xi+2) # [db]
# stream funciton
phi = np.zeros((tn, xi+2)) # [db2s-1]
# v-velocity
v = np.zeros((tn, xi+2)) # [db s-1]
# vorticity
zeta = np.zeros((tn, xi+2)) # [s-1]
# initial condition (if not zero)
phi[0, :] = np.zeros(xi+2) # [db2s-1]
v[0, 1:-1] = (phi[0, 2:] - phi[0, :-2]) / (2*dx)
zeta[0, 1:-1] = (phi[0, 2:] + phi[0, :-2] - 2*phi[0, 1:-1]) / (dx**2)
# boundary condition
# no penetration
phiw = np.zeros(tn) # west
phie = np.zeros(tn) # east
if bc=='noslip':
# no slip
vw = np.zeros(tn) # west
ve = np.zeros(tn) # east
elif bc=='freeslip':
# free slip
zetaw = np.zeros(tn) # west
zetae = np.zeros(tn) # east
# choose finite differencing parameters
if dmethod == 'forward':
alpd = 1.
betd = 0.
gamd = 0.
deld = 1.
epsd = 0.
elif dmethod == 'backward':
alpd = 1.
betd = 0.
gamd = 1.
deld = 0.
epsd = 0.
elif dmethod== 'leapfrog':
alpd = 0.
betd = 1.
gamd = 0.
deld = 2.
epsd = 0.
elif dmethod == 'trape':
alpd = 1.
betd = 0.
gamd = 0.5
deld = 0.5
epsd = 0.
elif dmethod == 'AB':
alpd = 1.
betd = 0.
gamd = 0.
deld = 1.5
epsd = -0.5
# --------------------------------------------------------------------
# iterate to solve the equation
# construct linear equation matrix
A = -2*sparse.eye(xi+2)*(1+dt*gamd*gamma) + \
sparse.eye(xi+2, k=1)*(1+dt*gamd*(gamma+beta*dx/2)) + \
sparse.eye(xi+2, k=-1)*(1+dt*gamd*(gamma-beta*dx/2))
# setup boundary condition
# no penetration
A[1, 0], A[1, 2], A[-2, -1], A[-2, -3] = 0, 0, 0, 0
A[1, 1], A[-2, -2] = 1, 1
# second order
if bc=='noslip':
A[0, 0] = -1
A[0, 2] = 1
A[-1, -3] = -1
A[-1, -1] = 1
A[0, 1] = 0
A[-1, -2] = 0
elif bc=='freeslip':
A[0, 0] = 1
A[0, 2] = 1
A[-1, -3] = 1
A[-1, -1] = 1
A[0, 1] = -2
A[-1, -2] = -2
# first step always use trapezoidal
A0 = -2*sparse.eye(xi+2)*(1+dt*0.5*gamma) + \
sparse.eye(xi+2, k=1)*(1+dt*0.5*(gamma+beta*dx/2)) + \
sparse.eye(xi+2, k=-1)*(1+dt*0.5*(gamma-beta*dx/2))
# setup boundary condition
# no penetration
A0[1, 0], A0[1, 2], A0[-2, -1], A0[-2, -3] = 0, 0, 0, 0
A0[1, 1], A0[-2, -2] = 1, 1
# second order
if bc=='noslip':
A0[0, 0] = -1
A0[0, 2] = 1
A0[-1, -3] = -1
A0[-1, -1] = 1
A0[0, 1] = 0
A0[-1, -2] = 0
elif bc=='freeslip':
A0[0, 0] = 1
A0[0, 2] = 1
A0[-1, -3] = 1
A0[-1, -1] = 1
A0[0, 1] = -2
A0[-1, -2] = -2
for n in range(tn-1):
if n==0:
# first step always use trapezoidal scheme
B = np.zeros(xi+2)
B[2:-2] = zeta[n, 2:-2]*dx*dx + \
dt*dx*dx*(0.5*wc + \
0.5*(-beta*v[n, 2:-2] + wc - gamma*zeta[n, 2:-2]))
# setup boundary condition
# no penetration
B[1] = phiw[n]
B[-2] = phie[n]
# second order
if bc=='noslip':
B[0] = 2*dx*vw[n]
B[-1] = 2*dx*ve[n]
elif bc=='freeslip':
B[0] = dx**2*zetaw[n]
B[-1] = dx**2*zetae[n]
# solve linear equation
phi[n+1, :] = spsolve(A0, B)
# update v and zeta
v[n+1, 1:-1] = (phi[n+1, 2:] - phi[n+1, :-2]) / (2*dx)
zeta[n+1, 1:-1] = (phi[n+1, 2:] + phi[n+1, :-2] - 2*phi[n+1, 1:-1]) / (dx**2)
continue
# --------------------------------------------------------------------
B = np.zeros(xi+2)
B[2:-2] = alpd*zeta[n, 2:-2]*dx*dx + \
betd*zeta[n-1, 2:-2]*dx*dx + \
dt*dx*dx*(gamd*wc + \
deld*(-beta*v[n, 2:-2] + wc - gamma*zeta[n, 2:-2]) + \
epsd*(-beta*v[n-1, 2:-2] + wc - gamma*zeta[n-1, 2:-2]) \
)
# setup boundary condition
# no penetration
B[1] = phiw[n]
B[-2] = phie[n]
# second order
if bc=='noslip':
B[0] = 2*dx*vw[n]
B[-1] = 2*dx*ve[n]
elif bc=='freeslip':
B[0] = dx**2*zetaw[n]
B[-1] = dx**2*zetae[n]
# solve linear equation
phi[n+1, :] = spsolve(A, B)
# update v and zeta
v[n+1, 1:-1] = (phi[n+1, 2:] - phi[n+1, :-2]) / (2*dx)
zeta[n+1, 1:-1] = (phi[n+1, 2:] + phi[n+1, :-2] - 2*phi[n+1, 1:-1]) / (dx**2)
# --------------------------------------------------------------------
# make plots
pltv = 0
if pltv == 1:
# plot v interactively
plt.figure()
plt.show(block=False)
for i in range(len(t)):
if (i % 100 == 0):
plt.plot(v[i, :])
plt.draw()
# plot the output as hovmuller diagram
plt_hov = 1
if plt_hov == 1:
plt.figure()
plt.pcolor(t[::5]/24/60/60, x[::10], v[::5, ::10].T, cmap=plt.cm.RdYlBu_r)
plt.xlabel('Days')
plt.ylabel('Distance')
plt.xlim(0, t[-1]/24/60/60)
plt.ylim(0, 1)
plt.clim(-5, 5)
cb = plt.colorbar()
cb.ax.set_ylabel(r'V Velocity')
plt.savefig('v_' + bc + '_' + dmethod + '.png', format='png', dpi=900)
plt.close()
|
def check_mispaired(input,output):
"""
Returns sam file only with reads mapped to chrM.
Rather than randomly selecting the origin of multimapped reads,
the program favours two paired reads to derive from
one chromosome, chrM.
"""
with open(input) as f, open(output, "w") as g:
lines = f.readlines()
M = "chrM"
for i, line in enumerate(lines, 0):
if line[0] == "@": # headers
if M in line or "@PG" in line: # only keep mtDNA and PG header
g.write(line)
else:
# split each line into columns
columns = line.rsplit("\t")
pair = columns[6]
# if both reads on mtDNA
if pair == "=":
if columns[2] == M:
g.write(line)
else:
# discard nuclear DNA
if M in line:
# if information on this line
if columns[2] != M:
# extract alternative pair
XA = columns[15]
# extract position of mtDNA read
before, chrM, after = XA.partition(M)
l = [x.strip() for x in after.split(',')]
pos = l[1]
# write new line
columns[2] = M
columns[3] = pos[1:]
columns[6] = "="
newline = "\t".join(columns)
g.write(newline)
# if information not on this line, look at pair
else:
try: # will not work for last line
if lines[i+1].rsplit("\t")[0] == columns[0]:
nextline = lines[i+1]
if lines[i-1].rsplit("\t")[0] == columns[0]:
nextline = lines[i-1]
except:
if lines[i-1].rsplit("\t")[0] == columns[0]:
nextline = lines[i-1]
# same thing as above
nextline_columns = nextline.rsplit("\t")
XA = nextline_columns[15]
before, chrM, after = XA.partition(M)
l = [x.strip() for x in after.split(',')]
pos = l[1]
columns[6] = M
columns[7] = pos[1:]
columns[6] = "="
newline = "\t".join(columns)
g.write(newline)
check_mispaired("aln.sam", "aln.chrM.sam")
|
# coding: utf-8
"""Wikipediaコーパスを解凍して記事のみを抽出し単一ファイルに出力する"""
__author__ = "Aso Taisei"
__date__ = "12 Mar 2020"
import os
import sys
import yaml
def dump():
"""Wikipediaコーパスを解凍して記事のみを抽出し単一ファイルに出力する"""
# ファイルパス
wiki_extractor_path = "./script/WikiExtractor.py"
wiki_xml_path = "./data/jawiki-latest-pages-articles.xml.bz2"
wiki_dump_path = "./data/dumped.txt"
wiki_tmp_path = "./data/tmp/"
# 例外処理
error_flag = False
if not os.path.isfile(wiki_extractor_path):
print("{}: cannot find".format(wiki_extractor_path))
error_flag = True
if not os.path.isfile(wiki_xml_path):
print("{}: cannot find".format(wiki_xml_path))
error_flag = True
if error_flag:
sys.exit(1)
# Wikipediaコーパスを解凍して全てのファイルを一時保存する
os.system("python {} {} --output {}".format(wiki_extractor_path, wiki_xml_path, wiki_tmp_path))
# 解凍したファイルを単一ファイルにまとめる
os.system("find {} | grep wiki | awk \'{{system(\"cat \"$0\" >> {}\")}}\'".format(wiki_tmp_path, wiki_dump_path))
# 一時保存したファイルを全て削除する
os.system("rm -rf {}".format(wiki_tmp_path))
if __name__ == '__main__':
dump()
|
# noqa: D100
import logging
from typing import List, Optional, Union
import hail as hl
logging.basicConfig(
format="%(asctime)s (%(name)s %(lineno)s): %(message)s",
datefmt="%m/%d/%Y %I:%M:%S %p",
)
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
def get_reference_ht(
ref: hl.ReferenceGenome,
contigs: Optional[List[str]] = None,
excluded_intervals: Optional[List[hl.Interval]] = None,
add_all_substitutions: bool = False,
filter_n: bool = True,
) -> hl.Table:
"""
Create a reference Table with locus and alleles (containing only the reference allele by default) from the given reference genome.
.. note::
If the `contigs` argument is not provided, all contigs (including obscure ones) will be added to the table.
This can be slow as contigs are added one by one.
:param ref: Input reference genome
:param contigs: An optional list of contigs that the Table should include
:param excluded_intervals: An optional list of intervals to exclude
:param add_all_substitutions: If set, then all possible substitutions are added in the alleles array
:param filter_n: If set, bases where the reference is unknown (n) are filtered.
:return:
"""
if not ref.has_sequence():
add_reference_sequence(ref)
if not contigs:
contigs = ref.contigs
if add_all_substitutions:
SUBSTITUTIONS_TABLE = hl.literal(
{
"a": ["c", "g", "t"],
"c": ["a", "g", "t"],
"g": ["a", "c", "t"],
"t": ["a", "c", "g"],
}
)
context = []
for contig in contigs:
n_partitions = max(1, int(ref.contig_length(contig) / 5000000))
logger.info(
"Creating reference contig %s with %d partitions.", contig, n_partitions
)
_context = hl.utils.range_table(
ref.contig_length(contig), n_partitions=n_partitions
)
locus_expr = hl.locus(contig=contig, pos=_context.idx + 1, reference_genome=ref)
ref_allele_expr = locus_expr.sequence_context().lower()
if add_all_substitutions:
alleles_expr = hl.array([ref_allele_expr]).extend(
SUBSTITUTIONS_TABLE.get(ref_allele_expr, hl.empty_array(hl.tstr))
)
else:
alleles_expr = [ref_allele_expr]
_context = (
_context.select(locus=locus_expr, alleles=alleles_expr)
.key_by("locus", "alleles")
.drop("idx")
)
if excluded_intervals is not None:
_context = hl.filter_intervals(_context, excluded_intervals, keep=False)
if filter_n:
_context = _context.filter(_context.alleles[0] == "n", keep=False)
context.append(_context)
return context.pop().union(*context)
def add_reference_sequence(ref: hl.ReferenceGenome) -> hl.ReferenceGenome:
"""
Add the fasta sequence to a Hail reference genome.
Only GRCh37 and GRCh38 references are supported.
:param ref: Input reference genome.
:return:
"""
if not ref.has_sequence():
if ref.name == "GRCh38":
ref.add_sequence(
"gs://hail-common/references/Homo_sapiens_assembly38.fasta.gz",
"gs://hail-common/references/Homo_sapiens_assembly38.fasta.fai",
)
elif ref.name == "GRCh37":
ref.add_sequence(
"gs://hail-common/references/human_g1k_v37.fasta.gz",
"gs://hail-common/references/human_g1k_v37.fasta.fai",
)
else:
raise NotImplementedError(
f"No known location for the fasta/fai files for genome {ref.name}. Only GRCh37 and GRCh38 are supported at this time."
)
else:
logger.info(
"Reference genome sequence already present. Ignoring add_reference_sequence."
)
return ref
def get_reference_genome(
locus: Union[hl.expr.LocusExpression, hl.expr.IntervalExpression],
add_sequence: bool = False,
) -> hl.ReferenceGenome:
"""
Return the reference genome associated with the input Locus expression.
:param locus: Input locus
:param add_sequence: If set, the fasta sequence is added to the reference genome
:return: Reference genome
"""
if isinstance(locus, hl.expr.LocusExpression):
ref = locus.dtype.reference_genome
else:
assert isinstance(locus, hl.expr.IntervalExpression)
ref = locus.dtype.point_type.reference_genome
if add_sequence:
ref = add_reference_sequence(ref)
return ref
|
# Generated by Django 3.0.8 on 2020-07-20 15:44
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('NetflixApp', '0002_auto_20200719_1518'),
]
operations = [
migrations.DeleteModel(
name='Rating',
),
migrations.DeleteModel(
name='Recommendation',
),
]
|
import os
import cv2
import numpy as np
from PIL import Image
import pickle
from pathlib import Path
import string
from sklearn.model_selection import train_test_split
from keras.layers import Dense, LSTM, Reshape, BatchNormalization, Input, Conv2D, MaxPool2D, Lambda, Bidirectional
import keras.backend as K
from keras.models import Model
from keras.callbacks import ModelCheckpoint
from keras.preprocessing.sequence import pad_sequences
from keras.activations import relu, sigmoid, softmax
from keras.utils import to_categorical
imgpath = './Data/img/'
txtpath = './Data/txt/'
vi = 'áàảãạắằẳẵặấầẩẫậớờởỡợếềểễệéèẻẽẹốồổỗộđúùủũụọóỏõòứừửữựíìỉĩịÁÀẢÃẠẮẰẲẴẶẤẦẨẪẬỚỜỞỠỢẾỀỂỄỆÉÈẺẼẸỐỒỔỖỘĐÚÙỦŨỤỌÓỎÕÒỨỪỬỮỰÍÌỈĨỊưâƯÂăĂơƠêÊôÔýỳỷỹỵÝỲỶỸỴ'
char_list = string.ascii_letters + string.digits + string.punctuation + string.whitespace + vi
max_label_len = 0
# lists for training dataset
training_img = []
training_txt = []
train_input_length = []
train_label_length = []
orig_txt = []
#lists for validation dataset
valid_img = []
valid_txt = []
valid_input_length = []
valid_label_length = []
valid_orig_txt = []
def encode_to_labels(txt):
dig_lst = []
for index, char in enumerate(txt):
try:
dig_lst.append(char_list.index(char))
except:
print(char)
return dig_lst
def getImages():
i = 1
filetext = list(Path(txtpath).rglob('*.[txt]*'))
names = [str(path.name).split('.')[0] for path in filetext]
for name in names:
image_path = imgpath+name+'.png'
image = cv2.imread(image_path)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
with open(txtpath+name+'.txt','r',encoding = 'utf8') as f:
txt = f.read()
if i%10 == 0:
valid_orig_txt.append(txt)
valid_label_length.append(len(txt))
valid_input_length.append(31)
valid_img.append(image)
valid_txt.append(encode_to_labels(txt))
else:
orig_txt.append(txt)
train_label_length.append(len(txt))
train_input_length.append(31)
training_img.append(image)
training_txt.append(encode_to_labels(txt))
train_padded_txt = pad_sequences(training_txt, maxlen=max_label_len, padding='post', value = len(char_list))
valid_padded_txt = pad_sequences(valid_txt, maxlen=max_label_len, padding='post', value = len(char_list))
getImages()
def decode_to_labels(dig_lst):
txt = []
output = ""
for i in dig_lst:
txt.append(char_list[i])
for text in txt :
output = output+text
return output
inputs = Input(shape=(32,128,1))
# convolution layer with kernel size (3,3)
conv_1 = Conv2D(64, (3,3), activation = 'relu', padding='same')(inputs)
# poolig layer with kernel size (2,2)
pool_1 = MaxPool2D(pool_size=(2, 2), strides=2)(conv_1)
conv_2 = Conv2D(128, (3,3), activation = 'relu', padding='same')(pool_1)
pool_2 = MaxPool2D(pool_size=(2, 2), strides=2)(conv_2)
conv_3 = Conv2D(256, (3,3), activation = 'relu', padding='same')(pool_2)
conv_4 = Conv2D(256, (3,3), activation = 'relu', padding='same')(conv_3)
# poolig layer with kernel size (2,1)
pool_4 = MaxPool2D(pool_size=(2, 1))(conv_4)
conv_5 = Conv2D(512, (3,3), activation = 'relu', padding='same')(pool_4)
# Batch normalization layer
batch_norm_5 = BatchNormalization()(conv_5)
conv_6 = Conv2D(512, (3,3), activation = 'relu', padding='same')(batch_norm_5)
batch_norm_6 = BatchNormalization()(conv_6)
pool_6 = MaxPool2D(pool_size=(2, 1))(batch_norm_6)
conv_7 = Conv2D(512, (2,2), activation = 'relu')(pool_6)
squeezed = Lambda(lambda x: K.squeeze(x, 1))(conv_7)
# bidirectional LSTM layers with units=128
blstm_1 = Bidirectional(LSTM(128, return_sequences=True, dropout = 0.2))(squeezed)
blstm_2 = Bidirectional(LSTM(128, return_sequences=True, dropout = 0.2))(blstm_1)
outputs = Dense(len(char_list)+1, activation = 'softmax')(blstm_2)
act_model = Model(inputs, outputs)
labels = Input(name='the_labels', shape=[max_label_len], dtype='float32')
input_length = Input(name='input_length', shape=[1], dtype='int64')
label_length = Input(name='label_length', shape=[1], dtype='int64')
def ctc_lambda_func(args):
y_pred, labels, input_length, label_length = args
return K.ctc_batch_cost(labels, y_pred, input_length, label_length)
loss_out = Lambda(ctc_lambda_func, output_shape=(1,), name='ctc')([outputs, labels, input_length, label_length])
#model to be used at training time
model = Model(inputs=[inputs, labels, input_length, label_length], outputs=loss_out)
model.compile(loss={'ctc': lambda y_true, y_pred: y_pred}, optimizer = 'adam')
filepath="best_model.hdf5"
checkpoint = ModelCheckpoint(filepath=filepath, monitor='val_loss', verbose=1, save_best_only=True, mode='auto')
callbacks_list = [checkpoint]
training_img = np.array(training_img)
train_input_length = np.array(train_input_length)
train_label_length = np.array(train_label_length)
valid_img = np.array(valid_img)
valid_input_length = np.array(valid_input_length)
valid_label_length = np.array(valid_label_length)
batch_size = 256
epochs = 10
batch_size = 256
epochs = 10
model.fit(x=[training_img, train_padded_txt, train_input_length,
train_label_length], y=np.zeros(len(training_img)),
batch_size=batch_size, epochs = epochs,
validation_data = ([valid_img, valid_padded_txt, valid_input_length, valid_label_length],
[np.zeros(len(valid_img))]), verbose = 1, callbacks = callbacks_list) |
# -*- coding: utf-8 -*-
from odoo import api, fields, models, _
class Users(models.Model):
_inherit = 'res.users'
menu_ids = fields.Many2many('ir.ui.menu', 'user_menu_rel', 'uid', 'menu_id', string='Menu To Hide', help='Select Menus To Hide From This User')
report_ids = fields.Many2many('ir.actions.report', 'user_report_rel', 'user_id', 'report_id', 'Report To Hide',
help='Select Report To Hide From This User')
class ResGroups(models.Model):
_inherit = 'res.groups'
menu_ids = fields.Many2many('ir.ui.menu', 'group_menu_rel', 'group_id', 'menu_id', string='Menu To Hide')
report_ids = fields.Many2many('ir.actions.report', 'group_report_rel', 'group_id', 'report_id', 'Report To Hide',
help='Select Report To Hide From This User')
class IrActionsReport(models.Model):
_inherit = 'ir.actions.report'
hide_user_ids = fields.Many2many('res.users', 'user_report_rel', 'report_id', 'user_id', string='Hide From Users')
hide_group_ids = fields.Many2many('res.groups', 'group_report_rel', 'report_id', 'group_id', string='Hide From Groups')
class IrUiMenu(models.Model):
_inherit = 'ir.ui.menu'
hide_group_ids = fields.Many2many('res.groups', 'group_menu_rel', 'menu_id', 'group_id', string='Hide From Groups')
hide_user_ids = fields.Many2many('res.users', 'user_menu_rel', 'menu_id', 'user_id', string='Hide From Users')
@api.model
def search(self, args, offset=0, limit=None, order=None, count=False):
if self.env.user == self.env.ref('base.user_root'):
return super(IrUiMenu, self).search(args, offset=0, limit=None, order=order, count=False)
else:
menus = super(IrUiMenu, self).search(args, offset=0, limit=None, order=order, count=False)
if menus:
menu_ids = [menu for menu in self.env.user.menu_ids]
menu_ids2 = [menu for group in self.env.user.groups_id for menu in group.menu_ids]
for menu in list(set(menu_ids).union(menu_ids2)):
if menu in menus:
menus -= menu
if offset:
menus = menus[offset:]
if limit:
menus = menus[:limit]
return len(menus) if count else menus
class IrModel(models.Model):
_inherit = 'ir.model'
field_configuration_ids = fields.One2many('field.configuration', 'model_id', string='Field Configuration')
class FieldConfiguration(models.Model):
_name = 'field.configuration'
_description = 'Field Configuration'
model_id = fields.Many2one('ir.model', string='Model', required=True)
field_id = fields.Many2one('ir.model.fields', string='Field', required=True)
field_name = fields.Char(related='field_id.name', string='Technical Name', readonly=True)
group_ids = fields.Many2many('res.groups', 'field_config_group_rel', 'group_id', 'field_config_id', required=True, string='Groups')
readonly = fields.Boolean('ReadOnly', default=False)
invisible = fields.Boolean('Invisible', default=False)
_sql_constraints = [
('field_model_readonly_unique', 'UNIQUE ( field_id, model_id, readonly)',
_('Readonly Attribute Is Already Added To This Field, You Can Add Group To This Field!')),
('model_field_invisible_uniq', 'UNIQUE (model_id, field_id, invisible)',
_('Invisible Attribute Is Already Added To This Field, You Can Add Group To This Field'))
]
|
#Import module
import pygame, sys, random
from pygame.math import Vector2 #mempermudah supaya saat manggil g nulis pake "pygame.math.Vector2" terus2an
#Membuat kelas FARMER
class FARMER:
def __init__(self): #menginisiasi
self.randomize()
def draw_farmer(self):
#membuat rect
farmer_rect = pygame.Rect(int(self.pos.x * cell_size), int(self.pos.y * cell_size), cell_size, cell_size) #xywh
screen.blit(farmer,farmer_rect)
def randomize(self):
self.x = random.randint(0, cell_number - 1) # -1 supaya tetap ada di layar
self.y = random.randint(0, cell_number - 1)
self.pos = Vector2(self.x, self.y)
#Membuat kelas FOOD
class FOOD:
def __init__(self): #menginisiasi
self.randomize()
def draw_food(self):
#membuat rect
food_rect = pygame.Rect(int(self.pos.x * cell_size), int(self.pos.y * cell_size), cell_size, cell_size) #xywh
screen.blit(mouse,food_rect)
#menggambar rectangle
#pygame.draw.rect(screen,(126,166,144), food_rect)
def randomize(self):
self.x = random.randint(0, cell_number - 1) # -1 supaya tetap ada di layar
self.y = random.randint(0, cell_number - 1)
self.pos = Vector2(self.x, self.y)
#Membuat kelas SNAKE
class SNAKE:
def __init__(self): #menginisiasi
# index 0 index 1 index 2 (enumerate tadi di draw_snake)
self.body = [Vector2(5,10),Vector2(4,10),Vector2(3,10)] #badan dari snake. posisi awal snake.
self.direction = Vector2(0,0)
self.new_block = False
#load asset kepala snake
self.head_up = pygame.image.load('asset/Snake/head_up.png').convert_alpha()
self.head_down = pygame.image.load('asset/Snake/head_down.png').convert_alpha()
self.head_right = pygame.image.load('asset/Snake/head_right.png').convert_alpha()
self.head_left = pygame.image.load('asset/Snake/head_left.png').convert_alpha()
#load asset body snake
self.body_vertical = pygame.image.load('asset/Snake/body_vertical.png').convert_alpha()
self.body_horizontal = pygame.image.load('asset/Snake/body_horizontal.png').convert_alpha()
#load asset body snake saat belok
self.body_tr = pygame.image.load('asset/Snake/body_topright.png').convert_alpha()
self.body_tl = pygame.image.load('asset/Snake/body_topleft.png').convert_alpha()
self.body_br = pygame.image.load('asset/Snake/body_bottomright.png').convert_alpha()
self.body_bl = pygame.image.load('asset/Snake/body_bottomleft.png').convert_alpha()
#load asset ekor snake
self.tail_up = pygame.image.load('asset/Snake/tail_up.png').convert_alpha()
self.tail_down = pygame.image.load('asset/Snake/tail_down.png').convert_alpha()
self.tail_right = pygame.image.load('asset/Snake/tail_right.png').convert_alpha()
self.tail_left = pygame.image.load('asset/Snake/tail_left.png').convert_alpha()
#import audio
self.munch_sound = pygame.mixer.Sound('asset/munch.mp3')
self.crash_sound = pygame.mixer.Sound('asset/crash.mp3')
def draw_snake(self):
self.update_head_graphics()
self.update_tail_graphics()
for index, block in enumerate(self.body): #enumerate ngasih index di list
#Membuat rect untuk ngasih posisi
x_pos = int(block.x * cell_size)
y_pos = int(block.y * cell_size)
block_rect = pygame.Rect(x_pos, y_pos, cell_size, cell_size) #xywh
#Mencari tau arah dari kepala snake
if index == 0: #index 0 = head
screen.blit(self.head,block_rect)
elif index == len(self.body)-1: #last item in self.body. -1 karena terhitung dari 0
screen.blit(self.tail,block_rect)
else:
previous_block = self.body[index+1] - block #index yg sekarang ditambah satu
next_block = self.body[index-1] - block
if previous_block.x == next_block.x:
screen.blit(self.body_vertical,block_rect)
elif previous_block.y == next_block.y:
screen.blit(self.body_horizontal,block_rect)
else: # belokan badan
if previous_block.x == -1 and next_block.y == -1 or previous_block.y == -1 and next_block.x == -1:
screen.blit(self.body_tl,block_rect)
elif previous_block.x == 1 and next_block.y == -1 or previous_block.y == -1 and next_block.x == 1:
screen.blit(self.body_tr,block_rect)
elif previous_block.x == -1 and next_block.y == 1 or previous_block.y == 1 and next_block.x == -1:
screen.blit(self.body_bl,block_rect)
elif previous_block.x == 1 and next_block.y == 1 or previous_block.y == 1 and next_block.x == 1:
screen.blit(self.body_br,block_rect)
def update_head_graphics(self):
head_relation = self.body[1] - self.body [0] #
if head_relation == Vector2(1,0):
self.head = self.head_left
elif head_relation == Vector2(-1,0):
self.head = self.head_right
elif head_relation == Vector2(0,1):
self.head = self.head_up
elif head_relation == Vector2(0,-1):
self.head = self.head_down
def update_tail_graphics(self):
tail_relation = self.body[-2] - self.body[-1] #
if tail_relation == Vector2(1, 0):
self.tail = self.tail_left
elif tail_relation == Vector2(-1, 0):
self.tail = self.tail_right
elif tail_relation == Vector2(0, 1):
self.tail = self.tail_up
elif tail_relation == Vector2(0, -1):
self.tail = self.tail_down
#membuat method untuk membuat snake bergerak
def move_snake(self):
if self.new_block == True:
body_copy = self.body[:]
body_copy.insert(0, body_copy[0] + self.direction) # 0 kepala
self.body = body_copy[:] # mengembalikan seluruh list kembali ke body
self.new_block = False #supaya tidak memanjang terus (nilai tidak true)
else:
body_copy = self.body[:-1] #menggunakan slicing untuk mendapatkan 2 elemen pertama dari body list
body_copy.insert(0, body_copy[0] + self.direction) #0 kepala
self.body = body_copy[:] #mengembalikan seluruh list kembali ke body
def add_block(self):
self.new_block = True
def play_munch_sound(self):
self.munch_sound.play()
def play_crash_sound(self):
self.crash_sound.play()
def reset(self):
self.body = [Vector2(5,10),Vector2(4,10),Vector2(3,10)] #posisi awal kayak pas mulai game
self.direction = Vector2(0, 0)
#Membuat kelas MAIN yg berisi game logic, objek snake, dan food
class MAIN:
#menginstansiasi
def __init__(self):
self.snake = SNAKE() #membuat objek snake dari kelas SNAKE
self.food = FOOD() #membuat objek food dari kelas FOOD
self.farmer = FARMER() #membuat objek farmer dari kelas farmer
def update(self):
self.snake.move_snake()
self.check_collision()
self.check_fail()
def draw_elements(self):
self.draw_grass()
self.food.draw_food()
self.farmer.draw_farmer()
self.snake.draw_snake()
self.draw_score()
def check_collision(self):
#TIKUS
if self.food.pos == self.snake.body[0]: #jika posisi buah dan body snake sama, buah termakan dan hilang
self.food.randomize() #muncul food baru secara acak
self.farmer.randomize() #muncul farmer secara acak
self.snake.add_block() #menambahkan panjang snake
self.snake.play_munch_sound()
for block in self.snake.body[1:]:
if block == self.food.pos: #jika buah dan snake berada di posisi yang sama
self.food.randomize()
#FARMER
if self.farmer.pos == self.snake.body[0]: #jika posisi farmer dan body snake sama (kepala)
self.snake.play_crash_sound()
self.game_over()
self.farmer.randomize() #muncul farmer baru secara acak
self.food.randomize() #muncul food baru secara acak
def check_fail(self):
#Jika snake keluar dari screen
if not 0 <= self.snake.body[0].x < cell_number or not 0 <= self.snake.body[0].y < cell_number: #tabrakan dengan tembok kanan dan kiri
self.snake.play_crash_sound()
self.game_over()
#mengecek jika snake bertabrakan dengan badannya sendiri
for block in self.snake.body[1:]:
if block == self.snake.body[0]:
self.game_over()
#method untuk reset
def game_over(self):
self.snake.reset()
def draw_grass(self):
grass_color = (167,209,61)
for row in range(cell_number):
if row % 2 == 0:
for col in range(cell_number):
if col % 2 == 0:
grass_rect = pygame.Rect(col*cell_size,row*cell_size,cell_size,cell_number)
pygame.draw.rect(screen,grass_color,grass_rect)
else:
for col in range(cell_number):
if col % 2 != 0:
grass_rect = pygame.Rect(col*cell_size,row*cell_size,cell_size,cell_number)
pygame.draw.rect(screen,grass_color,grass_rect)
def draw_score(self):
score_text = str(len(self.snake.body) - 3)
score_surface = game_font.render(score_text, True, (56,74,12)) #text, anti alias, color
score_x = int(cell_size * cell_number - 60)
score_y = int(cell_size * cell_number - 40)
score_rect = score_surface.get_rect(center = (score_x,score_y))
mouse_rect = mouse.get_rect(midright =(score_rect.left, score_rect.centery))
bg_rect = pygame.Rect(mouse_rect.left-10, mouse_rect.top-5, mouse_rect.width + score_rect.width + 20, mouse_rect.height+10)
pygame.draw.rect(screen,(167,209,61),bg_rect)
screen.blit(score_surface, score_rect)
screen.blit(mouse,mouse_rect)
pygame.draw.rect(screen,(56,209,61),bg_rect, 2) #ketebalan garis
def pause(self):
pause_text = "PAUSE"
pause_surface = game_font.render(pause_text, True, (56, 74, 12)) # text, anti alias, color
pause_x = int(cell_size * cell_number - 60)
pause_y = int(cell_size * cell_number - 40)
pause_rect = pause_surface.get_rect(center = (pause_x,pause_y))
bg_rect = pygame.Rect(pause_rect.left - 10, pause_rect.top - 5, pause_rect.width + pause_rect.width + 20, pause_rect.height + 10)
pygame.draw.rect(screen, (167, 209, 61), bg_rect)
screen.blit(pause_surface, pause_rect)
pygame.draw.rect(screen, (56, 209, 61), bg_rect, 2) # ketebalan garis
pygame.mixer.pre_init(44100,-16,2,512)
pygame.init()
pygame.mixer.music.load('asset/bgm.mp3')
pygame.mixer.music.play(-1, 0.0)
cell_size = 35 #40
cell_number = 20
screen = pygame.display.set_mode((cell_number * cell_size, cell_number * cell_size))
clock = pygame.time.Clock()
############TEKS###########################3
# Warna putih untuk teks
color = (255, 255, 255)
# Menyimpan lear dari screen ke dalam variabel
width = screen.get_width()
# Menyimpan tinggi dari screen ke dalam variabel
height = screen.get_height()
# Mendefinisikan font
smallfont = pygame.font.SysFont('Corbel', 35)
# Merender text di bawah
text = smallfont.render('Press up, right, left or down to start', True, color)
text2 = smallfont.render('', True, color)
text3 = smallfont.render('', True, color)
#####################################
mouse = pygame.image.load('asset/mouse.png').convert_alpha()
farmer = pygame.image.load('asset/farmer.png').convert_alpha()
game_font = pygame.font.Font('asset/font/Snake Chan.ttf', 25) #font(.ttf), font size
SCREEN_UPDATE = pygame.USEREVENT #custom event menggunakan triggger (menggunakan timer)
pygame.time.set_timer(SCREEN_UPDATE,150) #event tertrigger setiap 150ms
main_game = MAIN()
#Game loop
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == SCREEN_UPDATE:
main_game.update()
if event.type == pygame.KEYDOWN: #Controller
if event.key == pygame.K_UP:
text = smallfont.render('Press and hold h for help', True, color)
if main_game.snake.direction.y !=1: #supaya tidak bertabrakan dengan badan sendiri
main_game.snake.direction = Vector2(0,-1)
if event.key == pygame.K_DOWN:
text = smallfont.render('Press and hold h for help', True, color)
if main_game.snake.direction.y != -1:
main_game.snake.direction = Vector2(0,1)
if event.key == pygame.K_RIGHT:
text = smallfont.render('Press and hold h for help', True, color)
if main_game.snake.direction.x != -1:
main_game.snake.direction = Vector2(1,0)
if event.key == pygame.K_LEFT:
text = smallfont.render('Press and hold h for help', True, color)
if main_game.snake.direction.x != 1:
main_game.snake.direction = Vector2(-1,0)
#QUIT game (pake ESC)
if event.key == pygame.K_ESCAPE:
pygame.quit()
sys.exit()
#PAUSE game (pake P dan Space)
if event.key == pygame.K_p:
pygame.time.set_timer(SCREEN_UPDATE, 0) # buat pause pake P
main_game.draw_score()
if event.key == pygame.K_SPACE:
pygame.time.set_timer(SCREEN_UPDATE, 150) # buat continue pake space
#HELP game (pake H)
if event.key == pygame.K_h:
# superimposing the text onto our button
text = smallfont.render('Press p for pause', True, color)
text2 = smallfont.render('SPACE for continue', True, color)
text3 = smallfont.render('ESC for quit', True, color)
screen.blit(text, (1, 4))
screen.blit(text2, (1, 54))
screen.blit(text3, (1, 104))
if event.type == pygame.KEYUP: # Controller
if event.key == pygame.K_h:
# superimposing the text onto our button
text = smallfont.render('Press and hold h for help', True, color)
text2 = smallfont.render('', True, color)
text3 = smallfont.render('', True, color)
#screen.blit(text, (1, 4))
screen.fill((175,215,70))
#main_game.level_speed()
main_game.draw_elements()
# tulisan instruksi help
screen.blit(text, (1, 4))
screen.blit(text2, (1, 54))
screen.blit(text3, (1, 104))
pygame.display.update()
clock.tick(60) #framerate |
from nanpy import (ArduinoApi, SerialManager)
import time
try:
connection = SerialManager()
a = ArduinoApi(connection = connection)
except:
print("Failed to connect to Arduino.")
trigger = 7
echo = 8
a.pinMode(trigger, a.OUTPUT)
a.pinMode(echo, a.INPUT)
a.digitalWrite(trigger, a.LOW)
print("Waiting for sensor to settle..")
time.sleep(0.5)
print("Calculating distance...")
a.digitalWrite(trigger, a.HIGH)
time.sleep(0.00001)
a.digitalWrite(trigger, a.LOW)
while a.digitalRead(echo) == 0:
startTime = time.time()
while a.digitalRead(echo) == 1:
endTime = time.time()
duration = endTime - startTime
distance = (duration * 34300) /2
print("Distance:", distance, "cm")
|
# -*- coding: utf-8 -*-
# Copyright (C) 2012 Dr. Ralf Schlatterbeck All rights reserved
# Reichergasse 131, A-3411 Weidling, Austria. rsc@runtux.com
# #*** <License> ************************************************************#
# This module is part of the package FFM.
#
# This module is licensed under the terms of the BSD 3-Clause License
# <http://www.c-tanzer.at/license/bsd_3c.html>.
# #*** </License> ***********************************************************#
#
#++
# Name
# FFM.Attr_Type
#
# Purpose
# Define attribute types for package FFM
#
# Revision Dates
# 27-Aug-2012 (RS) Creation
# 22-Sep-2012 (RS) Factor `A_DNS_Label` and correct syntax
# 11-Oct-2012 (RS) RFC 1123 section 2.1 permits DNS label
# to start with a digit, change `A_DNS_Label` syntax
# ««revision-date»»···
#--
from _GTW import GTW
from _MOM.import_MOM import *
from _MOM.import_MOM import _A_Composite_, _A_Named_Value_
from _MOM.import_MOM import _A_Unit_, _A_Int_
from _GTW._OMP._DNS import DNS
from _TFL.I18N import _
from _TFL.Regexp import Regexp
class A_DNS_Time (_A_Unit_, _A_Int_) :
""" Allow specification of DNS times in other units than seconds """
typ = _ ("DNS Time")
needs_raw_value = True
min_value = 0
max_value = 2147483647
_unit_dict = dict \
( seconds = 1
, minutes = 60
, hours = 60 * 60
, days = 60 * 60 * 24
, weeks = 60 * 60 * 24 * 7
)
# end class A_DNS_Time
class A_DNS_Label (Syntax_Re_Mixin, A_String) :
""" A single DNS label (without dots)
See rfc1034 *and* rfc1123 section 2.1 for details.
"""
max_length = 63
ignore_case = True
syntax = _ \
( u"A label starts"
" with a letter or digit and is optionally followed by letters,"
" digits or dashes and ends with a letter or digit. "
"A label may be up to 63 characters long."
)
_label = r"[a-zA-Z0-9](?:[-a-zA-Z0-9]{0,61}[a-zA-Z0-9])?"
_syntax_re = Regexp (_label)
# end class A_DNS_Label
class A_DNS_Name (Syntax_Re_Mixin, A_String) :
""" DNS name consisting of labels separated by '.'
See rfc1034 for details.
"""
max_length = 253
ignore_case = True
syntax = _ \
( u"DNS name must consist of up to 127 labels. ") + A_DNS_Label.syntax
_syntax_re = Regexp \
(r"%s([.]%s){0,126}" % (A_DNS_Label._label, A_DNS_Label._label))
# end class A_DNS_Name
if __name__ != "__main__" :
GTW.OMP.DNS._Export ("*")
### __END__ GTW.OMP.DNS.Attr_Type
|
from django.urls import path
from . import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
#path('', views.home, name='takatarecovery-home'),
path('', views.home, name='takatarecovery-home'),
path('makemodel/', views.makeModelCheck, name='takatarecovery-makemodel'),
path('aboutus/', views.aboutus, name='takatarecovery-aboutus'),
path('privacy/', views.privacy, name='takatarecovery-privacy'),
path('contact/', views.contact, name='takatarecovery-contact'),
path('index-result/', views.details, name='takatarecovery-details')#,
#path('make-model/', views.makeModelCheck, name='takatarecovery-makeModelCheck')
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) |
import time
import requests
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
RETRIES_STATUS_CODES = [429, 500, 502, 503, 504] # not used rn
"""
Used self-retry logic. but check this package:: Read about requests.retries here: [doc](https://findwork.dev/blog/advanced-usage-python-requests-timeouts-retries-hooks/#retry-on-failure), [stkofw](https://stackoverflow.com/questions/23267409/how-to-implement-retry-mechanism-into-python-requests-library?rq=1)
"""
def hitGetWithRetry(url, HEADER='',VERIFY=False ,retry_count=3,SLEEP_SECONDS=15,TIMEOUT=None):
data = requests.get(url, verify=VERIFY,headers= HEADER, timeout=TIMEOUT)
if(data.status_code==200):
return data
while (retry_count > 0 and data.status_code != 200):
print(" \txxxxxx------------ Found Status Code: {} sleeping for {} sec.Retries remaining = {} --------------xxxxx".format(data.status_code,SLEEP_SECONDS,retry_count-1))
data = requests.get(url, verify=VERIFY,headers= HEADER, timeout=TIMEOUT)
retry_count -= 1
if(data.status_code==200):
return data
else:
return -1 |
import PyQt5.QtWidgets as QtWidgets
import PyQt5.QtCore as QtCore
import PyQt5.QtGui as QtGui
import cfg.game as game_cfg
import lib.view_lib as view_lib
import view.h_list_view as h_list_view
import view.h_row_view as h_row_view
# 轨迹默认配置视图
class TrajectoryChangeView(h_list_view.HListLabel):
select_trajectory_id = 0
def __init__(self, *args):
super(TrajectoryChangeView, self).__init__(*args)
# 上方标题
self.label_title = QtWidgets.QLabel("轨迹修改", self)
self.label_title.setAlignment(QtCore.Qt.AlignCenter)
view_lib.set_background_color(self.label_title)
# 轨迹编号
self.id_label_edit = h_row_view.HLabelEdit(self)
self.id_label_edit.init(
game_cfg.button_size[0], game_cfg.button_size[1], "轨迹编号", "0"
)
# 移动时间
self.move_time_label_edit = h_row_view.HLabelEdit(self)
self.move_time_label_edit.init(
game_cfg.button_size[0], game_cfg.button_size[1], "移动时间", "1"
)
# 确定修改
self.button_change = QtWidgets.QPushButton("确定修改", self)
self.button_change.clicked.connect(self.click_change)
# 添加到菜单列表
self.add_view(self.label_title)
self.add_view(self.id_label_edit)
self.add_view(self.move_time_label_edit)
self.add_view(self.button_change)
# 点击确定修改
def click_change(self):
self.parent().change_trajectory()
# 设置选中的轨迹点
def set_select_trajectory(self, trajectory_obj):
self.select_trajectory_id = trajectory_obj.trajectory_id
self.id_label_edit.setText(str(trajectory_obj.trajectory_id))
self.move_time_label_edit.setText(str(trajectory_obj.move_time))
|
'''
For given integer x, print 'True' if it is positive, print 'False' if it is negative and print 'Zero' if it is zero
'''
a = int(input("Enter any number"))
if a==0:
print ("It is Zero")
elif a>=0:
print ("It is positive")
else:
print ("It is negative") |
#!/usr/bin/env python2.6
"""
The primary startup script for winnie. Initializes
the IRC connection
"""
from winnie.protocols.irc import connection as IRC
from winnie.web import server as HTTP
def main():
try:
irc = IRC.Connection()
irc.start()
except KeyboardInterrupt, e:
irc.running = False
irc.die()
if __name__ == '__main__':
main()
else:
print 'Usage: python ./main.py'
|
# -*- coding: utf-8 -*-
import yaml
import os
class StreamingConf:
def __init__(self, conf_file):
home_dir = os.environ['MYSTR_HOME']
f = open(home_dir + '/conf/' + conf_file, 'r')
self.conf = yaml.load(f)
f.close()
#def get_job_manager(self):
# return self.conf['job_manager']
def get_jm_address(self):
return self.conf['job_manager']['address']
def get_jm_mac(self):
return self.conf['job_manager']['mac']
def get_jm_port(self):
return self.conf['job_manager']['port']
def get_task_managers(self):
return self.conf['task_manager']
def get_tm_address(self, name):
return self.conf['task_manager'][name]['address']
def get_tm_mac(self, name):
return self.conf['task_manager'][name]['mac']
def get_tm_port(self, name):
return self.conf['task_manager'][name]['port']
def get_tm_device_type(self, name):
return self.conf['task_manager'][name]['device_type']
def get_tm_slots(self, name):
return self.conf['task_manager'][name]['slots']
def get_tm_data_interfaces(self, name):
interfaces = self.conf['task_manager'][name]['data_interfaces']
return tuple(interfaces)
def get_network_bundling(self):
return self.conf['network_event_bundling']
|
"""
Ad-hoc csv report generation script.
"""
import os, sys
import argparse
from datetime import datetime
import pandas as pd
BASE_DIR = os.path.dirname(__file__)
REPORT_DIR = os.path.abspath(os.path.join(BASE_DIR, '..', '..', '..', '_reports'))
sys.path.append(os.path.join(BASE_DIR, '..', '..'))
import db
rpt_cols = ['datetime_today', 'rseq', 'enum_id', 'cust_name', 'addy_no',
'addy_street', 'acct_status', 'acct_no', 'tariff', 'cust_mobile1',
'cust_mobile2']
def get_duplicate_rseqs(df):
key = 'rseq'
d = df[df.duplicated(key) == True]
duplicates = pd.DataFrame()
for v in d[key].values:
duplicates = duplicates.append(df[df[key] == v][rpt_cols])
for col in rpt_cols:
duplicates[col] = duplicates[col].apply(lambda x: str(x).upper())
return duplicates
def get_duplicate_accts(df):
key = 'acct_no'
f = df[df[key].isnull() == False]
d = f[f.duplicated(key) == True]
duplicates = pd.DataFrame()
for v in d[key].values:
duplicates = duplicates.append(df[df[key] == v][rpt_cols])
for col in rpt_cols:
duplicates[col] = duplicates[col].apply(lambda x: str(x).upper())
return duplicates
def get_invalid_stations(df, codes):
if not codes:
raise ValueError('Invalid codes not provided')
key = 'station'
df[key] = df['rseq'].apply(lambda x: x.upper().split('/')[0])
records = pd.DataFrame()
for v in [c.upper() for c in codes]:
records = records.append(df[df[key] == v][[key] + rpt_cols])
for col in ([key] + rpt_cols):
records[col] = records[col].apply(lambda x: str(x).upper())
return records
def get_records_by_upriser(upriser_code):
query = {'rseq': {'$regex': '.*%s/*' % upriser_code, '$options':'i' }}
captures = db.Capture.query(paginate=False, **query)
df = pd.DataFrame(list(captures))
result = df[rpt_cols]
result = result.sort(['rseq'], ascending=[1])
return result
def get_records_by_acct_status(status, project_id):
query = {'acct_status': status}
if project_id:
query.update({'project_id': project_id})
captures = db.Capture.query(paginate=False, **query)
df = pd.DataFrame(list(captures))
result = df.sort(['project_id', 'rseq'], ascending=[1, 1])
result = result[rpt_cols]
return result
def run(args, target_dir):
records, report_title = None, None
print('Generating report...')
if args.upriser:
name_fmt = 'captures-by-upriser-%s.xls'
report_title = name_fmt % args.upriser.replace('/','_')
records = get_records_by_upriser(args.upriser)
elif args.acct_status:
if not args.project_id:
raise Exception("Project Id/Code required.")
name_fmt = 'captures-by-acct-status-%s-%s.xls'
report_title = name_fmt % (args.project_id, datetime.today().strftime('%Y%m%d'))
records = get_records_by_acct_status(args.acct_status, args.project_id)
# write out file
if records.index.size > 0:
filename = os.path.join(target_dir, report_title)
writer = pd.ExcelWriter(filename)
records.to_excel(writer)
writer.save()
print('success: report written')
if __name__ == '__main__':
# define parser
parser = argparse.ArgumentParser(description="Report Generation Script")
add = parser.add_argument
add('-u', '--upriser', help="Upriser code")
add('-p', '--project-id', help="Project code")
add('-a', '--acct-status', help="Account status")
if not os.path.exists(REPORT_DIR):
os.makedirs(REPORT_DIR)
args = parser.parse_args()
run(args, REPORT_DIR)
|
import matplotlib.pyplot as plt
class Imageprocessor:
def load(path):
img = plt.imread(path)
print ("Loading image of dimensions " + str(len(img[0])) + ' x ' + str(len(img[1])))
return img
def display(path):
plt.imshow(path)
plt.show
arr = Imageprocessor.load("42AI.png")
Imageprocessor.display(arr) |
import numpy as np
import random
homeNum = 1 # 车场个数
carNum = 3 # 车型个数
clientNum = 5 # 客户个数
garbageNum = 4 # 垃圾种类数
chargerNum = 3 # 充电桩个数
# 每个客户的垃圾重量规格矩阵
clientWeightMatrix = np.zeros(shape=(clientNum, garbageNum))
# 每个客户的时间窗
clientTimeWindow = np.zeros(shape=(clientNum, 2))
# 每个客户需要的服务时间
clientServeTime = np.zeros(shape=(clientNum, 2))
# 每种车型的垃圾容量矩阵
collectorMatrix = np.zeros(shape=(carNum, garbageNum))
# 每种车型工作时长
carServeTime = np.zeros(shape=(carNum, 1))
# 每种车型电池规格
carPowerCapacity = np.zeros(shape=(carNum, 1))
# 车子运行速度
moveSpeed = 1
# 充电速度
chargeSpeed = 1
antNum = 10 # 蚂蚁个数
times = 100 # 迭代次数
# 节点个数,车场+客户+充电桩
nodeNum = homeNum + clientNum + chargerNum
# 距离矩阵(边矩阵 nodeNum * nodeNum),第0个代表车场,第1到homeNum个为客户,第homeNum+1到nodeNum-1为充电桩
distanceMatrix = np.zeros(shape=(nodeNum, nodeNum))
# 信息素浓度矩阵,同上
pheromoneMatrix = np.zeros(shape=(nodeNum, nodeNum))
# 每个客户点最近距离的充电桩
leastCloseChargerList = np.zeros(shape=(clientNum, 1))
# 当前车型重量矩阵
curCarWegithMatrix = np.zeros(shape=(1, garbageNum))
# 当前车型号
curCarIndex = 0
# 蚂蚁行走路径
route = []
# 移动速度
move_speed = 1;
# 充电速度
charge_speed = 1;
# 计算重量备选集,表示当前能够去服务的客户点,只考虑重量约束
def getAllowedWeightList(leftList, clientWeightMatrix, curCarWegithMatrix, curCarIndex):
resList = []
for i in range(len(leftList)):
clientId = leftList[i];
realClientId = clientId - homeNum;
can = True;
for j in range(garbageNum):
if curCarWegithMatrix[0][j] + clientWeightMatrix[realClientId][j] > collectorMatrix[curCarIndex][j]:
can = False;
break;
if can:
resList.append(clientId)
return resList;
# 计算时间窗约束备选集1, 从当前点直接去下一个客户点
def getAllowedTimeList1(leftList, curTime, curPosition, clientTimeWindow, distanceMatrix, v):
resList = []
for i in range(len(leftList)):
clientId = leftList[i]
realClientId = clientId - homeNum;
expandTime = distanceMatrix[curPosition][clientId] / v;
if curTime + expandTime <= clientTimeWindow[realClientId][1]:
resList.append(clientId)
return resList;
# 计算时间窗约束备选集2,从当前点去最近充电桩,然后去下一个客户点
def getAllowedTimeList2(leftList, curtimme, curPower, curPosition, curCarIndex, clientTimeWindow, distanceMatrix, v,
chargeV):
resList = []
for i in range(len(leftList)):
clientId = leftList[i]
realClientId = clientId - homeNum
leastCloseChargerId = leastCloseChargerList[realClientId];
distance = distanceMatrix[curPosition][leastCloseChargerId] + distanceMatrix[leastCloseChargerId][clientId];
chargePower = carPowerCapacity[curCarIndex] * 0.8 + calPower(
distanceMatrix[curPosition][leastCloseChargerId]) - curPower;
chargeTime = chargePower / chargeV;
expandTime = distance / v + chargeTime;
if expandTime + curtimme <= clientTimeWindow[realClientId][1]:
resList.append(clientId)
return resList;
# 计算电量备选集1, 从当前点直接去客户点
def getAllowedPowerList1(leftList, curPosition, curPower, distanceMatrix):
resList = []
for i in range(len(leftList)):
clientId = leftList[i];
distance = distanceMatrix[curPosition][clientId] + distanceMatrix[0][clientId];
if curPower >= calPower(distance):
resList.append(clientId);
return resList;
# 计算电量备选集2,从当前点(不为车场和充电桩),先去最近的充电桩,然后再去客户点
def getAllowedPowerList2(leftList, curPosition, curPower, distanceMatrix):
resList = []
for i in range(len(leftList)):
clientId = leftList[i];
realClientId = clientId - homeNum;
# 获取最近的充电桩
leastCloseChargerId = leastCloseChargerList[realClientId];
distance = distanceMatrix[curPosition][leastCloseChargerId];
if curPower >= calPower(distance):
resList.append(distance)
return resList;
# 计算耗电量
def calPower(x):
a = 1;
b = 1;
return a * x + b;
# 计算Transition rule
alpha = 1;
beta = 1;
gamma = 1;
# 计算转移概率,并且根据轮盘赌返回一个客户点
def getClientIdByTransitionRule(resList, curPosition):
xi_list = [];
for clientId in resList:
# 节约数
mu = distanceMatrix[curPosition][0] + distanceMatrix[0][clientId] - distanceMatrix[curPosition][clientId];
xi = pheromoneMatrix[curPosition][clientId] ** alpha + \
distanceMatrix[curPosition][clientId] ** beta + \
mu ** gamma
last_xi = 0;
if len(xi_list) > 0:
last_xi = xi_list[-1];
xi_list.append(last_xi + xi);
start = 0;
end = xi_list[-1];
rand_xi = random.uniform(start, end);
for i in range(len(xi_list)-1):
if xi_list[i] <= rand_xi and rand_xi < xi_list:
return resList[i];
return resList[-1];
# 初始化
def initial():
print("initializing");
carNumMatrix = np.zeros(shape=(carNum, 1));
print(carNumMatrix);
def process_when_is_depot(leftList, carFistVisited, curCarWeightMatrix, curCarIndex, curTime):
curPosition = 0; # 代表当前在车场
if carFistVisited == True:
# 表示当前车辆第一次访问车场
nextClientId = getClientIdByTransitionRule(leftList, curPosition);
return nextClientId;
else:
allowed_list = getAllowedTimeList1(leftList, curTime, curPosition, clientTimeWindow, distanceMatrix, move_speed)
if len(allowed_list) == 0:
## 方案不可行
return -1;
else:
nextClientId = getClientIdByTransitionRule(allowed_list, curPosition);
return nextClientId;
def process_when_is_customer(leftList, curCarIndex, curCarWeightMatrix, curTime, curPosition, curPower):
weight_allowed_list = getAllowedWeightList(leftList, clientWeightMatrix, curCarWeightMatrix, curCarIndex);
if len(weight_allowed_list) == 0:
# 只能返回车场
return 0;
else:
# 时间窗约束, 直接从当前客户点到下一个客户点
time_allowed_list1 = getAllowedTimeList1(weight_allowed_list, curTime, curPosition, clientTimeWindow, distanceMatrix, move_speed);
if len(time_allowed_list1) > 0:
nextCientId = getClientIdByTransitionRule(time_allowed_list1, curPosition);
return nextCientId;
else:
time_allowed_list2 = getAllowedTimeList2(weight_allowed_list, curTime, curPower, curPosition, curCarIndex
,clientTimeWindow, distanceMatrix, move_speed, charge_speed);
if len(time_allowed_list2) > 0:
nextClientId = getClientIdByTransitionRule(time_allowed_list2, curPosition);
return nextClientId;
else:
# 返回车场
return 0;
if __name__ == "__main__":
initial();
|
from wtforms import Form, SelectField, SubmitField, validators, ValidationError, DateField
from wtforms_components import DateTimeField, DateRange
from datetime import datetime
cities = [('Vancouver', 'Vancouver'), ('Portland', 'Portland'), ('San Francisco', 'San Francisco'),
('Seattle', 'Seattle'), ('Los Angeles', 'Los Angeles'), ('San Diego', 'San Diego'),
('Las Vegas', 'Las Vegas'), ('Phoenix', 'Phoenix'), ('Albuquerque', 'Albuquerque'),
('Denver', 'Denver'), ('San Antonio', 'San Antonio'), ('Dallas', 'Dallas'), ('Houston', 'Houston'),
('Kansas City', 'Kansas City'), ('Minneapolis', 'Minneapolis'), ('Saint Louis', 'Saint Louis'),
('Chicago', 'Chicago'), ('Nashville', 'Nashville'), ('Indianapolis', 'Indianapolis'), ('Atlanta', 'Atlanta'),
('Detroit', 'Detroit'), ('Jacksonville', 'Jacksonville'), ('Charlotte', 'Charlotte'), ('Miami', 'Miami'),
('Pittsburgh', 'Pittsburgh'), ('Toronto', 'Toronto'), ('Philadelphia', 'Philadelphia'),
('New York', 'New York'), ('Montreal', 'Montreal'), ('Boston', 'Boston'), ('Beersheba', 'Beersheba'),
('Tel Aviv District', 'Tel Aviv District'), ('Eilat', 'Eilat'), ('Haifa', 'Haifa'),
('Nahariyya', 'Nahariyya'), ('Jerusalem', 'Jerusalem')]
'''mytest = [('Vancouver', 'Vancouver'), ('Portland', 'Portland'), ('San Francisco', 'San Francisco')]
mytest2 = [(0, 'Vancouver'), (1, 'Portland'), (2, 'San Francisco')]
print(type(mytest[0][0]))
print(type(mytest[0][1]))'''
class InputForm(Form):
city = SelectField(label='City', coerce=str, choices=cities)
date = DateField(label='Date (Y-m-d)', format='%Y-%m-%d' , validators=[DateRange(min=datetime(2017, 1, 1),max=datetime(2017, 11, 30))])
submit = SubmitField('Submit') |
#!/usr/bin/env python3
import sys
import os
import shutil
palPath = r"{{palPath}}"
def printUsage():
print("Usage: pal [-h] command\n")
print("Quickly create new pal projects.\n")
print("Available commands:")
print(" new Create a new pal project in the current directory.")
print(" help Print this help message.")
print(" install Install pal on your system.")
print(" update Update to the latest pal library sources (on this machine).")
print()
print("Optional arguments:")
print(" -h Print this help message.")
def copyPalFilesToCurrentDir(files):
overwriteAll = False
for file in files:
print(f'Copying {os.path.join(palPath, file)} to {file}')
source = os.path.join(palPath, file)
dest = file
if os.path.exists(file):
overwrite = overwriteAll
if not overwriteAll:
while True:
answer = input(f'File {file} already present, do you want to overwrite it? [(y)es, (n)o overwrite, yes to (a)ll] ')
if len(answer) == 1:
if answer == 'y':
overwrite = True
break
elif answer == 'n':
overwrite = False
break
elif answer == 'a':
overwrite = True
overwriteAll = True
break
print('Please answer y, n or a')
if overwrite:
if os.path.isdir(file):
shutil.rmtree(file)
else:
os.remove(file)
if os.path.isdir(source):
shutil.copytree(source, dest)
else:
shutil.copy(source, dest)
if len(sys.argv) < 2:
print("Error: expected a command.")
printUsage()
exit()
if sys.argv[1] == '-h' or sys.argv[1] == 'help':
printUsage()
elif sys.argv[1] == "new":
installFiles = ["main.cpp", "makefile", "pal", "pal.sln", "pal.vcxproj", "pal.vcxproj.filters", "pal.vcxproj.user", "windows"]
copyPalFilesToCurrentDir(installFiles)
elif sys.argv[1] == "update":
installFiles = ["makefile", "pal"]
answer = input("Updating pal will overwrite the pal/ sources and makefile. Proceed? [y/n]: ")
if (answer.lower() == "y"):
copyPalFilesToCurrentDir(installFiles)
else:
print("Update cancelled.")
elif sys.argv[1] == "install":
f = open('pal.py', 'r')
text = f.read()
f.close()
installationPath = os.path.join(os.getcwd(), 'installation')
text = text.replace("{{" + "palPath" + "}}", os.getcwd())
if os.path.exists('installation'):
shutil.rmtree('installation')
os.mkdir('installation')
f = open(os.path.join('installation', 'pal.py'), 'w')
f.write(text)
f.close()
f = open(os.path.join('installation', 'pal.bat'), 'w')
f.write(f"python {installationPath}\\pal.py %*")
f.close()
print("To finish installation add the following to you Path environment vairable:")
print(installationPath)
elif sys.argv[1] == "example":
if (len(sys.argv) < 3):
print("Usage: pal example <example name>")
exit(1)
installFiles = ["makefile", "pal"]
exampleName = sys.argv[2]
exampleFolder = os.path.join(palPath, "examples", exampleName)
if not os.path.exists(exampleFolder):
print(f"Error: could not find the example {exampleName}. Please make sure that you have spelled the name correctly with correct capitalization. See {os.path.join(palPath, 'examples')} for available examples.")
exit(1)
exampleFilesFilePath = os.path.join(exampleFolder, "examplefiles")
if not os.path.exists(exampleFilesFilePath):
print(f"Error: could not find the 'examplefiles' file in {exampleName}. The example is broken. Please report this issue on GitHub.")
exit(1)
exampleFilesFile = open(exampleFilesFilePath, 'r')
exampleFiles = exampleFilesFile.readlines()
exampleFilesFile.close()
copyPalFilesToCurrentDir(installFiles)
for file in exampleFiles:
file = file.strip()
if file.startswith("#"):
continue
if file == "":
continue
path = os.path.join(exampleFolder, file)
if not os.path.exists(path):
print(f"Error: could not find the file '{path}' specified in '{exampleFilesFilePath}.")
exit(1)
print(f'Copying {path} to {file}')
os.system(f'cp -r {path} {file}')
else:
print(f"Error: unrecognized command {sys.argv[1]}.")
printUsage() |
#import the random
#import random
#winning_number= random.randint(0,10)
#print(winning_number)
#num_guesses = 5
#user_won = False
#while num_guesses != 0 and user_won == False:
# user_guess = int(input("Enter your guess: "))
# if user_guess == winning_number:
# print("Hey, you won!")
# user_won = True
# else:
# num_guesses -= 1
# if num_guesses == 0:
# print("Nope, you lost.")
# else:
# print("Nope, try again")
import random
winning_number = random.randint(0, 100)
total_guesses = 10
guesses = []
user_won = False
guesses_taken = 0
while guesses_taken < total_guesses and user_won == False:
user_guess = int(input("Enter your guess: "))
guesses.append(user_guess)
guesses_taken += 1
if user_guess == winning_number:
user_won = True
print("Congrats! You won!")
elif abs(user_guess - winning_number) <= 5:
print("Hot!")
elif abs(user_guess - winning_number) <= 10:
print("Warm!")
else:
print("Cold :(")
print("You took", guesses_taken)
print("Your guesses were: ")
print(guesses)
|
"""
Test configuration loading
@author aevans
"""
import os
from nlp_server.config import load_config
def test_load_config():
"""
Test loading a configuration
"""
current_dir = os.path.curdir
test_path = os.path.sep.join([current_dir, 'data', 'test_config.json'])
cfg = load_config.load_config(test_path)
assert cfg is not None
assert cfg.use_gpu is False
|
#!/usr/bin/env phthon
import MySQLdb, os, commands,re, time
def get_db_con(dbname="resource_pool"):
DB_HOST="localhost"
DB_USER="root"
DB_PASS="virtcompute"
try:
conn=MySQLdb.connect(host=DB_HOST,user=DB_USER,passwd=DB_PASS,db=dbname)
except MySQLdb.Error,e:
print "Mysql Error %d: %s" % (e.args[0], e.args[1])
return
return conn
def get_res_info(con,queuename):
''' get an queue ifno by its name, ie [name,min,running,max]'''
res_info = []
con.ping(True)
cursor = con.cursor()
cursor.execute("select name,min,max,running,available,reserve_time from resource where name = '%s'"%queuename)
rows = cursor.fetchall()
cursor.close()
for row in rows:
print row
res_info.append(row[0])
res_info.append(row[1])
res_info.append(row[2])
res_info.append(row[3])
res_info.append(row[4])
res_info.append(row[5])
return res_info
def update_res_running(con,queuename,running):
con.ping(True)
cursor = con.cursor()
cursor.execute("update resource set running = %s where name='%s'"%(running,queuename))
cursor.close()
def update_res_avail(con,queuename,avail,allocate_time):
con.ping(True)
cursor = con.cursor()
cursor.execute("update resource set available=%s,reserve_time='%s' where name='%s'"%(avail,allocate_time,queuename))
cursor.close()
if __name__ == '__main__':
con = get_db_con()
|
from collections import defaultdict
import string
S = input()
letters = defaultdict(lambda: False)
for s in S:
letters[s] = True
ans = 'None'
for l in string.ascii_lowercase:
if letters[l] == False:
ans = l
break
print(ans)
|
from tkinter import *
from tkinter.ttk import Combobox, Scrollbar
import tkinter.ttk as ttk
import datetime
import mysql.connector as mysql
class GymManagementSystem:
def __init__(self,root):
self.root=root
self.root.title("GYM MANAGEMENT PROJECT")
self.root.geometry("1300x660+0+0")
self.memberid_var=StringVar()
self.name_var=StringVar()
self.Phnno_var=StringVar()
self.Gender_var=StringVar()
self.Address1_var=StringVar()
self.Address2_var=StringVar()
self.Height_var=StringVar()
self.Weight_var=StringVar()
self.Datejoining=StringVar()
self.Dateexpired=StringVar()
self.Identification=StringVar()
self.BloodG=StringVar()
self.Fees=StringVar()
self.Paid=StringVar()
self.Balance=StringVar()
self.Referral=StringVar()
def savedata():
conn = mysql.connect(user='root', password='root', host='localhost', database="gymdb")
cur = conn.cursor()
cur.execute("insert into gym_table values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)",
(self.memberid_var.get(), self.name_var.get(), self.Phnno_var.get(),
self.Gender_var.get(), self.Address1_var.get(),
self.Address2_var.get(), self.Height_var.get(),
self.Weight_var.get(), self.Datejoining.set(datetime.datetime.today()), self.Dateexpired.set(datetime.datetime.today()+datetime.timedelta(days=90))
, self.Identification.get(), self.BloodG.get(),
self.Fees.get(), self.Paid.get(),
self.Balance.get(), self.Referral.get()))
print("Data inserted...")
conn.commit()
fetch_data()
conn.close()
def showData():
self.txtBox.delete("1.0", 'end')
self.txtBox.insert(END, "MemberId\t\t" + self.memberid_var.get() + "\n")
self.txtBox.insert(END, "Name\t\t" + self.name_var.get() + "\n")
self.txtBox.insert(END, "Phnno\t\t" + self.Phnno_var.get() + "\n")
self.txtBox.insert(END, "Gender\t\t" + self.Gender_var.get() + "\n")
self.txtBox.insert(END, "Address1\t\t" + self.Address1_var.get() + "\n")
self.txtBox.insert(END, "Address2\t\t" + self.Address2_var.get() + "\n")
self.txtBox.insert(END, "Height\t\t" + self.Height_var.get() + "\n")
self.txtBox.insert(END, "Weight\t\t" + self.Weight_var.get() + "\n")
self.txtBox.insert(END, "Datejoining\t\t" + self.Datejoining.get() + "\n")
self.txtBox.insert(END, "Dateexpired\t\t" + self.Dateexpired.get() + "\n")
self.txtBox.insert(END, "Identification\t\t" + self.Identification.get() + "\n")
self.txtBox.insert(END, "BloodG\t\t" + self.BloodG.get() + "\n")
self.txtBox.insert(END, "Fees\t\t" + self.Fees.get() + "\n")
self.txtBox.insert(END, "Paid\t\t" + self.Paid.get() + "\n")
self.txtBox.insert(END, "Balance\t\t" + self.Balance.get() + "\n")
self.txtBox.insert(END, "Referral\t\t" + self.Referral.get() + "\n")
def update_data():
conn = mysql.connect(user='root', password='root', host='localhost', database="gymdb")
cur = conn.cursor()
cur.execute(
"update gym_table set name=%s,Phnno=%s,Gender=%s,Address1=%s,Address2=%s,Height=%s,Weight=%s,Datejoining=%s,Dateexpired=%s,Identification=%s,BloodG=%s,Fees=%s,Paid=%s,Balance=%s,Referral=%s where memberid=%s",
(self.name_var.get(), self.Phnno_var.get(),
self.Gender_var.get(), self.Address1_var.get(),
self.Address2_var.get(), self.Height_var.get(),
self.Weight_var.get(), self.Datejoining.get(), self.Dateexpired.get()
, self.Identification.get(), self.BloodG.get(),
self.Fees.get(), self.Paid.get(),
self.Balance.get(), self.Referral.get(),self.memberid_var.get()))
print("Data updated...")
conn.commit()
fetch_data()
conn.close()
def delete_Data():
conn = mysql.connect(user='root', password='root', host='localhost', database="gymdb")
cur = conn.cursor()
cur.execute("delete from gym_table where memberid=%s", (self.memberid_var.get(),))
print("Data Deleted...")
conn.commit()
reset_data()
fetch_data()
conn.close()
def reset_data():
self.txtBox.delete("1.0", 'end')
self.memberid_var.set("")
self.name_var.set("")
self.Phnno_var.set("")
self.Gender_var.set("")
self.Address1_var.set("")
self.Address2_var.set("")
self.Height_var.set("")
self.Weight_var.set("")
self.Datejoining.set("")
self.Dateexpired.set("")
self.Identification.set("")
self.BloodG.set("")
self.Fees.set("")
self.Paid.set("")
self.Balance.set("")
self.Referral.set("")
def ext():
self.root.destroy()
def fetch_data():
conn = mysql.connect(user='root', password='root', host='localhost', database="gymdb")
cur = conn.cursor()
cur.execute("select * from gym_table")
rows = cur.fetchall()
if len(rows) != 0:
self.library_table.delete(*self.library_table.get_children())
for i in rows:
self.library_table.insert("", END, values=i)
conn.commit()
else:
self.library_table.delete(*self.library_table.get_children())
conn.close()
def get_cursor(event=""):
cur_row=self.library_table.focus()
content=self.library_table.item(cur_row)
row=content['values']
self.memberid_var.set(row[0])
self.name_var.set(row[1])
self.Phnno_var.set(row[2])
self.Gender_var.set(row[3])
self.Address1_var.set(row[4])
self.Address2_var.set(row[5])
self.Height_var.set(row[6])
self.Weight_var.set(row[7])
self.Datejoining.set(row[8])
self.Dateexpired.set(row[9])
self.Identification.set(row[10])
self.BloodG.set(row[11])
self.Fees.set(row[12])
self.Paid.set(row[13])
self.Balance.set(row[14])
self.Referral.set(row[15])
lbltitle = Label(self.root, text="GYM MANAGEMENT SYSTEM", bg="black", fg="white", bd=13,
relief=RIDGE, font=("Comic Sans MS", 30), padx=2, pady=6)
lbltitle.pack(side=TOP, fill=X)
frame = Frame(self.root, bd=12, relief=RIDGE, bg="#918e86", padx=20)
frame.place(x=0, y=90, width=1365, height=400)
#######Left frame########
DataFrameLeft = LabelFrame(frame, text="Gym membership info", bg="#918e86",
fg="black", bd=10, relief=RIDGE, font=("Cambria", 15, "bold"), padx=2,
pady=6)
DataFrameLeft.place(x=0, y=3, width=650, height=350)
lblMember = Label(DataFrameLeft, font=("Cambria", 12), text="Member Id -",bg="#918e86", padx=2, pady=6)
lblMember.grid(row=0, column=0, sticky=W)
txtMember = Entry(DataFrameLeft, font=("Cambria", 12), width=20, textvariable=self.memberid_var)
txtMember.grid(row=0, column=1)
lblname = Label(DataFrameLeft, font=("Cambria", 12), text="Name -", bg="#918e86", padx=2, pady=6)
lblname.grid(row=1, column=0, sticky=W)
txtname = Entry(DataFrameLeft, font=("Cambria", 12), width=20, textvariable=self.name_var)
txtname.grid(row=1, column=1)
lblphnno = Label(DataFrameLeft, font=("Cambria", 12), text="Phn no -", bg="#918e86", padx=2, pady=6)
lblphnno.grid(row=2, column=0, sticky=W)
txtphnno = Entry(DataFrameLeft, font=("Cambria", 12), width=20, textvariable=self.Phnno_var)
txtphnno.grid(row=2, column=1)
lblgender = Label(DataFrameLeft, font=("Cambria", 12), text="Gender -", bg="#918e86", padx=2, pady=6)
lblgender.grid(row=3, column=0, sticky=W)
txtgender = Entry(DataFrameLeft, font=("Cambria", 12), width=20, textvariable=self.Gender_var)
txtgender.grid(row=3, column=1)
lblAddress1 = Label(DataFrameLeft, font=("Cambria", 12), text="Address1 -", bg="#918e86", padx=2, pady=6)
lblAddress1.grid(row=4, column=0, sticky=W)
txtAddress1 = Entry(DataFrameLeft, font=("Cambria", 12), width=20, textvariable=self.Address1_var)
txtAddress1.grid(row=4, column=1)
lblAddress2 = Label(DataFrameLeft, font=("Cambria", 12), text="Address2 -", bg="#918e86", padx=2, pady=6)
lblAddress2.grid(row=5, column=0, sticky=W)
txtAddress2 = Entry(DataFrameLeft, font=("Cambria", 12), width=20, textvariable=self.Address2_var)
txtAddress2.grid(row=5, column=1)
lblHeight = Label(DataFrameLeft, font=("Cambria", 12), text="Height -", bg="#918e86", padx=2, pady=6)
lblHeight.grid(row=6, column=0, sticky=W)
txtHeight = Entry(DataFrameLeft, font=("Cambria", 12), width=20, textvariable=self.Height_var)
txtHeight.grid(row=6, column=1)
lblWeight = Label(DataFrameLeft, font=("Cambria", 12), text="Weight -", bg="#918e86", padx=2, pady=6)
lblWeight.grid(row=7, column=0, sticky=W)
txtWeight = Entry(DataFrameLeft, font=("Cambria", 12), width=20, textvariable=self.Weight_var)
txtWeight.grid(row=7, column=1)
lblDatejoining = Label(DataFrameLeft, font=("Cambria", 12), text="Datejoining -", bg="#918e86", padx=2, pady=6)
lblDatejoining.grid(row=0, column=2, sticky=W)
txtDatejoining = Entry(DataFrameLeft, font=("Cambria", 12), width=20, textvariable=self.Datejoining)
txtDatejoining.grid(row=0, column=3)
lblDateexpired = Label(DataFrameLeft, font=("Cambria", 12), text="Dateexpired -", bg="#918e86", padx=2, pady=6)
lblDateexpired.grid(row=1, column=2, sticky=W)
txtDateexpired = Entry(DataFrameLeft, font=("Cambria", 12), width=20, textvariable=self.Dateexpired)
txtDateexpired.grid(row=1, column=3)
lblIdentification = Label(DataFrameLeft, font=("Cambria", 12), text="Identification marks -", bg="#918e86", padx=2, pady=6)
lblIdentification.grid(row=2, column=2, sticky=W)
txtIdentification = Entry(DataFrameLeft, font=("Cambria", 12), width=20, textvariable=self.Identification)
txtIdentification.grid(row=2, column=3)
lblBloodG = Label(DataFrameLeft, font=("Cambria", 12), text="BloodGroup -", bg="#918e86",padx=2, pady=6)
lblBloodG.grid(row=3, column=2, sticky=W)
txtBloodG = Entry(DataFrameLeft, font=("Cambria", 12), width=20, textvariable=self.BloodG)
txtBloodG.grid(row=3, column=3)
lblFees = Label(DataFrameLeft, font=("Cambria", 12), text="Fees -", bg="#918e86", padx=2, pady=6)
lblFees.grid(row=4, column=2, sticky=W)
txtFees = Entry(DataFrameLeft, font=("Cambria", 12), width=20, textvariable=self.Fees)
txtFees.grid(row=4, column=3)
lblPaid = Label(DataFrameLeft, font=("Cambria", 12), text="Paid -", bg="#918e86", padx=2, pady=6)
lblPaid.grid(row=5, column=2, sticky=W)
txtPaid = Entry(DataFrameLeft, font=("Cambria", 12), width=20, textvariable=self.Paid)
txtPaid.grid(row=5, column=3)
lblBalance = Label(DataFrameLeft, font=("Cambria", 12), text="Balance -", bg="#918e86", padx=2, pady=6)
lblBalance.grid(row=6, column=2, sticky=W)
txtBalance = Entry(DataFrameLeft, font=("Cambria", 12), width=20, textvariable=self.Balance)
txtBalance.grid(row=6, column=3)
lblReferral = Label(DataFrameLeft, font=("Cambria", 12), text="Referral -", bg="#918e86", padx=2, pady=6)
lblReferral.grid(row=7, column=2, sticky=W)
txtReferral = Entry(DataFrameLeft, font=("Cambria", 12), width=20, textvariable=self.Referral)
txtReferral.grid(row=7, column=3)
#######Right frame########
DataFrameRight = LabelFrame(frame, text="Member Info", bg="#918e86", fg="black", bd=10,
relief=RIDGE, font=("Cambria", 15, "bold"), padx=2, pady=6)
DataFrameRight.place(x=651, y=3, width=650, height=350)
self.txtBox = Text(DataFrameRight, font=("Comic Sans MS", 12), width=60, height=12)
self.txtBox.grid(row=0, column=2,padx=10)
#####button frame####
Framebutton = Frame(self.root, bg="#918e86", bd=10, relief=RIDGE, padx=20)
Framebutton.place(x=0, y=490, width=1365, height=70)
btnAddData = Button(Framebutton, text='Add data', font=("Comic Sans MS", 10, "bold"), width=26, bg="black",
fg="white", command=savedata)
btnAddData.grid(row=0, column=0,pady=6)
btnShowData = Button(Framebutton, text='Show data', font=("Comic Sans MS", 10, "bold"), width=26, bg="black",
fg="white", command=showData)
btnShowData.grid(row=0, column=1)
btnUpdateData = Button(Framebutton, text='Update', font=("Comic Sans MS", 10, "bold"), width=26, bg="black",
fg="white", command=update_data)
btnUpdateData.grid(row=0, column=2)
btnDeleteData = Button(Framebutton, text='Delete data', font=("Comic Sans MS", 10, "bold"), width=26,bg="black",
fg="white", command=delete_Data)
btnDeleteData.grid(row=0, column=3)
btnResetData = Button(Framebutton, text='Reset', font=("Comic Sans MS", 10, "bold"), width=26, bg="black",
fg="white", command=reset_data)
btnResetData.grid(row=0, column=5)
btnExit = Button(Framebutton, text='Exit', font=("Comic Sans MS", 10, "bold"), width=26, bg="black",
fg="white",command=ext)
btnExit.grid(row=0, column=6)
#####information frame####
FrameDetails = Frame(self.root, bg="#918e86", bd=10, relief=RIDGE, padx=20)
FrameDetails.place(x=0, y=560, width=1365, height=130)
Table_frame = Frame(FrameDetails, bg="#918e86", bd=5, relief=RIDGE)
Table_frame.place(x=0, y=5, width=1300, height=100)
xscroll = Scrollbar(Table_frame, orient=HORIZONTAL)
yscroll = Scrollbar(Table_frame, orient=VERTICAL)
self.library_table = ttk.Treeview(Table_frame, column=("memberid", "name", "Phnno", "Gender", "Address1",
"Address2", "Height", "Weight", "Datejoining", "Dateexpired",
"Identification",
"BloodG", "Fees", "Paid", "Balance",
"Referral"), xscrollcommand=xscroll.set,
yscrollcommand=yscroll.set)
xscroll.pack(side=BOTTOM, fill=X)
yscroll.pack(side=RIGHT, fill=Y)
xscroll.config(command=self.library_table.xview)
yscroll.config(command=self.library_table.yview)
self.library_table.heading("memberid", text="MemberID")
self.library_table.heading("name", text="Name")
self.library_table.heading("Phnno", text="Phnno")
self.library_table.heading("Gender", text="Gender")
self.library_table.heading("Address1", text="Address1")
self.library_table.heading("Address2", text="Address2")
self.library_table.heading("Height", text="Height")
self.library_table.heading("Weight", text="Weight")
self.library_table.heading("Datejoining", text="Datejoining")
self.library_table.heading("Dateexpired", text="Dateexpired")
self.library_table.heading("Identification", text="Identification")
self.library_table.heading("BloodG", text="BloodG")
self.library_table.heading("Fees", text="Fees")
self.library_table.heading("Paid", text="Paid")
self.library_table.heading("Balance", text="Balance")
self.library_table.heading("Referral", text="Referral")
self.library_table["show"] = "headings"
self.library_table.pack(fill=BOTH, expand=1)
fetch_data()
self.library_table.bind("<ButtonRelease-1>", get_cursor)
if __name__=='__main__':
root=Tk()
obj=GymManagementSystem(root)
root.mainloop()
|
print("**********LATIHAN1*******")
print("program menghitung laba perusahan dengan modal awal 100juta")
print("")
print("Note")
print("Bulan pertama dan ke 2 = 0%")
print("pada bulan ke 3 = 1%")
print("pada bulan ke 5 = 5%")
print("pada bulan ke 8 = 2%")
print("")
a=1000000
for x in range(1,9):
if(x>1 and x<2):
print("laba bulan ke-",x,":",b )
if(x>3 and x<=4):
c = a&0,1
print("laba bulan ke-",x,":",c )
if(x>5 and x<=7):
d = a&0,5
print("laba bulan ke-",x,":",d )
if(x==0):
c= a&0,2
print("laba bulan ke-",x,":",e )
total= b+b+c+c+d+d+d+e
print("total laba didapat adalah",total)
|
# Imports the monkeyrunner modules used by this program
from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice
device = None
def touch(x, y):
global d
device.touch(x, y, "DOWN_AND_UP")
def fight():
global d
invoke_hero()
MonkeyRunner.sleep(0.5)
call_all_skill()
MonkeyRunner.sleep(0.5)
max_hero_level()
def invoke_hero():
global d
d.touch(1350, 1000, "DOWN_AND_UP") # change to hero
MonkeyRunner.sleep(0.5)
touch_bottom()
def call_all_skill():
global d
d.touch(1200, 1000, "DOWN_AND_UP") # change to monster
MonkeyRunner.sleep(0.5)
touch_bottom()
def max_hero_level():
global d
d.touch(1350, 1000, "DOWN_AND_UP") # change to hero
MonkeyRunner.sleep(0.5)
for _ in range(50):
touch_bottom()
MonkeyRunner.sleep(0.1)
def touch_bottom():
global d
d.touch(250, 900, "DOWN_AND_UP") # 1st hero
d.touch(450, 900, "DOWN_AND_UP") # 2ed hero
d.touch(650, 900, "DOWN_AND_UP") # 3rd hero
d.touch(850, 900, "DOWN_AND_UP") # 4ur hero
d.touch(1050, 900, "DOWN_AND_UP") # 5th hero
if __name__ == '__main__':
global device
# Connects to the current device, returning a MonkeyDevice object
device = MonkeyRunner.waitForConnection()
package = 'jp.co.happyelements.toto'
activity = 'jp.co.happyelements.unity_plugins.MainActivity'
runComponent = package + '/' + activity
device.startActivity(component=runComponent)
MonkeyRunner.sleep(5)
X = float(device.getProperty("display.width"))
Y = float(device.getProperty("display.height"))
# Presses the Menu button
# device.press('KEYCODE_MENU', MonkeyDevice.DOWN_AND_UP)
MonkeyRunner.sleep(10)
touch( int(X/2), int(Y/2))
# Takes a screenshot
result = device.takeSnapshot()
# Writes the screenshot to a file
result.writeToFile('shot1.png','png')
|
import turtle
turtle.pensize(3)
turtle.penup()
turtle.goto(-200, -50)
turtle.pendown()
turtle.circle(40, steps=3)
turtle.penup()
turtle.goto(-100, -50)
turtle.pendown()
turtle.circle(40, steps=4)
turtle.penup()
turtle.goto(0, -50)
turtle.pendown()
turtle.circle(40, steps=5)
turtle.penup()
turtle.goto(100, -50)
turtle.pendown()
turtle.circle(40, steps=6)
turtle.penup()
turtle.goto(200, -50)
turtle.pendown()
turtle.circle(40)
turtle.down() |
# numpyライブラリをインポート
import numpy as np
# 整数型の配列を用意
arr_int32 = np.array([100, 200, 300, 400, 500], dtype=np.int32)
print(arr_int32)
# 浮動小数点型の配列を用意
arr_float = np.array([0.1, 0.2, 0.3, 0.4, 0.5], dtype=np.float64)
print(arr_float)
# 配列通しの計算を + で表現できます。
arr_sum = arr_int32 + arr_float
print(arr_sum) |
# Copyright (c) 2012-2021, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from typing import Optional
from .aws import Action as BaseAction
from .aws import BaseARN
service_name = "AWS Cloud Map"
prefix = "servicediscovery"
class Action(BaseAction):
def __init__(self, action: Optional[str] = None) -> None:
super().__init__(prefix, action)
class ARN(BaseARN):
def __init__(self, resource: str = "", region: str = "", account: str = "") -> None:
super().__init__(
service=prefix, resource=resource, region=region, account=account
)
CreateHttpNamespace = Action("CreateHttpNamespace")
CreatePrivateDnsNamespace = Action("CreatePrivateDnsNamespace")
CreatePublicDnsNamespace = Action("CreatePublicDnsNamespace")
CreateService = Action("CreateService")
DeleteNamespace = Action("DeleteNamespace")
DeleteService = Action("DeleteService")
DeregisterInstance = Action("DeregisterInstance")
DiscoverInstances = Action("DiscoverInstances")
GetInstance = Action("GetInstance")
GetInstancesHealthStatus = Action("GetInstancesHealthStatus")
GetNamespace = Action("GetNamespace")
GetOperation = Action("GetOperation")
GetService = Action("GetService")
ListInstances = Action("ListInstances")
ListNamespaces = Action("ListNamespaces")
ListOperations = Action("ListOperations")
ListServices = Action("ListServices")
ListTagsForResource = Action("ListTagsForResource")
RegisterInstance = Action("RegisterInstance")
TagResource = Action("TagResource")
UntagResource = Action("UntagResource")
UpdateHttpNamespace = Action("UpdateHttpNamespace")
UpdateInstanceCustomHealthStatus = Action("UpdateInstanceCustomHealthStatus")
UpdateInstanceHeartbeatStatus = Action("UpdateInstanceHeartbeatStatus")
UpdatePrivateDnsNamespace = Action("UpdatePrivateDnsNamespace")
UpdatePublicDnsNamespace = Action("UpdatePublicDnsNamespace")
UpdateService = Action("UpdateService")
|
# Create a list where each element is an individual base of DNA.
# Make the array 15 bases long.
bases = ['A', 'T', 'T', 'C', 'G', 'G', 'T', 'C', 'A', 'T', 'G', 'C', 'T', 'A', 'A']
# Print the length of the list
print("DNA sequence length:", len(bases))
# Create a for loop to output every base of the sequence on a new line.
print("All bases:")
for base in bases:
print(base)
# Create a while loop that starts at the third base in the sequence
# and outputs every third base until the 12th.
print("Every 3rd base:")
pos = 2
while pos <= 12:
print(pos, bases[pos])
pos += 3
|
from abc import ABC, abstractmethod
import traceback
class ClientActionException(Exception):
def __init__(self, message = ""):
self.message = message
super().__init__(self.message)
class ServerActionException(Exception):
def __init__(self, message = ""):
self.message = message
super().__init__(self.message)
class Action(ABC):
def __init__(self, sock, params, state, logger):
self.sock = sock
self.params = params
self.state = state
self.logger = logger
# parse all necessary params before execution
def parse(self):
pass
# execute the current action
@abstractmethod
def execute(self):
pass
# analyze the result and the state and do some additional actions based on it
def analyze_result(self):
pass
# call parse, execute and analyze_result functions one by one
def do_action(self):
self.parse()
self.execute()
self.analyze_result()
# default function to analyze answer of server
def wait_server_answer(self, analyze_answer = True, abort_if_fail = True):
response = self.sock.recv(1024).decode("utf-8")
self.logger.info("Server answer: {}".format(response))
if analyze_answer:
self.state.prev_action_done = (response == "done")
if not self.state.prev_action_done:
if response == "abort":
self.state.is_aborted_server = True
raise ServerActionException("Server sent abort status")
elif response == "failed":
if abort_if_fail:
raise ServerActionException("Action failed on server side")
else:
raise ServerActionException("Unknown server status: {}".format(response))
# decorator to send answer to client
def server_action_decorator(func):
def server_action_decorator_impl(self):
try:
result = func(self)
if result:
self.sock.send("done".encode("utf-8"))
else:
self.sock.send("failed".encode("utf-8"))
except Exception as e:
self.logger.error("Failed to execute action: {}".format(str(e)))
self.logger.error("Traceback: {}".format(traceback.format_exc()))
self.sock.send("failed".encode("utf-8"))
return server_action_decorator_impl
|
# Foremast - Pipeline Tooling
#
# Copyright 2016 Gogo, LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Add the appropriate ELB Listeners."""
import logging
from ..utils import get_env_credential
LOG = logging.getLogger(__name__)
def format_listeners(elb_settings=None, env='dev'):
"""Format ELB Listeners into standard list.
Args:
elb_settings (dict): ELB settings including ELB Listeners to add,
e.g.::
# old
{
"certificate": null,
"i_port": 8080,
"lb_port": 80,
"subnet_purpose": "internal",
"target": "HTTP:8080/health"
}
# new
{
"ports": [
{
"instance": "HTTP:8080",
"loadbalancer": "HTTP:80"
},
{
"certificate": "cert_name",
"instance": "HTTP:8443",
"loadbalancer": "HTTPS:443"
}
],
"subnet_purpose": "internal",
"target": "HTTP:8080/health"
}
env (str): Environment to find the Account Number for.
Returns:
list: ELB Listeners formatted into dicts for Spinnaker::
[
{
'externalPort': 80,
'externalProtocol': 'HTTP',
'internalPort': 8080,
'internalProtocol': 'HTTP',
'sslCertificateId': None,
'listenerPolicies': []
},
...
]
"""
LOG.debug('ELB settings:\n%s', elb_settings)
credential = get_env_credential(env=env)
account = credential['accountId']
listeners = []
if 'ports' in elb_settings:
for listener in elb_settings['ports']:
cert_name = format_cert_name(account=account,
certificate=listener.get(
'certificate', None))
lb_proto, lb_port = listener['loadbalancer'].split(':')
i_proto, i_port = listener['instance'].split(':')
listener_policies = listener.get('policies', [])
elb_data = {
'externalPort': int(lb_port),
'externalProtocol': lb_proto.upper(),
'internalPort': int(i_port),
'internalProtocol': i_proto.upper(),
'sslCertificateId': cert_name,
'listenerPolicies': listener_policies,
}
listeners.append(elb_data)
else:
listeners = [{
'externalPort': int(elb_settings['lb_port']),
'externalProtocol': elb_settings['lb_proto'],
'internalPort': int(elb_settings['i_port']),
'internalProtocol': elb_settings['i_proto'],
'sslCertificateId': elb_settings['certificate'],
'listenerPolicies': elb_settings['policies'],
}]
for listener in listeners:
LOG.info('ELB Listener:\n'
'loadbalancer %(externalProtocol)s:%(externalPort)d\n'
'instance %(internalProtocol)s:%(internalPort)d\n'
'certificate: %(sslCertificateId)s\n'
'listenerpolicies: %(listenerPolicies)s', listener)
return listeners
def format_cert_name(account='', certificate=None):
"""Format the SSL certificate name into ARN for ELB.
Args:
account (str): Account number for ARN.
certificate (str): Name of SSL certificate.
Returns:
None: Certificate is not desired.
str: Fully qualified ARN for SSL certificate.
"""
cert_name = None
if certificate:
if certificate.startswith('arn'):
cert_name = certificate
else:
cert_name = ('arn:aws:iam::{account}:server-certificate/'
'{name}'.format(account=account,
name=certificate))
LOG.debug('Certificate name: %s', cert_name)
return cert_name
|
from array import array
t = int(input())
for i in range(t):
n, r = tuple(map(int, input().split()))
l = list(map(int, input().split()))
# print(*(l[n-r:]+l[:n-r]))
x = r % n #mostimp concept
print(*(l[n-x:]+l[:n-x]))
def left_rotation(arr, d, n):
for i in range(d):
temp = arr[0]
for j in range(n-1):
arr[j] = arr[j + 1]
arr[n-1] = temp
lst = array('i', [1, 2, 3, 4, 5])
d, n = 2, len(lst)
left_rotation(lst, d, n)
print(lst)
|
class selectCalData:
def selectCalData(self):
calAll = []
calAll.append([])
calAll[0] = ['월','일정','이번달','고사','여름','겨울','졸시','휴학']
calAll.append([])
calAll[1] = ['1학기','2학기']
calAll.append([])
calAll[2] = ['전기','후기','중간','성적','동계','하계','수강','졸업','방학']
calAll.append([])
calAll[3] = ['개강','시험','기말','입력','확인','열람','정정','성적보고',
'심사', '논문','재입학','복학','등록기간','사정회의','학위',
'방학','계절','종강','신청','변경','취소','1/4','2/4','3/4']
calAll.append([])
calAll[4] = ['설날','삼일절','개교','근로자','어린이날','대체휴일','석가탄실일',
'현충일','광복절','추석','대체공휴일','개천절','한글날','성탄절']
return calAll
|
import os, time
import struct
from string import Template
import numpy as np
from astropy.io import fits
import astropy.units as u
import astropy.constants as ct
from hyperion.model import ModelOutput
from scipy.interpolate import griddata, interp2d
from myutils.logger import get_logger
from myutils.math import rebin_irregular_nd, map_sph_to_cart_axisym, rebin_regular_nd
from myutils.classes.data_3d import Data3D
from myutils.decorators import timed
from Plotter.mesh_plotter import NMeshPlotter
from ..distributions.temperature import get_temp_func
def fill_inner_radius(r, th, temperature, density, yso):
rstar = yso.params.getquantity('Star','r')
rmin = yso.params.getfloat('Disc','rmin') *\
yso.params.getquantity('Disc','rsub')
tstar = yso.params.getquantity('Star','t').value
# Inside star
ind = r.cgs<=rstar.cgs
temperature[ind] = tstar
# Inside sublimation radius
ind = (r.cgs>rstar) & (r.cgs<rmin.cgs)
temperature[ind] = tstar*((rstar.cgs/r.cgs[ind])**(1./2.1)).value
# Fill density
x = r*np.sin(th)
z = r*np.cos(th)
density[ind] = yso(x[ind], np.zeros(z[ind].shape), z[ind], ignore_rim=True)
return temperature, density
def write_fits(dirname, **kwargs):
fitsnames = []
for key, val in kwargs.items():
hdu = fits.PrimaryHDU(val)
fitsnames += [os.path.join(dirname, key+'.fits')]
hdu.writeto(fitsnames[-1], overwrite=True)
return fitsnames
def get_walls(*args):
walls = []
for val in args:
dv = np.min(val[val>0.*u.cm])
vw = val - dv
vw = np.append(vw.value, vw[-1].value+2.*dv.value)*vw.unit
walls += [vw]
return walls
def rebin_2Dsph_to_cart(val, new_pos, yso, pos=None, rebin=False, interp=False,
min_height_to_disc=None, logger=get_logger(__name__), **kwargs):
"""Function for rebin or interpolate an input grid into a new grid.
Parameters:
val: 2-D spherically symmetric grid of values for 1st and 4th quadrant.
new_pos: new grid centres.
yso (YSO): YSO object containg the physical parameters.
pos: original positions in the grid in spherical coords.
rebin: rebin original grid
interp: interpolate original grid
kwargs: keyword arguments for the rebin or interpolate functions.
"""
# Checks
kwargs.setdefault('statistic', 'average')
# Rebin if needed
if rebin and pos is not None:
logger.info('Rebinning grid')
# Current position mesh
R, TH = np.meshgrid(pos[0], pos[1])
YI = R * np.sin(TH)
ZI = R * np.cos(TH)
# Extend new positions until maximum radial distance
maxr = np.nanmax(np.sqrt(new_pos[1].value**2+new_pos[0].value**2))
delta = np.abs(new_pos[1][0].value-new_pos[1][1].value)
nymax = int(np.ceil(maxr/delta))
extra = np.nanmax(new_pos[1].value) + \
np.arange(1,abs(nymax-int(np.sum(new_pos[1]>0)))+1)*delta
new_pos0 = np.append(-1.*extra, new_pos[1].value)
new_pos0 = np.append(new_pos0, extra)
new_pos0 = np.sort(new_pos0) * new_pos[1].unit
# Meshes
#YN, ZN = np.meshgrid(new_pos[1], new_pos[2])
YN, ZN = np.meshgrid(new_pos0, new_pos[2])
# Evaluate the function
if interp:
#val1 = rebin_2Dsph_to_cart(val, (new_pos[0], np.array([0.])*new_pos[1].unit,
# new_pos[2]), yso, pos=pos, interp=True, logger=logger)
val1 = rebin_2Dsph_to_cart(val, (new_pos0, np.array([0.])*new_pos[1].unit,
new_pos[2]), yso, pos=pos, interp=True, logger=logger)
val1 = val1[:,0,:]
else:
val1 = yso(YN, np.zeros(YN.shape), ZN)
assert val1.cgs.unit == u.g/u.cm**3
val1 = val1.cgs.value
# Walls
#walls = get_walls(new_pos[1], new_pos[-1])
walls = get_walls(new_pos0, new_pos[-1])
walls = [wall.to(pos[0].unit).value for wall in walls]
# Rebin 2-D
val2 = rebin_irregular_nd(val[0,:,:],
walls[::-1], ZI, YI, statistic=kwargs['statistic'],
weights=kwargs.get('weights'))
# Replace nans
ind = np.isnan(val2)
val2[ind] = val1[ind]
# Interpolate
ZN3, YN3, XN = np.meshgrid(*new_pos[::-1], indexing='ij')
NEWX = np.sqrt(XN**2+YN3**2)
val2 = griddata((YN.value.flatten(), ZN.value.flatten()),
val2.flatten(), (NEWX.to(ZN.unit).value.flatten(),
ZN3.to(ZN.unit).value.flatten()),
method=kwargs.get('method', 'nearest'))
return val2.reshape(XN.shape)
elif interp and pos is not None:
logger.info('Interpolating grid')
val1 = map_sph_to_cart_axisym(val[0,:,:], pos[0], pos[1], *new_pos)
return val1
else:
logger.info('Evaluating grid')
# Meshes
ZN, YN, XN = np.meshgrid(*new_pos[::-1], indexing='ij')
# Evaluate the function
val1 = yso(XN, YN, ZN, ignore_rim=True,
min_height_to_disc=min_height_to_disc)
assert val1.cgs.unit == u.g/u.cm**3
val1 = val1.cgs.value
return val1
def get_quadrant_ind(x, y, z):
ind = [(x<=0) & (y<=0) & (z<=0)]
ind += [(x<=0) & (y<=0) & (z>0)]
ind += [(x<=0) & (y>0) & (z<=0)]
ind += [(x<=0) & (y>0) & (z>0)]
ind += [(x>0) & (y<=0) & (z<=0)]
ind += [(x>0) & (y<=0) & (z>0)]
ind += [(x>0) & (y>0) & (z<=0)]
ind += [(x>0) & (y>0) & (z>0)]
return ind
def get_bins_quadrant(bins):
"""
Bins assumed sorted and odd length (even number of cells).
"""
xmid = (len(bins[0]) - 1)/2
ymid = (len(bins[1]) - 1)/2
zmid = (len(bins[2]) - 1)/2
newbins = [[bins[0][:xmid+1], bins[1][:ymid+1], bins[2][:zmid+1]]]
newbins += [[bins[0][:xmid+1], bins[1][:ymid+1], bins[2][zmid:]]]
newbins += [[bins[0][:xmid+1], bins[1][ymid:], bins[2][:zmid+1]]]
newbins += [[bins[0][:xmid+1], bins[1][ymid:], bins[2][zmid:]]]
newbins += [[bins[0][xmid:], bins[1][:ymid+1], bins[2][:zmid+1]]]
newbins += [[bins[0][xmid:], bins[1][:ymid+1], bins[2][zmid:]]]
newbins += [[bins[0][xmid:], bins[1][ymid:], bins[2][:zmid+1]]]
newbins += [[bins[0][xmid:], bins[1][ymid:], bins[2][zmid:]]]
return newbins
def eval_by_quadrant(x, y, z, func, nret=1, **kwargs):
def replace(val, aux, ind):
for i in range(nret):
try:
val[i][ind] = aux[i]
except IndexError:
val[i][ind] = aux
return val
val = [np.zeros(x.shape) for i in range(nret)]
inds = get_quadrant_ind(x, y, z)
for ind in inds:
aux = func(x[ind], y[ind], z[ind], **kwargs)
val = replace(val, aux, ind)
for i in range(nret):
try:
val[i] = val[i] * aux[i].unit
except IndexError:
val[i] = val[i] * aux.unit
return val
def rebin_by_quadrant(val, x, y, z, bins):
inds1 = get_quadrant_ind(x, y, z)
bins_quadrants = get_bins_quadrant(bins)
ZN, YN, XN = np.meshgrid(z, y, x, indexing='ij')
inds3 = get_quadrant_ind(XN, YN, ZN)
newx = (bins[0][1:] + bins[0][:-1])/2.
newy = (bins[1][1:] + bins[1][:-1])/2.
newz = (bins[2][1:] + bins[2][:-1])/2.
ZN, YN, XN = np.meshgrid(newz, newy, newx, indexing='ij')
newval = np.zeros(XN.shape)
inds2 = get_quadrant_ind(XN, YN, ZN)
for ind1, ind2, ind3, qbins in zip(inds1, inds2, inds3, bins_quadrants):
print newval[ind2].shape
newvali[ind2] = rebin_regular_nd(val[ind3], z[ind1], y[ind1], x[ind1],
bins=qbins[::-1], statistic='sum')
print newvali.shape
newval[ind1] = newvali
return newval
def rebin_by_chunks(val, x, y, z, bins, chunks=1):
return 0
@timed
def phys_oversampled_cart(x, y, z, yso, temp_func, oversample=5,
logger=get_logger(__name__)):
"""Calculate the density and velocity distributions by oversampling the
grid.
This function first creates a new oversampled grid and then rebin this grid
to the input one by taking weighted averages of the physical quantities.
Parameters:
yso (YSO object): the object containing the model parameters.
xlim (tuple): lower and upper limits of the x-axis.
ylim (tuple): lower and upper limits of the y-axis.
zlim (tuple): lower and upper limits of the z-axis.
cellsize (float): physical size of the cell in the coarse grid.
oversample (int, default=5): oversampling factor.
logger (logging): logger manager.
"""
# Hydrogen mass
mH = ct.m_p + ct.m_e
# Special case
if oversample==1:
logger.info('Evaluating the grid')
ZN, YN, XN = np.meshgrid(z, y, x, indexing='ij')
n, vx, vy, vz, temp = yso.get_all(XN, YN, ZN,
temperature=temp_func, component='gas')
n = n / (2.33 * mH)
temp[temp<2.7*u.K] = 2.7*u.K
assert n.cgs.unit == 1/u.cm**3
assert temp.unit == u.K
assert vx.cgs.unit == u.cm/u.s
assert vy.cgs.unit == u.cm/u.s
assert vz.cgs.unit == u.cm/u.s
return n, (vx, vy, vz), temp
logger.info('Resampling grid')
# Create new grid
dx = np.abs(x[0]-x[1])
dy = np.abs(y[0]-y[1])
dz = np.abs(z[0]-z[1])
xw,xstep = np.linspace(np.min(x)-dx/2., np.max(x)+dx/2., num=len(x)*oversample+1,
endpoint=True, retstep=True)
xover = (xw[:-1] + xw[1:]) / 2.
logger.info('Resampled grid x-step = %s', xstep.to(u.au))
yw,ystep = np.linspace(np.min(y)-dy/2., np.max(y)+dy/2., num=len(y)*oversample+1,
endpoint=True, retstep=True)
yover = (yw[:-1] + yw[1:]) / 2.
logger.info('Resampled grid y-step = %s', ystep.to(u.au))
zw,zstep = np.linspace(np.min(z)-dz/2., np.max(z)+dz/2., num=len(z)*oversample+1,
endpoint=True, retstep=True)
zover = (zw[:-1] + zw[1:]) / 2.
logger.info('Resampled grid z-step = %s', zstep.to(u.au))
ZN, YN, XN = np.meshgrid(zover, yover, xover, indexing='ij')
# Volumes
vol = dx*dy*dz
vol_over = xstep*ystep*zstep
# Number density
bins = get_walls(z, y, x)
n_over, vx_over, vy_over, vz_over, temp = yso.get_all(XN, YN, ZN,
temperature=temp_func, component='gas', nquad=oversample)
n_over = n_over / (2.33 * mH)
assert n_over.cgs.unit == 1/u.cm**3
N = vol_over * rebin_regular_nd(n_over.cgs.value, zover, yover, xover, bins=bins,
statistic='sum') * n_over.cgs.unit
dens = N / vol
assert dens.cgs.unit == 1/u.cm**3
# Temperature
temp = rebin_regular_nd(temp.value*n_over.cgs.value, zover, yover,
xover, bins=bins, statistic='sum') * \
temp.unit * n_over.cgs.unit
temp = vol_over * temp / N
temp[temp<2.7*u.K] = 2.7*u.K
assert temp.unit == u.K
# Velocity
assert vx_over.cgs.unit == u.cm/u.s
assert vy_over.cgs.unit == u.cm/u.s
assert vz_over.cgs.unit == u.cm/u.s
v = []
for vi in (vx_over, vy_over, vz_over):
vsum = rebin_regular_nd(vi.cgs.value*n_over.cgs.value, zover, yover,
xover, bins=bins, statistic='sum') * \
vi.cgs.unit * n_over.cgs.unit
vsum = vol_over * vsum / N
vsum[np.isnan(vsum)] = 0.
assert vsum.cgs.unit == u.cm/u.s
v += [vsum]
return dens, v, temp
@timed
def get_physical_props_single(yso, grids, cell_sizes, save_dir, oversample=[3],
dust_out=None, logger=get_logger(__name__)):
"""Calculate and write the physical properties a model with one source.
Parameters:
yso: the model parameters.
grids: grids where the model will be evaluated
template: filename of the *define_model.c* file.
logger: logging system.
"""
# Models with more than one source should be treated in another function
# because the oversampling should be different.
# FITS list
fitslist = []
# Validate oversample
if len(oversample)==1 and len(oversample)!=len(cell_sizes):
oversample = oversample * len(cell_sizes)
elif len(oversample)==len(cell_sizes):
pass
else:
raise ValueError('The length of oversample != number of grids')
# Temperature function
if yso.params.get('DEFAULT', 'quantities_from'):
hmodel = yso.params.get('DEFAULT', 'quantities_from')
logger.info('Loading Hyperion model: %s', os.path.basename(hmodel))
hmodel = ModelOutput(os.path.expanduser(hmodel))
q = hmodel.get_quantities()
temperature = np.sum(q['temperature'].array[1:], axis=0)
r, th = q.r*u.cm, q.t*u.rad
temp_func = get_temp_func(yso.params, temperature, r, th)
elif dust_out is not None:
logger.info('Loading Hyperion model: %s', os.path.basename(dust_out))
hmodel = ModelOutput(os.path.expanduser(dust_out))
q = hmodel.get_quantities()
temperature = np.sum(q['temperature'].array[1:], axis=0)
r, th = q.r*u.cm, q.t*u.rad
temp_func = get_temp_func(yso.params, temperature, r, th)
else:
raise NotImplementedError
# Start from smaller to larger grid
inv_i = len(grids) - 1
for i,(grid,cellsz) in enumerate(zip(grids, cell_sizes)):
# Initialize grid axes
print '='*80
logger.info('Working on grid: %i', i)
logger.info('Oversampling factor: %i', oversample[i])
logger.info('Grid cell size: %i', cellsz)
# Multiply by units
x = grid[0]['x'] * grid[1]['x']
y = grid[0]['y'] * grid[1]['y']
z = grid[0]['z'] * grid[1]['z']
xi = np.unique(x)
yi = np.unique(y)
zi = np.unique(z)
# Density and velocity
dens, (vx, vy, vz), temp = phys_oversampled_cart(
xi, yi, zi, yso, temp_func, oversample=oversample[i],
logger=logger)
# Replace out of range values
dens[dens.cgs<=0./u.cm**3] = 10./u.cm**3
temp[np.logical_or(np.isnan(temp.value), temp.value<2.7)] = 2.7 * u.K
# Replace the inner region by rebbining the previous grid
if i>0:
# Walls of central cells
j = cell_sizes.index(cellsz)
xlen = cell_sizes[j-1] * len(xprev) * u.au
nxmid = int(xlen.value) / cellsz
xw = np.linspace(-0.5*xlen.value, 0.5*xlen.value, nxmid+1) * u.au
ylen = cell_sizes[j-1] * len(yprev) * u.au
nymid = int(ylen.value) / cellsz
yw = np.linspace(-0.5*ylen.value, 0.5*ylen.value, nymid+1) * u.au
zlen = cell_sizes[j-1] * len(zprev) * u.au
nzmid = int(zlen.value) / cellsz
zw = np.linspace(-0.5*zlen.value, 0.5*zlen.value, nzmid+1) * u.au
if nxmid==nymid==nzmid==0:
logger.warning('The inner grid is smaller than current grid size')
else:
logger.info('The inner %ix%ix%i cells will be replaced', nxmid,
nymid, nzmid)
# Rebin previous grid
# Density
vol_prev = (cell_sizes[j-1]*u.au)**3
vol = (cellsz * u.au)**3
N_cen = vol_prev.cgs * rebin_regular_nd(dens_prev.cgs.value,
zprev.cgs.value, yprev.cgs.value, xprev.cgs.value,
bins=(zw.cgs.value,yw.cgs.value,xw.cgs.value),
statistic='sum') * dens_prev.cgs.unit
dens_cen = N_cen / vol
dens_cen = dens_cen.to(dens.unit)
# Temperature
T_cen = rebin_regular_nd(temp_prev.value * dens_prev.cgs.value,
zprev.cgs.value, yprev.cgs.value, xprev.cgs.value,
bins=(zw.cgs.value,yw.cgs.value, xw.cgs.value),
statistic='sum') * temp_prev.unit * dens_prev.cgs.unit
T_cen = vol_prev.cgs * T_cen / N_cen.cgs
T_cen = T_cen.to(temp.unit)
# Replace
dens[len(zi)/2-nzmid/2:len(zi)/2+nzmid/2,
len(yi)/2-nymid/2:len(yi)/2+nymid/2,
len(xi)/2-nxmid/2:len(xi)/2+nxmid/2] = dens_cen
temp[len(zi)/2-nzmid/2:len(zi)/2+nzmid/2,
len(yi)/2-nymid/2:len(yi)/2+nymid/2,
len(xi)/2-nxmid/2:len(xi)/2+nxmid/2] = T_cen
dens_prev = dens
temp_prev = temp
xprev = xi
yprev = yi
zprev = zi
# Linewidth and abundance
linewidth = yso.linewidth(x, y, z, temp).to(u.cm/u.s)
# Abundance per molecule
abns = {}
abn_fmt = 'abn_%s_%i'
j = 1
for section in yso.params.sections():
if not section.lower().startswith('abundance'):
continue
mol = yso[section, 'molecule']
abns[abn_fmt % (mol, inv_i)] = yso.abundance(x, y, z, temp,
index=j, ignore_min=False)
j = j+1
# Write FITS
kw = {'temp%i'%inv_i: temp.value, 'dens%i'%inv_i: dens.cgs.value,
'vx%i'%inv_i: vx.cgs.value, 'vy%i'%inv_i: vy.cgs.value,
'vz%i'%inv_i: vz.cgs.value,
'lwidth%i'%inv_i: linewidth.cgs.value}
kw.update(abns)
fitsnames = write_fits(os.path.expanduser(save_dir),
**kw)
fitslist += fitsnames
inv_i = inv_i - 1
return fitslist
# Keep for backwards compatibility with script
def set_physical_props(yso, grids, cell_sizes, save_dir, oversample=3,
dust_out=None, logger=get_logger(__name__)):
"""Calculate and write the physical properties of the model.
Parameters:
yso: the model parameters.
grids: grids where the model will be evaluated
template: filename of the *define_model.c* file.
logger: logging system.
"""
# Load temperature function
if yso.params.get('DEFAULT', 'quantities_from'):
hmodel = yso.params.get('DEFAULT', 'quantities_from')
logger.info('Loading Hyperion model: %s', os.path.basename(hmodel))
hmodel = ModelOutput(os.path.expanduser(hmodel))
q = hmodel.get_quantities()
temperature = np.sum(q['temperature'].array[1:], axis=0)
r, th = q.r*u.cm, q.t*u.rad
temp_func = get_temp_func(yso.params, temperature, r, th)
elif dust_out is not None:
logger.info('Loading Hyperion model: %s', os.path.basename(dust_out))
hmodel = ModelOutput(os.path.expanduser(dust_out))
q = hmodel.get_quantities()
temperature = np.sum(q['temperature'].array[1:], axis=0)
r, th = q.r*u.cm, q.t*u.rad
temp_func = get_temp_func(yso.params, temperature, r, th)
else:
raise NotImplementedError
# Open template
fitslist = []
# Start from smaller to larger grid
for i,grid,cellsz in zip(range(len(grids))[::-1], grids, cell_sizes):
print '='*80
logger.info('Working on grid: %i', i)
logger.info('Grid cell size: %i', cellsz)
x = grid[0]['x'] * grid[1]['x']
y = grid[0]['y'] * grid[1]['y']
z = grid[0]['z'] * grid[1]['z']
xi = np.unique(x)
yi = np.unique(y)
zi = np.unique(z)
# Density and velocity
dens, (vx, vy, vz), temp = phys_oversampled_cart(xi, yi, zi, yso,
temp_func, oversample=oversample if i!=2 else 5, logger=logger)
dens[dens.cgs<=0./u.cm**3] = 10./u.cm**3
temp[np.isnan(temp.value)] = 2.7 * u.K
# Replace the inner region by rebbining the previous grid
if i<len(grids)-1:
# Walls of central cells
j = cell_sizes.index(cellsz)
xlen = cell_sizes[j-1] * len(xprev) * u.au
nxmid = int(xlen.value) / cellsz
xw = np.linspace(-0.5*xlen.value, 0.5*xlen.value, nxmid+1) * u.au
ylen = cell_sizes[j-1] * len(yprev) * u.au
nymid = int(ylen.value) / cellsz
yw = np.linspace(-0.5*ylen.value, 0.5*ylen.value, nymid+1) * u.au
zlen = cell_sizes[j-1] * len(zprev) * u.au
nzmid = int(zlen.value) / cellsz
zw = np.linspace(-0.5*zlen.value, 0.5*zlen.value, nzmid+1) * u.au
if nxmid==nymid==nzmid==0:
logger.warning('The inner grid is smaller than current grid size')
else:
logger.info('The inner %ix%ix%i cells will be replaced', nxmid,
nymid, nzmid)
# Rebin previous grid
# Density
vol_prev = (cell_sizes[j-1]*u.au)**3
vol = (cellsz * u.au)**3
N_cen = vol_prev.cgs * rebin_regular_nd(dens_prev.cgs.value,
zprev.cgs.value, yprev.cgs.value, xprev.cgs.value,
bins=(zw.cgs.value,yw.cgs.value,xw.cgs.value),
statistic='sum') * dens_prev.cgs.unit
dens_cen = N_cen / vol
dens_cen = dens_cen.to(dens.unit)
# Temperature
T_cen = rebin_regular_nd(temp_prev.value * dens_prev.cgs.value,
zprev.cgs.value, yprev.cgs.value, xprev.cgs.value,
bins=(zw.cgs.value,yw.cgs.value, xw.cgs.value),
statistic='sum') * temp_prev.unit * dens_prev.cgs.unit
T_cen = vol_prev.cgs * T_cen / N_cen.cgs
T_cen = T_cen.to(temp.unit)
# Replace
dens[len(zi)/2-nzmid/2:len(zi)/2+nzmid/2,
len(yi)/2-nymid/2:len(yi)/2+nymid/2,
len(xi)/2-nxmid/2:len(xi)/2+nxmid/2] = dens_cen
temp[len(zi)/2-nzmid/2:len(zi)/2+nzmid/2,
len(yi)/2-nymid/2:len(yi)/2+nymid/2,
len(xi)/2-nxmid/2:len(xi)/2+nxmid/2] = T_cen
dens_prev = dens
temp_prev = temp
xprev = xi
yprev = yi
zprev = zi
# Abundance
abundance = yso.abundance(temp)
# Linewidth
amu = 1.660531e-24 * u.g
atoms = yso.params.getfloat('Velocity', 'atoms')
c_s2 = ct.k_B * temp / (atoms * amu)
linewidth = np.sqrt(yso.params.getquantity('Velocity', 'linewidth')**2
+ c_s2)
# Write FITS
fitsnames = write_fits(os.path.expanduser(save_dir),
**{'temp%i'%i: temp.value, 'dens%i'%i: dens.cgs.value,
'vx%i'%i: vx.cgs.value, 'vy%i'%i: vy.cgs.value, 'vz%i'%i:
vz.cgs.value, 'abn%i'%i: abundance,
'lwidth%i'%i: linewidth.cgs.value})
fitslist += fitsnames
return fitslist
def write_setup(section, model, template, rt='mollie', incl=0*u.deg,
phi=0*u.deg):
# Open template
with open(os.path.expanduser(template)) as ftemp:
temp = Template(ftemp.read())
# Data to write:
fmt = '%.8f'
radius = model.setup.getquantity(rt, 'radius').to(u.pc)
kwd = {'chwidth': model.images.getquantity(section, 'chwidth').cgs.value,
'nchan': model.images.get(section, 'nchan'),
'minlwidth': model.images.getquantity(section,
'minlwidth').cgs.value,
'maxlwidth': model.images.getquantity(section,
'maxlwidth').cgs.value,
'radius': fmt % radius.value,
'nphi': model.setup.get(rt, 'nphi'),
'nth': model.setup.get(rt, 'nth'),
'nlines': model.images.get(section, 'nlines'),
'line_id': model.images.get(section, 'line_id'),
'th': incl.to(u.deg).value,
'phi': phi.to(u.deg).value,
'npix': model.images.get(section, 'npix'),
'pixsize': model.images.getquantity(section,
'pixsize').to(u.pc).value,
'n_state': model.images.get(section,'n_state'),
'n_lines': model.images.get(section,'n_lines')}
# Write file
dirname = os.path.dirname(os.path.expanduser(template))
fname = 'setup.c'
while True:
try:
with open(os.path.join(dirname, fname), 'w') as out:
out.write(temp.substitute(**kwd))
break
except IOError:
print 'Re-trying saving setup.c'
time.sleep(2)
continue
def load_model(model, source, filename, logger, old=False, older=False,
write='combined_jy', velocity=True, pa=None):
"""Load a Mollie model.
Written by: K. G. Johnston.
Modified by: F. Olguin
Parameters:
model: model file name.
source (astroSource): source information.
logger: logger.
write: type of image to write (default: data cube in Jy).
velocity: output cube 3rd axis in velocity or frequency.
pa: source position angle.
"""
maxname = 20
if older: maxname = 16
logger.info('Opening file: %s', model)
f = open(model, "rb")
endian = '>'
byte = f.read(4)
nlines = struct.unpack(endian+'l',byte)[0]
swap_bytes = False
if nlines > 200:
swap_bytes = True
endian = '<'
logger.info('Swapping bytes? %s', swap_bytes)
nlines = struct.unpack(endian+'l',byte)[0]
logger.info('There are %i lines in this data set', nlines)
nchan = np.zeros(nlines,dtype=int)
restfreq = np.zeros(nlines)
nviews = struct.unpack(endian+'l',f.read(4))[0]
logger.info('There are %i views in this data set', nviews)
for line in range(nlines):
nch = struct.unpack(endian+'l',f.read(4))[0]
nchan[line] = nch
logger.info('The numbers of channels are %i', nchan)
nx = struct.unpack(endian+'l',f.read(4))[0]
ny = struct.unpack(endian+'l',f.read(4))[0]
cellx = struct.unpack(endian+'f',f.read(4))[0] * u.pc
celly = struct.unpack(endian+'f',f.read(4))[0] * u.pc
beamx = struct.unpack(endian+'f',f.read(4))[0] * u.pc
beamy = struct.unpack(endian+'f',f.read(4))[0] * u.pc
logger.info('Grid size nx=%i, ny=%i', nx, ny)
logger.info('Cell size %sx%s', cellx, celly)
linename = (nlines)*['']
for i in range(nlines):
for j in range(maxname):
bytvar = struct.unpack(endian+'c',f.read(1))[0]
linename[i] += bytvar.decode('ascii')
linename[i] = linename[i].strip()
if (not old) and (not older):
for i in range(nlines):
restfreq[i] = struct.unpack(endian+'d',f.read(8))[0]
logger.info('The lines are:')
restfreq = restfreq * u.Hz
for i in range(nlines):
logger.info('%s at %s', linename[i], restfreq[i].to(u.GHz))
maxch = max(nchan)
chvel = np.zeros((nlines,maxch))
for i in range(nlines):
for n in range(nchan[i]):
chvel[i,n] = struct.unpack(endian+'f',f.read(4))[0]
chvel = chvel * u.cm/u.s
for i in range(nlines):
logger.info('Velocities for line %s: %s, %s', linename[i],
chvel[i,0].to(u.km/u.s), chvel[i,nchan[i]-1].to(u.km/u.s))
lng = np.zeros(nviews)
lat = np.zeros(nviews)
for i in range(nviews):
lng[i] = struct.unpack(endian+'f',f.read(4))[0]
lat[i] = struct.unpack(endian+'f',f.read(4))[0]
logger.info('Longitudes: %r', lng)
# fix inclination convention to Hyperion
lat = 90 - np.array(lat)
logger.info('Latitudes: %r', lat)
xc = np.zeros(nx)
for i in range(nx):
xc[i] = struct.unpack(endian+'f',f.read(4))[0]
yc = np.zeros(ny)
for i in range(ny):
yc[i] = struct.unpack(endian+'f',f.read(4))[0]
data = np.ones((nlines,nviews,nx,ny,maxch)) * np.nan
for l in range(nlines):
data_bytes = f.read(4 * nviews * nx * ny * nchan[l])
data[l,:,:,:,:nchan[l]] = np.fromstring(data_bytes, dtype=endian + \
'f4').reshape(nviews, nx,
ny, nchan[l])
logger.info('Max in line %i is %.3e', l, np.nanmax(data[l]))
f.close()
logger.info('Min and max brightness in data set: %.3e, %.3e',
np.nanmin(data), np.nanmax(data))
if linename[0].strip().lower().startswith("mc"):
logger.warn('Remember to run CH3CN_CUBE after LOAD_MODEL\n' + \
'in order to stack the CH3CN lines into a single spectrum')
# Set up header common to all files
rightascension, declination = source.position.ra, source.position.dec
distance = source.distance.to(u.pc)
header_template = fits.Header()
header_template['OBJECT'] = source.name
header_template['TELESCOP'] = 'MOLLIE'
header_template['INSTRUME'] = 'MOLLIE'
header_template['OBSERVER'] = 'MOLLIE'
header_template['CTYPE1'] = 'RA---SIN'
header_template['CTYPE2'] = 'DEC--SIN'
header_template['CUNIT1'] = 'degree'
header_template['CUNIT2'] = 'degree'
header_template['CRPIX1'] = nx / 2.
header_template['CRPIX2'] = ny / 2. + 1.
header_template['CDELT1'] = -1.*np.abs(np.degrees((cellx.si/distance.si).value))
header_template['CDELT2'] = np.degrees((celly.si / distance.si).value)
header_template['CRVAL1'] = rightascension.to(u.deg).value
header_template['CRVAL2'] = declination.to(u.deg).value
header_template['EPOCH'] = 2000
if pa or source.get_quantity('pa') is not None:
header_template['CROTA1'] = 0
if pa is None:
pa = source.get_quantity('pa')
header_template['CROTA2'] = (360*u.deg - pa.to(u.deg)).value
#header_template['BMAJ'] = np.degrees((beamx.si / distance.si).value * 2.35)
#header_template['BMIN'] = np.degrees((beamx.si / distance.si).value * 2.35)
header_template['EQUINOX'] = 2000.
for v in range(nviews):
for l in range(nlines):
### Set up header ###
header = header_template.copy()
header['LINE'] = linename[l]
cdelt3 = (chvel[l,1] - chvel[l,0]).to(u.km/u.s)
if velocity:
header['CTYPE3'] = 'VELO-LSR'
header['CUNIT3'] = 'KM/S'
crval3 = chvel[l,0].to(u.km/u.s)
#cdelt3 = (chvel[l,1]/1.e5 - chvel[l,0]/1.e5)
logger.info("Channel width %s", cdelt3)
else:
header['CTYPE3'] = 'FREQ'
header['CUNIT3'] = 'Hz'
crval3 = (restfreq[0]*(1.e0 - cdelt3.cgs/ct.c.cgs)).to(u.Hz)
cdelt3 = (restfreq[0]*cdelt3.cgs/ct.c.cgs).to(u.Hz)
logger.info("Channel width %s", cdelt3.to(u.MHz))
header['CRPIX3'] = 1.
header['CDELT3'] = cdelt3.value
header['CRVAL3'] = crval3.value
header['RESTFREQ'] = restfreq[l].to(u.Hz).value
#logger.info("Channel width %.3e km/s", header['CDELT3'])
### Write cube in native units (K) ###
header_K = header.copy()
header_K['BUNIT'] = 'K'
if write == 'indiv_K':
fits.writeto(filename, data[l,v,:,:,:].transpose(),
header, clobber=True)
### Write cube in Jy/pixel ###
#K_to_Jy_per_beam = (header['RESTFREQ'] / 1e9) ** 2 * \
# header['BMAJ']* header['BMIN'] * 3600 ** 2 / 1.224e6
#header_Jy_per_beam = header.copy()
#header_Jy_per_beam['BUNIT'] = 'Jy/beam'
#if write == 'indiv_jy_beam':
# fits.writeto(filename,
# data[l,v,:,:,:].transpose() * K_to_Jy_per_beam,
# header, clobber=True)
# Avoid referring to beam since for some cases beam = 0
pixel_area_deg = np.abs(header['CDELT1']) * header['CDELT2']
#beam_area_deg = 1.1331 * header['BMAJ'] * header['BMIN']
#pixels_per_beam = beam_area_deg / pixel_area_deg
#K_to_Jy_old = K_to_Jy_per_beam / pixels_per_beam
K_to_Jy = (header['RESTFREQ']*u.Hz).to(u.GHz).value** 2 * 3600 ** 2 / 1.224e6 /\
1.1331 * pixel_area_deg
#logger.info("K to Jy/beam = %.3e", K_to_Jy_per_beam)
logger.info("K to Jy/pixel = %.3f", K_to_Jy)
#logger.info("K to Jy/pixel [old]= %.3f", K_to_Jy_old)
header_Jy = header.copy()
header_Jy['BUNIT'] = 'Jy'
if write == 'indiv_jy':
fits.writeto(filename,
data[l,v,:,:,:].transpose() * K_to_Jy,
header, clobber=True)
### Now make a stacked cube ###
logger.info("Writing out stacked cube...")
for line in range(nlines):
datamax = np.nanmax(data[line,:,:,:,:])
logger.info('Line %s, datamax: %.3e', line, datamax)
minimum_line = nlines - 1
minimum_velocity = chvel[nlines - 1,0]
# Now figure out the velocity shift due to line frequencies
velocity_shift = -1. * ct.c.cgs * (restfreq - restfreq[minimum_line]) / \
restfreq[minimum_line]
for line in range(nlines):
logger.info('Velocity shift: %s', velocity_shift[line].to(u.km/u.s))
maximum_velocity = chvel[0,nchan[0]-1] + velocity_shift[0]
logger.info('Min and max velocities: %s, %s',
minimum_velocity.to(u.km/u.s), maximum_velocity.to(u.km/u.s))
# Make a new velocity array starting at the minimum velocity
dv = (chvel[0,1]-chvel[0,0])
logger.info('Channel width %s', dv.to(u.km/u.s))
number_channels = int(((maximum_velocity.cgs - minimum_velocity.cgs) /\
dv.cgs).value) + 1
logger.info('Number of channels: %i', number_channels)
velo = np.linspace(0., number_channels-1., number_channels)*dv + \
minimum_velocity
logger.info('New velocity range [%s:%s]', velo[0].to(u.km/u.s),
velo[number_channels-1].to(u.km/u.s))
# New array to hold 1 line with all the spectra
# from the 11 lines
data1 = np.zeros((1,number_channels))
for i in range(number_channels):
data1[0,i] = velo[i].cgs.value
data2 = np.zeros((nviews,nx,ny,number_channels))
for line in range(nlines):
for i in range(nchan[line]):
j = int(((chvel[line,i].cgs + velocity_shift[line].cgs -\
velo[0].cgs)/dv.cgs).value)
data2[:,:,:,j] = (data[line,:,:,:,i] + data2[:,:,:,j])
nchan[0] = number_channels
images = []
for v in range(nviews):
header = header_template.copy()
header['LINE'] = 'CH3CN (all)'
cdelt3 = dv.to(u.km/u.s)
if velocity:
header['CTYPE3'] = 'VELO-LSR'
header['CUNIT3'] = 'KM/S'
crval3 = minimum_velocity.to(u.km/u.s)
#cdelt3 = dv/1.e5
logger.info("Channel width %s", cdelt3)
else:
header['CTYPE3'] = 'FREQ'
header['CUNIT3'] = 'Hz'
crval3 = (restfreq[0]*(1.e0 - cdelt3.cgs/ct.c.cgs)).to(u.Hz)
cdelt3 = (restfreq[0]*cdelt3.cgs/ct.c.cgs).to(u.Hz)
logger.info("Channel width %s", cdelt3.to(u.MHz))
header['CRPIX3'] = 1.
header['CDELT3'] = cdelt3.value
header['CRVAL3'] = crval3.value
header['RESTFREQ'] = restfreq[l].to(u.Hz).value
#logger.info("Channel width %.3e km/s", cdelt3)
header_K['BUNIT'] = 'K'
if write == 'combined_K':
fits.writeto(filename, data2[v,:nchan[0]].transpose(),
header, clobber=True)
#K_to_Jy_per_beam = (header['RESTFREQ']*u.Hz).to(u.GHz).value** 2 * header['BMAJ'] *\
# header['BMIN'] * 3600 ** 2 / 1.224e6
#header_Jy_per_beam = header.copy()
#header_Jy_per_beam['BUNIT'] = 'Jy/beam'
#if write == 'combined_jy_beam':
# fits.writeto(filename,
# data2[v,:nchan[0]].transpose() * K_to_Jy_per_beam,
# header, clobber=True)
# Avoid referring to beam since for some cases beam = 0
pixel_area_deg = np.abs(header['CDELT1']) * header['CDELT2']
#beam_area_deg = 1.1331 * header['BMAJ'] * header['BMIN']
#pixels_per_beam = beam_area_deg / pixel_area_deg
#K_to_Jy_old = K_to_Jy_per_beam / pixels_per_beam
K_to_Jy = (header['RESTFREQ']*u.Hz).to(u.GHz).value**2 * 3600**2 / 1.224e6 / \
1.1331 * pixel_area_deg
if write == 'combined_jy':
header['BUNIT'] = 'JY/PIXEL'
#data2[v] = data[v][:,::-1,:]
#newdata2 = data2[v,:,:,:nchan[0]].transpose()
fits.writeto(filename,
data2[v,:,:,:nchan[0]].transpose() * K_to_Jy,
header, overwrite=True)
images += [Data3D(filename)]
return images
def load_model_cube(model_file, source, filename, pa=0*u.deg,
logger=get_logger(__name__,__package__+'.log'), velocity=True,
bunit=u.Jy):
"""Load a Mollie model.
Written by: K. G. Johnston.
Modified by: F. Olguin
References to older versions were removed
Parameters:
model_file (str): model file name.
source (astroSource): source information.
filename (str): output file name.
pa (astropy.quantity, default=0.): source position angle.
logger (logging, optional): logger.
velocity (bool, default=True): output cube 3rd axis in velocity or frequency.
bunit (astropy.unit, default=Jy): output flux unit.
"""
# Open file
logger.info('Opening file: %s', os.path.basename(model_file))
f = open(model_file, "rb")
endian = '>'
byte = f.read(4)
nlines = struct.unpack(endian+'l', byte)[0]
# Swap bytes
swap_bytes = False
if nlines > 200:
swap_bytes = True
endian = '<'
logger.info('Swapping bytes? %s', swap_bytes)
# Number of lines
nlines = struct.unpack(endian+'l', byte)[0]
logger.info('Number of lines: %i', nlines)
# Number of viewing angles
nviews = struct.unpack(endian+'l',f.read(4))[0]
logger.info('Number of viewing angles: %i', nviews)
# Number of channels
nchan = np.zeros(nlines,dtype=int)
for line in range(nlines):
nch = struct.unpack(endian+'l',f.read(4))[0]
nchan[line] = nch
logger.info('Number of channels: %r', nchan)
# Grid parameters
nx = struct.unpack(endian+'l',f.read(4))[0]
ny = struct.unpack(endian+'l',f.read(4))[0]
cellx = struct.unpack(endian+'f',f.read(4))[0] * u.pc
celly = struct.unpack(endian+'f',f.read(4))[0] * u.pc
beamx = struct.unpack(endian+'f',f.read(4))[0] * u.pc
beamy = struct.unpack(endian+'f',f.read(4))[0] * u.pc
logger.info('Grid size nx=%i, ny=%i', nx, ny)
logger.info('Cell size %sx%s', cellx, celly)
# Line names
maxname = 20
linename = (nlines)*['']
for i in range(nlines):
for j in range(maxname):
bytvar = struct.unpack(endian+'c',f.read(1))[0]
linename[i] += bytvar.decode('ascii')
linename[i] = linename[i].strip()
# Rest frequencies
restfreq = np.zeros(nlines) * u.Hz
for i in range(nlines):
restfreq[i] = struct.unpack(endian+'d',f.read(8))[0]*u.Hz
logger.info('The lines are:')
logger.info('%s at %s', linename[i], restfreq[i].to(u.GHz))
# Channel velocity ranges
maxch = max(nchan)
chvel = np.zeros((nlines,maxch)) * u.cm/u.s
for i in range(nlines):
for n in range(nchan[i]):
chvel[i,n] = struct.unpack(endian+'f',f.read(4))[0] * u.cm/u.s
logger.info('Velocity range for line %s: %s, %s', linename[i],
chvel[i,0].to(u.km/u.s), chvel[i,nchan[i]-1].to(u.km/u.s))
# Viewing angles
lng = np.zeros(nviews) * u.deg
lat = np.zeros(nviews) * u.deg
for i in range(nviews):
lng[i] = struct.unpack(endian+'f',f.read(4))[0] * u.deg
lat[i] = struct.unpack(endian+'f',f.read(4))[0] * u.deg
logger.info('Longitudes: %s', lng)
# Fix inclination convention to Hyperion
lat = 90.*u.deg - lat
logger.info('Latitudes: %s', lat)
# RA axis
xc = np.zeros(nx)
for i in range(nx):
xc[i] = struct.unpack(endian+'f',f.read(4))[0]
# Dec axis
yc = np.zeros(ny)
for i in range(ny):
yc[i] = struct.unpack(endian+'f',f.read(4))[0]
# Data
data = np.ones((nlines,nviews,nx,ny,maxch)) * np.nan
for l in range(nlines):
data_bytes = f.read(4 * nviews * nx * ny * nchan[l])
data[l,:,:,:,:nchan[l]] = np.fromstring(data_bytes,
dtype=endian + 'f4').reshape(nviews, nx, ny, nchan[l])
logger.info('Max in line %i is %.3e', l, np.nanmax(data[l]))
f.close()
logger.info('Min and max brightness in data set: %.3e, %.3e',
np.nanmin(data), np.nanmax(data))
# Set up header common to all files
ra, dec = source.position.ra, source.position.dec
distance = source.distance.to(u.pc)
header_template = fits.Header()
header_template['OBJECT'] = 'MODEL'
header_template['TELESCOP'] = 'MOLLIE'
header_template['INSTRUME'] = 'MOLLIE'
header_template['OBSERVER'] = 'MOLLIE'
header_template['CTYPE1'] = 'RA---SIN'
header_template['CTYPE2'] = 'DEC--SIN'
header_template['CUNIT1'] = 'degree'
header_template['CUNIT2'] = 'degree'
header_template['CRPIX1'] = nx / 2.
header_template['CRPIX2'] = ny / 2. + 1.
header_template['CDELT1'] = -1.*np.abs(np.degrees((cellx.si/distance.si).value))
header_template['CDELT2'] = np.degrees((celly.si/distance.si).value)
header_template['CRVAL1'] = ra.to(u.deg).value
header_template['CRVAL2'] = dec.to(u.deg).value
header_template['EPOCH'] = 2000
header_template['EQUINOX'] = 2000.
if pa or source.get_quantity('pa') is not None:
header_template['CROTA1'] = 0
if pa is None:
pa = source.get_quantity('pa')
header_template['CROTA2'] = (360*u.deg - pa.to(u.deg)).value
# Line indices
minimum_line = nlines - 1
minimum_velocity = chvel[nlines - 1,0]
# Now figure out the velocity shift due to line frequencies
velocity_shift = -1. * ct.c.cgs * (restfreq - restfreq[minimum_line]) / \
restfreq[minimum_line]
for line in range(nlines):
logger.info('Velocity shift for line %s: %s', linename[line],
velocity_shift[line].to(u.km/u.s))
# Maximum velocity
maximum_velocity = chvel[0,nchan[0]-1] + velocity_shift[0]
logger.info('Min and max velocities: %s, %s',
minimum_velocity.to(u.km/u.s), maximum_velocity.to(u.km/u.s))
# Make a new velocity array starting at the minimum velocity
dv = (chvel[0,1]-chvel[0,0])
logger.info('Channel width %s', dv.to(u.km/u.s))
number_channels = int(((maximum_velocity.cgs - minimum_velocity.cgs) /\
dv.cgs).value) + 1
logger.info('Number of channels: %i', number_channels)
velo = np.linspace(0., number_channels-1., number_channels)*dv + \
minimum_velocity
logger.info('New velocity range [%s:%s]', velo[0].to(u.km/u.s),
velo[number_channels-1].to(u.km/u.s))
# New array to hold 1 line with all the spectra
cube = np.zeros((nviews,nx,ny,number_channels))
for line in range(nlines):
for i in range(nchan[line]):
j = int(((chvel[line,i].cgs + velocity_shift[line].cgs -\
velo[0].cgs)/dv.cgs).value)
cube[:,:,:,j] = (data[line,:,:,:,i] + cube[:,:,:,j])
nchan[0] = number_channels
# Save images per viewing angle
images = []
for v in range(nviews):
# Header
header = header_template.copy()
header['LINE'] = '%s (all)' % linename[0].split('(')[0]
# Save velocity or frequency
cdelt3 = dv.to(u.km/u.s)
if velocity:
header['CTYPE3'] = 'VELO-LSR'
header['CUNIT3'] = 'KM/S'
crval3 = minimum_velocity.to(u.km/u.s)
logger.info("Channel width %s", cdelt3)
else:
header['CTYPE3'] = 'FREQ'
header['CUNIT3'] = 'Hz'
crval3 = (restfreq[0]*(1. - cdelt3.cgs/ct.c.cgs)).to(u.Hz)
cdelt3 = (restfreq[0]*cdelt3.cgs/ct.c.cgs).to(u.Hz)
logger.info("Channel width %s", cdelt3.to(u.MHz))
header['CRPIX3'] = 1.
header['CDELT3'] = cdelt3.value
header['CRVAL3'] = crval3.value
header['RESTFREQ'] = restfreq[l].to(u.Hz).value
# Save file
logger.info('Cube file name: %s', os.path.basename(filename))
if bunit is u.K:
header['BUNIT'] = 'K'
logger.info('Saving cube with units: K')
fits.writeto(filename, cube[v,:nchan[0]].transpose(),
header, overwrite=True)
images += [Data3D(filename)]
elif bunit is u.Jy:
pixel_area_deg = np.abs(header['CDELT1']) * header['CDELT2']
K_to_Jy = (header['RESTFREQ']*u.Hz).to(u.GHz).value**2 * \
3600**2 / 1.224e6 / 1.1331 * pixel_area_deg
header['BUNIT'] = 'JY/PIXEL'
logger.info('Saving cube with units: Jy/pixel')
fits.writeto(filename,
cube[v,:,:,:nchan[0]].transpose() * K_to_Jy, header,
overwrite=True)
images += [Data3D(filename)]
else:
raise NotImplementedError
return images
|
from django.urls import path
from . import views
urlpatterns = [
path('', views.index),
path('show/new', views.add_new_show),
path('show/create', views.create_show),
path('show/<int:id>', views.display_show),
path('show/<int:id>/edit', views.edit_show),
path('show/<int:id>/update', views.update_show),
path('show/<int:id>/destroy', views.delete_show)
] |
import modules as mod # from other file
# All of the following modules are from STD
import random as rand
import math as math
import datetime as dt
import calendar as calendar
import os
courses = ['History', 'Math', 'Physics', 'Eecs', 'Art']
index = mod.find_index(courses, 'Eecs')
print(index)
random_course = rand.choice(courses)
print(random_course)
rads = math.radians(90)
print(rads)
print(math.sin(rads))
today = dt.date.today()
print(today)
print(calendar.isleap(2017))
print(os.__file__)
|
def odd_even():
for i in range(0,2001):
if (i % 2 == 1):
print 'number is '+ str(i)+". This is an odd number"
if (i % 2 == 0):
print 'number is '+ str(i)+". This is an even number"
odd_even() |
import _pickle as cPickle
from YCgplearn.genetic import SymbolicRegressor
from YCgplearn.fitness import make_fitness
import pydotplus
from ycquant.yc_interpreter import *
import os
# from ctypes import *
from ycquant.yc_backtest import *
import numpy as np
class YCGP:
"""
Gentic Programming Algorithm based on gplearn,
which is able to handle changing target during the training (like reinforcement learning)
"""
_yc_gp = True
def __init__(self, price_table, strategy, split_list=None, reward_weight=None):
"""
:param n_dim: int, default 0
dimension of x_data
currently is useless
:param price_table: list of float
the closed price corresponding to the x_data
will be used to evaluate the fitenss
"""
if split_list is None:
split_list = [0, len(price_table)]
if reward_weight is None:
reward_weight = [1]
self.split_list = split_list
self.reward_weight = reward_weight
self.price_table = price_table
self.len_price_table = len(price_table)
self.strategy = strategy
self.explict_fiteness_func = self.make_explict_func()
self.est = None
self.max_samples = 1.0
def make_explict_func(self):
reward_func = self.strategy.get_reward
split_list = self.split_list
price_table = self.price_table
reward_weight = self.reward_weight
def explicit_fitness(y, y_pred, sample_weight):
y_pred[y_pred == 0] = 1
total_bool_sample_weight = np.array(sample_weight, dtype=bool)
result = 0
total_data = split_list[-1] - split_list[0]
ratio = np.around(np.sum(total_bool_sample_weight) / total_data, decimals=1)
is_training_data = total_bool_sample_weight[0]
for i in range(len(split_list) - 1):
start = split_list[i]
end = split_list[i + 1]
n_data = int(ratio * (end - start))
_y_pred = np.array(y_pred[start:end])
_price_table = np.array(price_table[start:end])
if is_training_data:
indices = np.array(range(n_data))
else:
indices = np.array(range(end - n_data, end))
result += reward_weight[i] * reward_func(_y_pred, _price_table, indices)
# if is_training_data:
# print(indices)
# op_arr = CrossBarStrategy.get_op_arr(y_pred)
# profit_arr = CrossBarStrategy.get_profit_by_op(op_arr, price_table, indices)
# print(np.sum(profit_arr))
# print(result)
# for i in range(len(y_pred)):
# print(y_pred[i], op_arr[i], _price_table[i], profit_arr[i])
#
# print(result, print(np.sum(profit_arr)))
# input()
return result
return explicit_fitness
def get_best_oob_est(self):
_programs = self.est._programs[0]
best_est = None
best_oob_fintess = 0
for _program in _programs:
if not _program is None:
if self.greater_is_better:
if best_oob_fintess < _program.oob_fitness_:
best_oob_fintess = _program.oob_fitness_
best_est = _program
else:
if best_oob_fintess > _program.oob_fitness_:
best_oob_fintess = _program.oob_fitness_
best_est = _program
return best_est
def set_params(self, population_size=500, generations=10, tournament_size=20, stopping_criteria=10, p_crossover=0.7, p_subtree_mutation=0.1,
greater_is_better=True,
p_hoist_mutation=0.05, p_point_mutation=0.1, verbose=1, parsimony_coefficient=0.01, function_set=None, max_samples=1.0):
self.population_size = population_size
self.generations = generations
self.stopping_criteria = stopping_criteria
self.p_crossover = p_crossover
self.p_subtree_mutation = p_subtree_mutation
self.p_hoist_mutation = p_hoist_mutation
self.p_point_mutation = p_point_mutation
self.verbose = verbose
self.parsimony_coefficient = parsimony_coefficient
self.max_samples = max_samples
self.greater_is_better = greater_is_better
self.tournament_size = tournament_size
if function_set is None:
function_set = ['add', 'sub', 'mul', 'div', 'sin']
self.function_set = function_set
def fit(self, x_data):
if not hasattr(self, 'function_set'):
print("Automatically initilizing....")
self.set_params()
metric = make_fitness(self.explict_fiteness_func, greater_is_better=self.greater_is_better)
# here the random_state is set to be 223 to ensure
# the cut-split not the sampling split
self.est = SymbolicRegressor(population_size=self.population_size, tournament_size=self.tournament_size,
generations=self.generations, stopping_criteria=self.stopping_criteria,
p_crossover=self.p_crossover, p_subtree_mutation=self.p_subtree_mutation,
p_hoist_mutation=self.p_hoist_mutation, p_point_mutation=self.p_point_mutation,
metric=metric, max_samples=self.max_samples,
function_set=self.function_set,
verbose=self.verbose, parsimony_coefficient=self.parsimony_coefficient)
print("x_data.shape[0]", x_data.shape[0])
self.est.fit(x_data, np.arange(x_data.shape[0]))
return self.est
def predict(self, x_data):
return self.est.predict(x_data)
def save(self, folder_path, to_save_generation=True):
"""Due to pickle not supporting saving ctype,
so we have to save the best program without metric function rather than whole regressor
:param folder_path: str
where to save the best est
"""
if not os.path.exists(folder_path):
os.makedirs(folder_path)
model_path = "{fd}/model.pkl".format(fd=folder_path)
plot_path = "{fd}/expression.png".format(fd=folder_path)
formula_path = "{fd}/mc_formula.txt".format(fd=folder_path)
best_program = self.est._program
graph = pydotplus.graphviz.graph_from_dot_data(best_program.export_graphviz())
graph.write_png(plot_path)
best_program.metric = None
setattr(best_program, "predict", best_program.execute)
with open(model_path, "wb") as f:
cPickle.dump(best_program, f)
# save as mc_formula
formula = best_program.__str__()
mc_formula = YCInterpreter.mc_interprete(formula)
with open(formula_path, "w") as f:
f.write("f[1]=" + mc_formula + ";")
if to_save_generation:
self._save_generation("{fd}/generation.pkl".format(fd=folder_path))
def _save_generation(self, generation_path):
_programs = self.est._programs[0]
__programs = []
for _program in _programs:
if not _program is None:
_program.metric = None
setattr(_program, "predict", _program.execute)
__programs.append(_program)
__programs = sorted(__programs, key=lambda x: x.fitness_, reverse=True)
with open(generation_path, "wb") as f:
cPickle.dump(__programs, f)
|
from djikstra import *
import pylab as pl
N =100
varx = N*2
vary =N*2
resolution = 1
g = make_grid(N, N)
data = []
for a in range(1,100,resolution):
data.append([])
for (i,j) in g:
g[ (i,j) ] = gaussian(i,j, dy=-N/2, A=a)
for path_constant in range(1,100,resolution):
print a,path_constant
c,p = djikstra(g, (0,0), (0,N-1), constant=path_constant)
m = max([w[0] for w in p])
data[-1].append(m)
data = pl.array(data)
pl.pcolor(data)
pl.colorbar()
pl.show()
|
import pygame, sys, math
from pygame.locals import *
from viewpoint import *
from smap import *
from imagedata import *
pygame.init()
(s_w, s_h) = pygame.display.list_modes()[0]
s_dimen = (s_w, s_h)
FPS = 40
clock = pygame.time.Clock()
screen = pygame.display.set_mode(s_dimen)
pygame.display.toggle_fullscreen()
font = pygame.font.Font(pygame.font.match_font('Monospace'), 12)
def draw_text(text, top, left):
text= font.render(text, True, (0, 0, 0), (255, 255, 255))
text_r = text.get_rect()
text_r.top = top
text_r.left = left
screen.blit(text, text_r)
def dist(p1, p2):
return math.sqrt((p1[0]-p2[0]) ** 2 + (p1[1]-p2[1]) ** 2)
def main():
running = True
s = smap()
s.scale('sc1', s_dimen)
v = viewpoint(s.imgs['sc1']['topleft'][0], s.imgs['sc1']['topleft'][1], s.imgs['sc1']['bottomright'][0], s.imgs['sc1']['bottomright'][1])
data = dataset(sys.argv[1])
while running:
m_pos = pygame.mouse.get_pos()
lat = v.tlat + (float(m_pos[1])/s_h) * v.v_range
lon = v.tlon + (float(m_pos[0])/s_w) * v.h_range
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == K_ESCAPE:
running = False
for img in s.imgs:
screen.blit(s.imgs[img]['file'], (0, 0))
for datum in data.imgs:
ypos = ((data.imgs[datum]['coords'][0] - v.tlat)/v.v_range) * s_h
xpos = ((data.imgs[datum]['coords'][1] - v.tlon)/v.h_range) * s_w
print xpos, '->', s_w, ' ', ypos, '->', s_h
pygame.draw.circle(screen, (0, 0, 0), (xpos, ypos), 4)
pygame.draw.circle(screen, (255, 0, 0), (xpos, ypos), 2)
if dist((xpos,ypos), m_pos) < 10:
screen.blit(data.imgs[datum]['file'] , (xpos, ypos))
draw_text(str((lat, lon)), 0, 0)
pygame.display.flip()
if __name__ == '__main__':
main()
|
"""
Zawiera algorytm minimax.
"""
import copy
import math
import random
import properties
def alphabeta(current_board, depth):
"""
Zwraca ruch wykonany przez przeciwnika.
:param current_board: Aktualna plansza.
:param depth: Głębokość algorytmu.
:return: Ruch wykonany przez przeciwnika.
"""
possible_moves = current_board.get_possible_moves()
random.shuffle(possible_moves)
best_move = possible_moves[0]
best_score = -math.inf
alpha = -math.inf
beta = math.inf
for move in possible_moves:
temp_board = copy.deepcopy(current_board)
temp_board.make_move(move, properties.ENEMY)
board_score = minimize(temp_board, depth - 1, alpha, beta)
if board_score > best_score:
best_score = board_score
best_move = move
return best_move
def minimize(current_board, depth, alpha, beta):
possible_moves = current_board.get_possible_moves()
if depth == 0 or len(possible_moves) == 0 or current_board.is_game_over():
return current_board.evaluate(properties.ENEMY)
for move in possible_moves:
score = math.inf
if alpha < beta:
temp_board = copy.deepcopy(current_board)
temp_board.make_move(move, properties.PLAYER)
score = maximize(temp_board, depth - 1, alpha, beta)
if score < beta:
beta = score
return beta
def maximize(current_board, depth, alpha, beta):
possible_moves = current_board.get_possible_moves()
if depth == 0 or len(possible_moves) == 0 or current_board.is_game_over():
return current_board.evaluate(properties.ENEMY)
for move in possible_moves:
score = -math.inf
if alpha < beta:
temp_board = copy.deepcopy(current_board)
temp_board.make_move(move, properties.ENEMY)
score = minimize(temp_board, depth - 1, alpha, beta)
if score > alpha:
alpha = score
return alpha
|
from copy import deepcopy
import random
def find_path(scanner, memory):
DIR_reverse = {"N": 'S', "S": 'N', "W": 'E', "E": 'W'}
DIR = {"N": (-1, 0), "S": (1, 0), "W": (0, -1), "E": (0, 1)}
memory_binary = bin(memory)[2:]
memory_binary = '0'*(100-len(memory_binary)) + memory_binary
memory_list = [[j for j in memory_binary[i*10:(i+1)*10]] for i in range(10)]
memory_list[0][0] = '1'
path = []
pool = []
for (direction, distance) in scanner.items():
if distance and memory_list[DIR[direction][0]][DIR[direction][1]] == '0':
pool.append([direction,1])
if pool:
if len(pool) > 1:
random.seed()
[final_direction, final_distance] = random.choice(pool)
else:
final_direction = random.choice([i for i in scanner.keys() if scanner[i]])
final_distance = 1
if final_direction in 'WE':
for i in range(1,10):
memory_list[0][i] = '0'
else:
for i in range(1,10):
memory_list[i][0] = '0'
path += [final_direction]*final_distance
for i in range(final_distance):
for j, l in enumerate(memory_list):
memory_list[j] = l[DIR[final_direction][1]%10:] + l[:DIR[final_direction][1]%10]
memory_list = memory_list[DIR[final_direction][0]%10:] + memory_list[:DIR[final_direction][0]%10]
memory_binary = ''.join(k for k in [''.join(j) for j in memory_list])
return ''.join(path), int('0b'+memory_binary,2)
# for debuging
raise ValueError
if __name__ == '__main__':
# These "asserts" using only for self-checking and not necessary for auto-testing
DIR = {"N": (-1, 0), "S": (1, 0), "W": (0, -1), "E": (0, 1)}
WALL = "X"
EXIT = "E"
EMPTY = "."
MAX_STEP = 300
def get_visible(maze, player):
result = {}
for direction, (dr, dc) in DIR.items():
cr, cc = player
distance = -1
while maze[cr][cc] != WALL:
cr += dr
cc += dc
distance += 1
result[direction] = distance
return result
def checker(func, player, maze):
step = 0
memory = 0
while True:
result, memory = func(get_visible(maze, player), memory)
if not isinstance(result, str) or any(ch not in DIR.keys() for ch in result):
print("The function should return a string with directions.")
return False
if not isinstance(memory, int) or memory < 0 or memory >= 2 ** 100:
print("The memory number should be an integer from 0 to 2**100.")
return False
for act in result:
if step >= MAX_STEP:
print("You are tired and your scanner is off. Bye bye.")
return False
r, c = player[0] + DIR[act][0], player[1] + DIR[act][1]
if maze[r][c] == WALL:
print("BAM! You in the wall at {}, {}.".format(r, c))
return False
elif maze[r][c] == EXIT:
print("GRATZ!")
return True
else:
player = r, c
step += 1
assert checker(find_path, (1, 1), [
"XXXXXXXXXXXX",
"X..........X",
"X.XXXXXXXX.X",
"X.X......X.X",
"X.X......X.X",
"X.X......X.X",
"X.X......X.X",
"X.X......X.X",
"X.X......X.X",
"X.XXXXXXXX.X",
"X.........EX",
"XXXXXXXXXXXX",
]), "Simple"
assert checker(find_path, (1, 4), [
"XXXXXXXXXXXX",
"XX...X.....X",
"X..X.X.X.X.X",
"X.XX.X.X.X.X",
"X..X.X.X.X.X",
"XX.X.X.X.X.X",
"X..X.X.X.X.X",
"X.XX.X.X.X.X",
"X..X.X.X.X.X",
"XX.X.X.X.X.X",
"XE.X.....X.X",
"XXXXXXXXXXXX",
]), "Up Down"
assert checker(find_path, (10, 10), [
"XXXXXXXXXXXX",
"X..........X",
"X.XXXXXXXX.X",
"X.X......X.X",
"X.X.XX.X.X.X",
"X.X......X.X",
"X.X......X.X",
"X.X..E...X.X",
"X.X......X.X",
"X.XXXX.XXX.X",
"X..........X",
"XXXXXXXXXXXX",
]), "Left"
|
#!/usr/bin/python3
import sys
import os
import shutil
if len(sys.argv) != 3:
print("Zla ilosc paramaterow")
raise SystemExit()
dirDeleteFrom = sys.qrgv[1]
dirCopyTo = sys.argv[2]
for file in os.listdir(dirDeleteFrom):
if os.path.isdir(dirDeleteFrom + "/" + file):
for file2 in os.listdir(dirDeleteFrom + "/" + file):
if file2.lower().endswith('.txt'):
os.rename(dirDeleteFrom + "/" + file + "/" + file2, dirCopyTo + "/" + file2)
print("Backup file: " + dirDeleteFrom + "/" + file + "/" + file2)
os.removedirs(dirDeleteFrom + "/" + file)
|
#!/bin/python3
import sys
def nim(heaps, misere=False):
if heaps==[0,1]: return (1,1)
X = reduce(lambda x,y: x^y, heaps)#gives the xor of all the elements of the list
if X == 0: # Will lose unless all non-empty heaps have size one
# if max(heaps) > 1:
# print "You will lose :("
for i, heap in enumerate(heaps):
if heap > 0: # Empty any (non-empty) heap
chosen_heap, nb_remove = i, heap
break
else:
sums = [t^X < t for t in heaps]
chosen_heap = sums.index(True)
nb_remove = heaps[chosen_heap] - (heaps[chosen_heap]^X)
heaps_twomore = 0
for i, heap in enumerate(heaps):
n = heap-nb_remove if chosen_heap == i else heap
if n>1: heaps_twomore += 1
if heaps_twomore == 0:
chosen_heap = heaps.index(max(heaps))
heaps_one = sum(t==1 for t in heaps)
nb_remove = heaps[chosen_heap]-1 if heaps_one%2!=misere else heaps[chosen_heap]
return chosen_heap, nb_remove
g = int(raw_input().strip())
for a0 in range(g):
n = int(raw_input().strip())
heaps = [int(p_temp) for p_temp in raw_input().strip().split(' ')]
# print(heaps)
step_count=0
if n == heaps.count(1):
if n%2 == 0:
print("L")
else:
print("W")
else:
while not all(i==0 for i in heaps):
nim_sum = reduce(lambda x,y: x^y, heaps)
if nim_sum==0:
zero_moves = len(heaps) - heaps.count(0)
if zero_moves%2 != 0:
step_count += 1
break
move = nim(heaps,misere=False)
# print("Move", move)
heaps[move[0]] -= move[1]
step_count += 1
if step_count%2 == 0:
print("L")
else:
print("W")
|
from preprocess_utilities import *
raw_m = mne.io.read_raw_bdf(askopenfilename(title="Please choose "),preload=True)
raw_m.drop_channels(["A24", "C31", "D6", "D30"]) # bridged/noisy channels we choose to remove ##n
raw_m.drop_channels(['Ana' + str(i) for i in range(1, 9)])
raw_m.load_data().filter(l_freq=1., h_freq=None) ##n
raw_m.set_montage(montage=mne.channels.make_standard_montage('biosemi256', head_size=0.089), raise_if_subset=False)
ica = mne.preprocessing.ICA(n_components=.99, random_state=97, max_iter=800)
ica.fit(raw_m)
ica.save('ica_muscles.fif')
# %%
# plot components topography
ica.plot_components(outlines='skirt', picks=range(20))
# %%
ica.plot_sources(raw_m, range(10, 20))
# %%
# plot properties of component by demand
ica.plot_properties(raw_m, picks=range(11))
|
'''
1. Write a program that asks the user to enter a word that contains the letter a. The program should then print the
following two lines: On the first line should be the part of the string up to and including the first a, and on the
second line should be the rest of the string.
Sample output is shown below:
>>> Enter a word: buffalo
buffa
lo
'''
S1=input("Enter the String >")
m=len(S1)
for i in range(m): #checking line by line
if S1[i]=="a": #if string contain a it split the string
print(S1[:i+1],S1[i+1:],sep="\n")
break
|
# 迭代器练习
it = iter([1,2,3,4,5])
while True:
try:
x = next(it)
print(x)
except StopIteration:
break
|
from django import template
from capweb.helpers import reverse
from django.urls.resolvers import NoReverseMatch
register = template.Library()
@register.simple_tag()
def process_link(link, *args, **kwargs):
"""
:param link: Either a link or a route
:return: Either the original link, or the link made from the reversed route
"""
if link and (not link.startswith("http")):
# if it doesn't start with http, see if it's a django path. if not: 🤷
try:
return reverse(link)
except NoReverseMatch:
pass
else:
return link
|
from pygame.sprite import Group
from Enemy import *
from Player import *
from Projectile import ProjectileEnemy
from plateforme import Plateforme
from Move import *
class GameState:
def __init__(self):
self.player = Player(20, self) # On a un personnage
self.enemy = Enemy(700) # Un ennemi
self.platforms = [
pygame.Rect(0, 450, 300, 50), pygame.Rect(800, 450, 300, 50),
pygame.Rect(400, 300, 300, 50)
] # Trois plateformes
self.platforms_group = Group()
for plateform_rect in self.platforms: # Forme de la plateforme
plateform = Plateforme(plateform_rect)
self.platforms_group.add(plateform)
self.projectiles_group = Group() # On a plusieurs projectile pour le joueur
self.projectile_enemy_group = Group() # et pour l'ennemi
# Variables utililes pour l'exeperience utilisateur
self.delay = 0
self.delay_IA = 0
self.after_jump_IA = False
self.decalage_droite_IA = False
self.decalage_gauche_IA = False
def draw(self, window):
# Elements principaux
window.blit(GameConfig.Background_IMG, (0, 0))
self.player.draw(window)
self.enemy.draw(window)
for plateforme in self.platforms_group:
pygame.draw.rect(window, (0, 255, 0), plateforme)
# Projectiles
# Joueur
if self.player.a_tire and self.player.delay >= 20: # Si le joueur tire et que le temps entre ce tir et le précédent est correct
projectile = Projectile(self.player.rect.x + 20, self.player.rect.y, [GameConfig.ROCK_W, GameConfig.ROCK_H],
self.player.direction) # On créer un projectile
self.projectiles_group.add(projectile) # On l'ajoute au group
self.player.a_tire = False # Le joueur ne tire plus
for projectile in self.projectiles_group: # Pour tous les projectiles
projectile.mouvement(20) # On fait avancer le mouvement du projectile (valeur de 20 car plutôt réaliste)
if projectile.rect.top >= GameConfig.Y_GROUND: # Si le projectile touche le sol
self.projectiles_group.remove(projectile) # Il est détruit
if self.enemy.rect.colliderect(projectile.rect): # S'il touche l'ennemi
self.enemy.get_hit(10, 0, 0) # L'ennemi se prends un dégat
self.projectiles_group.remove(projectile) # Le projectile est détruit
self.enemy.rect.x += 3 # L'ennemi bouge un petit peu pour simuler un choc
for projectile in self.projectiles_group: # Pour tous les projectiles
projectile.draw(window) # On les dessines
# Ennemi
if self.enemy.a_tire: # Si l'ennemi tire
projectile_enemy = ProjectileEnemy(self.enemy.rect.x + 20, self.enemy.rect.y - 10, 20,
(random.random(), random.random())) # On créer un projectile
self.projectile_enemy_group.add(projectile_enemy) # On l'ajoute au group
self.enemy.a_tire = False # L'ennemi ne tire plus
for projectile in self.projectile_enemy_group: # Pour tous les projectiles
projectile.mouvement() # On fait avancer le mouvement du projectile
if self.player.rect.colliderect(projectile.rect): # Si le projectile touche le joueur
self.player.get_hit(10, 0, 0) # Le joueur se prends un dégat
self.projectile_enemy_group.remove(projectile) # Il est détruit
self.player.rect.x += 3 # Le joueur bouche pour simuler un choc
self.enemy.nb_tir -= 1 # Le nombre de projectile iré décrémente
for projectile in self.projectile_enemy_group: # Pour tous les projectiles
projectile.draw(window) # On les dessines
def is_win(self): # Gagné si le joueur et toujours en vie et l'ennemi non
return self.player.life > 0 and self.enemy.life <= 0
def is_lose(self): # Perdu si le joueur est mort et l'ennemi toujours en vie
return self.player.life <= 0 and self.enemy.life > 0
def advance_state(self, next_move): # On fait avancer l'état de la partie
self.player.advance_state(next_move, self.enemy)
self.enemy.advance_state(next_move, self.player)
def get_ia_command(self): # Foncion de l'IA
next_move = Move() # On répure les mouvements possibles
if self.player.rect.colliderect(self.enemy.rect): # Si le joueur est en colision avec l'ennemi (cas bagare)
if self.delay_IA < 70: # Si le delai avant de sauter n'est pas encore bon
self.delay_IA += 1 # Le délai augmente (le temps passe)
if random.randint(0, 1) == 0: # On choisi un coup au hasard grace a un int
next_move.punch = True # Soit un coup de poing
else:
next_move.punch_foot = True # Soit un coup de pied
else: # Si le joueur a passer assez de temps a taper l'ennemi (cas début fuite)
next_move.up = True # Il saute
self.after_jump_IA = True # variable utile dans la seconde partie de l'IA
self.delay_IA = 0
else: # Sinon, le joueur n'est pas en colision avec l'ennemi (cas régulier)
delta_x = self.player.rect.x - self.enemy.rect.x # On calcule l'ecart de position en X entre les deux
if self.after_jump_IA: # Si on a réaliser un saut juste avant (suite du cas de fuite)
if self.player.touch_border_left() or self.decalage_droite_IA:
# Si on est contre le bord gauche (on vient de faire le saut) ou qu'on est entrain de se decaler
next_move.right = True # On va a droite pour s'éloigner de l'ennemi
self.decalage_droite_IA = True # On commence donc le décalage
if self.player.touch_border_right() or self.decalage_gauche_IA:
# Si on est contre le bord droit (on vient de faire le saut) ou qu'on est entrain de se decaler
next_move.left = True # On va a gauche pour s'éloigner de l'ennemi
self.decalage_gauche_IA = True # On commence donc le décalage
if abs(delta_x > 500): # Si le décalage est assez suffisant pour reprendre en cycle normal
self.after_jump_IA = False # On est plus dans le cas particulier du saut + decalage
self.decalage_gauche_IA = False
self.decalage_droite_IA = False
else: # On est dans le cas régulier ou le perso tire des pierre
if (-450 < delta_x < -300 and self.player.direction == Player.RIGHT) or (
300 < delta_x < 450 and self.player.direction == Player.LEFT):
# Il tire dans le cas ou l'impact est a bonne distance pour touche l'ennemi et qu'il est dans la bonne direction
next_move.tir = True
if delta_x <= -450 or (0 < delta_x < 300): # S'il est trop loin (J a gauche, E a droite) ou trop proche (J:D, E:G)
next_move.right = True # Se rapproche ou s'éloine suivant la situation
if (0 > delta_x > -300) or delta_x > 450: # S'il est trop proche (J:G, E:D) ou trop loin (J:D, E:G)
next_move.left = True # Se rapproche ou s'éloine suivant la situation
# Tentative de l'utilisation de la fonction du lancer pour determiner le moment du lancer
'''result_y = self.parabole(self.enemy.rect.x, 36400.0)
print(result_y)
if result_y < GameConfig.Y_GROUND:
next_move.right = True
if result_y > GameConfig.Y_GROUND:
next_move.left = True
if result_y == GameConfig.Y_GROUND:
next_move.tir = True'''
return next_move
|
from math import tanh
from sqlite3 import dbapi2 as sqlite
def dtanh(y):
return 1.0-y*y
class searchnet:
def __init__(self,dbname):
self.con = sqlite.connect(dbname)
def __del__(self):
self.con.close()
def maketables(self):
self.con.execute('create table hiddennode(create_key)')
self.con.execute('create table wordhidden(fromid,toid,strength)')
self.con.execute('create table hiddenurl(fromid,toid,strength)')
self.con.commit()
def getstrength(self,fromid,toid,layer):
if layer == 0:
table = 'wordhidden'
else:
table = 'hiddenurl'
res = self.con.execute(
'select strength from %s where fromid=%d and toid=%d'%(table,fromid,toid)
).fetchone()
if res == None:
if layer == 0:
return -0.2
if layer == 1:
return 0
return res[0]
def setstrength(self,fromid,toid,layer,strength):
if layer==0:
table = 'wordhidden'
else:
table = 'hiddenurl'
res = self.con.execute(
'select rowid from %s where fromid=%d and toid=%d'%(table,fromid,toid)).fetchone()
if res==None:
self.con.execute(
'insert into %s(fromid,toid,strength) values (%d,%d,%f)'
%(table,fromid,toid,strength))
else :
rowid = res[0]
self.con.execute('update %s set strength=%f where rowid=%d'
%(table,strength,rowid))
def generatehiddennode(self,wordids,urls):
if len(wordids)>3:
return None
createkey = '_'.join(sorted([str(wi) for wi in wordids]))
res = self.con.execute(
"select rowid from hiddennode where create_key='%s'"%createkey).fetchone()
if res == None:
cur = self.con.execute(
"insert into hiddennode (create_key) values ('%s')" %createkey)
hiddenid = cur.lastrowid
for wordid in wordids:
self.setstrength(wordid,hiddenid,0,1.0/len(wordids))
for urlid in urls:
self.setstrength(hiddenid,urlid,1,0.1)
self.con.commit()
def getallhiddenids(self,wordids,urlids):
l1 = {}
for wordid in wordids:
cur = self.con.execute(
'select toid from wordhidden where fromid=%d'%wordid)
for row in cur:
l1[row[0]] = 1
for urlid in urlids:
cur = self.con.execute(
'select fromid from hiddenurl where toid=%d' %urlid)
for row in cur:
l1[row[0]] = 1
return l1.keys()
def setupnetwork(self,wordids,urlids):
self.wordids = wordids
self.hiddenids = self.getallhiddenids(wordids,urlids)
self.urlids = urlids
self.ai = [1.0]*len(self.wordids)
self.ah = [1.0]*len(self.hiddenids)
self.ao = [1.0]*len(self.urlids)
self.wi = [[self.getstrength(wordid,hiddenid,0)
for hiddenid in self.hiddenids]
for wordid in self.wordids]
self.wo = [[self.getstrength(hiddenid,urlid,1)
for urlid in self.urlids]
for hiddenid in self.hiddenids]
def feedforword(self):
for i in range(len(self.wordids)):
self.ai[i] = 1.0
for j in range(len(self.hiddenids)):
sum = 0.0
for i in range(len(self.wordids)):
sum += self.ai[i]*self.wi[i][j]
self.ah[j] = tanh(sum)
for k in range(len(self.urlids)):
sum = 0.0
for j in range(len(self.hiddenids)):
sum += self.ah[j]*self.wo[j][k]
self.ao[k] = tanh(sum)
return self.ao[:]
def getresult(self,wordids,urlids):
self.setupnetwork(wordids,urlids)
return self.feedforword()
def backPropagate(self,targets,N=0.5):
output_deltas = [0.0]*len(self.urlids)
for k in range(len(self.urlids)):
error = targets[k] - self.ao[k]
output_deltas[k] = dtanh(self.ao[k]) * error
hidden_deltas = [0.0]*len(self.hiddenids)
for j in range(len(self.hiddenids)):
error = 0.0
for k in range(len(self.urlids)):
error += output_deltas[k]*self.wo[j][k]
hidden_deltas[j] = dtanh(self.ah[j])*error
for j in range(len(self.hiddenids)):
for k in range(len(self.urlids)):
change = output_deltas[k]*self.ah[j]
self.wo[j][k] += N*change
for i in range(len(self.wordids)):
for j in range(len(self.hiddenids)):
change = hidden_deltas[j]*self.ai[i]
self.wi[i][j] += N*change
def updatedatabase(self):
for i in range(len(self.wordids)):
for j in range(len(self.hiddenids)):
self.setstrength(self.wordids[i],self.hiddenids[j],0,self.wi[i][j])
for j in range(len(self.hiddenids)):
for k in range(len(self.urlids)):
self.setstrength(self.hiddenids[j],self.urlids[k],1,self.wo[j][k])
self.con.commit()
def trainquery(self,wordids,urlids,selectedurl):
self.generatehiddennode(wordids,urlids)
self.setupnetwork(wordids,urlids)
self.feedforword()
targets = [0.0]*len(urlids)
targets[urlids.index(selectedurl)]=1.0
self.backPropagate(targets)
self.updatedatabase()
#wWorld,wRiver,wBank = 101,102,103
#uWorldBank,uRiver,uEarth = 201,202,203
#mynet = searchnet('nn.db')
"""
mynet.maketables()
mynet.generatehiddennode([wWorld,wBank],[uWorldBank,uRiver,uEarth])
for c in mynet.con.execute('select * from wordhidden'):
print c
for c in mynet.con.execute('select * from hiddenurl'):
print c
"""
#print mynet.getresult([wWorld,wBank],[uWorldBank,uRiver,uEarth])
#mynet.trainquery([wWorld,wBank],[uWorldBank,uRiver,uEarth],uWorldBank)
#print mynet.getresult([wWorld,wBank],[uWorldBank,uRiver,uEarth])
"""
allurls = [uWorldBank,uRiver,uEarth]
for i in range(30):
mynet.trainquery([wWorld,wBank],allurls,uWorldBank)
mynet.trainquery([wRiver,wBank],allurls,uRiver)
mynet.trainquery([wWorld],allurls,uEarth)
print mynet.getresult([wWorld,wBank],allurls)
print mynet.getresult([wRiver,wBank],allurls)
print mynet.getresult([wBank],allurls)
"""
|
# -*- coding: utf-8 -*-
from pyramid.response import Response
from pyramid.view import view_config
import model
import colander
import deform
from colanderalchemy import SQLAlchemySchemaNode
from deform import Form, ValidationFailure
from pyramid.renderers import render_to_response
from pyramid.renderers import get_renderer
from deform import ZPTRendererFactory
from pkg_resources import resource_filename
from colander import Range
import datetime
import widget
from sqlalchemy import or_
import sqlalchemy
@view_config(route_name='home', renderer='home.mako')
def home_view(request):
return {'info' : None ,
'tab' : 'home'}
@view_config(route_name='program', renderer='program.mako')
def program_view(request):
return {'info' : None,
'tab' : 'program'}
@view_config(route_name='participants', renderer='participants.mako')
def participants_view(request):
participants = model.session.query(model.User).filter(or_(model.User.student == True,model.User.paid == True)).all()
model.session.commit()
return {'participants':participants ,
'tab' : 'participants'}
@view_config(route_name='venue_accommodation', renderer='venue_accommodation.mako')
def venue_accommodation_view(request):
return {'info' : None,
'tab' : 'venue_accommodation'}
@view_config(route_name='travel', renderer='travel.mako')
def travel_view(request):
return {'info' : None,
'tab' : 'travel'}
#renderer='templates/form.pt'
# form = deform.Form(schema, buttons=('submit',), use_ajax=True)
# return self.render_form(form, success=succeed)
@view_config(route_name='registration', renderer='registration.mako')
def registration_view(request):
# schema = SQLAlchemySchemaNode(model.User)
# form = Form(schema, buttons=('submit',) , use_ajax=True )
#
#
# if 'submit' in request.POST: # detect that the submit button was clicked
#
# controls = request.POST.items() # get the form controls
#
# try:
# appstruct = form.validate(controls) # call validate
# user = model.User(email = appstruct['email'], name = appstruct['name'], surname = appstruct['surname'])
# model.session.add(user)
# model.session.commit()
# except ValidationFailure, e: # catch the exception:
##TODO update db with registry
# return {'form':e.render() ,'values': False} # re-render the form with an exception
# except Exception as e:
#
# return {'form': 'DB error' ,'values': False}
# # the form submission succeeded, we have the data
# return {'form':form.render() , "values": appstruct }
# return {'form':form.render() , "values": None , 'tab' : 'registration'}
return {'info' : None,
'tab' : 'registration'}
@view_config(route_name='contact', renderer='contact.mako')
def contact_view(request):
return {'contact' : None, 'tab' : 'contact'}
@view_config(route_name='prova', renderer='prova.mako')
def prova_view(request):
deform_templates = resource_filename('deform', 'templates')
#TODO search_path independent way of setting
bootstrap_templates = resource_filename('des_bcn','bootstrap_deform_templates')
#search_path = ('/Users/dpiscia/python_projects/bootstrap_dir/demo_bootstrap/deform_bootstrap/deform_bootstrap/templates', deform_templates)
search_path = (bootstrap_templates,deform_templates)
renderer = ZPTRendererFactory(search_path)
widget_email = deform.widget.CheckedInputWidget(
subject='Email',
confirm_subject='Confirm Email',
size=40)
arrival_choices = (("0", 'On my own'), ("1", 'BUS Morning'),
("2", 'BUS Afternoon'))
departure_choices = (("0", 'On my own'), ("1", 'BUS Afternoon'))
bus_stop_morning = (("0", 'From Airport (11:00) '), ("1", 'From City (11:30)'))
bus_stop_afternoon = (("0", 'From Airport (16:30)'), ("1", 'From City (17:00)'))
bus_stop_departure = (("0", 'To Airport'), ("1", 'To City'))
hotel_choices = (("0", 'Eden Roc'), ("1", 'On my own'))
occ_choices = (("0", 'Single'), ("1", 'Double'))
double_choices = (("0", 'Accompanying person'), ("1", 'other DES participant'))
gender_choices = (("0", 'Male'), ("1", 'Female'))
class Personal_information(colander.Schema):
name = colander.SchemaNode(
colander.String(),
description='')
Surname = colander.SchemaNode(
colander.String(),
description='')
email = colander.SchemaNode(
colander.String(),
title='Email Address',
description='',
validator=colander.Email(),
widget=widget_email)
Institution = colander.SchemaNode(
colander.String(),
description='')
Student = colander.SchemaNode(
colander.Boolean(),
description='',
widget=deform.widget.CheckboxWidget(),
title='Student')
Vegetarian = colander.SchemaNode(
colander.Boolean(),
description='',
widget=deform.widget.CheckboxWidget(),
title='Vegetarian meals')
class Arrival_information(colander.Schema):
Expected_Arrival_date = colander.SchemaNode(
colander.Date(),
#widget = deform.widget.DatePartsWidget(),
description='')
Expected_arrival_time = colander.SchemaNode(
colander.Time(),
widget = widget.TimeInputWidget(),
description='')
Arrival_BUS_option = colander.SchemaNode(
colander.String(),
validator=colander.OneOf([x[0] for x in arrival_choices]),
widget=deform.widget.RadioChoiceWidget(values=arrival_choices , inline=True),
title='Choose your option',
description='')
BUS_option_arrival_morning = colander.SchemaNode(
colander.String(),
missing=unicode(''),
widget=deform.widget.RadioChoiceWidget(values=bus_stop_morning , inline=True),
title='Choose your option',
description=''
)
BUS_option_arrival_afternoon = colander.SchemaNode(
colander.String(),
missing=unicode(''),
widget=deform.widget.RadioChoiceWidget(values=bus_stop_afternoon , inline=True),
title='Choose your option',
description=''
)
class Hotel_information(colander.Schema):
Occupancy = colander.SchemaNode(
colander.String(),
widget=deform.widget.RadioChoiceWidget(values=occ_choices , inline=True),
title='Room type',
description='')
Double_use = colander.SchemaNode(
colander.String(),
missing=unicode(''),
widget=deform.widget.RadioChoiceWidget(values=double_choices , inline=True),
title='Sharing with',
description='')
Gender_double_use = colander.SchemaNode(
colander.String(),
missing=unicode(''),
widget=deform.widget.RadioChoiceWidget(values=gender_choices , inline=True),
title='Your gender',
description='')
Proposed_name = colander.SchemaNode(
colander.String(),
missing=unicode(''),
title='To share with (optional)',
description='')
class Departure_information(colander.Schema):
Expected_departure_date = colander.SchemaNode(
colander.Date(),
description='')
Expected_departure_time = colander.SchemaNode(
colander.Time(),
widget = widget.TimeInputWidget(),
description='')
Departure_BUS_option = colander.SchemaNode(
colander.String(),
validator=colander.OneOf([x[0] for x in departure_choices]),
widget=deform.widget.RadioChoiceWidget(values=departure_choices , inline=True),
title='Choose your option',
description='')
BUS_option_departure = colander.SchemaNode(
colander.String(),
missing=unicode(''),
widget=deform.widget.RadioChoiceWidget(values=bus_stop_departure , inline=True),
title='Choose your option',
description=''
)
def validator_bus_arrival(form, value):
if (value['Arrival_BUS_option'] in ['1'] and not (value['BUS_option_arrival_morning'] in [x[0] for x in bus_stop_morning] ) ):
exc = colander.Invalid(form, 'Must select one option')
exc['BUS_option_arrival_morning'] = 'Must select one option '
raise exc
if (value['Arrival_BUS_option'] in ['2'] and not value['BUS_option_arrival_afternoon'] in [x[0] for x in bus_stop_afternoon] ):
exc = colander.Invalid(form, 'Must select one option')
exc['BUS_option_arrival_afternoon'] = 'Must select one option '
raise exc
def validator_bus_departure(form, value):
if (value['Departure_BUS_option'] in ['1'] and not ( value['BUS_option_departure'] in [x[0] for x in bus_stop_departure] ) ):
exc = colander.Invalid(form, 'Must select one option')
exc['BUS_option_departure'] = 'Must select one option '
raise exc
def validator_hotel_stay(form, value):
if (value['Occupancy'] in ['1']):
if not ( value['Double_use'] in [x[0] for x in double_choices]):
exc = colander.Invalid(form, 'Must select one option')
exc['Double_use'] = 'Must select one option '
raise exc
elif (value['Double_use'] in ['1']):
if not ( value['Gender_double_use'] in [x[0] for x in gender_choices] ):
exc = colander.Invalid(form, 'Must select one option')
exc['Gender_double_use'] = 'Must select one option '
raise exc
#validator=colander.OneOf([x[0] for x in bus_stop]),
def succeed(id_reg=None):
return Response('<div id="thanks"><h3>Thanks! You have </h3></div>')
class Schema(colander.Schema):
personal_information = Personal_information()
hotel_information = Hotel_information( title = "Eden Rock Hotel Information", validator=validator_hotel_stay)
arrival_information = Arrival_information(validator=validator_bus_arrival)
departure_information = Departure_information(validator=validator_bus_departure)
schema = Schema()
form = deform.Form(schema, buttons=('submit',) , renderer=renderer )
when_date_arr = datetime.date(2013, 9, 29)
when_time_arr = datetime.time(10, 35)
when_date_dep = datetime.date(2013, 10, 4)
when_time_dep = datetime.time(14, 35)
return render_to_response('templates/prova.pt', render_form(request, form ,
appstruct={'arrival_information': {'Expected_Arrival_date' :when_date_arr, 'Expected_arrival_time':when_time_arr },
'departure_information' : {'Expected_departure_date' :when_date_dep, 'Expected_departure_time':when_time_dep } }
, success=succeed ) , request )
def render_form(request, form, appstruct=colander.null, submitted='submit',
success=None, readonly=False):
captured = None
if submitted in request.POST:
# the request represents a form submission
try:
# try to validate the submitted values
controls = request.POST.items()
captured = form.validate(controls)
print captured
if success:
try:
# call validate
user = model.User(name = captured['personal_information']['name'],
surname = captured['personal_information']['Surname'],
email = captured['personal_information']['email'],
institution = captured['personal_information']['Institution'],
arrival_datetime = datetime.datetime.combine(captured['arrival_information']['Expected_Arrival_date'],
captured['arrival_information']['Expected_arrival_time']),
arrival_busoption = captured['arrival_information']['Arrival_BUS_option'],
arrival_bus_morning = captured['arrival_information']['BUS_option_arrival_morning'],
departure_datetime = datetime.datetime.combine(captured['departure_information']['Expected_departure_date'],
captured['departure_information']['Expected_departure_time']),
departure_busoption = captured['departure_information']['Departure_BUS_option'],
departure_bus = captured['departure_information']['BUS_option_departure'],
vegeterian = captured['personal_information']['Vegetarian'],
student = captured['personal_information']['Student'],
hotel = 1,
Occupancy = captured['hotel_information']['Occupancy'],
Double_use = captured['hotel_information']['Double_use'],
Gender_double_use = captured['hotel_information']['Gender_double_use'],
Proposed_name = captured['hotel_information']['Proposed_name'])
model.session.add(user)
model.session.commit()
id_reg = user.id
except sqlalchemy.exc.IntegrityError, exc:
reason = exc.message
if reason.endswith('is not unique'):
err_msg = "%s already exists" % exc.params[0]
model.session.rollback()
return {'form' : err_msg}
except sqlalchemy.exc.SQLAlchemyError:
err_msg = "DB connection problems, plase try again or contact with administrator"
model.session.rollback()
return {'form' : err_msg}
response = success()
if response is not None:
import mailer
mailer.send_email("smtp.gmail.com",587,"DESBarcelona2013@gmail.com","XXXXXXX",captured['personal_information']['email'], form , "DES-BCN ID registration "+str(id_reg))
if captured['personal_information']['Student'] == True:
msg = '<h3> Thanks! your registration number is '+str(id_reg)+' <br> As you registered as student you do not have to pay the registration fee </h3>'
else :
msg = '<h3> Thanks! your registration number is '+str(id_reg)+' <br> Please take note of this registration ID because it is required for the payment process</h3> <br> <a href= "https://tp.ifae.es/cgi-bin/des.cgi" button class="btn-large btn-primary"> Proceed to payment</a>'
return {'form' : msg }
html = form.render(captured)
except deform.ValidationFailure as e:
# the submitted values could not be validated
html = e.render()
else:
# the request requires a simple form rendering
html = form.render(appstruct, readonly=readonly)
if request.is_xhr:
return Response(html)
reqts = form.get_widget_resources()
# values passed to template for rendering
return {
'form':html,
'captured':repr(captured),
'demos':[],
'showmenu':False,
'title': "prova",
'css_links':reqts['css'],
'js_links':reqts['js'],
}
|
from stack import Stack
import time
p='{}{{{}}{{{{}}}}}'
s=Stack()
for item in p:
if item=="{" :
if s.peek()!=item and not s.is_empty():
s.pop()
elif s.peek()==item or s.is_empty():
s.push(item)
print(s.stack())
elif item=="}":
if s.is_empty() or s.peek()==item:
s.push(item)
print(s.stack())
continue
elif s.peek()!=item:
s.pop()
print(s.stack())
print('final stack',s.stack())
print('parenthesis are balanced') if s.is_empty() else print('unbalanced parenthesis')
|
print("hola alumnos")
print("hola mundo") ; print("adios bbys")
#para ayudarme
nombre = "mi nombre es dubian"
nombre
nombre ="mi nombre es \
dubian"
nombre
5+6
10%3
10**3
9//2
hola ="""esto es u mensaje
con tres saltos
de linea """
print(hola)
n1=2
n2=4
if n1<n2:
print("el numero 2 es mayor")
def mensaje():
print("hola hola hola")
mensaje()
"listas "
listas = [1,3,"sombrero",1+1]
listas
listas[1]
listas[:]
listas[6]
lista2 = [1,5,7,8,"marrano","cerdo","cochino"]
lista2 [0:4]
lista2 [2:]
lista2 [:4]
lista2.append("puerco")
lista2
lista2.insert(3,"choncho")
lista2
lista2.extend([0,0,0,0,0,0,0])
lista2
lista2.index(0)
print(0 in lista2)
print("dubian" in lista2)
lista2.remove(0)
lista2
lista2.pop()
lista2
lista3 = ["sandra","lucia"]
lista4 = lista2+lista3
lista4
lista3 = ["sandra","lucia"]*3
lista3
"tuplas"
tupla1 = (1,2,5,7,9)
tupla1
tupla1[2]
lista_t1=list(tupla1)
lista_t1
tupla=tuple(lista_t1)
tupla
print(2 in tupla)
lista2.count(0)
tupla.count(10)
len(lista2)
len(tupla)
tupla2 = ("dubian",)
len(tupla2)
nac = ("dubian", 10 ,3, 1998)
nombre , dia , mes , agno = nac
nombre
dia
mes
agno
nac.index(3)
"diccionarios"
capital = {"colombia": "bogota","argentina":"buenos aires", "cuba": "cuba"}
capital["colombia"]
capital["argentina"]
capital["mexico"]="medellin"
capital
capital["mexico"]="mexico"
capital
del capital["colombia"]
capital
tuplita = ("colombia","eeuu","ecuador")
diccionario = {tuplita[0]:"bogota",tuplita[1]:"washintong",tuplita[2]:"quito"}
diccionario
basquet ={23:"jordan","nombre":"michael","equipo":"chicago","anillos":[1991,1993,1995,1997]}
basquet[23]
basquet["anillos"]
basquet.keys()
basquet.values()
len(basquet)
"condicionales"
"if"
def evaluar(nota):
valoracion ="aprobado"
if nota < 5:
valoracion = "suspendido"
return valoracion
evaluar(4)
print("programa de evaluación de notas de alumnos")
nota_alumno = input("introduce la nota del alumno")
def evaluar(nota):
valoracion ="aprobado"
if nota < 5:
valoracion = "suspendido"
return valoracion
evaluar(int(nota_alumno))
print("control del edad para las personas")
edad = int(input("dijite su edad : "))
if edad < 18:
print("puede pasar")
elif edad > 105:
print("la edad es incorrecta")
else:
print("no puede pasar")
nota1 = int(input("escriba la nota: "))
if nota1 < 4:
print("perdio")
elif nota1 < 5:
print("mejor")
elif nota1 < 7:
print("paso")
elif nota1 < 9:
print("super")
else:
print("eres pro")
"ejercicios"
def DevuelveMax(a,b):
print(a," es el numero mayor")
DevuelveMax(5,7)
def DevuelveMax(a,b):
if a>b :
print(a," es el numero mayor")
else:
print(b," es el numero mayor")
DevuelveMax(5,7)
"ejercicio 2"
nombre = input("nombre: ")
apellido = input("apellido: ")
telefono = input("telefono: ")
diccionario = {"Nombre ":nombre, "Apellido":apellido,"Tel":telefono}
print("los datos son: ", diccionario)
"ejercicio 3"
n1 = int(input("escribe primer numero: "))
n2 = int(input("escribe segundo numero: "))
n3 = int(input("escribe tercer numero: "))
print((n1+n2+n3)/3)
"condicionales and. or y in"
edad = 700
if 0<edad <100:
print("edad correcta")
else:
print("edad incorrecta")
s1 = 100000
print("el salario del precidente es ",s1)
s2 = 10000
s3 = 1000
s4 = 100
if s1>s2>s3>s4:
print("el orden es correcto")
else:
print("el orden es incorrecto")
distancia = 5
hermanos = 7
salario = 10000
if distancia > 40 and hermanos >= 2 and salario < 20000 or salario< 5000:
print("felicitaciones, optubiste la beca")
else:
print("no cumples para la beca ")
"bucles"
for i in ["primavera","verano","otoño"]:
print("es la ",i," vez que se imprime")
|
#!/usr/bin/env python
# coding: utf-8
# In[9]:
number=20 # which number in fibonacci list do you want?(take the 20th as an example)
fibo=[1,1] #set up a basic list
for i in range(2,1000): #set up a cycle
a=fibo[i-1]+fibo[i-2] #get the fibonacci list
fibo.append(a) #add the new number into the list
print(fibo[number]) #return the asked number
# In[13]:
def blabla(list): #define a function
number=len(list) #how many factors?
low=list[0] #get the first number
high=list[number-1] #get the last number
new=[high,low] #set up a new list
return new #return the new list
blabla([1,2,3,4,5,6,7,8]) #example
# In[16]:
def bla(list): #define a function
dododo=[] #set up a list
for i in list: #start a cycle
if i/2-int(i/2)==0: #for all factors in the given list,if it is even
dododo.append(i)#then it should be added into the new list
return dododo #retrun the new list
bla([3,45,23,43,43,4,12343,43,24]) #exapmle
# In[20]:
def blablabla(year): #define a function
if year/4-int(year/4)==0: # if the year is leap
print("True!!!") #then return True
blablabla(2000) #example
# In[23]:
a=input("what da you want to say?") #define a input variable
b=a.split() #divided the input into parts by " "
sentence = " ".join(b[::-1]) #reunion the parts in descending order
sentence #print it
|
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
import os,sys
import traceback
import re
from bs4 import BeautifulSoup
from openpyxl.reader.excel import load_workbook
from openpyxl import Workbook
from openpyxl.cell import get_column_letter
from openpyxl.styles import colors, Style, PatternFill, Border, Side, Alignment, Protection, Font
class Tables():
def __init__(self):
self.titles = []
self.tables = []
self.hostlist = None
self.blacklist = None
def clear(self):
"""clear the data have been loaded.
"""
self.titles = []
self.tables = []
def load(self,filename):
"""load data from given file path,the file can be .xlsx or .htm(l)
"""
name, ext = os.path.splitext(filename)
if ext == ".xlsx":
try:
self.load_xlsx(filename)
except:
print traceback.print_exc()
return False
elif ext in ('.htm','.html'):
try:
self.load_html(filename)
except:
print traceback.print_exc()
return False
else:
print "error: can load %s!"%filename
return False
return True
def load_html(self,html_file):
html = file(os.path.realpath(html_file),'r').read().decode('utf-8')
soup = BeautifulSoup(html)
if soup.html:
tables = soup.html.body.find_all('table',recursive=False)
else:
tables = soup.find_all('table',recursive=False)
for table in tables:
try:
title = table.find_previous('p').get_text().encode('utf-8')
except:
title = ''
self.titles.append(title)
self.tables.append([])
for row in table.find_all('tr',recursive=False):
line = []
for val in row.find_all('td',recursive=False):
value = val.get_text().strip()
if type(value) == unicode:
value = value.encode('utf-8')
line.append(value)
if self.__black_filter(line):
pass
elif self.__host_filter(line):
self.tables[-1].append(line)
else:
pass
def load_xlsx(self,xlsx_file):
wb = load_workbook(filename = xlsx_file)
sheet_ranges = wb.active
row = 1
end = sheet_ranges.get_highest_row()
th = ""
col_max = sheet_ranges.get_highest_column()
col_max2 = col_max
while row <= end:
col = []
col_empty = 0
col_max_empty = 5
col_end = False
while not col_end:
column = len(col)+1
value = sheet_ranges.cell(row=row,column=column).value
if value:
if type(value) == unicode:
value = value.encode('utf-8').strip()
col_empty = 0
else:
value = ''
col_empty += 1
col.append(value)
if column >= col_max2:
col_end = True
elif col_empty >= col_max_empty:
col = col[:-col_empty]
col_end = True
if len(col) == 1:
if th:
self.titles.append(th)
self.tables.append(worktable)
col_max2 = col_max
th = col[0]
worktable = []
elif len(col) > 1:
if self.__black_filter(col):
pass
elif th and self.__host_filter(col):
worktable.append(col)
if col[0] == '序号':
col_max2= len(col)
row += 1
self.titles.append(th)
self.tables.append(worktable)
return 0
def __load_xlsx_list(self,xlsx_file):
wb = load_workbook(filename = xlsx_file)
sheet_ranges = wb.active
end = sheet_ranges.get_highest_row()
row = 1
keyset = set()
while row <= end:
value = sheet_ranges.cell(row=row,column=1).value
if type(value) == unicode:
keyset.add(value.encode('utf-8'))
row += 1
return keyset
def load_list(self,list_file):
"""load a list from a text or xlsx file,return python set type.
"""
if not list_file:
keyset = set()
elif list_file[-5:] == '.xlsx':
keyset = self.__load_xlsx_list(list_file)
else:
with open(list_file) as list_f:
keyset = set()
for line in list_f:
if line.strip():
keyset.add(line.strip())
return keyset
def __filter(self,row,keyset):
for value in row:
if type(value) == str:
if value in keyset:
return True
return False
def __host_filter(self,row):
keyset = self.hostlist
if not keyset:
return True
if '序号' == row[0]:
return True
else:
return self.__filter(row,keyset)
def __black_filter(self,row):
keyset = self.blacklist
if not keyset:
return False
else:
return self.__filter(row,keyset)
def get_html(self,titles = 'all'):
"""return the tables you given titles use html table format,default is all tables.
"""
tables = self.tables
output = ''
if titles == 'all':
for i, title in enumerate(self.titles):
output += ('<p>%s</p>\n'%title)
output += table2html(tables[i])
output += '<br/>\n'
else:
for title in titles.split(','):
output += ('%s<br/>\n'%title)
n = 0
finded = []
for value in self.titles:
if value == title:
finded.append(n)
n += 1
for num in finded:
output += table2html(tables[num])
output += '<br/>\n'
return output
def get_xlsx(self,dest_filename):
"""create a .xlsx file have all data have been loaded to you given path and filename.
"""
tables = self.tables
wb = Workbook()
ws = wb.worksheets[0]
row_num = 0
column_widths = []
titlestyle = Style(font=Font(size=13))
thstyle = Style(font=Font(size=10,bold=True,color=colors.BLUE),
border=Border(top=Side(border_style='medium',color=colors.BLACK),
bottom=Side(border_style='medium',color=colors.BLACK),
left=Side(border_style='medium',color=colors.BLACK),
right=Side(border_style='medium',color=colors.BLACK))
)
tdstyle = Style(font=Font(size=10),
border=Border(top=Side(border_style='medium',color=colors.BLACK),
bottom=Side(border_style='medium',color=colors.BLACK),
left=Side(border_style='medium',color=colors.BLACK),
right=Side(border_style='medium',color=colors.BLACK))
)
for title_num, title in enumerate(self.titles):
row_num += 1
cell = ws.cell('%s%s'%(get_column_letter(1), row_num))
cell.value = title
cell.style = titlestyle
row_num += 1
th = False
for row in tables[title_num]:
row_num += 1
col_num = 0
th = False
for i, value in enumerate(row):
# count column width
if type(value) == str:
l = len(value.decode('utf-8'))
if l == len(value):
pass
else:
l = l*2
elif type(value) == int:
l = len(str(value))
else:
l = len(value)
if len(column_widths) > i:
if l > column_widths[i]:
column_widths[i] = l
else:
column_widths.append(l)
col_num += 1
cell = ws.cell('%s%s'%(get_column_letter(col_num), row_num))
cell.value = value
if value == '序号':
th = True
if th:
ws.row_dimensions[row_num].style = thstyle
else:
ws.row_dimensions[row_num].style = tdstyle
row_num += 1
for i, column_width in enumerate(column_widths):
if column_width < 6:
ws.column_dimensions[get_column_letter(i+1)].width = 6
elif column_width > 40:
ws.column_dimensions[get_column_letter(i+1)].width = 40
else:
ws.column_dimensions[get_column_letter(i+1)].width = column_width
wb.save(filename = dest_filename)
TABLE_STYLE = 'border=1 cellSpacing=0 borderColor=#000000 cellPadding=1 style="font-family: 宋体, Georgia, serif;font-size:14px;word-wrap: break-word;word-break: normal"'
TH_STYLE = 'style="white-space:nowrap;font-weight:bold;color:blue"'
TD_STYLE = ''
def table2html(table):
column_widths = []
PER = 10
MIN_WIDTH = 2
MAX_WIDTH = 50
for row in table:
for i, value in enumerate(row):
if type(value) == str:
l = len(value.decode('utf-8'))
if l == len(value):
l = l/2 + 1
elif type(value) == int:
l = len(str(value))
else:
l = len(value)
if len(column_widths) > i:
if l > column_widths[i]:
column_widths[i] = l
else:
column_widths.append(l)
total_width = 0
for width in column_widths:
if width < MAX_WIDTH:
total_width += width
else:
total_width += MAX_WIDTH
html = '<table width=%d %s>\n'%(total_width*PER,TABLE_STYLE)
for row in table:
if row[0] == '序号':
html += ' <tr>\n'
for i, val in enumerate(row):
if column_widths[i] < MIN_WIDTH:
width = MIN_WIDTH
elif column_widths[i] > MAX_WIDTH:
width = MAX_WIDTH
else:
width = column_widths[i]
html += "<th width=%d %s>%s</th>"%(width*PER,TH_STYLE,val)
html += ' </tr>\n'
else:
html += ' <tr>\n'
for val in row:
html += "<td %s>%s</td>"%(TD_STYLE,val)
html += ' </tr>\n'
html += '</table>'
return html
def get_html(filename,titles = 'all',host_file = None,blacklist = None):
t = Tables()
if host_file:
t.hostlist = t.load_list(host_file)
if blacklist:
t.blacklist = t.load_list(blacklist)
t.load(filename)
#t.get_xlsx('test.xlsx')
return t.get_html(titles)
if __name__ == "__main__":
if len(sys.argv) == 5:
print get_html(sys.argv[1],sys.argv[2],sys.argv[3],sys.argv[4])
elif len(sys.argv) == 4:
print get_html(sys.argv[1],sys.argv[2],sys.argv[3])
elif len(sys.argv) == 3:
print get_html(sys.argv[1],sys.argv[2])
else:
print """Usage:
readxlsx.py <FILE> all/title1[,title2] [HOST_FILE] [Blacklist_FILE]
FILE can be an unix text file or xlsx file.
"""
|
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from __future__ import annotations
import json
from datetime import timedelta
from typing import TYPE_CHECKING, Any, Sequence
from airflow.configuration import conf
from airflow.exceptions import AirflowException
from airflow.models import BaseOperator
from airflow.providers.amazon.aws.hooks.step_function import StepFunctionHook
from airflow.providers.amazon.aws.triggers.step_function import StepFunctionsExecutionCompleteTrigger
if TYPE_CHECKING:
from airflow.utils.context import Context
class StepFunctionStartExecutionOperator(BaseOperator):
"""
An Operator that begins execution of an AWS Step Function State Machine.
Additional arguments may be specified and are passed down to the underlying BaseOperator.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:StepFunctionStartExecutionOperator`
:param state_machine_arn: ARN of the Step Function State Machine
:param name: The name of the execution.
:param state_machine_input: JSON data input to pass to the State Machine
:param aws_conn_id: aws connection to uses
:param do_xcom_push: if True, execution_arn is pushed to XCom with key execution_arn.
:param waiter_max_attempts: Maximum number of attempts to poll the execution.
:param waiter_delay: Number of seconds between polling the state of the execution.
:param deferrable: If True, the operator will wait asynchronously for the job to complete.
This implies waiting for completion. This mode requires aiobotocore module to be installed.
(default: False, but can be overridden in config file by setting default_deferrable to True)
"""
template_fields: Sequence[str] = ("state_machine_arn", "name", "input")
template_ext: Sequence[str] = ()
ui_color = "#f9c915"
def __init__(
self,
*,
state_machine_arn: str,
name: str | None = None,
state_machine_input: dict | str | None = None,
aws_conn_id: str = "aws_default",
region_name: str | None = None,
waiter_max_attempts: int = 30,
waiter_delay: int = 60,
deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False),
**kwargs,
):
super().__init__(**kwargs)
self.state_machine_arn = state_machine_arn
self.name = name
self.input = state_machine_input
self.aws_conn_id = aws_conn_id
self.region_name = region_name
self.waiter_delay = waiter_delay
self.waiter_max_attempts = waiter_max_attempts
self.deferrable = deferrable
def execute(self, context: Context):
hook = StepFunctionHook(aws_conn_id=self.aws_conn_id, region_name=self.region_name)
execution_arn = hook.start_execution(self.state_machine_arn, self.name, self.input)
if execution_arn is None:
raise AirflowException(f"Failed to start State Machine execution for: {self.state_machine_arn}")
self.log.info("Started State Machine execution for %s: %s", self.state_machine_arn, execution_arn)
if self.deferrable:
self.defer(
trigger=StepFunctionsExecutionCompleteTrigger(
execution_arn=execution_arn,
waiter_delay=self.waiter_delay,
waiter_max_attempts=self.waiter_max_attempts,
aws_conn_id=self.aws_conn_id,
region_name=self.region_name,
),
method_name="execute_complete",
timeout=timedelta(seconds=self.waiter_max_attempts * self.waiter_delay),
)
return execution_arn
def execute_complete(self, context: Context, event: dict[str, Any] | None = None) -> None:
if event is None or event["status"] != "success":
raise AirflowException(f"Trigger error: event is {event}")
self.log.info("State Machine execution completed successfully")
return event["execution_arn"]
class StepFunctionGetExecutionOutputOperator(BaseOperator):
"""
An Operator that returns the output of an AWS Step Function State Machine execution.
Additional arguments may be specified and are passed down to the underlying BaseOperator.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:StepFunctionGetExecutionOutputOperator`
:param execution_arn: ARN of the Step Function State Machine Execution
:param aws_conn_id: aws connection to use, defaults to 'aws_default'
"""
template_fields: Sequence[str] = ("execution_arn",)
template_ext: Sequence[str] = ()
ui_color = "#f9c915"
def __init__(
self,
*,
execution_arn: str,
aws_conn_id: str = "aws_default",
region_name: str | None = None,
**kwargs,
):
super().__init__(**kwargs)
self.execution_arn = execution_arn
self.aws_conn_id = aws_conn_id
self.region_name = region_name
def execute(self, context: Context):
hook = StepFunctionHook(aws_conn_id=self.aws_conn_id, region_name=self.region_name)
execution_status = hook.describe_execution(self.execution_arn)
response = None
if "output" in execution_status:
response = json.loads(execution_status["output"])
elif "error" in execution_status:
response = json.loads(execution_status["error"])
self.log.info("Got State Machine Execution output for %s", self.execution_arn)
return response
|
import json
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.decorators import login_required
from django.db import IntegrityError
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from django.views import View
from network.forms import NewPostForm
from network.models import Post
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse
from django.core.paginator import Paginator
from .models import User
class Index(View):
def get(self, request):
success_url = "network/index.html"
# pagination
page_obj = paginatorAll(request)
# Give the user the post form if they are logged in.
if request.user.is_authenticated:
post_form = NewPostForm()
ctx = {
'page': "all-posts",
'post_form': post_form,
'posts': page_obj,}
return render(request, success_url, ctx)
# User is not logged in so don't display the post form.
else:
ctx = {
'page': "default",
'posts': page_obj,}
return render(request, success_url, ctx)
def post(self, request):
post_form = NewPostForm(request.POST)
if post_form.is_valid():
post_form.instance.owner = request.user
post_form.save()
return HttpResponseRedirect(reverse("index"))
class ProfileView(View):
def get(self, request, username):
profile = User.objects.get(username=username)
# pagination
page_obj = paginatorUser(request, profile.id)
ctx = {
'page': "profile",
'posts': page_obj,
'profile': profile}
return render(request, "network/index.html", ctx)
class Following(LoginRequiredMixin, View):
def get(self, request):
# pagination
page_obj = paginatorFollowing(request)
ctx = {
'page': 'following',
'posts': page_obj,
}
return render(request, "network/index.html", ctx)
def login_view(request):
if request.method == "POST":
# Attempt to sign user in
username = request.POST["username"]
password = request.POST["password"]
user = authenticate(request, username=username, password=password)
# Check if authentication successful
if user is not None:
login(request, user)
return HttpResponseRedirect(reverse("index"))
else:
return render(request, "network/login.html", {
"message": "Invalid username and/or password."
})
else:
return render(request, "network/login.html")
def logout_view(request):
logout(request)
return HttpResponseRedirect(reverse("index"))
def register(request):
if request.method == "POST":
username = request.POST["username"]
email = request.POST["email"]
# Ensure password matches confirmation
password = request.POST["password"]
confirmation = request.POST["confirmation"]
if password != confirmation:
return render(request, "network/register.html", {
"message": "Passwords must match."
})
# Attempt to create new user
try:
user = User.objects.create_user(username, email, password)
user.save()
except IntegrityError:
return render(request, "network/register.html", {
"message": "Username already taken."
})
login(request, user)
return HttpResponseRedirect(reverse("index"))
else:
return render(request, "network/register.html")
### Api routes
### ------------------
@csrf_exempt
@login_required
def follow(request, user_id):
# Query for requested user
try:
followee = User.objects.get(id=user_id)
print(f"followee: {followee}")
except User.DoesNotExist:
return JsonResponse({"error": "User not found."}, status=404)
# Return user contents
if request.method == "GET":
return JsonResponse(followee.serialize())
# Update whether followee is followed or not
elif request.method == "PUT":
data = json.loads(request.body)
if data.get("new_follower_id") is not None:
new_follower_id = data["new_follower_id"]
user = User.objects.get(id=request.user.id)
# Toggle follwee's membership from user's followers field.
if followee in user.follows.all():
print(f"UNFOLLOW: {request.user} will unfollow: {new_follower_id}")
user.follows.remove(followee)
user.save()
followee_follows_count = followee.followers.all().count()
return JsonResponse({
"follow-button-text": "Follow",
"username": followee.username.capitalize(),
"followee_follows_count": followee_follows_count,
})
else:
print(f"FOLLOW: {request.user} will follow: {new_follower_id}")
user.follows.add(followee)
user.save()
followee_follows_count = followee.followers.all().count()
return JsonResponse({
"follow-button-text": "Unfollow",
"username": followee.username.capitalize(),
"followee_follows_count": followee_follows_count,
})
# Email must be via GET or PUT
else:
return JsonResponse({
"error": "GET or PUT request required."
}, status=400)
@csrf_exempt
@login_required
def update_post(request, post_id):
# Query for requested user
try:
post = Post.objects.get(id=post_id)
print(f"post: {post}")
except User.DoesNotExist:
return JsonResponse({"error": "Post not found."}, status=404)
# Return user contents
if request.method == "GET":
return JsonResponse(post.serialize())
# Update post
elif request.method == "PUT":
data = json.loads(request.body)
if data.get("text") is not None:
edited_text = data["text"]
print(f"User: {request.user} edited their post to say: {edited_text}")
post.text = edited_text
elif data.get("liked") is not None:
edited_like = data["liked"]
print(f"User: {request.user} liked post#: {post.id}")
print(post.likes.all())
if (request.user in post.likes.all()):
post.likes.remove(request.user)
else:
post.likes.add(request.user)
post.save()
print(post.likes.all().count())
like_count = post.likes.all().count()
return JsonResponse({"data": like_count})
# Email must be via GET or PUT
else:
return JsonResponse({
"error": "GET or PUT request required."
}, status=400)
### Utility Functions
### ------------------
def query_all_posts():
return Post.objects.all().order_by('-timestamp')
def query_user_posts(user_pk):
return Post.objects.filter(owner=user_pk).order_by('-timestamp')
# pagination
def paginatorAll(request):
post_list = query_all_posts()
paginator = Paginator(post_list, 10)
page_number = request.GET.get('page')
page_obj = paginator.get_page(page_number)
return page_obj
def paginatorUser(request, pk):
post_list = query_user_posts(pk)
paginator = Paginator(post_list, 10)
page_number = request.GET.get('page')
page_obj = paginator.get_page(page_number)
return page_obj
def paginatorFollowing(request):
print(request.user.follows.values_list('id', flat=True).distinct())
follower_user_ids = request.user.follows.values_list('id', flat=True)
print(Post.objects.filter(owner__in=follower_user_ids))
post_list = Post.objects.filter(owner__in=follower_user_ids).order_by('-timestamp')
paginator = Paginator(post_list, 10)
page_number = request.GET.get('page')
page_obj = paginator.get_page(page_number)
return page_obj
|
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'EFXPaths.ui'
#
# Created by: PyQt5 UI code generator 5.7.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(378, 131)
self.horizontalLayout = QtWidgets.QHBoxLayout(Form)
self.horizontalLayout.setContentsMargins(0, 0, 0, 0)
self.horizontalLayout.setObjectName("horizontalLayout")
self.efxPathsGroup = QtWidgets.QGroupBox(Form)
self.efxPathsGroup.setObjectName("efxPathsGroup")
self.verticalLayout_5 = QtWidgets.QVBoxLayout(self.efxPathsGroup)
self.verticalLayout_5.setObjectName("verticalLayout_5")
self.path0 = saneQLineEdit(self.efxPathsGroup)
self.path0.setObjectName("path0")
self.verticalLayout_5.addWidget(self.path0)
self.path1 = saneQLineEdit(self.efxPathsGroup)
self.path1.setObjectName("path1")
self.verticalLayout_5.addWidget(self.path1)
self.path2 = saneQLineEdit(self.efxPathsGroup)
self.path2.setObjectName("path2")
self.verticalLayout_5.addWidget(self.path2)
self.path3 = saneQLineEdit(self.efxPathsGroup)
self.path3.setObjectName("path3")
self.verticalLayout_5.addWidget(self.path3)
self.horizontalLayout.addWidget(self.efxPathsGroup)
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "Form"))
self.efxPathsGroup.setTitle(_translate("Form", "EFX Paths"))
from model.lineEditOverride import saneQLineEdit
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
Form = QtWidgets.QWidget()
ui = Ui_Form()
ui.setupUi(Form)
Form.show()
sys.exit(app.exec_())
|
import os
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
SITE_ID = 1
DEBUG = True
TEMPLATE_DEBUG=DEBUG
ALLOWED_HOSTS = ['']
ROOT_URLCONF = 'HelpingHandServer.urls'
STATIC_URL = '/static/'
WSGI_APPLICATION = 'HelpingHandServer.wsgi.application'
STATIC_ROOT = os.path.join(BASE_DIR,'static')
STATICFILE_DIRS = (
os.path.join(BASE_DIR,'main/static/'),
os.path.join(BASE_DIR,'page/static/'),
)
#Middleware classes
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
#Context Processors
TEMPLATE_CONTEXT_PROCESSORS = (
"django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.static",
"django.core.context_processors.tz",
"django.contrib.messages.context_processors.messages",
"main.context_processors.loginForm",
"main.context_processors.logoutForm",
"main.context_processors.signupForm",
"django.core.context_processors.request"
)
SECRET_KEY = '18p-q%byt_6oi5njkle(os(icwy3_bf-7*p--=1u1w^e!#$-d#'
#Administrators
ADMINS = (
('John Carlyle', 'john.w.carlyle@gmail.com'),
('Jeremy Crowe', 'crowe.jb@gmail.com'),
('Morgan McDermott', 'morganmcdermott@gmail.com')
)
MANAGERS = ADMINS
INSTALLED_APPS = (
'south',
'main',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'main',
'page',)
#Template directories
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, 'main/templates'),
os.path.join(BASE_DIR, 'page/templates')
)
DATABASES = { 'default': {
'ENGINE' : 'django.db.backends.sqlite3', 'NAME' : os.path.join(BASE_DIR, 'db.db')
} }
|
# coding=utf-8
import discord
import json
import random
from discord.ext import commands
# Store the clues card info
class Card:
"""
This class is only for data generation
Args:
name_en,
name_tw,
url
"""
def __init__(self, name_en, name_tw = '', url = ''):
self.name_en = name_en
self.name_tw = name_tw
self.url = url
class CluesList:
"""Stores all the clues card info"""
clueslist = []
def __init__(self):
with open('cards.json', 'r', encoding='utf8') as jfile:
self.jdata = json.load(jfile)
self.clueslist = self.jdata['Clues']
def get(self):
return self.clueslist.copy()
def getBGurl(self):
"""Return the card background URL"""
return self.jdata['CluesMethods-merge-BG']
def get_singleBGurl(self):
return self.jdata['Clues-BG']
class MethodList:
"""Stores all the method card info, btw 'weapon' means 'method' for legacy reason."""
weaponslist = []
def __init__(self):
with open('cards.json', 'r', encoding='utf8') as jfile:
self.jdata = json.load(jfile)
self.weaponslist = self.jdata['Weapons']
def get(self):
return self.weaponslist.copy()
def getBGurl(self):
return self.jdata['CluesMethods-merge-BG']
def get_singleBGurl(self):
return self.jdata['Methods-BG']
class EventList:
"""Stores all the event card info."""
eventList = []
def __init__(self):
with open('event_cards.json', 'r', encoding='utf8') as jfile:
self.jdata = json.load(jfile)
self.eventList = self.jdata['events']
def get(self):
return self.eventList.copy()
def getBGurl(self):
return self.jdata['event-BGurl']
class UtilList:
"""Stores all the utility's card info"""
def __init__(self):
with open('cards_options.json', 'r', encoding='utf8') as jfile:
self.jdata = json.load(jfile)
self.hintslist : list = self.jdata['Hints']
self.locCard : dict = self.jdata['locationOC']
self.codCard : dict = self.jdata['CauseOfDeath']
def getlocCard(self):
return self.locCard.copy()
def getcodCard(self):
return self.codCard.copy()
def gethintslist(self):
return self.hintslist.copy()
def hintBG(self):
return self.jdata['Hints-BG-url']
def codBG(self):
return self.codCard['url']
def locBG(self):
return self.locCard['url']
class CardData(commands.Cog):
def __init__(self, bot):
self.bot = bot
# Events
@commands.Cog.listener()
async def on_ready(self):
print('[CardData] module loaded.')
# Commands
@commands.command(name = 'cluesList')
async def _cluesList(self, ctx):
"""Return a whole clues list for the game
Should be used only for debug"""
clueslist = CluesList().get()
for every_card in clueslist:
output_string = '> ' + every_card['name_en']
await ctx.send(output_string)
@commands.command(name = 'weaponsList')
async def _weaponsList(self, ctx):
"""Return a whole weapon list for the game
Should be used only for debug"""
weaponslist = MethodList().get()
for every_card in weaponslist:
output_string = '> ' + every_card['name_en']
await ctx.send(output_string)
@commands.command(name = "whoissuperman", aliases=["superman"])
async def _whoissuperman(self, ctx):
wid = random.randint(300,1000)
hei = random.randint(300,1000)
url = 'https://place-puppy.com/'+str(wid)+'x'+str(hei)
embed=discord.Embed(title="I am Superman", description="A!", color=0xff0000)
embed.set_image(url = url)
await ctx.send(embed=embed)
def setup(bot):
bot.add_cog(CardData(bot)) |
from django.contrib.auth.models import User
from django_extensions.db.models import TimeStampedModel
from django.db import models
class Store(TimeStampedModel):
owner = models.ForeignKey(User)
name = models.CharField(max_length=50)
code = models.CharField(max_length=20, unique=True)
address_line_1 = models.CharField(max_length=50)
address_line_2 = models.CharField(max_length=50, blank=True)
city = models.CharField(max_length=50)
state = models.CharField(max_length=50)
pincode = models.CharField(max_length=6)
contact = models.CharField(max_length=10)
def __unicode__(self):
return "{0}-{1}-{2}".format(self.owner, self.name, self.code)
class Product(TimeStampedModel):
name = models.CharField(max_length=50)
code = models.CharField(max_length=20, unique=True)
category = models.CharField(max_length=10)
sub_category = models.CharField(max_length=10)
def __unicode__(self):
return "{0}-{1}".format(self.name, self.code)
class Vendor(TimeStampedModel):
store = models.ForeignKey(Store)
name = models.CharField(max_length=50)
code = models.CharField(max_length=20, unique=True)
address_line_1 = models.CharField(max_length=50)
address_line_2 = models.CharField(max_length=50, blank=True)
city = models.CharField(max_length=50)
state = models.CharField(max_length=50)
pincode = models.CharField(max_length=6)
contact = models.CharField(max_length=10)
def __unicode__(self):
return "{0}-{1}".format(self.name, self.code)
class PurchaseBill(TimeStampedModel):
store = models.ForeignKey(Store)
vendor = models.ForeignKey(Vendor)
bill_no = models.PositiveIntegerField()
billing_date = models.DateTimeField()
total_discount = models.FloatField(default=0)
total_tax = models.FloatField(default=0)
total_amount = models.FloatField()
total_payable_amount = models.FloatField()
def __unicode__(self):
return "{0}-{1}".format(self.vendor, self.bill_no)
class PurchaseDetail(TimeStampedModel):
bill = models.ForeignKey(PurchaseBill)
product = models.ForeignKey(Product)
discount_per_unit = models.FloatField(default=0)
tax_per_unit = models.FloatField(default=0)
unit_price = models.FloatField()
mrp = models.FloatField()
quantity = models.PositiveIntegerField()
expiry_date = models.DateField()
def __unicode__(self):
return "{0}-{1}".format(self.bill, self.product)
class SellBill(TimeStampedModel):
store = models.ForeignKey(Store)
customer_name = models.CharField(max_length=50)
bill_no = models.PositiveIntegerField()
billing_date = models.DateTimeField()
total_discount = models.FloatField(default=0)
total_tax = models.FloatField(default=0)
total_amount = models.FloatField()
total_payable_amount = models.FloatField()
def __unicode__(self):
return "{0}-{1}".format(self.customer_name, self.bill_no)
class SellDetail(TimeStampedModel):
bill = models.ForeignKey(SellBill)
product = models.ForeignKey(Product)
discount_per_unit = models.FloatField(default=0)
tax_per_unit = models.FloatField(default=0)
mrp = models.FloatField()
quantity = models.PositiveIntegerField()
expiry_date = models.DateField(blank=True, null=True)
def __unicode__(self):
return "{0}-{1}".format(self.bill, self.product)
|
from django.contrib import admin
from django.conf.urls.defaults import *
from models import Sequence, TestStep, StepTemplate
class TestStepInline(admin.TabularInline):
model = Sequence.tests.through
class SequenceAdmin(admin.ModelAdmin):
inlines = [
TestStepInline,
]
exclude = ('tests',)
admin.site.register(Sequence, SequenceAdmin)
admin.site.register([TestStep, StepTemplate])
|
import numpy as np
import math
from scipy import optimize as op
import matplotlib.pyplot as plt
class NonlinearTimeVaryingMPC:
def __init__(self):
self.Nx=3 #状态量个数
self.Np=15 #预测时域
self.Nc=2 #控制量个数
self.L=1 #轴距
self.Q=10*np.eye(self.Np+1)
self.R=10*np.eye(self.Np+1)
self.N=100 #仿真次数
self.T=0.05 #时间间隔
self.x_real = np.zeros((self.N+1, self.Nx)) #真实位置
self.x_real[0,:]=[0,0,math.pi/6] #初始位置
self.Xout=np.zeros((self.N,self.Nx)) #轨迹点序列
for i in range(self.N):
self.Xout[i,0]=i*self.T
self.Xout[i,1]=2
self.Xout[i,2]=0
self.lb = np.array([0.7, -0.44])
self.ub = np.array([5, 0.8])
self.initX=np.array([2,0,2,0])
self.position=[1,25,5]
self.State_Initial=np.zeros((self.N,3))
self.State_Initial[0,:]=[0,0,math.pi/6]
self.Xref=np.zeros((self.Np,1))
self.Yref=np.zeros((self.Np,1))
self.PHIref=np.zeros((self.Np,1))
def getCostFunction(self, x, R, Q,n):
cost = 0
[X, Y, PHI] = self.x_real[n, :]
X_predict = np.zeros((self.Np, 1))
Y_predict = np.zeros((self.Np, 1))
PHI_predict = np.zeros((self.Np, 1))
X_error = np.zeros((self.Np + 1, 1))
Y_error = np.zeros((self.Np + 1, 1))
PHI_error = np.zeros((self.Np + 1, 1))
v = np.zeros((self.Np, 1))
delta_f = np.zeros((self.Np, 1))
for i in range(self.Np):
if i == 0:
v[i, 0] = x[0]
delta_f[i, 0] = x[1]
X_predict[i, 0] = X + self.T * v[i, 0] * math.cos(PHI)
Y_predict[i, 0] = Y + self.T * v[i, 0] * math.sin(PHI)
PHI_predict[i, 0] = PHI + self.T * v[i, 0] * math.tan(delta_f[i, 0]) / self.L
else:
v[i, 0] = x[2]
delta_f[i, 0] = x[3]
X_predict[i, 0] = X_predict[i - 1] + self.T * v[i, 0] * math.cos(PHI_predict[i - 1])
Y_predict[i, 0] = Y_predict[i - 1] + self.T * v[i, 0] * math.sin(PHI_predict[i - 1])
PHI_predict[i, 0] = PHI_predict[i - 1] + self.T * v[i, 0] * math.tan(delta_f[i, 0]) / self.L
X_real = np.zeros((self.Np + 1, 1))
Y_real = np.zeros((self.Np + 1, 1))
X_real[0, 0] = X
X_real[1:self.Np+1, 0] = np.ravel(X_predict)
Y_real[0, 0] = Y
Y_real[1:self.Np+1, 0] = np.ravel(Y_predict)
X_error[i, 0] = X_real[i, 0] - self.Xout[i, 0]
Y_error[i, 0] = Y_real[i, 0] - self.Xout[i, 1]
PHI_error[i, 0] = PHI_predict[i, 0] - self.Xout[i, 2]
cost = cost + np.dot(np.dot(Y_error.T, R) , Y_error)*self.position[1] + np.dot(np.dot(X_error.T, Q), X_error)*self.position[0]+np.dot(np.dot(PHI_error.T,Q),PHI_error)*self.position[2]
return cost[0][0]
def getCon(self):
cons=({'type':'ineq','fun':lambda x:x[0]-self.lb[0]},
{'type':'ineq','fun':lambda x:-x[0]+self.ub[0]},
{'type':'ineq','fun':lambda x:x[2]-self.lb[0]},
{'type':'ineq','fun':lambda x:-x[2]+self.ub[0]},
{'type':'ineq','fun':lambda x:x[1]-self.lb[1]},
{'type':'ineq','fun':lambda x:-x[1]+self.ub[1]},
{'type':'ineq','fun':lambda x:x[3]-self.lb[1]},
{'type':'ineq','fun':lambda x:-x[3]+self.ub[1]})
return cons
def getXYZ(self,X00,v,deltaf):
if deltaf==0:
deltaf=0.00001
X=X00[0] - math.sin(X00[2])/math.tan(deltaf) + math.sin(X00[2] + self.T*v*math.tan(deltaf))/math.tan(deltaf)
Y=X00[1] + math.cos(X00[2])/math.tan(deltaf) - math.cos(X00[2] + self.T*v*math.tan(deltaf))/math.tan(deltaf)
Z=X00[2] + self.T*v*math.tan(deltaf)
return np.array([X,Y,Z])
def MPC(self):
X00=np.zeros((self.Nx,1))
for j in range(self.N):
cons=self.getCon()
res=op.minimize(fun=self.getCostFunction,x0=self.initX,args=(self.R,self.Q,j),constraints=cons)
v=res.x[0]
deltaf=res.x[1]
X00[0,0]=self.x_real[j,0]
X00[1,0]=self.x_real[j,1]
X00[2,0]=self.x_real[j,2]
self.x_real[j+1,:]=np.ravel(self.getXYZ(X00,v,deltaf))
if __name__ == '__main__':
nonLinearMPC=NonlinearTimeVaryingMPC()
nonLinearMPC.MPC()
plt.figure(2)
plt.plot(nonLinearMPC.x_real[:, 0], nonLinearMPC.x_real[:, 1], "*")
plt.plot(nonLinearMPC.Xout[:, 0], nonLinearMPC.Xout[:, 1])
plt.savefig("NonlinearTimeVaryingMPC.png", dpi=700)
plt.show() |
"""
@author : macab (macab@debian)
@file : assert
@created : Sunday Mar 17, 2019 00:28:58 IST
"""
'''
Python provides the assert statement to check if a given logical expression is true or false. Program execution proceeds
only if the expression is true and raises the AssertionError when it is false. The following code shows the usage of the
assert statement.It is much like an if-else
'''
x = int(input())
assert x >= 0
print(x)
|
# Chapter 5 Exercise 4
# Python 3 version
import os
start_time = 0
LOOP_COUNT = 200
words = []
words_dict = {}
########################################################
# TIMER FUNCTIONS
def start_timer():
global start_time
(utime, stime) = os.times()[0:2]
start_time = utime+stime
def end_timer(txt):
(utime, stime) = os.times()[0:2]
end_time = utime+stime
print("{0:<12}: {1:01.3f} seconds".format(txt, end_time-start_time))
def load_data():
global words
script_dir = os.path.dirname(__file__)
rel_path = "words"
abs_file_path = os.path.join(script_dir, rel_path)
words = open(abs_file_path).read().split('\n')
def brute_force():
global words
for i, word in enumerate(words):
if word == 'Zulu':
line = i
return line
break
def infunc():
global words
if 'Zulu' in words:
return 1
else:
return 0
def index():
global words
return words.index('Zulu')
def dictionary():
global words_dict
return words_dict['Zulu']
########################################################
# MAIN
load_data()
# Brute force
line = 0
start_timer()
for i in range(1, LOOP_COUNT):
line = brute_force()
end_timer("Brute_force")
print("Brute_force line number:", line)
line = 0
# index
start_timer()
for i in range(1, LOOP_COUNT):
line = index()
end_timer("Index")
print("Index line number:", line)
line = 0
# in
start_timer()
for i in range(0, LOOP_COUNT):
line = infunc()
end_timer("In")
line = 0
# Create a dictionary from the words list
i = 0
start_timer()
globals()['words_dict'] = dict(zip(words, range(len(words))))
for i in range(1, LOOP_COUNT):
line = dictionary()
end_timer("Dictionary")
print("Dictionary line number:", line)
line = 0
|
import numpy as np
import matplotlib.pyplot as plt
def Plotter():
Y1 = np.loadtxt("WICC_2_yValues_QL_5.txt")
Y1 = Y1[81:]
array_y = []
gap = len(Y1) / 91
rewardsForEveryHundred = np.split(np.array(Y1), len(Y1) / gap)
for r in rewardsForEveryHundred:
array_y.append(sum(r / gap))
Y1 = np.loadtxt("WICC_0_yValues_QL_1.txt")
Y3 = np.loadtxt("WICC_1_yValues_QL_1.txt")
Y5 = np.loadtxt("WICC_2_yValues_QL_1.txt")
Y7 = np.loadtxt("WOCC_yValues_QL_1.txt")
X = np.loadtxt("WICC_0_xValues_QL_1.txt")
ZeroLine = [0] * np.shape(Y1)[0]
Figure, ax = plt.subplots()
Y1 = np.array(array_y)
ax.plot(X, Y1 / 1, color='blue', label='Card counting (2 Arrays)')
ax.plot(X, Y3 / 1, color='cyan', label='Card counting (3 Arrays)')
ax.plot(X, Y5 / 1, color='green', label='Card counting (10 Arrays)')
ax.plot(X, Y7 / 1, color='blue', label='No Card counting')
ax.plot(X, ZeroLine, color='black', linewidth=0.5)
ax.set_ylim(-1, 1)
plt.xlabel("Number of Episodes")
plt.ylabel("Estimated Rewards per Round")
plt.title("Q Learning for 1 Round")
plt.legend(loc=4)
plt.show()
if __name__ == '__main__':
Plotter()
|
from pysnooper import snoop
class Solution:
"""
s = '226'
set[0] = 2
set[1] = [[2,2],[22]]
set[2] = [[2,26],[22,6],[2,2,6]]
"""
@snoop()
def numDecodings(self, s: str) -> int:
if not s or s.startswith('0'): return 0
dp = [0] * len(s)
dp[0] = 1
for i in range(1, len(s)):
if s[i] != '0':
dp[i] += dp[i - 1]
if s[i - 1] != '0' and int(s[i - 1:i + 1]) <= 26:
tmp = dp[i - 2] if i - 2 >= 0 else 1
dp[i] += tmp
return dp[-1]
# todo return multiply of len of all subset
if __name__ == "__main__":
a = Solution()
s = "4757562545844617494555774581341211511296816786586787755257741178599337186486723247528324612117156948"
a.numDecodings(s)
|
from .account_api import route as accounts_router
from app.commons.common_util import TypedAPIRouter
accounts_router = TypedAPIRouter(router=accounts_router, prefix='/v1', tags=['登录/校验相关 API'])
|
#!/usr/bin/python
from collections import defaultdict
def get_input(filename):
data = []
with open(filename) as fp:
for line in fp:
if line.strip():
start, end = line.split('->')
x1, y1 = start.split(',')
x2, y2 = end.split(',')
data.append([(int(x1), int(y1)), (int(x2), int(y2))])
return data
def a():
data = get_input('input_05.txt')
vents = defaultdict(int)
for start, end in data:
start_x = min([start[0], end[0]])
end_x = max([start[0], end[0]])
start_y = min([start[1], end[1]])
end_y = max([start[1], end[1]])
if start[0] == end[0]:
for i in range(start_y, end_y + 1):
vents[(start[0], i)] += 1
if start[1] == end[1]:
for i in range(start_x, end_x + 1):
vents[(i, start[1])] += 1
points = 0
for point in vents.values():
if point >= 2:
points += 1
print(points)
def b():
data = get_input('input_05.txt')
vents = defaultdict(int)
for start, end in data:
start_x = min([start[0], end[0]])
end_x = max([start[0], end[0]])
start_y = min([start[1], end[1]])
end_y = max([start[1], end[1]])
if start[0] == end[0]:
for i in range(start_y, end_y + 1):
vents[(start[0], i)] += 1
if start[1] == end[1]:
for i in range(start_x, end_x + 1):
vents[(i, start[1])] += 1
if (
abs(start[0] - start[1]) == abs(end[0] - end[1])
or start[0] + start[1] == end[0] + end[1]
):
print('dia')
if start[0] > end[0]:
end_x = end[0] - 1
step_x = -1
else:
end_x = end[0] + 1
step_x = 1
if start[1] > end[1]:
end_y = end[1] - 1
step_y = -1
else:
end_y = end[1] + 1
step_y = 1
for x, y in zip(
range(start[0], end_x, step_x),
range(start[1], end_y, step_y)
):
vents[(x, y)] += 1
points = 0
for point in vents.values():
if point >= 2:
points += 1
print(points)
def main():
a()
b()
if __name__ == '__main__':
main()
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import shopApp.models
class Migration(migrations.Migration):
dependencies = [
('shopApp', '0027_auto_20160212_1426'),
]
operations = [
migrations.AlterField(
model_name='banneraddpage',
name='ad_banner1',
field=models.ImageField(help_text=b"<font color='green'>*You should upload a image file between 60px height and 60px width resolution</font>", upload_to=shopApp.models.upload_to1, verbose_name=b'*ad_banner1'),
preserve_default=True,
),
migrations.AlterField(
model_name='banneraddpage',
name='ad_description',
field=models.CharField(max_length=500, verbose_name=b'*ad_description'),
preserve_default=True,
),
migrations.AlterField(
model_name='banneraddpage',
name='ad_name',
field=models.CharField(default=0, max_length=800, verbose_name=b'*ad_name'),
preserve_default=False,
),
migrations.AlterField(
model_name='banneraddpage',
name='ad_title',
field=models.CharField(default=0, max_length=800, verbose_name=b'*ad_title'),
preserve_default=False,
),
migrations.AlterField(
model_name='banneraddpage',
name='ad_type',
field=models.CharField(default=0, max_length=800, verbose_name=b'*ad_type', choices=[(b'text', b'text'), (b'image', b'image')]),
preserve_default=False,
),
migrations.AlterField(
model_name='banneraddpage',
name='ad_url1',
field=models.URLField(max_length=800, verbose_name=b'*ad_url1'),
preserve_default=True,
),
migrations.AlterField(
model_name='banneraddpage',
name='category',
field=models.ForeignKey(default=0, verbose_name=b'*category', to='shopApp.Category'),
preserve_default=False,
),
]
|
from flask import render_template, request, redirect, url_for, session
from app import userUI
from management import managerUI
from app.tools import validate
from app.tools.dbTools import DataBaseManager
from app.tools.hashTools import Hash
@userUI.route('/newuser')
@managerUI.route('/newuser')
def create_user_landing():
if 'authorized' in session and session['authorized'] is True:
return redirect(url_for("render_gallery"))
return render_template("newuser.html", username=None, first_name=None, last_name=None,
email=None, password=None, password_conf=None)
@userUI.route('/newuser/create', methods=['POST'])
@managerUI.route('/newuser/create', methods=['POST'])
def create_user():
if 'authorized' in session and session['authorized'] is True:
return redirect(url_for("render_gallery"))
input_username = request.form.get("username")
input_first_name = request.form.get("first_name")
input_last_name = request.form.get("last_name")
input_email = request.form.get("email")
input_password = request.form.get("password")
input_password_conf = request.form.get("password_conf")
field = validate.regex()
username = field.validate(field.user_name_pattern, input_username)
first_name = field.validate(field.first_name_pattern, input_first_name)
last_name = field.validate(field.last_name_pattern, input_last_name)
email = field.validate(field.email_pattern, input_email)
password = field.validate(field.password_pattern, input_password)
password_conf = password == input_password_conf
err_msg = compose_error_message(username, first_name, last_name, email, password, password_conf)
if err_msg is not None:
return render_template("newuser.html", error=err_msg, username=input_username, first_name=input_first_name,
last_name=input_last_name, email=input_email, password=input_password,
password_conf=input_password_conf)
pwd_manager = Hash()
salt, hashpwd = pwd_manager.get_salt_hash(password)
stored_pwd = "$" + salt + "$" + hashpwd.decode("utf-8")
dbm = DataBaseManager()
email_already_registered = dbm.email_already_exists(email)
if not email_already_registered:
db_success = dbm.add_user(username, first_name, last_name, email, stored_pwd)
if db_success:
session['user'] = username
session['authorized'] = True
return redirect(url_for('render_gallery'))
else:
# Getting here means that either there was a database error or the username is already taken.
# Since the user will have to retry anyways, we might as well say there was an error with the
# chosen username
err_msg = ["Username is unavailable."]
return render_template("newuser.html", error=err_msg, username=input_username, first_name=input_first_name,
last_name=input_last_name, email=input_email, password=input_password,
password_conf=input_password_conf)
else:
err_msg = ["An account already exists with this Email"]
return render_template("newuser.html", error=err_msg, username=username, first_name=first_name,
last_name=last_name, email=email, password=password, password_conf=password_conf)
def compose_error_message(username, first_name, last_name, email, password, password_conf):
err_msg = []
if not username:
err_msg.append("Invalid username.")
if not first_name:
err_msg.append("Invalid first name.")
if not last_name:
err_msg.append("Invalid last name.")
if not email:
err_msg.append("Invalid email.")
if not password:
err_msg.append("Invalid password.")
if not password_conf:
err_msg.append("Password and verification do not match.")
if len(err_msg) > 0:
err_msg.append("Please hover your cursor over the fields below to check their requirements.")
else:
err_msg = None
return err_msg
|
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# license removed for brevity
import rospy
from geometry_msgs.msg import Twist
import random
def flowfield_generator():
# ROS节点初始化
rospy.init_node('flowfield_generator', anonymous=False)
#创建一个Publisher,发布名为/person_info的topic,消息类型为learning_topic::Person,队列长度10
flowfield_publisher = rospy.Publisher('flowfield_velocity', Twist, queue_size=10)
#设置循环的频率
rate = rospy.Rate(10)
while not rospy.is_shutdown():
flowfield_velocity = Twist()
#保证流场速度为[-0.5, 0.5]
flowfield_velocity.linear.x = 0
flowfield_velocity.linear.y = 0
flowfield_publisher.publish(flowfield_velocity)
#按照循环频率延时
rate.sleep()
if __name__ == '__main__':
try:
flowfield_generator()
except rospy.ROSInterruptException as r:
rospy.loginfo("flowfield_generator node terminated.")
rospy.loginfo(r)
|
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 27 02:35:49 2020
@author: Asad PC
"""
##through vscode 2
from pandas_datareader import data
#from pandas_datareader.utils import RemoteDataError
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from datetime import datetime
START_DATE = '2015-01-01'
END_DATE = str(datetime.now().strftime('%Y-%m-%d'))
STOCK = 'GOOG'
def stock_stats(stock_data):
return{
'short_rolling': stock_data.rolling(window=10).mean(),
'long_rolling': stock_data.rolling(window=100).mean()}
def plot(stock_data, ticker):
stats = stock_stats(stock_data)
plt.subplots(figsize=(20,10))
plt.plot(stock_data, label=ticker)
plt.show()
def get_data(ticker):
stock_data = data.DataReader(ticker, 'yahoo', START_DATE, END_DATE)
print(stock_data)
adj_close = stock_data['Adj Close']
plot(adj_close, ticker)
return stock_data
stock_data = get_data(STOCK) |
from cx_Freeze import setup, Executable
base = None
includefiles = [
('database/server_schema.sql','database/server_schema.sql'),
('config/magicked_admin.conf.example','magicked_admin.conf'),
('config/server_one.init.example','server_one.init'),
('config/server_one.motd.example','server_one.motd')
]
# "FuzzyWuzzy"
build_exe_options = {
"packages": ["os", "queue", "idna", "lxml", "requests", "encodings"],
"excludes": ["tkinter"],
"includes": [],
"include_files": includefiles,
"include_msvcr": True,
"zip_include_packages": "*",
"zip_exclude_packages": ""
}
setup(name="Magicked Administrator",
version="0.0.1",
description="Scripted management, stats, and bot for KF2-Server",
options = {"build_exe": build_exe_options},
executables=[
Executable("main.py",
base=base,
targetName="magicked_admin.exe",
icon="icon.ico"
)
]
)
|
from downloader import download
download(2017, 9)
with open('aoc2017_9input.txt') as inputfile:
data = inputfile.read()
print(data)
score = 0
level = 0
skip = False
garbage = False
remove = 0
for c in data.strip():
if skip:
skip = False
elif c == '!':
skip = True
elif c == '>':
garbage = False
elif garbage:
remove += 1
continue
elif c == '<':
garbage = True
elif c == '{':
level += 1
score += level
elif c == '}':
level -= 1
print(score)
print(remove)
|
# LP written by GAMS Convert at 12/13/18 10:24:46
#
# Equation counts
# Total E G L N X C B
# 52 27 9 16 0 0 0 0
#
# Variable counts
# x b i s1s s2s sc si
# Total cont binary integer sos1 sos2 scont sint
# 101 101 0 0 0 0 0 0
# FX 0 0 0 0 0 0 0 0
#
# Nonzero counts
# Total const NL DLL
# 645 645 0 0
#
# Reformulation has removed 1 variable and 1 equation
from pyomo.environ import *
model = m = ConcreteModel()
m.x1 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x2 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x3 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x4 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x5 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x6 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x7 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x8 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x9 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x10 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x11 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x12 = Var(within=Reals,bounds=(0,0.036),initialize=0)
m.x13 = Var(within=Reals,bounds=(0,0.298),initialize=0)
m.x14 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x15 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x16 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x17 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x18 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x19 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x20 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x21 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x22 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x23 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x24 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x25 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x26 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x27 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x28 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x29 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x30 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x31 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x32 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x33 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x34 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x35 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x36 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x37 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x38 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x39 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x40 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x41 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x42 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x43 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x44 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x45 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x46 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x47 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x48 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x49 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x50 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x51 = Var(within=Reals,bounds=(0,70.5),initialize=0)
m.x52 = Var(within=Reals,bounds=(0,70.5),initialize=0)
m.x53 = Var(within=Reals,bounds=(0,70.5),initialize=0)
m.x54 = Var(within=Reals,bounds=(0,70.5),initialize=0)
m.x55 = Var(within=Reals,bounds=(0,70.5),initialize=0)
m.x56 = Var(within=Reals,bounds=(0,70.5),initialize=0)
m.x57 = Var(within=Reals,bounds=(0,70.5),initialize=0)
m.x58 = Var(within=Reals,bounds=(0,70.5),initialize=0)
m.x59 = Var(within=Reals,bounds=(0,70.5),initialize=0)
m.x60 = Var(within=Reals,bounds=(0,70.5),initialize=0)
m.x61 = Var(within=Reals,bounds=(0,70.5),initialize=0)
m.x62 = Var(within=Reals,bounds=(0,70.5),initialize=0)
m.x63 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x64 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x65 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x66 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x67 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x68 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x69 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x70 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x71 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x72 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x73 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x74 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x75 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x76 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x77 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x78 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x79 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x80 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x81 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x82 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x83 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x84 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x85 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x86 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x87 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x88 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x89 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x90 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x91 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x92 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x93 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x94 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x95 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x96 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x98 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x99 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x100 = Var(within=Reals,bounds=(None,None),initialize=0)
m.x101 = Var(within=Reals,bounds=(None,None),initialize=0)
m.obj = Objective(expr= 934*m.x39 + 934*m.x40 + 934*m.x41 - m.x76 + m.x98 - m.x99 - m.x100 - m.x101, sense=maximize)
m.c1 = Constraint(expr= m.x3 + m.x5 + m.x7 + m.x8 + m.x10 + m.x12 + m.x14 + m.x20 + m.x22 + m.x28 <= 8.775)
m.c2 = Constraint(expr= m.x4 + m.x6 + m.x9 + m.x11 + m.x13 + m.x15 + m.x21 + m.x23 + 1.407*m.x24 + 0.611*m.x25
+ 0.631*m.x26 - m.x28 + m.x29 <= 11.64)
m.c3 = Constraint(expr= 0.209*m.x24 + 2.03*m.x25 + 0.9*m.x26 - m.x29 <= 21.92)
m.c4 = Constraint(expr= - m.x24 - m.x25 - m.x26 + m.x27 == 0)
m.c5 = Constraint(expr= - 5.141*m.x24 - 21.646*m.x25 - 49.845*m.x26 + m.x76 == 0)
m.c6 = Constraint(expr= 0.848*m.x1 + 0.569*m.x2 + 0.269*m.x16 + 0.149*m.x17 + 0.403*m.x18 + 0.133*m.x19 - m.x42 >= 0)
m.c7 = Constraint(expr= 0.221*m.x3 + 0.174*m.x4 - m.x43 >= 0)
m.c8 = Constraint(expr= 0.045*m.x5 + 0.03*m.x6 - m.x44 >= 0)
m.c9 = Constraint(expr= 0.285*m.x16 + 0.221*m.x17 + 0.274*m.x20 + 0.26*m.x21 + 0.288*m.x22 + 0.287*m.x23 - 0.225*m.x39
- 0.152*m.x40 - 0.15*m.x41 - m.x45 >= 0)
m.c10 = Constraint(expr= 0.251*m.x14 + 0.211*m.x15 + 0.115*m.x18 + 0.352*m.x19 - m.x46 >= 0)
m.c11 = Constraint(expr= 0.092*m.x7 - m.x47 >= 0)
m.c12 = Constraint(expr= 4.456*m.x8 + 3.964*m.x9 + 3.408*m.x22 + 1.031*m.x23 - 0.965*m.x39 - 2.64*m.x40 - 0.935*m.x41
- m.x48 >= 0)
m.c13 = Constraint(expr= 0.725*m.x10 + 0.563*m.x11 + 0.373*m.x14 + 0.264*m.x15 + 0.536*m.x16 + 0.544*m.x17
+ 0.361*m.x18 + 0.212*m.x19 + 0.594*m.x20 + 0.442*m.x21 + 0.503*m.x22 + 0.328*m.x23
- 0.235*m.x39 - 0.232*m.x40 - 0.581*m.x41 - m.x49 >= 0)
m.c14 = Constraint(expr= 2.244*m.x12 + 1.666*m.x13 - m.x50 >= 0)
m.c15 = Constraint(expr= - 0.848*m.x1 - 0.569*m.x2 - 0.269*m.x16 - 0.149*m.x17 - 0.403*m.x18 - 0.133*m.x19 + m.x30 == 0)
m.c16 = Constraint(expr= - 0.221*m.x3 - 0.174*m.x4 + m.x31 == 0)
m.c17 = Constraint(expr= - 0.045*m.x5 - 0.03*m.x6 + m.x32 == 0)
m.c18 = Constraint(expr= - 0.285*m.x16 - 0.221*m.x17 - 0.274*m.x20 - 0.26*m.x21 - 0.288*m.x22 - 0.287*m.x23 + m.x33
== 0)
m.c19 = Constraint(expr= - 0.251*m.x14 - 0.211*m.x15 - 0.115*m.x18 - 0.352*m.x19 + m.x34 == 0)
m.c20 = Constraint(expr= - 0.092*m.x7 + m.x35 == 0)
m.c21 = Constraint(expr= - 4.456*m.x8 - 3.964*m.x9 - 3.408*m.x22 - 1.031*m.x23 + m.x36 == 0)
m.c22 = Constraint(expr= - 0.725*m.x10 - 0.563*m.x11 - 0.373*m.x14 - 0.264*m.x15 - 0.536*m.x16 - 0.544*m.x17
- 0.361*m.x18 - 0.212*m.x19 - 0.594*m.x20 - 0.442*m.x21 - 0.503*m.x22 - 0.328*m.x23 + m.x37
== 0)
m.c23 = Constraint(expr= - 2.244*m.x12 - 1.666*m.x13 + m.x38 == 0)
m.c24 = Constraint(expr= m.x39 + m.x40 + m.x41 == 1)
m.c25 = Constraint(expr= 4.79*m.x1 + 4.79*m.x2 + 8.24*m.x3 + 8.24*m.x4 + 5.78*m.x5 + 5.78*m.x6 + 2*m.x7 + 5.71*m.x8
+ 5.71*m.x9 + 9.19*m.x10 + 9.19*m.x11 + 1.22*m.x12 + 1.22*m.x13 + 12.46*m.x14 + 12.46*m.x15
+ 5.54*m.x16 + 5.54*m.x17 + 9.18*m.x18 + 9.18*m.x19 + 6.87*m.x20 + 6.87*m.x21 + 7.44*m.x22
+ 7.44*m.x23 + 4.261*m.x24 + 1.873*m.x25 + 1.933*m.x26 - m.x51 - m.x63 - 25*m.x75 <= 0)
m.c26 = Constraint(expr= 10.89*m.x1 + 10.89*m.x2 + 0.89*m.x3 + 0.89*m.x4 + 3.37*m.x5 + 3.37*m.x6 + 2.36*m.x7
+ 7.6*m.x8 + 7.6*m.x9 + 14.42*m.x10 + 14.42*m.x11 + 1.11*m.x12 + 1.11*m.x13 + 11.35*m.x14
+ 11.35*m.x15 + 10.3*m.x16 + 10.3*m.x17 + 3.94*m.x18 + 3.94*m.x19 + 10.19*m.x20 + 10.19*m.x21
+ 10.21*m.x22 + 10.21*m.x23 + 2.854*m.x24 + 1.262*m.x25 + 1.302*m.x26 - m.x52 - m.x64
- 25*m.x75 <= 0)
m.c27 = Constraint(expr= 18.7*m.x1 + 18.7*m.x2 + 5.43*m.x3 + 5.43*m.x4 + 4.03*m.x5 + 4.03*m.x6 + 4.13*m.x7 + 7.28*m.x8
+ 7.28*m.x9 + 10.59*m.x10 + 10.59*m.x11 + 0.56*m.x12 + 0.56*m.x13 + 24.38*m.x14 + 24.38*m.x15
+ 9.24*m.x16 + 9.24*m.x17 + 16.15*m.x18 + 16.15*m.x19 + 10.61*m.x20 + 10.61*m.x21 + 9.63*m.x22
+ 9.63*m.x23 + 0.04*m.x24 + 0.04*m.x25 + 0.04*m.x26 - m.x53 - m.x65 - 25*m.x75 <= 0)
m.c28 = Constraint(expr= 9.83*m.x1 + 9.83*m.x2 + 3.31*m.x3 + 3.31*m.x4 + 7.09*m.x5 + 7.09*m.x6 + 2.13*m.x7 + 8.15*m.x8
+ 8.15*m.x9 + 12.01*m.x10 + 12.01*m.x11 + 0.78*m.x12 + 0.78*m.x13 + 22.03*m.x14 + 22.03*m.x15
+ 8.97*m.x16 + 8.97*m.x17 + 23.69*m.x18 + 23.69*m.x19 + 9.14*m.x20 + 9.14*m.x21 + 16.18*m.x22
+ 16.18*m.x23 + 0.04*m.x24 + 0.04*m.x25 + 0.04*m.x26 - m.x54 - m.x66 - 25*m.x75 <= 0)
m.c29 = Constraint(expr= 8.03*m.x1 + 8.03*m.x2 + 11.13*m.x3 + 11.13*m.x4 + 4.64*m.x5 + 4.64*m.x6 + 7.18*m.x7
+ 8.48*m.x8 + 8.48*m.x9 + 3.47*m.x10 + 3.47*m.x11 + 1.19*m.x12 + 1.19*m.x13 + 16.91*m.x14
+ 16.91*m.x15 + 15.82*m.x16 + 15.82*m.x17 + 28.12*m.x18 + 28.12*m.x19 + 18.38*m.x20
+ 18.38*m.x21 + 20.11*m.x22 + 20.11*m.x23 + 0.04*m.x24 + 0.04*m.x25 + 0.04*m.x26 - m.x55
- m.x67 - 25*m.x75 <= 0)
m.c30 = Constraint(expr= 20.95*m.x1 + 20.95*m.x2 + 10.33*m.x3 + 10.33*m.x4 + 5.91*m.x5 + 5.91*m.x6 + 5.88*m.x7
+ 10.71*m.x8 + 10.71*m.x9 + 10.75*m.x10 + 10.75*m.x11 + 0.44*m.x12 + 0.44*m.x13 + 9.47*m.x14
+ 9.47*m.x15 + 13*m.x16 + 13*m.x17 + 20.58*m.x18 + 20.58*m.x19 + 11.5*m.x20 + 11.5*m.x21
+ 16.86*m.x22 + 16.86*m.x23 + 0.04*m.x24 + 0.04*m.x25 + 0.04*m.x26 - m.x56 - m.x68 - 25*m.x75
<= 0)
m.c31 = Constraint(expr= 15.67*m.x1 + 15.67*m.x2 + 3.27*m.x3 + 3.27*m.x4 + 7.67*m.x5 + 7.67*m.x6 + 3.21*m.x7
+ 9.34*m.x8 + 9.34*m.x9 + 5.88*m.x10 + 5.88*m.x11 + 1.89*m.x12 + 1.89*m.x13 + 10.97*m.x14
+ 10.97*m.x15 + 14.74*m.x16 + 14.74*m.x17 + 17.73*m.x18 + 17.73*m.x19 + 9.22*m.x20 + 9.22*m.x21
+ 14.86*m.x22 + 14.86*m.x23 + 0.04*m.x24 + 0.04*m.x25 + 0.04*m.x26 - m.x57 - m.x69 - 25*m.x75
<= 0)
m.c32 = Constraint(expr= 15.48*m.x1 + 15.48*m.x2 + 2.65*m.x3 + 2.65*m.x4 + 9.23*m.x5 + 9.23*m.x6 + 9.2*m.x7
+ 12.76*m.x8 + 12.76*m.x9 + 7.3*m.x10 + 7.3*m.x11 + 3.04*m.x12 + 3.04*m.x13 + 9.7*m.x14
+ 9.7*m.x15 + 10.64*m.x16 + 10.64*m.x17 + 15.06*m.x18 + 15.06*m.x19 + 13.36*m.x20 + 13.36*m.x21
+ 14*m.x22 + 14*m.x23 + 0.04*m.x24 + 0.04*m.x25 + 0.04*m.x26 - m.x58 - m.x70 - 25*m.x75 <= 0)
m.c33 = Constraint(expr= 11.35*m.x1 + 11.35*m.x2 + 5.47*m.x3 + 5.47*m.x4 + 5.93*m.x5 + 5.93*m.x6 + 6.89*m.x7
+ 8.93*m.x8 + 8.93*m.x9 + 4.14*m.x10 + 4.14*m.x11 + 2.93*m.x12 + 2.93*m.x13 + 4.93*m.x14
+ 4.93*m.x15 + 5.64*m.x16 + 5.64*m.x17 + 4.58*m.x18 + 4.58*m.x19 + 3.85*m.x20 + 3.85*m.x21
+ 8.04*m.x22 + 8.04*m.x23 + 0.04*m.x24 + 0.04*m.x25 + 0.04*m.x26 - m.x59 - m.x71 - 25*m.x75
<= 0)
m.c34 = Constraint(expr= 8.38*m.x1 + 8.38*m.x2 + 3.67*m.x3 + 3.67*m.x4 + 9.05*m.x5 + 9.05*m.x6 + 3.3*m.x7 + 10.22*m.x8
+ 10.22*m.x9 + 4.25*m.x10 + 4.25*m.x11 + 4.99*m.x12 + 4.99*m.x13 + 6.41*m.x14 + 6.41*m.x15
+ 4.9*m.x16 + 4.9*m.x17 + 9.76*m.x18 + 9.76*m.x19 + 3.87*m.x20 + 3.87*m.x21 + 6.69*m.x22
+ 6.69*m.x23 + 0.04*m.x24 + 0.04*m.x25 + 0.04*m.x26 - m.x60 - m.x72 - 25*m.x75 <= 0)
m.c35 = Constraint(expr= 8.23*m.x1 + 8.23*m.x2 + 3.18*m.x3 + 3.18*m.x4 + 7.59*m.x5 + 7.59*m.x6 + 9.7*m.x7 + 6.18*m.x8
+ 6.18*m.x9 + 3.49*m.x10 + 3.49*m.x11 + 7.73*m.x12 + 7.73*m.x13 + 0.53*m.x14 + 0.53*m.x15
+ 4.73*m.x16 + 4.73*m.x17 + 7.39*m.x18 + 7.39*m.x19 + 2.65*m.x20 + 2.65*m.x21 + 5.49*m.x22
+ 5.49*m.x23 + 7.075*m.x24 + 3.095*m.x25 + 3.195*m.x26 - m.x61 - m.x73 - 25*m.x75 <= 0)
m.c36 = Constraint(expr= 4.54*m.x1 + 4.54*m.x2 + 1.44*m.x3 + 1.44*m.x4 + 6.37*m.x5 + 6.37*m.x6 + 8.87*m.x7 + 8.34*m.x8
+ 8.34*m.x9 + 2.11*m.x10 + 2.11*m.x11 + 9.44*m.x12 + 9.44*m.x13 + 0.89*m.x14 + 0.89*m.x15
+ 4.92*m.x16 + 4.92*m.x17 + 2.67*m.x18 + 2.67*m.x19 + 1.09*m.x20 + 1.09*m.x21 + 5.26*m.x22
+ 5.26*m.x23 + 7.075*m.x24 + 3.095*m.x25 + 3.195*m.x26 - m.x62 - m.x74 - 25*m.x75 <= 0)
m.c37 = Constraint(expr= - 602.060322854716*m.x43 - 4703.49984422058*m.x44 - 215.898400752587*m.x46
- 62.2127194392644*m.x48 - 34.3822170900693*m.x49 - m.x77 + m.x87 == 0)
m.c38 = Constraint(expr= 350.573491928632*m.x43 - 487.070308443245*m.x44 - 124.1768579492*m.x46
- 1.32274451803741*m.x48 + 13.6836027713626*m.x49 - m.x78 + m.x88 == 0)
m.c39 = Constraint(expr= 893.266779949023*m.x43 - 505.244573683664*m.x44 + 1065.85136406397*m.x46
+ 120.56652305318*m.x48 + 85.5658198614319*m.x49 - m.x79 + m.x89 == 0)
m.c40 = Constraint(expr= 556.60577740017*m.x43 + 5528.61148613563*m.x44 + 31.0442144873003*m.x46
+ 9.17175744325124*m.x48 - 7.53464203233256*m.x49 - m.x80 + m.x90 == 0)
m.c41 = Constraint(expr= 241.716227697536*m.x43 + 6164.71076955032*m.x44 - 394.637817497648*m.x46
- 44.7218828371166*m.x48 - 11.4318706697459*m.x49 - m.x81 + m.x91 == 0)
m.c42 = Constraint(expr= - 161.852166525064*m.x43 + 2566.20625194724*m.x44 - 39.5108184383818*m.x46
- 19.1415343064755*m.x48 + 1.99191685912241*m.x49 - m.x82 + m.x92 == 0)
m.c43 = Constraint(expr= - 854.82158028887*m.x43 - 7756.77640461107*m.x44 - 77.140169332079*m.x46
- 21.6558420680342*m.x48 - 15.7621247113164*m.x49 - m.x83 + m.x93 == 0)
m.c44 = Constraint(expr= - 422.047578589635*m.x43 - 414.373247481566*m.x44 - 281.749764816557*m.x46
+ 16.0587743553469*m.x48 - 10.5658198614319*m.x49 - m.x84 + m.x94 == 0)
m.c45 = Constraint(expr= - 165.569243840272*m.x43 - 450.721777962404*m.x44 - 279.397930385701*m.x46
+ 0.535656870940797*m.x48 - 22.6905311778291*m.x49 - m.x85 + m.x95 == 0)
m.c46 = Constraint(expr= 164.188615123194*m.x43 + 58.1576487693447*m.x44 + 315.616180620884*m.x46
+ 2.72201144620925*m.x48 + 1.12586605080831*m.x49 - m.x86 + m.x96 == 0)
m.c48 = Constraint(expr= - 211*m.x27 - 1900*m.x42 - 4000*m.x43 - 35000*m.x44 - 2500*m.x45 - 1500*m.x46 - 10000*m.x47
- 170*m.x48 - 150*m.x49 - 1000*m.x50 + m.x98 == 0)
m.c49 = Constraint(expr= - 122*m.x1 - 122*m.x2 - 45*m.x3 - 45*m.x4 - 36*m.x5 - 36*m.x6 - 291*m.x7 - 20*m.x8 - 20*m.x9
- 97*m.x10 - 97*m.x11 - 45*m.x16 - 45*m.x17 - 27*m.x18 - 27*m.x19 - 53*m.x20 - 53*m.x21
- 105*m.x22 - 105*m.x23 + m.x99 == 0)
m.c50 = Constraint(expr= - 3*m.x51 - 3*m.x52 - 3*m.x53 - 3*m.x54 - 3*m.x55 - 3*m.x56 - 3*m.x57 - 3*m.x58 - 3*m.x59
- 3*m.x60 - 3*m.x61 - 3*m.x62 - 10*m.x63 - 10*m.x64 - 10*m.x65 - 10*m.x66 - 10*m.x67 - 10*m.x68
- 10*m.x69 - 10*m.x70 - 10*m.x71 - 10*m.x72 - 10*m.x73 - 10*m.x74 - 2054*m.x75 + m.x100 == 0)
m.c51 = Constraint(expr= 10*m.x63 + 10*m.x64 + 10*m.x65 + 10*m.x66 + 10*m.x67 + 10*m.x68 + 10*m.x69 + 10*m.x70
+ 10*m.x71 + 10*m.x72 + 10*m.x73 + 10*m.x74 + 2054*m.x75 + m.x76 + m.x99 + m.x101 <= 7123.2)
m.c52 = Constraint(expr= - m.x27 + m.x101 == 0)
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2020-06-08 14:44
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('disturbance', '0071_temporaryuseapiarysite_selected'),
]
operations = [
migrations.AlterField(
model_name='temporaryuseapiarysite',
name='proposal_apiary_temporary_use',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='temporary_use_apiary_sites', to='disturbance.ProposalApiaryTemporaryUse'),
),
]
|
def solve(n):
ch=str(n) #création d'une chaine de caractères composée du nombre
b=0 #initialisation de la variable
for k in ch: #On parcourt chaque élément de la chaine
b+=int(k) #On convertit chaque élément en entier et on le somme à b
return(b) #La fonction renvoie la somme
def solve2(n):
r=0 #Deuxième façon de résoudre le problème. On initialise une variable à 0
while n!=0: #Le principe consiste à diviser eculidiennement par 10 successivement jusqu'à ce que le reste soit nul
r+=n%10 #On récupère à chaque le chiffre des unités du nombre. Ex 459: on ajoute 9 à r
n=n//10 #On divise de façon euclidienne. Ex 459: 45. Losrqu'on obtient 0 on a bien effectué la somme de tous les nombres.
return(r) # On renvoie la somme de tous les chiffres du nombre.
# D'un point de vue rigoureux, la deuxième méthode est plus mathématique.
|
#!/usr/bin/env python
#
# Created by: Alex Leach, November 2012
#
import numpy as np
from numpy.testing import TestCase, run_module_suite, assert_array_almost_equal, \
assert_array_almost_equal_nulp
from scipy.linalg.expokit import expm
#from scipy.linalg.expokit import dgchbv, dgexpv, dgpadm, dgphiv, dmexpv, dnchbv, \
# dschbv, dsexpv, dspadm, dsphiv, zgchbv, zgexpv, zgpadm, zgphiv, zhexpv, \
# zhpadm, zhphiv, znchbv
class TestPADM(TestCase):
def test_zero(self):
a = array([[0.,0],[0,0]])
assert_array_almost_equal(expm(a),[[1,0],[0,1]])
def test_simple(self):
a = array([[0.,1.],[0,0]])
assert_array_almost_equal(expm(a),[[1,1],[0,1]] )
def test_complex(self):
a = array([[0.,1.],[0,0]])
assert_array_almost_equal(expm(a),[[1,1],[0,1]] )
if __name__ == '__main__':
run_module_suite()
|
#!/usr/bin/env python3
from two1.wallet import Wallet
from two1.bitrequests import BitTransferRequests
# set up bitrequest client for BitTransfer requests
wallet = Wallet()
requests = BitTransferRequests(wallet)
# server address
server_url = 'http://localhost:5000/'
def buy_fortune():
url = server_url+'buy?payout_address={0}'
response = requests.get(url=url.format(wallet.get_payout_address()))
print((response.text))
if __name__ == '__main__':
buy_fortune()
|
# ***********************************************************************
# Import libraries
# ***********************************************************************
import sys
import os
import time
import datetime
import numpy as np
import pandas as pd
sys.path.append( os.path.abspath( '../../opti-trade' ) )
from mod.mfdMod import MfdMod
from dat.assets import OPTION_ETFS as ETFS
from dat.assets import FUTURES, INDEXES
# ***********************************************************************
# Set some parameters and read data
# ***********************************************************************
dfFile = 'random_signals.pkl'
minTrnDate = pd.to_datetime( '2004-01-06 09:00:00' )
maxTrnDate = pd.to_datetime( '2004-03-15 19:39:00' )
maxOosDate = pd.to_datetime( '2004-03-29 16:59:00' )
velNames = [ 'y1', 'y2', 'y3' ]
selParams = { 'inVelNames' : [ 'SPY' ],
'maxNumVars' : 3,
'minImprov' : 0.10,
'strategy' : 'forward' }
modFileName = 'model.dill'
# ***********************************************************************
# Build model
# ***********************************************************************
mfdMod = MfdMod( dfFile = dfFile,
minTrnDate = minTrnDate,
maxTrnDate = maxTrnDate,
maxOosDate = maxOosDate,
velNames = velNames,
maxOptItrs = 100,
optGTol = 1.0e-12,
optFTol = 1.0e-12,
factor = 1.0e-4,
regCoef = 1.0e-6,
selParams = None,
smoothCount = None,
logFileName = None,
verbose = 1 )
validFlag = mfdMod.build()
print( 'Success :', validFlag )
mfdMod.save( modFileName )
mfdMod.ecoMfd.pltResults()
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.9 on 2018-02-03 19:15
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pedido', '0002_auto_20180203_0503'),
]
operations = [
migrations.AddField(
model_name='pedido',
name='status',
field=models.CharField(blank=True, choices=[('m', 'Maintenance'), ('o', 'On loan'), ('a', 'Available'), ('r', 'Reserved')], default='m', help_text='Book availability', max_length=1),
),
]
|
class Solution:
def findDuplicate(self, paths: List[str]) -> List[List[str]]:
"""Hash Table
Running time: O(n) where is the number of files.
"""
from collections import defaultdict
d = defaultdict(list)
for path in paths:
parts = path.split(' ')
directory, files = parts[0], parts[1:]
for f in files:
idx = f.index('(')
d[f[idx+1:-1]].append(directory + '/' + f[:idx])
return [v for v in d.values() if len(v) > 1]
|
def consumo(distancia, quantidade_litros):
if distancia / quantidade_litros < 8:
return print('Venda o carro')
elif distancia / quantidade_litros <= 12:
return print('Econômico')
else:
return print('Super econômico')
retorno = consumo(100,10)
retorno2 = consumo(30, 4.5)
|
# Generated by Django 3.1 on 2020-08-31 22:32
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('pages', '0006_auto_20200817_0419'),
]
operations = [
migrations.AddField(
model_name='webpage',
name='link',
field=models.CharField(default='', max_length=100),
),
migrations.AlterField(
model_name='websection',
name='parent_section',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='pages.websection'),
),
migrations.CreateModel(
name='WebInnerLink',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('page', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='pages.webpage')),
('parent_section', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='pages.websection')),
],
),
]
|
# coding:utf-8
class Foo(object):
def __enter__(self):
print("enter called")
def __exit__(self, exc_type, exc_val, exc_tb):
print("离开方法")
# 上下文管理器
with Foo() as foo:
print("hello python") |
from useless.sqlgen.admin import grant_public, grant_user
from tables import primary_sequences
from tables import primary_tables
#from tables import SCRIPTS, MACHINE_SCRIPTS
from tables import TRAIT_SCRIPTS, MACHINE_SCRIPTS
from pgsql_functions import create_pgsql_functions
class SchemaError(RuntimeError):
pass
class AlreadyPresentError(RuntimeError):
pass
def insert_list(cursor, table, field, list):
for value in list:
cursor.insert(table=table, data={field : value})
def start_schema(conn, installuser='paella'):
cursor = conn.cursor(statement=True)
tables, mapping = primary_tables()
current_tables = cursor.tables()
primary_table_names = [t.name for t in tables]
startup = True
for tname in primary_table_names:
if tname in current_tables:
startup = False
if startup:
map(cursor.create_sequence, primary_sequences())
map(cursor.create_table, tables)
both = [s for s in MACHINE_SCRIPTS if s in TRAIT_SCRIPTS]
print both
traitscripts = [s for s in TRAIT_SCRIPTS if s not in both]
print traitscripts
machinescripts = [s for s in MACHINE_SCRIPTS if s not in both]
print machinescripts
for script in both:
cursor.insert(table='scriptnames', data=dict(script=script, type='both'))
for script in traitscripts:
cursor.insert(table='scriptnames', data=dict(script=script, type='trait'))
for script in machinescripts:
cursor.insert(table='scriptnames', data=dict(script=script, type='machine'))
paella_select = grant_user('SELECT', [x.name for x in tables], installuser)
paella_full = grant_user('ALL',
['current_environment'],
installuser)
paella_insert = grant_user('INSERT', ['default_environment'],
installuser)
for grant in paella_select, paella_full, paella_insert:
cursor.execute(grant)
create_pgsql_functions(cursor)
else:
all_there = True
for table in primary_table_names:
if table not in current_tables:
all_there = False
# the AlreadyPresentError is a convenience error
# it doesn't mean the schema is a-ok
if all_there:
raise AlreadyPresentError, 'it seems everything is already here'
else:
raise SchemaError, 'some primary tables already exist in the database'
|
# """
# Topological Sort
# Difficulty: Hard
# Given a list of tasks and a list of dependencies return
# a list of tasks in valid order. If no such order exists
# return an empty array.
#
# tasks = [1,2,3,4]
# deps = [
# [2, 3],
# [2, 4],
# [4, 3],
# [1, 3],
# [1, 4],
# ]
#
# topological_sort(tasks, deps) = [1,2,4,3] or [2,1,4,3]
#
# Author: BrannanC
# """
from collections import defaultdict
def topological_sort(j, deps):
jobs = j[::1]
r = []
ld = defaultdict(list)
lj = defaultdict(list)
for j in jobs:
ld[j] = []
for d in deps:
ld[d[1]].append(d[0])
lj[d[0]].append(d[1])
while len(jobs):
empty_keys = [k for k in ld.keys() if len(ld[k]) == 0]
if len(empty_keys) == 0:
return []
for k in empty_keys:
if k in jobs:
jobs.remove(k)
r.append(k)
del ld[k]
for d in lj[k]:
ld[d].remove(k)
return r
if __name__ == "__main__":
tasksx = [4, 3, 2, 1]
depsx = [
[2, 3],
[2, 4],
[4, 3],
[1, 3],
[1, 4],
]
print("topological_sort", topological_sort(tasksx, depsx))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.